-
-
Notifications
You must be signed in to change notification settings - Fork 385
Expand file tree
/
Copy pathfile.rs
More file actions
6941 lines (6161 loc) · 240 KB
/
Copy pathfile.rs
File metadata and controls
6941 lines (6161 loc) · 240 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)]
use crate::docs::ModuleDocumentation;
use crate::module::{
CheckedModule, ConstrainedModule, EntryPoint, Expectations, ExposedToHost,
FoundSpecializationsModule, LateSpecializationsModule, LoadedModule, ModuleHeader,
ModuleTiming, MonomorphizedModule, ParsedModule, ToplevelExpects, TypeCheckedModule,
};
use crate::module_cache::ModuleCache;
use bumpalo::{collections::CollectIn, Bump};
use crossbeam::channel::{bounded, Sender};
use crossbeam::deque::{Injector, Worker};
use crossbeam::thread;
use parking_lot::Mutex;
use roc_builtins::roc::module_source;
use roc_can::abilities::{AbilitiesStore, PendingAbilitiesStore, ResolvedImpl};
use roc_can::constraint::{Constraint as ConstraintSoa, Constraints, TypeOrVar};
use roc_can::env::Env;
use roc_can::expr::{Declarations, ExpectLookup, PendingDerives};
use roc_can::module::{
canonicalize_module_defs, ExposedByModule, ExposedForModule, ExposedModuleTypes, Module,
ModuleParams, ResolvedImplementations, TypeState,
};
use roc_can::scope::Scope;
use roc_can_solo::module::{solo_canonicalize_module_defs, SoloCanOutput};
use roc_collections::soa::slice_extend_new;
use roc_collections::{default_hasher, BumpMap, MutMap, MutSet, VecMap, VecSet};
use roc_constrain::module::constrain_module;
use roc_debug_flags::dbg_do;
#[cfg(debug_assertions)]
use roc_debug_flags::{
ROC_CHECK_MONO_IR, ROC_PRINT_IR_AFTER_DROP_SPECIALIZATION, ROC_PRINT_IR_AFTER_REFCOUNT,
ROC_PRINT_IR_AFTER_RESET_REUSE, ROC_PRINT_IR_AFTER_SPECIALIZATION, ROC_PRINT_IR_AFTER_TRMC,
ROC_PRINT_LOAD_LOG,
};
use roc_derive::SharedDerivedModule;
use roc_error_macros::internal_error;
use roc_late_solve::{AbilitiesView, WorldAbilities};
use roc_module::ident::{Ident, ModuleName, QualifiedModuleName};
use roc_module::symbol::{
IdentIds, IdentIdsByModule, Interns, ModuleId, ModuleIds, PQModuleName, PackageModuleIds,
PackageQualified, Symbol,
};
use roc_mono::ir::{
CapturedSymbols, ExternalSpecializations, GlueLayouts, HostExposedLambdaSets, PartialProc,
Proc, ProcLayout, Procs, ProcsBase, UpdateModeIds, UsageTrackingMap,
};
use roc_mono::layout::{
GlobalLayoutInterner, LambdaName, Layout, LayoutCache, LayoutProblem, Niche, STLayoutInterner,
};
use roc_mono::reset_reuse;
use roc_mono::{drop_specialization, inc_dec};
use roc_packaging::cache::RocCacheDir;
use roc_parse::ast::{self, CommentOrNewline, ExtractSpaces, Spaced, ValueDef};
use roc_parse::header::parse_module_defs;
use roc_parse::header::{
self, AppHeader, ExposedName, HeaderType, ImportsKeywordItem, PackageEntry, PackageHeader,
PlatformHeader, To,
};
use roc_parse::parser::{FileError, SourceError, SyntaxError};
use roc_problem::Severity;
use roc_region::all::{LineInfo, Loc, Region};
use roc_reporting::error::r#type::suggest;
#[cfg(not(target_family = "wasm"))]
use roc_reporting::report::to_https_problem_report_string;
use roc_reporting::report::{to_file_problem_report_string, Palette, RenderTarget};
use roc_solve::module::{extract_module_owned_implementations, SolveConfig, Solved, SolvedModule};
use roc_solve::FunctionKind;
use roc_solve_problem::TypeError;
use roc_target::Target;
use roc_types::subs::{CopiedImport, ExposedTypesStorageSubs, Subs, VarStore, Variable};
use roc_types::types::{Alias, Types};
use roc_worker::ChannelProblem;
use std::collections::hash_map::Entry::{Occupied, Vacant};
use std::collections::HashMap;
use std::io;
use std::ops::ControlFlow;
use std::path::{Path, PathBuf};
use std::str::from_utf8_unchecked;
use std::sync::Arc;
use std::{env, fs};
#[cfg(not(target_family = "wasm"))]
use {
roc_packaging::cache::{self},
roc_packaging::https::{PackageMetadata, Problem},
};
pub use roc_work::Phase;
use roc_work::{DepCycle, Dependencies};
#[cfg(target_family = "wasm")]
use crate::wasm_instant::{Duration, Instant};
#[cfg(not(target_family = "wasm"))]
use std::time::{Duration, Instant};
/// Filename extension for normal Roc modules
const ROC_FILE_EXTENSION: &str = "roc";
/// The . in between module names like Foo.Bar.Baz
const MODULE_SEPARATOR: char = '.';
/// Default name for the main module
const DEFAULT_MAIN_NAME: &str = "main.roc";
const EXPANDED_STACK_SIZE: usize = 8 * 1024 * 1024;
macro_rules! log {
($($arg:tt)*) => (dbg_do!(ROC_PRINT_LOAD_LOG, println!($($arg)*)))
}
#[derive(Debug)]
pub struct LoadConfig {
pub target: Target,
pub render: RenderTarget,
pub palette: Palette,
pub threading: Threading,
pub exec_mode: ExecutionMode,
pub function_kind: FunctionKind,
}
#[derive(Debug, Clone, Copy)]
pub enum ExecutionMode {
Check,
Executable,
/// Like [`ExecutionMode::Executable`], but stops in the presence of type errors.
ExecutableIfCheck,
/// Test is like [`ExecutionMode::ExecutableIfCheck`], but rather than producing a proper
/// executable, run tests.
Test,
}
impl ExecutionMode {
fn goal_phase(&self) -> Phase {
use ExecutionMode::*;
match self {
Executable => Phase::MakeSpecializations,
Check | ExecutableIfCheck | Test => Phase::SolveTypes,
}
}
fn build_if_checks(&self) -> bool {
matches!(self, Self::ExecutableIfCheck | Self::Test)
}
}
type SharedIdentIdsByModule = Arc<Mutex<roc_module::symbol::IdentIdsByModule>>;
fn start_phase<'a>(
module_id: ModuleId,
phase: Phase,
arena: &'a Bump,
state: &mut State<'a>,
) -> Vec<BuildTask<'a>> {
// we blindly assume all dependencies are met
use roc_work::PrepareStartPhase::*;
match state.dependencies.prepare_start_phase(module_id, phase) {
Continue => {
// fall through
}
Done => {
// no more work to do
return vec![];
}
Recurse(new) => {
return new
.into_iter()
.flat_map(|(module_id, phase)| start_phase(module_id, phase, arena, state))
.collect()
}
}
let task = {
match phase {
Phase::LoadHeader => {
let opt_dep_name = state.module_cache.module_names.get(&module_id);
match opt_dep_name {
None => {
panic!("Module {module_id:?} is not in module_cache.module_names")
}
Some(dep_name) => {
let module_name = dep_name.clone();
BuildTask::LoadModule {
module_name,
// Provide mutexes of ModuleIds and IdentIds by module,
// so other modules can populate them as they load.
module_ids: Arc::clone(&state.arc_modules),
shorthands: Arc::clone(&state.arc_shorthands),
ident_ids_by_module: Arc::clone(&state.ident_ids_by_module),
}
}
}
}
Phase::Parse => {
// parse the file
let header = state.module_cache.headers.remove(&module_id).unwrap();
BuildTask::Parse {
header,
arc_shorthands: Arc::clone(&state.arc_shorthands),
module_ids: Arc::clone(&state.arc_modules),
ident_ids_by_module: Arc::clone(&state.ident_ids_by_module),
root_type: state.root_type.clone(),
}
}
Phase::SoloCanonicalize => {
// canonicalize the file
let parsed = state.module_cache.parsed.get(&module_id).unwrap().clone();
BuildTask::SoloCanonicalize { parsed }
}
Phase::CanonicalizeAndConstrain => {
// canonicalize the file
let parsed = state.module_cache.parsed.remove(&module_id).unwrap();
let solo_can_output = state
.module_cache
.solo_canonicalized
.remove(&module_id)
.unwrap();
let deps_by_name = &parsed.deps_by_name;
let num_deps = deps_by_name.len();
let mut dep_idents: IdentIdsByModule = IdentIds::exposed_builtins(num_deps);
let State {
ident_ids_by_module,
..
} = &state;
{
let ident_ids_by_module = (*ident_ids_by_module).lock();
// Populate dep_idents with each of their IdentIds,
// which we'll need during canonicalization to translate
// identifier strings into IdentIds, which we need to build Symbols.
// We only include the modules we care about (the ones we import).
//
// At the end of this loop, dep_idents contains all the information to
// resolve a symbol from another module: if it's in here, that means
// we have both imported the module and the ident was exported by that module.
for dep_id in deps_by_name.values() {
// We already verified that these are all present,
// so unwrapping should always succeed here.
let idents = ident_ids_by_module.get(dep_id).unwrap();
dep_idents.insert(*dep_id, idents.clone());
}
}
// Clone the module_ids we'll need for canonicalization.
// This should be small, and cloning it should be quick.
// We release the lock as soon as we're done cloning, so we don't have
// to lock the global module_ids while canonicalizing any given module.
let qualified_module_ids = Arc::clone(&state.arc_modules);
let qualified_module_ids = { (*qualified_module_ids).lock().clone() };
let exposed_symbols = state
.exposed_symbols_by_module
.get(&module_id)
.expect("Could not find listener ID in exposed_symbols_by_module")
.clone();
let mut aliases = MutMap::default();
let mut abilities_store = PendingAbilitiesStore::default();
let mut imported_module_params = VecMap::default();
for imported in parsed.available_modules.keys() {
match state.module_cache.aliases.get(imported) {
None => unreachable!(
r"imported module {:?} did not register its aliases, so {:?} cannot use them",
imported, parsed.module_id,
),
Some(new) => {
aliases.extend(new.iter().filter_map(|(s, (exposed, a))| {
// only pass this on if it's exposed, or the alias is a transitive import
if *exposed || s.module_id() != *imported {
Some((*s, a.clone()))
} else {
None
}
}));
}
}
match state.module_cache.pending_abilities.get(imported) {
None => unreachable!(
r"imported module {:?} did not register its abilities, so {:?} cannot use them",
imported, parsed.module_id,
),
Some(import_store) => {
let exposed_symbols = state
.exposed_symbols_by_module
.get(imported)
.unwrap_or_else(|| {
internal_error!(
"Could not find exposed symbols of imported {:?}",
imported
)
});
// Add the declared abilities from the modules we import;
// we may not know all their types yet since type-solving happens in
// parallel, but we'll fill that in during type-checking our module.
abilities_store
.union(import_store.closure_from_imported(exposed_symbols));
}
}
if let Some(params) = state.module_cache.module_params.get(imported) {
imported_module_params.insert(*imported, params.clone());
}
}
let skip_constraint_gen = {
// Give this its own scope to make sure that the Guard from the lock() is dropped
// immediately after contains_key returns
state.cached_types.lock().contains_key(&module_id)
};
BuildTask::CanonicalizeAndConstrain {
parsed,
dep_idents,
exposed_symbols,
qualified_module_ids,
aliases,
abilities_store,
skip_constraint_gen,
exposed_module_ids: state.exposed_modules,
exec_mode: state.exec_mode,
imported_module_params,
solo_can_output,
}
}
Phase::SolveTypes => {
let constrained = state.module_cache.constrained.remove(&module_id).unwrap();
let ConstrainedModule {
module,
ident_ids,
module_timing,
constraints,
constraint,
var_store,
available_modules,
declarations,
dep_idents,
pending_derives,
types,
..
} = constrained;
let derived_module = SharedDerivedModule::clone(&state.derived_module);
#[cfg(debug_assertions)]
let checkmate = if roc_checkmate::is_checkmate_enabled() {
Some(roc_checkmate::Collector::new())
} else {
None
};
let is_host_exposed = state.root_id == module.module_id;
BuildTask::solve_module(
module,
ident_ids,
module_timing,
types,
constraints,
constraint,
state.function_kind,
pending_derives,
var_store,
available_modules,
&state.exposed_types,
dep_idents,
declarations,
state.cached_types.clone(),
derived_module,
state.exec_mode,
is_host_exposed,
//
#[cfg(debug_assertions)]
checkmate,
)
}
Phase::FindSpecializations => {
let typechecked = state.module_cache.typechecked.remove(&module_id).unwrap();
let TypeCheckedModule {
layout_cache,
module_id,
module_timing,
solved_subs,
decls,
ident_ids,
abilities_store,
expectations,
//
#[cfg(debug_assertions)]
checkmate: _,
} = typechecked;
let our_exposed_types = state
.exposed_types
.get(&module_id)
.unwrap_or_else(|| internal_error!("Exposed types for {:?} missing", module_id))
.clone();
state.world_abilities.insert(
module_id,
abilities_store.clone(),
our_exposed_types.exposed_types_storage_subs,
);
let mut imported_module_thunks = bumpalo::collections::Vec::new_in(arena);
if let Some(imports) = state.module_cache.imports.get(&module_id) {
for imported in imports.iter() {
imported_module_thunks.extend(
state.module_cache.top_level_thunks[imported]
.iter()
.copied(),
);
}
}
let derived_module = SharedDerivedModule::clone(&state.derived_module);
let build_expects =
matches!(state.exec_mode, ExecutionMode::Test) && expectations.is_some();
BuildTask::BuildPendingSpecializations {
layout_cache,
module_id,
module_timing,
solved_subs,
imported_module_thunks: imported_module_thunks.into_bump_slice(),
decls,
ident_ids,
exposed_to_host: state.exposed_to_host.clone(),
world_abilities: state.world_abilities.clone_ref(),
// TODO: awful, how can we get rid of the clone?
exposed_by_module: state.exposed_types.clone(),
derived_module,
expectations,
build_expects,
}
}
Phase::MakeSpecializations => {
let mut specializations_we_must_make = state
.module_cache
.external_specializations_requested
.remove(&module_id)
.unwrap_or_default();
if module_id == ModuleId::DERIVED_GEN {
// The derived gen module must also fulfill also specializations asked of the
// derived synth module.
let derived_synth_specializations = state
.module_cache
.external_specializations_requested
.remove(&ModuleId::DERIVED_SYNTH)
.unwrap_or_default();
specializations_we_must_make.extend(derived_synth_specializations)
}
let (
mut ident_ids,
mut subs,
expectations,
mut procs_base,
layout_cache,
mut module_timing,
) = if state.make_specializations_pass.current_pass() == 1
&& module_id == ModuleId::DERIVED_GEN
{
// This is the first time the derived module is introduced into the load
// graph. It has no abilities of its own or anything, just generate fresh
// information for it.
(
IdentIds::default(),
Subs::default(),
None, // no expectations for derived module
ProcsBase::default(),
LayoutCache::new(state.layout_interner.fork(), state.target),
ModuleTiming::new(Instant::now()),
)
} else if state.make_specializations_pass.current_pass() == 1 {
let found_specializations = state
.module_cache
.found_specializations
.remove(&module_id)
.unwrap();
let FoundSpecializationsModule {
ident_ids,
subs,
procs_base,
layout_cache,
module_timing,
expectations,
} = found_specializations;
(
ident_ids,
subs,
expectations,
procs_base,
layout_cache,
module_timing,
)
} else {
let LateSpecializationsModule {
ident_ids,
subs,
expectations,
module_timing,
layout_cache,
procs_base,
} = state
.module_cache
.late_specializations
.remove(&module_id)
.unwrap();
(
ident_ids,
subs,
expectations,
procs_base,
layout_cache,
module_timing,
)
};
if module_id == ModuleId::DERIVED_GEN {
load_derived_partial_procs(
module_id,
arena,
&mut subs,
&mut ident_ids,
&state.derived_module,
&mut module_timing,
state.target,
&state.exposed_types,
&mut procs_base,
&mut state.world_abilities,
);
}
let derived_module = SharedDerivedModule::clone(&state.derived_module);
BuildTask::MakeSpecializations {
module_id,
ident_ids,
subs,
procs_base,
layout_cache,
specializations_we_must_make,
module_timing,
world_abilities: state.world_abilities.clone_ref(),
// TODO: awful, how can we get rid of the clone?
exposed_by_module: state.exposed_types.clone(),
derived_module,
expectations,
}
}
}
};
vec![task]
}
/// Values used to render expect output
pub struct ExpectMetadata<'a> {
pub interns: Interns,
pub layout_interner: STLayoutInterner<'a>,
pub expectations: VecMap<ModuleId, Expectations>,
}
type LocExpects = VecMap<Region, Vec<ExpectLookup>>;
/// A message sent out _from_ a worker thread,
/// representing a result of work done, or a request for further work
#[derive(Debug)]
enum Msg<'a> {
Many(Vec<Msg<'a>>),
Header(ModuleHeader<'a>),
Parsed(ParsedModule<'a>),
SoloCanonicalized(ModuleId, CanSolo<'a>),
CanonicalizedAndConstrained(CanAndCon),
SolvedTypes {
module_id: ModuleId,
ident_ids: IdentIds,
solved_module: SolvedModule,
solved_subs: Solved<Subs>,
decls: Declarations,
dep_idents: IdentIdsByModule,
module_timing: ModuleTiming,
abilities_store: AbilitiesStore,
loc_expects: LocExpects,
has_dbgs: bool,
#[cfg(debug_assertions)]
checkmate: Option<roc_checkmate::Collector>,
},
FinishedAllTypeChecking {
solved_subs: Solved<Subs>,
exposed_vars_by_symbol: Vec<(Symbol, Variable)>,
exposed_aliases_by_symbol: MutMap<Symbol, (bool, Alias)>,
exposed_types_storage: ExposedTypesStorageSubs,
resolved_implementations: ResolvedImplementations,
dep_idents: IdentIdsByModule,
documentation: VecMap<ModuleId, ModuleDocumentation>,
abilities_store: AbilitiesStore,
#[cfg(debug_assertions)]
checkmate: Option<roc_checkmate::Collector>,
},
FoundSpecializations {
module_id: ModuleId,
ident_ids: IdentIds,
layout_cache: LayoutCache<'a>,
procs_base: ProcsBase<'a>,
solved_subs: Solved<Subs>,
module_timing: ModuleTiming,
toplevel_expects: ToplevelExpects,
expectations: Option<Expectations>,
},
MadeSpecializations {
module_id: ModuleId,
ident_ids: IdentIds,
layout_cache: LayoutCache<'a>,
external_specializations_requested: BumpMap<ModuleId, ExternalSpecializations<'a>>,
procs_base: ProcsBase<'a>,
procedures: MutMap<(Symbol, ProcLayout<'a>), Proc<'a>>,
host_exposed_lambda_sets: HostExposedLambdaSets<'a>,
update_mode_ids: UpdateModeIds,
module_timing: ModuleTiming,
subs: Subs,
expectations: Option<Expectations>,
},
/// The task is to only typecheck AND monomorphize modules
/// all modules are now monomorphized, we are done
FinishedAllSpecialization {
subs: Subs,
/// The layout interner after all passes in mono are done.
/// DO NOT use the one on state; that is left in an empty state after specialization is complete!
layout_interner: STLayoutInterner<'a>,
exposed_to_host: ExposedToHost,
module_expectations: VecMap<ModuleId, Expectations>,
},
FailedToParse(FileError<'a, SyntaxError<'a>>),
FailedToReadFile {
filename: PathBuf,
error: io::ErrorKind,
},
FailedToLoad(LoadingProblem<'a>),
IncorrectModuleName(FileError<'a, IncorrectModuleName<'a>>),
}
#[derive(Debug)]
struct CanSolo<'a>(SoloCanOutput<'a>);
#[derive(Debug)]
struct CanAndCon {
constrained_module: ConstrainedModule,
canonicalization_problems: Vec<roc_problem::can::Problem>,
module_docs: Option<ModuleDocumentation>,
}
#[derive(Debug, PartialEq, Eq)]
enum PlatformPath<'a> {
NotSpecified,
Valid(To<'a>),
RootIsModule,
RootIsHosted,
RootIsPlatformModule,
}
#[derive(Debug)]
struct PlatformData<'a> {
module_id: ModuleId,
provides: &'a [Loc<ExposedName<'a>>],
is_prebuilt: bool,
}
#[derive(Debug, Clone, Copy)]
enum MakeSpecializationsPass {
Pass(u8),
}
impl MakeSpecializationsPass {
fn inc(&mut self) {
match self {
&mut Self::Pass(n) => {
*self = Self::Pass(
n.checked_add(1)
.expect("way too many specialization passes!"),
)
}
}
}
fn current_pass(&self) -> u8 {
match self {
MakeSpecializationsPass::Pass(n) => *n,
}
}
}
#[derive(Debug)]
struct State<'a> {
pub root_id: ModuleId,
pub root_subs: Option<Subs>,
pub root_path: PathBuf,
pub root_type: RootType,
pub cache_dir: PathBuf,
/// If the root is an app module, the shorthand specified in its header's `to` field
pub opt_platform_shorthand: Option<&'a str>,
pub platform_data: Option<PlatformData<'a>>,
pub exposed_types: ExposedByModule,
pub platform_path: PlatformPath<'a>,
pub target: Target,
pub(self) function_kind: FunctionKind,
/// Note: only packages and platforms actually expose any modules;
/// for all others, this will be empty.
pub exposed_modules: &'a [ModuleId],
pub module_cache: ModuleCache<'a>,
pub dependencies: Dependencies<'a>,
pub procedures: MutMap<(Symbol, ProcLayout<'a>), Proc<'a>>,
pub host_exposed_lambda_sets: HostExposedLambdaSets<'a>,
pub toplevel_expects: MutMap<ModuleId, ToplevelExpects>,
pub exposed_to_host: ExposedToHost,
/// This is the "final" list of IdentIds, after canonicalization and constraint gen
/// have completed for a given module.
pub constrained_ident_ids: IdentIdsByModule,
/// From now on, these will be used by multiple threads; time to make an Arc<Mutex<_>>!
pub arc_modules: Arc<Mutex<PackageModuleIds<'a>>>,
pub arc_shorthands: Arc<Mutex<MutMap<&'a str, ShorthandPath>>>,
pub derived_module: SharedDerivedModule,
pub ident_ids_by_module: SharedIdentIdsByModule,
pub declarations_by_id: MutMap<ModuleId, Declarations>,
pub exposed_symbols_by_module: MutMap<ModuleId, VecSet<Symbol>>,
pub timings: MutMap<ModuleId, ModuleTiming>,
// Each thread gets its own layout cache. When one "pending specializations"
// pass completes, it returns its layout cache so another thread can use it.
// We don't bother trying to union them all together to maximize cache hits,
// since the unioning process could potentially take longer than the savings.
// (Granted, this has not been attempted or measured!)
pub layout_caches: std::vec::Vec<LayoutCache<'a>>,
pub render: RenderTarget,
pub palette: Palette,
pub exec_mode: ExecutionMode,
/// All abilities across all modules.
pub world_abilities: WorldAbilities,
make_specializations_pass: MakeSpecializationsPass,
// cached types (used for builtin modules, could include packages in the future too)
cached_types: CachedTypeState,
layout_interner: GlobalLayoutInterner<'a>,
}
type CachedTypeState = Arc<Mutex<MutMap<ModuleId, TypeState>>>;
impl<'a> State<'a> {
fn goal_phase(&self) -> Phase {
self.exec_mode.goal_phase()
}
fn new(
root_id: ModuleId,
root_path: PathBuf,
root_type: RootType,
opt_platform_shorthand: Option<&'a str>,
target: Target,
function_kind: FunctionKind,
exposed_types: ExposedByModule,
arc_modules: Arc<Mutex<PackageModuleIds<'a>>>,
ident_ids_by_module: SharedIdentIdsByModule,
arc_shorthands: Arc<Mutex<MutMap<&'a str, ShorthandPath>>>,
cached_types: MutMap<ModuleId, TypeState>,
render: RenderTarget,
palette: Palette,
number_of_workers: usize,
exec_mode: ExecutionMode,
) -> Self {
let cache_dir = roc_packaging::cache::roc_cache_packages_dir();
let dependencies = Dependencies::new(exec_mode.goal_phase());
Self {
root_id,
root_path,
root_subs: None,
root_type,
opt_platform_shorthand,
cache_dir,
target,
function_kind,
platform_data: None,
platform_path: PlatformPath::NotSpecified,
module_cache: ModuleCache::default(),
dependencies,
procedures: MutMap::default(),
host_exposed_lambda_sets: std::vec::Vec::new(),
toplevel_expects: MutMap::default(),
exposed_to_host: ExposedToHost::default(),
exposed_modules: &[],
exposed_types,
arc_modules,
arc_shorthands,
derived_module: Default::default(),
constrained_ident_ids: IdentIds::exposed_builtins(0),
ident_ids_by_module,
declarations_by_id: MutMap::default(),
exposed_symbols_by_module: MutMap::default(),
timings: MutMap::default(),
layout_caches: std::vec::Vec::with_capacity(number_of_workers),
cached_types: Arc::new(Mutex::new(cached_types)),
render,
palette,
exec_mode,
make_specializations_pass: MakeSpecializationsPass::Pass(1),
world_abilities: Default::default(),
layout_interner: GlobalLayoutInterner::with_capacity(128, target),
}
}
}
fn report_timing(
buf: &mut impl std::fmt::Write,
label: &str,
duration: Duration,
) -> std::fmt::Result {
writeln!(
buf,
" {:9.3} ms {}",
duration.as_secs_f64() * 1000.0,
label,
)
}
impl std::fmt::Display for ModuleTiming {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let module_timing = self;
report_timing(f, "Read .roc file from disk", module_timing.read_roc_file)?;
report_timing(f, "Parse header", module_timing.parse_header)?;
report_timing(f, "Parse body", module_timing.parse_body)?;
report_timing(f, "Canonicalize", module_timing.canonicalize)?;
report_timing(f, "Constrain", module_timing.constrain)?;
report_timing(f, "Solve", module_timing.solve)?;
report_timing(
f,
"Find Specializations",
module_timing.find_specializations,
)?;
let multiple_make_specializations_passes = module_timing.make_specializations.len() > 1;
for (i, pass_time) in module_timing.make_specializations.iter().enumerate() {
let suffix = if multiple_make_specializations_passes {
format!(" (Pass {i})")
} else {
String::new()
};
report_timing(f, &format!("Make Specializations{suffix}"), *pass_time)?;
}
report_timing(f, "Other", module_timing.other())?;
f.write_str("\n")?;
report_timing(f, "Total", module_timing.total())?;
Ok(())
}
}
/// A message sent _to_ a worker thread, describing the work to be done
#[derive(Debug)]
enum BuildTask<'a> {
LoadModule {
module_name: PQModuleName<'a>,
module_ids: Arc<Mutex<PackageModuleIds<'a>>>,
shorthands: Arc<Mutex<MutMap<&'a str, ShorthandPath>>>,
ident_ids_by_module: SharedIdentIdsByModule,
},
Parse {
header: ModuleHeader<'a>,
arc_shorthands: Arc<Mutex<MutMap<&'a str, ShorthandPath>>>,
module_ids: Arc<Mutex<PackageModuleIds<'a>>>,
ident_ids_by_module: SharedIdentIdsByModule,
root_type: RootType,
},
SoloCanonicalize {
parsed: ParsedModule<'a>,
},
CanonicalizeAndConstrain {
parsed: ParsedModule<'a>,
qualified_module_ids: PackageModuleIds<'a>,
dep_idents: IdentIdsByModule,
exposed_symbols: VecSet<Symbol>,
aliases: MutMap<Symbol, Alias>,
abilities_store: PendingAbilitiesStore,
exposed_module_ids: &'a [ModuleId],
skip_constraint_gen: bool,
exec_mode: ExecutionMode,
imported_module_params: VecMap<ModuleId, ModuleParams>,
solo_can_output: SoloCanOutput<'a>,
},
Solve {
module: Module,
ident_ids: IdentIds,
exposed_for_module: ExposedForModule,
module_timing: ModuleTiming,
types: Types,
constraints: Constraints,
constraint: ConstraintSoa,
function_kind: FunctionKind,
pending_derives: PendingDerives,
var_store: VarStore,
declarations: Declarations,
dep_idents: IdentIdsByModule,
cached_subs: CachedTypeState,
derived_module: SharedDerivedModule,
exec_mode: ExecutionMode,
is_host_exposed: bool,
#[cfg(debug_assertions)]
checkmate: Option<roc_checkmate::Collector>,
},
BuildPendingSpecializations {
module_timing: ModuleTiming,
layout_cache: LayoutCache<'a>,
solved_subs: Solved<Subs>,
imported_module_thunks: &'a [Symbol],
module_id: ModuleId,
ident_ids: IdentIds,
decls: Declarations,
exposed_to_host: ExposedToHost,
exposed_by_module: ExposedByModule,
world_abilities: WorldAbilities,
derived_module: SharedDerivedModule,
expectations: Option<Expectations>,
build_expects: bool,
},
MakeSpecializations {
module_id: ModuleId,
ident_ids: IdentIds,
subs: Subs,
procs_base: ProcsBase<'a>,
layout_cache: LayoutCache<'a>,
specializations_we_must_make: Vec<ExternalSpecializations<'a>>,
module_timing: ModuleTiming,
exposed_by_module: ExposedByModule,
world_abilities: WorldAbilities,
derived_module: SharedDerivedModule,
expectations: Option<Expectations>,
},
}
#[derive(Debug)]
pub struct IncorrectModuleName<'a> {
pub module_id: ModuleId,
pub found: Loc<PQModuleName<'a>>,
pub expected: PQModuleName<'a>,
}
#[derive(Debug)]
pub enum LoadingProblem<'a> {
FileProblem {
filename: PathBuf,
error: io::ErrorKind,
},
ParsingFailed(FileError<'a, SyntaxError<'a>>),
UnexpectedHeader(String),
MultiplePlatformPackages {
filename: PathBuf,
module_id: ModuleId,
source: &'a [u8],
region: Region,
},
NoPlatformPackage {