-
Notifications
You must be signed in to change notification settings - Fork 484
Expand file tree
/
Copy pathcompile.rs
More file actions
1598 lines (1464 loc) · 60.8 KB
/
Copy pathcompile.rs
File metadata and controls
1598 lines (1464 loc) · 60.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#![allow(clippy::too_many_arguments)]
mod dependency_cycle;
use super::build_types::*;
use super::logs;
use super::packages;
use crate::config;
use crate::config::Config;
use crate::helpers;
use crate::helpers::StrippedVerbatimPath;
use crate::project_context::ProjectContext;
use ahash::{AHashMap, AHashSet};
use anyhow::{Result, anyhow};
use console::style;
use log::{debug, info, trace, warn};
use rayon::prelude::*;
use std::cmp::Ordering;
use std::collections::BinaryHeap;
use std::path::Path;
use std::path::PathBuf;
use std::process::Command;
use std::sync::OnceLock;
use std::sync::mpsc;
use std::time::SystemTime;
use tracing::{info_span, instrument};
/// Decode captured compiler output (stdout or stderr) into a String.
///
/// The output is not guaranteed to be valid UTF-8: a code frame can truncate a
/// multi-byte character. Decode lossily so a bad byte becomes a replacement
/// character instead of crashing the build.
fn compiler_output_to_string(bytes: &[u8]) -> String {
String::from_utf8_lossy(bytes).to_string()
}
/// Execute js-post-build command for a compiled JavaScript file.
/// The command runs in the directory containing the rescript.json that defines it.
/// The absolute path to the JS file is passed as an argument.
fn execute_post_build_command(cmd: &str, js_file_path: &Path, working_dir: &Path) -> Result<()> {
let full_command = format!("{} {}", cmd, js_file_path.display());
let _span = info_span!(
"build.js_post_build",
command = %cmd,
js_file = %js_file_path.display(),
)
.entered();
debug!(
"Executing js-post-build: {} (in {})",
full_command,
working_dir.display()
);
let output = if cfg!(target_os = "windows") {
Command::new("cmd")
.args(["/C", &full_command])
.current_dir(working_dir)
.output()
} else {
Command::new("sh")
.args(["-c", &full_command])
.current_dir(working_dir)
.output()
};
match output {
Ok(output) => {
let stderr = String::from_utf8_lossy(&output.stderr);
let stdout = String::from_utf8_lossy(&output.stdout);
// Always log stdout/stderr - the user explicitly configured this command
// and likely cares about its output
if !stdout.is_empty() {
info!("{}", stdout.trim());
}
if !stderr.is_empty() {
warn!("{}", stderr.trim());
}
if !output.status.success() {
Err(anyhow!(
"js-post-build command failed for {}",
js_file_path.display()
))
} else {
Ok(())
}
}
Err(e) => Err(anyhow!("Failed to execute js-post-build command: {}", e)),
}
}
/// A unit of work in the ready queue. Ordered by `priority` so that the
/// `BinaryHeap` pops the module with the longest remaining critical path first.
#[derive(Debug)]
struct WorkUnit {
priority: i64,
module_name: String,
}
impl PartialEq for WorkUnit {
fn eq(&self, other: &Self) -> bool {
self.priority == other.priority
}
}
impl Eq for WorkUnit {}
impl PartialOrd for WorkUnit {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl Ord for WorkUnit {
fn cmp(&self, other: &Self) -> Ordering {
self.priority.cmp(&other.priority)
}
}
/// Result of a single module compilation, sent from a worker back to the
/// dispatcher on the main thread. Mirrors the tuple shape the wave-based
/// scheduler used to return.
struct CompletionMsg {
module_name: String,
result: Result<Option<String>>,
interface_result: Option<Result<Option<String>>>,
is_clean: bool,
is_compiled: bool,
}
struct CompileWarning {
module_name: String,
package_name: String,
warning: String,
}
/// Compute the critical-path priority of every module in the universe:
/// `priority(m) = 1 + max(priority(d) for d in in-universe dependents of m)`.
/// Runs a reverse-topological sweep from leaves to roots. Modules stuck in a
/// cycle get priority 0, and the actual cycle is diagnosed later by
/// `dependency_cycle::find` when the dispatcher detects a stall.
fn compute_critical_path_priorities(
universe: &AHashSet<String>,
build_state: &BuildState,
) -> AHashMap<String, i64> {
let mut priorities: AHashMap<String, i64> = AHashMap::with_capacity(universe.len());
let mut remaining_dependents: AHashMap<String, usize> = AHashMap::with_capacity(universe.len());
let mut queue: Vec<String> = Vec::new();
for name in universe {
let module = build_state.get_module(name).unwrap();
let count = module.dependents.iter().filter(|d| universe.contains(*d)).count();
remaining_dependents.insert(name.clone(), count);
if count == 0 {
queue.push(name.clone());
}
}
while let Some(name) = queue.pop() {
let module = build_state.get_module(&name).unwrap();
let max_dep_priority = module
.dependents
.iter()
.filter(|d| universe.contains(*d))
.filter_map(|d| priorities.get(d).copied())
.max()
.unwrap_or(0);
priorities.insert(name.clone(), max_dep_priority + 1);
for dep in &module.deps {
if !universe.contains(dep) {
continue;
}
if let Some(count) = remaining_dependents.get_mut(dep) {
*count -= 1;
if *count == 0 {
queue.push(dep.clone());
}
}
}
}
for name in universe {
priorities.entry(name.clone()).or_insert(0);
}
priorities
}
/// Run the short-circuit check or actual `bsc` invocation for a single module.
/// Invoked from worker threads inside the dispatcher scope; only reads
/// `BuildState`, never mutates it.
fn compile_one(
build_state: &BuildState,
module_name: &str,
is_dirty: bool,
warn_error_override: Option<String>,
) -> CompletionMsg {
let module = build_state.get_module(module_name).unwrap();
let package = build_state
.get_package(&module.package_name)
.expect("Package not found");
if !is_dirty {
return CompletionMsg {
module_name: module_name.to_string(),
result: Ok(None),
interface_result: Some(Ok(None)),
is_clean: true,
is_compiled: false,
};
}
match &module.source_type {
SourceType::MlMap(_) => {
// The mlmap is compiled during AST generation; the entry here just
// marks it compiled so its namespace members can proceed.
CompletionMsg {
module_name: package.namespace.to_suffix().unwrap(),
result: Ok(None),
interface_result: Some(Ok(None)),
is_clean: false,
is_compiled: false,
}
}
SourceType::SourceFile(source_file) => {
// Construct span + attributes only when a subscriber is listening.
// Otherwise root_config.get_package_specs() (which clones) and the
// attribute formatting run per-module on the build hot path.
let _file_span = if tracing::enabled!(tracing::Level::INFO) {
let root_config = build_state.get_root_config();
let specs = root_config.get_package_specs();
// A package can be built under multiple specs (e.g. ESM + CJS).
// Report all of them joined by "," instead of silently picking
// the first — the compile_file span covers work for every spec.
let suffix = specs
.iter()
.map(|s| root_config.get_suffix(s))
.collect::<Vec<_>>()
.join(",");
let module_system = specs
.iter()
.map(|s| s.module.as_str())
.collect::<Vec<_>>()
.join(",");
let namespace = package.namespace.to_suffix().unwrap_or_default();
info_span!("build.compile_file", module = %module_name, package = %package.name, suffix, module_system, namespace).entered()
} else {
tracing::Span::none().entered()
};
let cmi_path = helpers::get_compiler_asset(
package,
&package.namespace,
&source_file.implementation.path,
"cmi",
);
let cmi_digest = helpers::compute_file_hash(Path::new(&cmi_path));
let interface_result = source_file.interface.as_ref().map(|iface| {
compile_file(
package,
&helpers::get_ast_path(&iface.path),
module,
true,
build_state,
warn_error_override.clone(),
)
});
let result = compile_file(
package,
&helpers::get_ast_path(&source_file.implementation.path),
module,
false,
build_state,
warn_error_override,
);
let cmi_digest_after = helpers::compute_file_hash(Path::new(&cmi_path));
// If the cmi is byte-for-byte unchanged, downstream modules can
// short-circuit — we check both interface and implementation
// because e.g. `include MyModule` exposes implementation changes
// through the cmi even when the .resi is untouched.
let is_clean_cmi = matches!(
(cmi_digest, cmi_digest_after),
(Some(a), Some(b)) if a == b
);
CompletionMsg {
module_name: module_name.to_string(),
result,
interface_result,
is_clean: is_clean_cmi,
is_compiled: true,
}
}
}
}
fn collect_stored_warnings_for_modules_not_recompiled(
build_state: &BuildState,
recompiled_modules: &AHashSet<String>,
) -> Vec<CompileWarning> {
// Collect warnings from modules that were not recompiled in this build but still have stored
// warnings from a previous compilation. This includes ready modules that were in the compile
// universe but never scheduled because an earlier module failed.
let mut warnings = Vec::new();
for (module_name, module) in build_state.modules.iter() {
if recompiled_modules.contains(module_name) {
continue;
}
if let SourceType::SourceFile(ref source_file) = module.source_type {
if let Some(ref warning) = source_file.implementation.compile_warnings {
warnings.push(CompileWarning {
module_name: module_name.clone(),
package_name: module.package_name.clone(),
warning: warning.clone(),
});
}
if let Some(ref interface) = source_file.interface
&& let Some(ref warning) = interface.compile_warnings
{
warnings.push(CompileWarning {
module_name: module_name.clone(),
package_name: module.package_name.clone(),
warning: warning.clone(),
});
}
}
}
warnings
}
// Warning output should use the same deterministic module-name order whether a
// warning was emitted by this compile pass or replayed from a previous one.
fn append_compile_warnings(
build_state: &BuildState,
mut warning_entries: Vec<CompileWarning>,
compile_warnings: &mut String,
) {
warning_entries.sort_by(|a, b| a.module_name.cmp(&b.module_name));
for CompileWarning {
package_name,
warning,
..
} in warning_entries
{
if let Some(package) = build_state.get_package(&package_name) {
logs::append(package, &warning);
}
compile_warnings.push_str(&warning);
}
}
#[instrument(name = "build.compile", skip_all)]
pub fn compile(
build_state: &mut BuildCommandState,
show_progress: bool,
inc: impl Fn() + std::marker::Sync,
set_length: impl Fn(u64),
) -> anyhow::Result<(String, String, usize)> {
let dirty_modules = build_state
.modules
.iter()
.filter_map(|(module_name, module)| {
if module.compile_dirty {
Some(module_name.to_owned())
} else {
None
}
})
.collect::<AHashSet<String>>();
// Expand the compile universe: every dirty module plus everything that
// transitively depends on it.
let mut compile_universe = dirty_modules.clone();
let mut frontier = compile_universe.clone();
loop {
let mut dependents: AHashSet<String> = AHashSet::new();
for module_name in frontier.iter() {
dependents.extend(build_state.get_module(module_name).unwrap().dependents.clone());
}
frontier = dependents
.difference(&compile_universe)
.cloned()
.collect::<AHashSet<String>>();
if frontier.is_empty() {
break;
}
compile_universe.extend(frontier.iter().cloned());
}
let compile_universe_count = compile_universe.len();
set_length(compile_universe_count as u64);
let priorities = compute_critical_path_priorities(&compile_universe, &build_state.build_state);
// Count of not-yet-completed in-universe dependencies for each module.
// Only touched on the main thread.
let mut pending_deps: AHashMap<String, usize> = compile_universe
.iter()
.map(|name| {
let module = build_state.get_module(name).unwrap();
let count = module
.deps
.iter()
.filter(|d| compile_universe.contains(*d))
.count();
(name.clone(), count)
})
.collect();
let mut ready_heap: BinaryHeap<WorkUnit> = compile_universe
.iter()
.filter(|name| pending_deps[*name] == 0)
.map(|name| WorkUnit {
priority: *priorities.get(name).unwrap_or(&0),
module_name: name.clone(),
})
.collect();
// Dirtiness propagation tracked locally: when a module's cmi changes, its
// dependents are forced dirty. This mirrors the old `compile_dirty` flag
// mutation but keeps build_state borrow-free while workers are running.
let mut dirty_set: AHashSet<String> = dirty_modules;
let warn_error_override = build_state.get_warn_error_override();
let build_state_ref: &BuildState = &build_state.build_state;
let compile_span = tracing::Span::current();
let (tx, rx) = mpsc::channel::<CompletionMsg>();
// Bound concurrency to rayon's pool size so the priority heap actually
// orders work — dumping everything into rayon's deque would defeat #2.
let capacity = rayon::current_num_threads().max(1);
let mut completed: AHashSet<String> = AHashSet::new();
let mut results_buffer: Vec<CompletionMsg> = Vec::with_capacity(compile_universe_count);
let mut has_errors = false;
let mut stalled = false;
rayon::in_place_scope(|scope| {
let mut in_flight: usize = 0;
loop {
while in_flight < capacity && !has_errors {
let Some(work) = ready_heap.pop() else { break };
let module_name = work.module_name.clone();
let is_dirty = dirty_set.contains(&module_name);
let warn_override = warn_error_override.clone();
let parent_span = compile_span.clone();
let tx = tx.clone();
let inc_ref = &inc;
in_flight += 1;
scope.spawn(move |_| {
let _guard = parent_span.enter();
let msg = compile_one(build_state_ref, &module_name, is_dirty, warn_override);
if show_progress {
inc_ref();
}
// Receiver lives for the full scope, so send cannot fail
// unless the dispatcher has already hung up on purpose.
let _ = tx.send(msg);
});
}
if in_flight == 0 {
if !ready_heap.is_empty() {
// Errors suppressed new spawns; nothing left to drain.
break;
}
if completed.len() < compile_universe_count && !has_errors {
stalled = true;
}
break;
}
let Ok(msg) = rx.recv() else { break };
in_flight -= 1;
if msg.result.is_err() || msg.interface_result.as_ref().is_some_and(|r| r.is_err()) {
has_errors = true;
}
let is_clean = msg.is_clean;
let finished_name = msg.module_name.clone();
completed.insert(finished_name.clone());
results_buffer.push(msg);
// Look up dependents from the node the scheduler scheduled under —
// for mlmap, compile_one returns the namespace suffix, which is the
// key modules use to refer to the namespace entry.
let dependents = build_state.get_module(&finished_name).unwrap().dependents.clone();
for dep in &dependents {
if !compile_universe.contains(dep) {
continue;
}
if !is_clean {
dirty_set.insert(dep.clone());
}
let count = pending_deps.get_mut(dep).unwrap();
*count -= 1;
if *count == 0 && !completed.contains(dep) {
ready_heap.push(WorkUnit {
priority: priorities[dep],
module_name: dep.clone(),
});
}
}
}
});
// Close our sender handle so any lingering clones in already-spawned
// workers don't keep the channel open past the scope.
drop(tx);
trace!(
"Compiled {} out of {} in the universe",
completed.len(),
compile_universe_count,
);
let mut compile_errors = String::new();
let mut compile_warnings = String::new();
let mut warning_entries = Vec::new();
let mut num_compiled_modules = 0;
// Persist propagated dirtiness back onto build_state. Modules that were
// marked dirty (because a predecessor's cmi changed) but never scheduled
// — e.g. the first compile error aborted further dispatch — must keep
// compile_dirty = true so the next incremental build recompiles them.
// Successful recompiles in the result loop below override this back to
// false for the modules that actually ran.
for name in &dirty_set {
if let Some(module) = build_state.build_state.modules.get_mut(name) {
module.compile_dirty = true;
}
}
// Sort by module name so the accumulated error/warning strings and the
// per-package compile.log writes are deterministic across runs, even
// though modules complete in arbitrary order.
results_buffer.sort_by(|a, b| a.module_name.cmp(&b.module_name));
// These timestamps are used as a compile-generation marker by
// mark_modules_with_expired_deps_dirty, not as precise wall-clock compile
// times. All modules successfully compiled in one pass are mutually
// up-to-date for that pass, so they must receive the same timestamp.
let compile_timestamp = SystemTime::now();
let mut recompiled_modules = AHashSet::<String>::new();
for msg in results_buffer {
let CompletionMsg {
module_name,
result,
interface_result,
is_compiled,
..
} = msg;
if is_compiled {
num_compiled_modules += 1;
recompiled_modules.insert(module_name.clone());
}
let package_name = {
let module = build_state
.build_state
.modules
.get(&module_name)
.ok_or_else(|| anyhow!("Module not found"))?;
module.package_name.clone()
};
let package = build_state
.build_state
.packages
.get(&package_name)
.ok_or_else(|| anyhow!("Package name not found"))?;
let (compile_warning, compile_error, interface_warning, interface_error) = {
let module = build_state
.build_state
.modules
.get_mut(&module_name)
.ok_or_else(|| anyhow!("Module not found"))?;
let (compile_warning, compile_error) = match module.source_type {
SourceType::MlMap(ref mut mlmap) => {
module.compile_dirty = false;
mlmap.parse_dirty = false;
(None, None)
}
SourceType::SourceFile(ref mut source_file) => match &result {
Ok(None) if !is_compiled => (None, None),
Ok(Some(err)) => {
let warning_text = err.to_string();
source_file.implementation.compile_state = CompileState::Warning;
source_file.implementation.compile_warnings = Some(warning_text.clone());
(Some(warning_text), None)
}
Ok(None) => {
source_file.implementation.compile_state = CompileState::Success;
source_file.implementation.compile_warnings = None;
(None, None)
}
Err(err) => {
source_file.implementation.compile_state = CompileState::Error;
source_file.implementation.compile_warnings = None;
(None, Some(err.to_string()))
}
},
};
let (interface_warning, interface_error) = if let SourceType::SourceFile(ref mut source_file) =
module.source_type
{
match &interface_result {
Some(Ok(None)) if !is_compiled => (None, None),
Some(Ok(Some(err))) => {
let warning_text = err.to_string();
source_file.interface.as_mut().unwrap().compile_state = CompileState::Warning;
source_file.interface.as_mut().unwrap().compile_warnings = Some(warning_text.clone());
(Some(warning_text), None)
}
Some(Ok(None)) => {
if let Some(interface) = source_file.interface.as_mut() {
interface.compile_state = CompileState::Success;
interface.compile_warnings = None;
}
(None, None)
}
Some(Err(err)) => {
source_file.interface.as_mut().unwrap().compile_state = CompileState::Error;
source_file.interface.as_mut().unwrap().compile_warnings = None;
(None, Some(err.to_string()))
}
_ => (None, None),
}
} else {
(None, None)
};
if result.is_ok() && interface_result.as_ref().is_none_or(|r| r.is_ok()) {
module.compile_dirty = false;
module.last_compiled_cmi = Some(compile_timestamp);
module.last_compiled_cmt = Some(compile_timestamp);
}
(compile_warning, compile_error, interface_warning, interface_error)
};
if let Some(warning) = compile_warning {
warning_entries.push(CompileWarning {
module_name: module_name.clone(),
package_name: package_name.clone(),
warning,
});
}
if let Some(error) = compile_error {
logs::append(package, &error);
compile_errors.push_str(&error);
}
if let Some(warning) = interface_warning {
warning_entries.push(CompileWarning {
module_name: module_name.clone(),
package_name: package_name.clone(),
warning,
});
}
if let Some(error) = interface_error {
logs::append(package, &error);
compile_errors.push_str(&error);
}
}
if stalled {
let cycle = dependency_cycle::find(
&compile_universe
.iter()
.map(|s| (s, build_state.get_module(s).unwrap()))
.collect::<Vec<(&String, &Module)>>(),
);
let guidance = "Possible solutions:\n- Extract shared code into a new module both depend on.\n";
let message = format!(
"\n{}\n{}\n{}",
style("Can't continue... Found a circular dependency in your code:").red(),
dependency_cycle::format(&cycle, build_state),
guidance
);
let mut touched_packages = AHashSet::<String>::new();
for module_name in cycle.iter() {
if let Some(module) = build_state.get_module(module_name)
&& touched_packages.insert(module.package_name.clone())
&& let Some(package) = build_state.get_package(&module.package_name)
{
logs::append(package, &message);
}
}
compile_errors.push_str(&message);
}
// Collect replayed warnings into the same list as fresh warnings so mixed
// output matches the sorted order used when every module compiles normally.
warning_entries.extend(collect_stored_warnings_for_modules_not_recompiled(
&build_state.build_state,
&recompiled_modules,
));
append_compile_warnings(&build_state.build_state, warning_entries, &mut compile_warnings);
Ok((compile_errors, compile_warnings, num_compiled_modules))
}
static RUNTIME_PATH_MEMO: OnceLock<PathBuf> = OnceLock::new();
pub fn get_runtime_path(package_config: &Config, project_context: &ProjectContext) -> Result<PathBuf> {
if let Some(p) = RUNTIME_PATH_MEMO.get() {
return Ok(p.clone());
}
let resolved = match std::env::var("RESCRIPT_RUNTIME") {
Ok(runtime_path) => Ok(PathBuf::from(runtime_path)),
Err(_) => match helpers::try_package_path(package_config, project_context, "@rescript/runtime") {
Ok(runtime_path) => Ok(runtime_path),
Err(err) => Err(anyhow!(
"The rescript runtime package could not be found.\nPlease set RESCRIPT_RUNTIME environment variable or make sure the runtime package is installed.\nError: {err}"
)),
},
}?;
let _ = RUNTIME_PATH_MEMO.set(resolved.clone());
Ok(resolved)
}
pub fn get_runtime_path_args(
package_config: &Config,
project_context: &ProjectContext,
) -> Result<Vec<String>> {
let runtime_path = get_runtime_path(package_config, project_context)?;
Ok(vec![
"-runtime-path".to_string(),
runtime_path.to_string_lossy().to_string(),
])
}
pub fn compiler_args(
config: &config::Config,
ast_path: &Path,
file_path: &Path,
is_interface: bool,
has_interface: bool,
project_context: &ProjectContext,
// if packages are known, we pass a reference here
// this saves us a scan to find their paths.
// This is None when called by build::get_compiler_args
packages: &Option<&AHashMap<String, packages::Package>>,
// Is the file listed as "type":"dev"?
is_type_dev: bool,
is_local_dep: bool,
// Command-line --warn-error flag override (takes precedence over rescript.json config)
warn_error_override: Option<String>,
source_map_command: config::SourceMapCommand,
// Pre-expanded source directories for the current package (used by gentype).
// Pass an empty slice when unavailable (e.g. the compiler-args CLI command).
current_package_dirs: &[PathBuf],
) -> Result<Vec<String>> {
let bsc_flags = config::flatten_flags(&config.compiler_flags);
let dependency_paths = get_dependency_paths(config, project_context, packages, is_type_dev);
let module_name = helpers::file_path_to_module_name(file_path, &config.get_namespace());
let namespace_args = match &config.get_namespace() {
packages::Namespace::NamespaceWithEntry { namespace: _, entry } if &module_name == entry => {
// if the module is the entry we just want to open the namespace
vec![
"-open".to_string(),
config.get_namespace().to_suffix().unwrap().to_string(),
]
}
packages::Namespace::Namespace(_)
| packages::Namespace::NamespaceWithEntry {
namespace: _,
entry: _,
} => {
vec![
"-bs-ns".to_string(),
config.get_namespace().to_suffix().unwrap().to_string(),
]
}
packages::Namespace::NoNamespace => vec![],
};
let root_config = project_context.get_root_config();
let jsx_args = root_config.get_jsx_args();
let jsx_module_args = root_config.get_jsx_module_args();
let jsx_mode_args = root_config.get_jsx_mode_args();
let jsx_preserve_args = root_config.get_jsx_preserve_args();
let source_map_args = root_config.get_source_map_args(source_map_command);
let bsb_project_root = project_context.get_root_path();
let dep_paths: Vec<(String, PathBuf)> = if config.gentype_config.is_some() {
let resolved = packages.as_ref().map(|pkgs| {
config
.dependencies
.iter()
.flatten()
.filter_map(|dep| {
let name = dep.name();
pkgs.get(name).map(|pkg| (name.to_string(), pkg.path.clone()))
})
.collect::<Vec<_>>()
});
resolved.unwrap_or_default()
} else {
Vec::new()
};
let gentype_arg = config.get_gentype_args(current_package_dirs, Some(bsb_project_root), &dep_paths);
let experimental_args = root_config.get_experimental_features_args();
let warning_args = config.get_warning_args(is_local_dep, warn_error_override);
let read_cmi_args = match has_interface {
true => {
if is_interface {
vec![]
} else {
vec!["-bs-read-cmi".to_string()]
}
}
false => vec![],
};
let package_name_arg = vec!["-bs-package-name".to_string(), config.name.to_owned()];
let project_root_args = config.get_project_root_args();
let implementation_args = if is_interface {
debug!("Compiling interface file: {}", &module_name);
vec![]
} else {
debug!("Compiling file: {}", &module_name);
let specs = root_config.get_package_specs();
specs
.iter()
.flat_map(|spec| {
vec![
"-bs-package-output".to_string(),
format!(
"{}:{}:{}",
spec.module.as_str(),
if spec.in_source {
file_path.parent().unwrap().to_str().unwrap().to_string()
} else {
Path::new("lib")
.join(Path::join(
Path::new(&spec.get_out_of_source_dir()),
file_path.parent().unwrap(),
))
.to_str()
.unwrap()
.to_string()
},
root_config.get_suffix(spec),
),
]
})
.collect()
};
let runtime_path_args = get_runtime_path_args(config, project_context)?;
Ok(vec![
namespace_args,
read_cmi_args,
vec![
"-I".to_string(),
Path::new("..").join("ocaml").to_string_lossy().to_string(),
],
runtime_path_args,
dependency_paths,
jsx_args,
jsx_module_args,
jsx_mode_args,
jsx_preserve_args,
source_map_args,
bsc_flags.to_owned(),
warning_args,
gentype_arg,
experimental_args,
// vec!["-warn-error".to_string(), "A".to_string()],
// ^^ this one fails for bisect-ppx
// this is the default
// we should probably parse the right ones from the package config
// vec!["-w".to_string(), "a".to_string()],
package_name_arg,
project_root_args,
implementation_args,
// vec![
// "-I".to_string(),
// abs_node_modules_path.to_string() + "/rescript/ocaml",
// ],
vec![ast_path.to_string_lossy().to_string()],
]
.concat())
}
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum DependentPackage {
Normal(String),
Dev(String),
}
impl DependentPackage {
fn name(&self) -> &str {
match self {
Self::Normal(name) => name,
Self::Dev(name) => name,
}
}
fn is_dev(&self) -> bool {
match self {
Self::Normal(_) => false,
Self::Dev(_) => true,
}
}
}
fn get_dependency_paths(
config: &config::Config,
project_context: &ProjectContext,
packages: &Option<&AHashMap<String, packages::Package>>,
is_file_type_dev: bool,
) -> Vec<String> {
let normal_deps: Vec<DependentPackage> = config
.get_dependency_names()
.into_iter()
.map(DependentPackage::Normal)
.collect();
// We can only access dev dependencies for source_files that are marked as "type":"dev"
let dev_deps: Vec<DependentPackage> = if is_file_type_dev {
config
.get_dev_dependency_names()
.into_iter()
.map(DependentPackage::Dev)
.collect()
} else {
vec![]
};
[dev_deps, normal_deps]
.concat()
.par_iter()
.filter_map(|dependent_package| {
let package_name = dependent_package.name();
let dependency_path = if let Some(packages) = packages {
packages
.get(package_name)
.as_ref()
.map(|package| package.path.clone())
} else {
// packages will only be None when called by build::get_compiler_args
// in that case we can safely pass config as the package config.
packages::read_dependency(package_name, config, project_context).ok()
}
.map(|canonicalized_path| {
vec![
"-I".to_string(),
packages::get_ocaml_build_path(&canonicalized_path)
.to_string_lossy()
.to_string(),
]
});
if !dependent_package.is_dev() && dependency_path.is_none() {
panic!(
"Expected to find dependent package {} of {}",
package_name, config.name
);
}
dependency_path
})
.collect::<Vec<Vec<String>>>()
.concat()
}
fn compile_file(
package: &packages::Package,
ast_path: &Path,
module: &Module,
is_interface: bool,
build_state: &BuildState,
warn_error_override: Option<String>,
) -> Result<Option<String>> {
let BuildState {
packages,
project_context,
compiler_info,
..
} = build_state;
let root_config = build_state.get_root_config();