-
Notifications
You must be signed in to change notification settings - Fork 3.6k
/
lib.rs
1344 lines (1251 loc) · 49.4 KB
/
lib.rs
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
// Copyright (c) The Diem Core Contributors
// Copyright (c) The Move Contributors
// SPDX-License-Identifier: Apache-2.0
#![forbid(unsafe_code)]
use crate::{
ast::ModuleName,
builder::{model_builder::ModelBuilder, module_builder::BytecodeModule},
metadata::LanguageVersion,
model::{FunId, GlobalEnv, Loc, ModuleId, StructId},
options::ModelBuilderOptions,
};
use builder::module_builder::ModuleBuilder;
use codespan::ByteIndex;
use codespan_reporting::diagnostic::{Diagnostic, Label, LabelStyle};
use itertools::Itertools;
#[allow(unused_imports)]
use log::warn;
use move_binary_format::{
check_bounds::BoundsChecker,
file_format::{
self_module_name, AddressIdentifierIndex, CompiledModule, CompiledScript,
FunctionDefinition, FunctionHandle, FunctionHandleIndex, IdentifierIndex, ModuleHandle,
ModuleHandleIndex, Signature, SignatureIndex, Visibility,
},
};
use move_compiler::{
self,
compiled_unit::{self, AnnotatedCompiledScript, AnnotatedCompiledUnit},
diagnostics::{codes::Severity, Diagnostics},
expansion::ast::{self as E, ModuleIdent, ModuleIdent_},
naming::ast as N,
parser::ast::{self as P, CallKind, ModuleName as ParserModuleName},
shared::{
parse_named_address, unique_map::UniqueMap, CompilationEnv, Identifier as IdentifierTrait,
NumericalAddress, PackagePaths,
},
typing::ast as T,
Compiler, Flags, PASS_COMPILATION, PASS_EXPANSION, PASS_INLINING, PASS_PARSER,
};
use move_core_types::{account_address::AccountAddress, identifier::Identifier};
use move_ir_types::location::sp;
use move_symbol_pool::Symbol as MoveSymbol;
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
fmt::Debug,
rc::Rc,
};
pub mod ast;
mod builder;
pub mod code_writer;
pub mod constant_folder;
pub mod exp_generator;
pub mod exp_rewriter;
pub mod intrinsics;
pub mod metadata;
pub mod model;
pub mod options;
pub mod pragmas;
pub mod pureness_checker;
pub mod spec_translator;
pub mod symbol;
pub mod ty;
pub mod well_known;
// =================================================================================================
// Entry Point V2
/// Represents information about a package: the sources it contains and the package private
/// address mapping.
#[derive(Debug, Clone)]
pub struct PackageInfo {
pub sources: Vec<String>,
pub address_map: BTreeMap<String, NumericalAddress>,
}
/// Builds the Move model for the v2 compiler. This builds the model, compiling both code and specs
/// from sources into typed-checked AST. No bytecode is attached to the model. This currently uses
/// the v1 compiler as the parser (up to expansion AST), after that a new type checker.
///
/// Note that `source` and `source_deps` are either Move files or package subdirectories which
/// contain Move files, all of which should be compiled (not the root of a package, but the
/// `sources`, `scripts`, and/or `tests`, depending on compilation mode.
pub fn run_model_builder_in_compiler_mode(
source: PackageInfo,
source_deps: PackageInfo,
deps: Vec<PackageInfo>,
skip_attribute_checks: bool,
known_attributes: &BTreeSet<String>,
language_version: LanguageVersion,
compile_test_code: bool,
) -> anyhow::Result<GlobalEnv> {
let to_package_paths = |PackageInfo {
sources,
address_map,
}| PackagePaths {
name: None,
paths: sources,
named_address_map: address_map,
};
run_model_builder_with_options_and_compilation_flags(
vec![to_package_paths(source)],
vec![to_package_paths(source_deps)],
deps.into_iter().map(to_package_paths).collect(),
ModelBuilderOptions {
compile_via_model: true,
language_version,
..ModelBuilderOptions::default()
},
Flags::model_compilation()
.set_skip_attribute_checks(skip_attribute_checks)
.set_keep_testing_functions(compile_test_code)
.set_lang_v2(language_version != LanguageVersion::V1)
.set_compiler_v2(true),
known_attributes,
)
}
// =================================================================================================
// Entry Point V1
/// Build the move model with default compilation flags and custom options.
pub fn run_model_builder_with_options<
Paths: Into<MoveSymbol> + Clone + Debug,
NamedAddress: Into<MoveSymbol> + Clone + Debug,
>(
move_sources: Vec<PackagePaths<Paths, NamedAddress>>,
move_deps: Vec<PackagePaths<Paths, NamedAddress>>,
deps: Vec<PackagePaths<Paths, NamedAddress>>,
options: ModelBuilderOptions,
skip_attribute_checks: bool,
known_attributes: &BTreeSet<String>,
) -> anyhow::Result<GlobalEnv> {
let mut flags = Flags::verification();
flags = flags.set_skip_attribute_checks(skip_attribute_checks);
run_model_builder_with_options_and_compilation_flags(
move_sources,
move_deps,
deps,
options,
flags,
known_attributes,
)
}
/// Build the move model with custom compilation flags and custom options
pub fn run_model_builder_with_options_and_compilation_flags<
Paths: Into<MoveSymbol> + Clone + Debug,
NamedAddress: Into<MoveSymbol> + Clone + Debug,
>(
move_sources_targets: Vec<PackagePaths<Paths, NamedAddress>>,
move_sources_deps: Vec<PackagePaths<Paths, NamedAddress>>,
deps: Vec<PackagePaths<Paths, NamedAddress>>,
options: ModelBuilderOptions,
flags: Flags,
known_attributes: &BTreeSet<String>,
) -> anyhow::Result<GlobalEnv> {
let mut env = GlobalEnv::new();
env.set_language_version(options.language_version);
let compile_via_model = options.compile_via_model;
env.set_extension(options);
let move_sources = move_sources_targets
.iter()
.chain(move_sources_deps.iter())
.cloned()
.collect();
let target_sources_names: BTreeSet<String> = move_sources_targets
.iter()
.flat_map(|pack| pack.paths.iter())
.map(|sym| {
<Paths as Into<MoveSymbol>>::into(sym.clone())
.as_str()
.to_owned()
})
.collect();
// Step 1: parse the program to get comments and a separation of targets and dependencies.
let (files, comments_and_compiler_res) =
Compiler::from_package_paths(move_sources, deps, flags, known_attributes)
.run::<PASS_PARSER>()?;
let (comment_map, compiler) = match comments_and_compiler_res {
Err(diags) => {
// Add source files so that the env knows how to translate locations of parse errors
let empty_alias = Rc::new(BTreeMap::new());
for (fhash, (fname, fsrc)) in &files {
env.add_source(
*fhash,
empty_alias.clone(),
fname.as_str(),
fsrc,
/* is_target */ true,
target_sources_names.contains(fname.as_str()),
);
}
add_move_lang_diagnostics(&mut env, diags);
return Ok(env);
},
Ok(res) => res,
};
let (compiler, parsed_prog) = compiler.into_ast();
// Add source files for targets and dependencies
let dep_files: BTreeSet<_> = parsed_prog
.lib_definitions
.iter()
.map(|p| p.def.file_hash())
.collect();
for member in parsed_prog
.source_definitions
.iter()
.chain(parsed_prog.lib_definitions.iter())
{
let fhash = member.def.file_hash();
let (fname, fsrc) = files.get(&fhash).unwrap();
let is_target = !dep_files.contains(&fhash);
let aliases = parsed_prog
.named_address_maps
.get(member.named_address_map)
.iter()
.map(|(symbol, addr)| (env.symbol_pool().make(symbol.as_str()), *addr))
.collect();
env.add_source(
fhash,
Rc::new(aliases),
fname.as_str(),
fsrc,
is_target,
target_sources_names.contains(fname.as_str()),
);
}
// If a move file does not contain any definition, it will not appear in `parsed_prog`. Add them explicitly.
for fhash in files.keys().sorted() {
if env.get_file_id(*fhash).is_none() {
let (fname, fsrc) = files.get(fhash).unwrap();
let is_target = !dep_files.contains(fhash);
env.add_source(
*fhash,
Rc::new(BTreeMap::new()),
fname.as_str(),
fsrc,
is_target,
target_sources_names.contains(fname.as_str()),
);
}
}
// Add any documentation comments found by the Move compiler to the env.
for (fhash, documentation) in comment_map {
let file_id = env.get_file_id(fhash).expect("file name defined");
env.add_documentation(
file_id,
documentation
.into_iter()
.map(|(idx, s)| (ByteIndex(idx), s))
.collect(),
)
}
// Step 2: run the compiler up to expansion
let parsed_prog = {
let P::Program {
named_address_maps,
mut source_definitions,
lib_definitions,
} = parsed_prog;
source_definitions.extend(lib_definitions);
P::Program {
named_address_maps,
source_definitions,
lib_definitions: vec![],
}
};
let (compiler, expansion_ast) = match compiler.at_parser(parsed_prog).run::<PASS_EXPANSION>() {
Err(diags) => {
add_move_lang_diagnostics(&mut env, diags);
return Ok(env);
},
Ok(mut compiler) => {
// There may have been errors but nevertheless a stepped compiler is returned.
let compiler_env: &mut CompilationEnv = compiler.compilation_env();
if let Err(diags) = compiler_env.check_diags_at_or_above_severity(Severity::Warning) {
add_move_lang_diagnostics(&mut env, diags);
if env.has_errors() {
return Ok(env);
}
}
compiler.into_ast()
},
};
// Extract the module/script closure
let mut visited_modules = BTreeSet::new();
for (_, mident, mdef) in &expansion_ast.modules {
let src_file_hash = mdef.loc.file_hash();
if !dep_files.contains(&src_file_hash) {
collect_related_modules_recursive(mident, &expansion_ast.modules, &mut visited_modules);
}
}
for sdef in expansion_ast.scripts.values() {
let src_file_hash = sdef.loc.file_hash();
if !dep_files.contains(&src_file_hash) {
for (_, mident, _neighbor) in &sdef.immediate_neighbors {
collect_related_modules_recursive(
mident,
&expansion_ast.modules,
&mut visited_modules,
);
}
}
}
// Step 3: selective compilation.
let mut expansion_ast = {
let E::Program { modules, scripts } = expansion_ast;
let modules = modules.filter_map(|mident, mut mdef| {
// Always need to include the vector module because it can be implicitly used.
// TODO(#12492): we can remove this once this bug is fixed
let is_vector = mident.value.address.into_addr_bytes().into_inner()
== AccountAddress::ONE
&& mident.value.module.0.value.as_str() == "vector";
(is_vector || visited_modules.contains(&mident.value)).then(|| {
mdef.is_source_module = true;
mdef
})
});
E::Program { modules, scripts }
};
if !compile_via_model {
// Legacy compilation via v1 compiler
// TODO: eventually remove this code and related helpers
// Step 4: retrospectively add lambda-lifted function to expansion AST
let (compiler, inlining_ast) = match compiler
.at_expansion(expansion_ast.clone())
.run::<PASS_INLINING>()
{
Err(diags) => {
add_move_lang_diagnostics(&mut env, diags);
return Ok(env);
},
Ok(compiler) => compiler.into_ast(),
};
for (loc, module_id, expansion_module) in expansion_ast.modules.iter_mut() {
match inlining_ast.modules.get_(module_id) {
None => {
env.error(
&env.to_loc(&loc),
"unable to find matching module in inlining AST",
);
},
Some(inlining_module) => {
retrospective_lambda_lifting(inlining_module, expansion_module);
},
}
}
// Step 5: Run the compiler from instrumented expansion AST fully to the compiled units
let units = match compiler
.at_expansion(expansion_ast.clone())
.run::<PASS_COMPILATION>()
{
Err(diags) => {
add_move_lang_diagnostics(&mut env, diags);
return Ok(env);
},
Ok(compiler) => {
let (units, warnings) = compiler.into_compiled_units();
if !warnings.is_empty() {
// NOTE: these diagnostics are just warnings. it should be feasible to continue the
// model building here. But before that, register the warnings to the `GlobalEnv`
// first so we get a chance to report these warnings as well.
add_move_lang_diagnostics(&mut env, warnings);
}
units
},
};
// Check for bytecode verifier errors (there should not be any)
let diags = compiled_unit::verify_units(&units);
if !diags.is_empty() {
add_move_lang_diagnostics(&mut env, diags);
return Ok(env);
}
// Now that it is known that the program has no errors, run the spec checker on verified units
// plus expanded AST. This will populate the environment including any errors.
run_spec_checker(&mut env, units, expansion_ast);
Ok(env)
} else {
// New compilation via model (compiler v2). The expansion AST will be type checked.
// No bytecode is attached.
run_move_checker(&mut env, expansion_ast);
Ok(env)
}
}
fn run_move_checker(env: &mut GlobalEnv, program: E::Program) {
let mut builder = ModelBuilder::new(env);
for (module_count, (module_id, module_def)) in program
.modules
.into_iter()
.sorted_by_key(|(_, def)| def.dependency_order)
.enumerate()
{
let loc = builder.to_loc(&module_def.loc);
let addr_bytes = builder.resolve_address(&loc, &module_id.value.address);
let module_name = ModuleName::from_address_bytes_and_name(
addr_bytes,
builder
.env
.symbol_pool()
.make(&module_id.value.module.0.value),
);
// Assign new module id in the model.
let module_id = ModuleId::new(module_count);
// Associate the module name with the module id for lookups.
builder.module_table.insert(module_name.clone(), module_id);
let mut module_translator = ModuleBuilder::new(&mut builder, module_id, module_name);
module_translator.translate(loc, module_def, None);
}
for (i, (_, script_def)) in program.scripts.into_iter().enumerate() {
let loc = builder.to_loc(&script_def.loc);
let module_name = ModuleName::pseudo_script_name(builder.env.symbol_pool(), i);
let module_id = ModuleId::new(builder.env.module_data.len());
let mut module_translator = ModuleBuilder::new(&mut builder, module_id, module_name);
let module_def = expansion_script_to_module(script_def);
module_translator.translate(loc, module_def, None);
}
// Populate GlobalEnv with model-level information
builder.populate_env();
// After all specs have been processed, warn about any unused schemas.
builder.warn_unused_schemas();
// Perform any remaining friend-declaration checks and update friend module id information.
check_and_update_friend_info(builder);
}
/// Checks if any friend declarations are invalid because:
/// - they are self-friend declarations
/// - they are out-of-address friend declarations
/// - they refer to unbound modules
/// If so, report errors.
/// Also, update friend module id information: this function assumes all modules have been assigned ids.
///
/// Note: we assume (a) friend declarations creating cyclic dependencies (cycle size > 1),
/// (b) duplicate friend declarations
/// have been reported already. Currently, these checks happen in the expansion phase.
fn check_and_update_friend_info(mut builder: ModelBuilder) {
let module_table = std::mem::take(&mut builder.module_table);
let env = builder.env;
// To save (loc, name) info about self friend decls.
let mut self_friends = vec![];
// To save (loc, friend_module_name, current_module_name) info about out-of-address friend decls.
let mut out_of_address_friends = vec![];
// To save (loc, friend_module_name) info about unbound modules in friend decls.
let mut unbound_friend_modules = vec![];
// Patch up information about friend module ids, as all the modules have ids by now.
for module in env.module_data.iter_mut() {
let mut friend_modules = BTreeSet::new();
for friend_decl in module.friend_decls.iter_mut() {
// Save information of out-of-address friend decls to report error later.
if friend_decl.module_name.addr() != module.name.addr() {
out_of_address_friends.push((
friend_decl.loc.clone(),
friend_decl.module_name.clone(),
module.name.clone(),
));
}
if let Some(friend_mod_id) = module_table.get(&friend_decl.module_name) {
friend_decl.module_id = Some(*friend_mod_id);
friend_modules.insert(*friend_mod_id);
// Save information of self-friend decls to report error later.
if module.id == *friend_mod_id {
self_friends.push((friend_decl.loc.clone(), friend_decl.module_name.clone()));
}
} else {
// Save information of unbound modules in friend decls to report error later.
unbound_friend_modules
.push((friend_decl.loc.clone(), friend_decl.module_name.clone()));
}
}
module.friend_modules = friend_modules;
}
// Report self-friend errors.
for (loc, module_name) in self_friends {
env.error(
&loc,
&format!(
"cannot declare module `{}` as a friend of itself",
module_name.display_full(env)
),
);
}
// Report out-of-address friend errors.
for (loc, friend_mod_name, cur_mod_name) in out_of_address_friends {
env.error(
&loc,
&format!(
"friend modules of `{}` must have the same address, \
but the declared friend module `{}` has a different address",
cur_mod_name.display_full(env),
friend_mod_name.display_full(env),
),
);
}
// Report unbound friend errors.
for (loc, friend_mod_name) in unbound_friend_modules {
env.error(
&loc,
&format!(
"unbound module `{}` in friend declaration",
friend_mod_name.display_full(env)
),
);
}
}
fn collect_related_modules_recursive<'a>(
mident: &'a ModuleIdent_,
modules: &'a UniqueMap<ModuleIdent, E::ModuleDefinition>,
visited_modules: &mut BTreeSet<ModuleIdent_>,
) {
if visited_modules.contains(mident) {
return;
}
let mdef = modules.get_(mident).unwrap();
visited_modules.insert(*mident);
for (_, next_mident, _) in &mdef.immediate_neighbors {
collect_related_modules_recursive(next_mident, modules, visited_modules);
}
}
pub fn add_move_lang_diagnostics(env: &mut GlobalEnv, diags: Diagnostics) {
let mk_label = |is_primary: bool, (loc, msg): (move_ir_types::location::Loc, String)| {
let style = if is_primary {
LabelStyle::Primary
} else {
LabelStyle::Secondary
};
let loc = env.to_loc(&loc);
Label::new(style, loc.file_id(), loc.span()).with_message(msg)
};
for (severity, msg, primary_label, secondary_labels, notes) in diags.into_codespan_format() {
let diag = Diagnostic::new(severity)
.with_labels(vec![mk_label(true, primary_label)])
.with_message(msg)
.with_labels(
secondary_labels
.into_iter()
.map(|e| mk_label(false, e))
.collect(),
)
.with_notes(notes);
env.add_diag(diag);
}
}
#[allow(deprecated)]
pub fn script_into_module(compiled_script: CompiledScript, name: &str) -> CompiledModule {
let mut script = compiled_script;
// Add the "<SELF>" identifier if it isn't present.
//
// Note: When adding an element to the table, in theory it is possible for the index
// to overflow. This will not be a problem if we get rid of the script/module conversion.
let self_ident_idx = match script
.identifiers
.iter()
.position(|ident| ident.as_ident_str().as_str() == name)
{
Some(idx) => IdentifierIndex::new(idx as u16),
None => {
let idx = IdentifierIndex::new(script.identifiers.len() as u16);
script
.identifiers
.push(Identifier::new(name.to_string()).unwrap());
idx
},
};
// Add a dummy address if none exists.
let dummy_addr = AccountAddress::MAX_ADDRESS;
let dummy_addr_idx = match script
.address_identifiers
.iter()
.position(|addr| addr == &dummy_addr)
{
Some(idx) => AddressIdentifierIndex::new(idx as u16),
None => {
let idx = AddressIdentifierIndex::new(script.address_identifiers.len() as u16);
script.address_identifiers.push(dummy_addr);
idx
},
};
// Add a self module handle.
let self_module_handle_idx = match script
.module_handles
.iter()
.position(|handle| handle.address == dummy_addr_idx && handle.name == self_ident_idx)
{
Some(idx) => ModuleHandleIndex::new(idx as u16),
None => {
let idx = ModuleHandleIndex::new(script.module_handles.len() as u16);
script.module_handles.push(ModuleHandle {
address: dummy_addr_idx,
name: self_ident_idx,
});
idx
},
};
// Find the index to the empty signature [].
// Create one if it doesn't exist.
let return_sig_idx = match script.signatures.iter().position(|sig| sig.0.is_empty()) {
Some(idx) => SignatureIndex::new(idx as u16),
None => {
let idx = SignatureIndex::new(script.signatures.len() as u16);
script.signatures.push(Signature(vec![]));
idx
},
};
// Create a function handle for the main function.
let main_handle_idx = FunctionHandleIndex::new(script.function_handles.len() as u16);
script.function_handles.push(FunctionHandle {
module: self_module_handle_idx,
name: self_ident_idx,
parameters: script.parameters,
return_: return_sig_idx,
type_parameters: script.type_parameters,
access_specifiers: None, // TODO: access specifiers for script functions
});
// Create a function definition for the main function.
let main_def = FunctionDefinition {
function: main_handle_idx,
visibility: Visibility::Public,
is_entry: true,
acquires_global_resources: vec![],
code: Some(script.code),
};
let module = CompiledModule {
version: script.version,
module_handles: script.module_handles,
self_module_handle_idx,
struct_handles: script.struct_handles,
function_handles: script.function_handles,
field_handles: vec![],
friend_decls: vec![],
struct_def_instantiations: vec![],
function_instantiations: script.function_instantiations,
field_instantiations: vec![],
signatures: script.signatures,
identifiers: script.identifiers,
address_identifiers: script.address_identifiers,
constant_pool: script.constant_pool,
metadata: script.metadata,
struct_defs: vec![],
function_defs: vec![main_def],
};
BoundsChecker::verify_module(&module).expect("invalid bounds in module");
module
}
#[allow(deprecated)]
fn run_spec_checker(env: &mut GlobalEnv, units: Vec<AnnotatedCompiledUnit>, mut eprog: E::Program) {
let mut builder = ModelBuilder::new(env);
// Merge the compiled units with source ASTs, preserving the order of the compiled
// units which is topological w.r.t. use relation.
let mut modules = vec![];
for unit in units {
match unit {
AnnotatedCompiledUnit::Module(annot_module) => {
let module_ident = annot_module.module_ident();
let expanded_module = match eprog.modules.remove(&module_ident) {
Some(m) => m,
None => {
env.error(
&env.unknown_loc(),
&format!(
"[internal] cannot associate bytecode module `{}` with expansion AST",
module_ident
)
);
return;
},
};
modules.push((
module_ident,
expanded_module,
annot_module.named_module.module,
annot_module.named_module.source_map,
annot_module.function_infos,
));
},
AnnotatedCompiledUnit::Script(AnnotatedCompiledScript {
loc: _loc,
named_script: script,
function_info,
}) => {
let expanded_script = match eprog.scripts.remove(&script.name) {
Some(s) => s,
None => {
env.error(
&env.unknown_loc(),
&format!(
"[internal] cannot associate bytecode script `{}` with expansion AST",
script.name
)
);
return;
},
};
// Convert the script into a module.
let address = E::Address::Numerical(
None,
sp(expanded_script.loc, NumericalAddress::MAX_ADDRESS),
);
let ident = sp(
expanded_script.loc,
ModuleIdent_::new(address, ParserModuleName(expanded_script.function_name.0)),
);
let mut function_infos = UniqueMap::new();
function_infos
.add(expanded_script.function_name, function_info)
.unwrap();
let expanded_module = expansion_script_to_module(expanded_script);
let module = script_into_module(script.script, self_module_name().as_str());
modules.push((
ident,
expanded_module,
module,
script.source_map,
function_infos,
));
},
}
}
for (module_count, (module_id, expanded_module, compiled_module, source_map, function_infos)) in
modules.into_iter().enumerate()
{
let loc = builder.to_loc(&expanded_module.loc);
let addr_bytes = builder.resolve_address(&loc, &module_id.value.address);
let module_name = ModuleName::from_address_bytes_and_name(
addr_bytes,
builder
.env
.symbol_pool()
.make(&module_id.value.module.0.value),
);
let module_id = ModuleId::new(module_count);
let mut module_translator = ModuleBuilder::new(&mut builder, module_id, module_name);
let compiled_module = BytecodeModule {
compiled_module,
source_map,
function_infos,
};
module_translator.translate(loc, expanded_module, Some(compiled_module));
}
// Populate GlobalEnv with model-level information
builder.populate_env();
// After all specs have been processed, warn about any unused schemas.
builder.warn_unused_schemas();
}
fn retrospective_lambda_lifting(
inlined_module: &T::ModuleDefinition,
expansion_module: &mut E::ModuleDefinition,
) {
// extract lifted lambda pack
let mut lifted = vec![];
for (_, _, fdef) in inlined_module.functions.iter() {
match &fdef.body.value {
T::FunctionBody_::Native => (),
T::FunctionBody_::Defined(seq) => {
collect_lambda_lifted_functions_in_sequence(&mut lifted, seq);
},
};
}
// downgrade the AST
for lifted_fun in lifted {
let T::SpecLambdaLiftedFunction {
name: lifted_name,
signature: lifted_signature,
body: lifted_body,
preset_args: _,
} = lifted_fun;
// convert function signature
let N::FunctionSignature {
type_parameters: lifted_ty_params,
parameters: lifted_params,
return_type: lifted_ret_ty,
} = lifted_signature;
let new_type_params = lifted_ty_params
.into_iter()
.map(|param| (param.user_specified_name, param.abilities))
.collect();
let new_params = lifted_params
.into_iter()
.map(|(v, t)| (v, downgrade_type_inlining_to_expansion(&t)))
.collect();
let new_ret_ty = downgrade_type_inlining_to_expansion(&lifted_ret_ty);
// convert function body
let new_body_exp = downgrade_exp_inlining_to_expansion(&lifted_body);
let new_body_loc = new_body_exp.loc;
let mut new_body_seq = E::Sequence::new();
new_body_seq.push_back(sp(new_body_loc, E::SequenceItem_::Seq(new_body_exp)));
let new_body = sp(new_body_loc, E::FunctionBody_::Defined(new_body_seq));
// define the new function
let new_fun = E::Function {
attributes: E::Attributes::new(),
loc: new_body_loc,
inline: false,
visibility: E::Visibility::Internal,
signature: E::FunctionSignature {
type_parameters: new_type_params,
parameters: new_params,
return_type: new_ret_ty,
},
entry: None,
acquires: vec![], // TODO: might need inference here
access_specifiers: None,
body: new_body,
specs: BTreeMap::new(),
};
let new_name = P::FunctionName(sp(new_body_loc, lifted_name));
expansion_module
.functions
.add(new_name, new_fun)
.expect("duplicated entry of lambda function");
}
}
// =================================================================================================
// Helpers
pub fn parse_addresses_from_options(
named_addr_strings: Vec<String>,
) -> anyhow::Result<BTreeMap<String, NumericalAddress>> {
named_addr_strings
.iter()
.map(|x| parse_named_address(x))
.collect()
}
fn expansion_script_to_module(script: E::Script) -> E::ModuleDefinition {
let E::Script {
package_name,
attributes,
loc,
immediate_neighbors,
used_addresses,
function_name,
constants,
function,
specs,
use_decls,
} = script;
// Construct a pseudo module definition.
let mut functions = UniqueMap::new();
functions.add(function_name, function).unwrap();
E::ModuleDefinition {
package_name,
attributes,
loc,
dependency_order: usize::MAX,
immediate_neighbors,
used_addresses,
is_source_module: true,
friends: UniqueMap::new(),
structs: UniqueMap::new(),
constants,
functions,
specs,
use_decls,
}
}
// =================================================================================================
// AST visitors
fn collect_lambda_lifted_functions_in_sequence(
collection: &mut Vec<T::SpecLambdaLiftedFunction>,
sequence: &T::Sequence,
) {
for stmt in sequence {
match &stmt.value {
T::SequenceItem_::Seq(exp) | T::SequenceItem_::Bind(_, _, exp) => {
collect_lambda_lifted_functions_in_exp(collection, exp.as_ref());
},
T::SequenceItem_::Declare(_) => (),
}
}
}
fn collect_lambda_lifted_functions_in_exp(
collection: &mut Vec<T::SpecLambdaLiftedFunction>,
exp: &T::Exp,
) {
use T::UnannotatedExp_;
match &exp.exp.value {
UnannotatedExp_::Spec(anchor) => {
collection.extend(anchor.used_lambda_funs.values().cloned());
},
UnannotatedExp_::Unit { .. }
| UnannotatedExp_::Value(..)
| UnannotatedExp_::Move { .. }
| UnannotatedExp_::Copy { .. }
| UnannotatedExp_::Use(..)
| UnannotatedExp_::Constant(..)
| UnannotatedExp_::BorrowLocal(..)
| UnannotatedExp_::Break
| UnannotatedExp_::Continue
| UnannotatedExp_::UnresolvedError => (),
UnannotatedExp_::ModuleCall(call) => {
collect_lambda_lifted_functions_in_exp(collection, call.arguments.as_ref());
},
UnannotatedExp_::VarCall(_, args) | UnannotatedExp_::Builtin(_, args) => {
collect_lambda_lifted_functions_in_exp(collection, args.as_ref());
},
UnannotatedExp_::Vector(_, _, _, args) => {
collect_lambda_lifted_functions_in_exp(collection, args.as_ref());
},
UnannotatedExp_::IfElse(cond, lhs, rhs) => {
collect_lambda_lifted_functions_in_exp(collection, cond.as_ref());
collect_lambda_lifted_functions_in_exp(collection, lhs.as_ref());
collect_lambda_lifted_functions_in_exp(collection, rhs.as_ref());
},
UnannotatedExp_::While(cond, body) => {
collect_lambda_lifted_functions_in_exp(collection, cond.as_ref());
collect_lambda_lifted_functions_in_exp(collection, body.as_ref());
},
UnannotatedExp_::Loop { body, .. } => {
collect_lambda_lifted_functions_in_exp(collection, body.as_ref());
},
UnannotatedExp_::Block(seq) => {
collect_lambda_lifted_functions_in_sequence(collection, seq);
},
UnannotatedExp_::Lambda(_, body) => {
collect_lambda_lifted_functions_in_exp(collection, body);
},
UnannotatedExp_::Assign(_, _, val)
| UnannotatedExp_::Return(val)
| UnannotatedExp_::Abort(val)
| UnannotatedExp_::Dereference(val)
| UnannotatedExp_::UnaryExp(_, val)
| UnannotatedExp_::Cast(val, _)
| UnannotatedExp_::Annotate(val, _)
| UnannotatedExp_::Borrow(_, val, _)
| UnannotatedExp_::TempBorrow(_, val) => {
collect_lambda_lifted_functions_in_exp(collection, val);
},
UnannotatedExp_::Mutate(lhs, rhs) | UnannotatedExp_::BinopExp(lhs, _, _, rhs) => {
collect_lambda_lifted_functions_in_exp(collection, lhs);
collect_lambda_lifted_functions_in_exp(collection, rhs);
},
UnannotatedExp_::Pack(_, _, _, fields) => {
for (_, _, (_, (_, val))) in fields.iter() {
collect_lambda_lifted_functions_in_exp(collection, val);
}
},
UnannotatedExp_::ExpList(exprs) => {
for e in exprs {
match e {