-
Notifications
You must be signed in to change notification settings - Fork 3.7k
/
translate.rs
3777 lines (3578 loc) · 134 KB
/
translate.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
use super::aliases::{AliasMapBuilder, OldAliasMap};
use crate::{
command_line::SKIP_ATTRIBUTE_CHECKS,
diag,
diagnostics::{codes::DeprecatedItem, Diagnostic},
expansion::{
aliases::{AliasMap, AliasSet},
ast::{
self as E, Address, Fields, LValueOrDotDot_, LValue_, ModuleAccess_, ModuleIdent,
ModuleIdent_, SequenceItem_, SpecId,
},
byte_string, hex_string,
},
parser::ast::{
self as P, Ability, AccessSpecifier_, AddressSpecifier_, CallKind, ConstantName, Field,
FunctionName, LeadingNameAccess, LeadingNameAccess_, ModuleMember, ModuleName,
NameAccessChain, NameAccessChain_, StructName, Var,
},
shared::{
known_attributes::{AttributeKind, AttributePosition, KnownAttribute},
parse_u128, parse_u64, parse_u8,
unique_map::UniqueMap,
CompilationEnv, Identifier, Name, NamedAddressMap, NamedAddressMaps, NumericalAddress,
},
FullyCompiledProgram,
};
use move_binary_format::file_format;
use move_command_line_common::parser::{parse_u16, parse_u256, parse_u32};
use move_ir_types::location::*;
use move_symbol_pool::Symbol;
use once_cell::sync::Lazy;
use std::{
collections::{BTreeMap, BTreeSet, VecDeque},
iter::IntoIterator,
};
use str;
//**************************************************************************************************
// Context
//**************************************************************************************************
type ModuleMembers = BTreeMap<Name, ModuleMemberInfo>;
struct Context<'env, 'map> {
module_members: UniqueMap<ModuleIdent, ModuleMembers>,
module_deprecation_attribute_locs: BTreeMap<ModuleIdent, Loc>, // if any
named_address_mapping: Option<&'map NamedAddressMap>,
address: Option<Address>,
current_module: Option<ModuleIdent>,
aliases: AliasMap,
is_source_definition: bool,
in_spec_context: bool,
in_deprecated_code: bool,
in_aptos_libs: bool,
exp_specs: BTreeMap<SpecId, E::SpecBlock>,
env: &'env mut CompilationEnv,
}
impl<'env, 'map> Context<'env, 'map> {
fn new(
compilation_env: &'env mut CompilationEnv,
module_members: UniqueMap<ModuleIdent, ModuleMembers>,
module_deprecation_attribute_locs: BTreeMap<ModuleIdent, Loc>,
) -> Self {
Self {
module_members,
module_deprecation_attribute_locs,
env: compilation_env,
named_address_mapping: None,
address: None,
current_module: None,
aliases: AliasMap::new(),
is_source_definition: false,
in_spec_context: false,
in_deprecated_code: false,
in_aptos_libs: false,
exp_specs: BTreeMap::new(),
}
}
fn cur_address(&self) -> &Address {
self.address.as_ref().unwrap()
}
fn set_current_module(&mut self, module: Option<ModuleIdent>) {
self.in_deprecated_code = match &module {
Some(m) => self.module_deprecation_attribute_locs.contains_key(m),
None => false,
};
self.current_module = module;
}
fn current_module(&self) -> Option<&ModuleIdent> {
self.current_module.as_ref()
}
/// Returns previous state: whether we were already in deprecated code
fn enter_possibly_deprecated_member(&mut self, name: &Name) -> bool {
let was_in_deprecated_code = self.in_deprecated_code;
if let Some(moduleid) = self.current_module() {
if let Some(member_info_map) = self.module_members.get(moduleid) {
if let Some(member_info) = member_info_map.get(name) {
if member_info.deprecation.is_some() {
self.in_deprecated_code = true;
}
}
}
};
was_in_deprecated_code
}
fn set_in_deprecated_code(&mut self, was_deprecated: bool) {
self.in_deprecated_code = was_deprecated;
}
/// Resets the alias map and reports errors for aliases that were unused
pub fn set_to_outer_scope(&mut self, outer_scope: OldAliasMap) {
let AliasSet { modules, members } = self.aliases.set_to_outer_scope(outer_scope);
for alias in modules {
unused_alias(self, alias)
}
for alias in members {
unused_alias(self, alias)
}
}
pub fn bind_exp_spec(&mut self, spec_block: P::SpecBlock) -> (SpecId, UnboundNames) {
let espec_block = spec(self, spec_block);
let mut unbound_names = UnboundNames::default();
unbound_names_spec_block(&mut unbound_names, &espec_block);
let id = SpecId::new(self.exp_specs.len());
self.exp_specs.insert(id, espec_block);
(id, unbound_names)
}
pub fn extract_exp_specs(&mut self) -> BTreeMap<SpecId, E::SpecBlock> {
std::mem::take(&mut self.exp_specs)
}
}
//**************************************************************************************************
// Entry
//**************************************************************************************************
pub fn program(
compilation_env: &mut CompilationEnv,
pre_compiled_lib: Option<&FullyCompiledProgram>,
prog: P::Program,
) -> E::Program {
let mut module_deprecation_attribute_locs = BTreeMap::new();
// Process all members from program source, lib, and pre-compiled libs,
// recording just module->SpannedSymbol->ModuleMemberInfo for each,
// plus per-module deprecation info in module_deprecation_attribute_locs.
let module_members = {
let mut members = UniqueMap::new();
all_module_members(
compilation_env,
&prog.named_address_maps,
&mut members,
&mut module_deprecation_attribute_locs,
true,
&prog.source_definitions,
);
all_module_members(
compilation_env,
&prog.named_address_maps,
&mut members,
&mut module_deprecation_attribute_locs,
true,
&prog.lib_definitions,
);
if let Some(pre_compiled) = pre_compiled_lib {
assert!(pre_compiled.parser.lib_definitions.is_empty());
all_module_members(
compilation_env,
&pre_compiled.parser.named_address_maps,
&mut members,
&mut module_deprecation_attribute_locs,
false,
&pre_compiled.parser.source_definitions,
);
}
members
};
let mut context = Context::new(
compilation_env,
module_members,
module_deprecation_attribute_locs,
);
let mut source_module_map = UniqueMap::new();
let mut lib_module_map = UniqueMap::new();
let mut scripts = vec![];
let P::Program {
named_address_maps,
source_definitions,
lib_definitions,
} = prog;
context.is_source_definition = true;
for P::PackageDefinition {
package,
named_address_map,
def,
} in source_definitions
{
context.named_address_mapping = Some(named_address_maps.get(named_address_map));
definition(
&mut context,
&mut source_module_map,
&mut scripts,
package,
def,
)
}
context.is_source_definition = false;
for P::PackageDefinition {
package,
named_address_map,
def,
} in lib_definitions
{
context.named_address_mapping = Some(named_address_maps.get(named_address_map));
definition(
&mut context,
&mut lib_module_map,
&mut scripts,
package,
def,
)
}
for (mident, module) in lib_module_map {
if let Err((mident, old_loc)) = source_module_map.add(mident, module) {
if !context.env.flags().sources_shadow_deps() {
duplicate_module(&mut context, &source_module_map, mident, old_loc)
}
}
}
let mut module_map = source_module_map;
let mut scripts = {
let mut collected: BTreeMap<Symbol, Vec<E::Script>> = BTreeMap::new();
for s in scripts {
collected
.entry(s.function_name.value())
.or_default()
.push(s)
}
let mut keyed: BTreeMap<Symbol, E::Script> = BTreeMap::new();
for (n, mut ss) in collected {
match ss.len() {
0 => unreachable!(),
1 => assert!(
keyed.insert(n, ss.pop().unwrap()).is_none(),
"ICE duplicate script key"
),
_ => {
for (i, s) in ss.into_iter().enumerate() {
let k = format!("{}_{}", n, i);
assert!(
keyed.insert(k.into(), s).is_none(),
"ICE duplicate script key"
)
}
},
}
}
keyed
};
super::dependency_ordering::verify(context.env, &mut module_map, &mut scripts);
E::Program {
modules: module_map,
scripts,
}
}
fn definition(
context: &mut Context,
module_map: &mut UniqueMap<ModuleIdent, E::ModuleDefinition>,
scripts: &mut Vec<E::Script>,
package_name: Option<Symbol>,
def: P::Definition,
) {
match def {
P::Definition::Module(mut m) => {
let module_paddr = std::mem::take(&mut m.address);
let module_addr = module_paddr
.map(|a| sp(a.loc, address(context, /* suggest_declaration */ true, a)));
module(context, module_map, package_name, module_addr, m)
},
P::Definition::Address(a) => {
let addr = address(context, /* suggest_declaration */ false, a.addr);
for mut m in a.modules {
let module_addr = check_module_address(context, a.loc, addr, &mut m);
module(context, module_map, package_name, Some(module_addr), m)
}
},
P::Definition::Script(_) if !context.is_source_definition => (),
P::Definition::Script(s) => script(context, scripts, package_name, s),
}
}
fn address_without_value_error(suggest_declaration: bool, loc: Loc, n: &Name) -> Diagnostic {
let mut msg = format!("address '{}' is not assigned a value", n);
if suggest_declaration {
msg = format!(
"{}. Try assigning it a value when calling the compiler",
msg,
)
}
diag!(NameResolution::AddressWithoutValue, (loc, msg))
}
// Access a top level address as declared, not affected by any aliasing/shadowing
fn address(context: &mut Context, suggest_declaration: bool, ln: P::LeadingNameAccess) -> Address {
address_(
context.env,
context.named_address_mapping.as_ref().unwrap(),
suggest_declaration,
ln,
)
}
fn address_(
compilation_env: &mut CompilationEnv,
named_address_mapping: &NamedAddressMap,
suggest_declaration: bool,
ln: P::LeadingNameAccess,
) -> Address {
let name_res = check_valid_address_name_(compilation_env, &ln);
let sp!(loc, ln_) = ln;
match ln_ {
P::LeadingNameAccess_::AnonymousAddress(bytes) => {
debug_assert!(name_res.is_ok()); //
Address::Numerical(None, sp(loc, bytes))
},
P::LeadingNameAccess_::Name(n) => match named_address_mapping.get(&n.value).copied() {
Some(addr) => Address::Numerical(Some(n), sp(loc, addr)),
None => {
if name_res.is_ok() {
compilation_env.add_diag(address_without_value_error(
suggest_declaration,
loc,
&n,
));
}
Address::NamedUnassigned(n)
},
},
}
}
fn module_ident(context: &mut Context, sp!(loc, mident_): P::ModuleIdent) -> ModuleIdent {
let P::ModuleIdent_ {
address: ln,
module,
} = mident_;
let addr = address(context, /* suggest_declaration */ false, ln);
sp(loc, ModuleIdent_::new(addr, module))
}
fn check_module_address(
context: &mut Context,
loc: Loc,
addr: Address,
m: &mut P::ModuleDefinition,
) -> Spanned<Address> {
let module_address = std::mem::take(&mut m.address);
match module_address {
Some(other_paddr) => {
let other_loc = other_paddr.loc;
let other_addr = address(context, /* suggest_declaration */ true, other_paddr);
let msg = if addr == other_addr {
"Redundant address specification"
} else {
"Multiple addresses specified for module"
};
context.env.add_diag(diag!(
Declarations::DuplicateItem,
(other_loc, msg),
(loc, "Address previously specified here")
));
sp(other_loc, other_addr)
},
None => sp(loc, addr),
}
}
fn duplicate_module(
context: &mut Context,
module_map: &UniqueMap<ModuleIdent, E::ModuleDefinition>,
mident: ModuleIdent,
old_loc: Loc,
) {
let old_mident = module_map.get_key(&mident).unwrap();
let dup_msg = format!("Duplicate definition for module '{}'", mident);
let prev_msg = format!("Module previously defined here, with '{}'", old_mident);
context.env.add_diag(diag!(
Declarations::DuplicateItem,
(mident.loc, dup_msg),
(old_loc, prev_msg),
))
}
fn module(
context: &mut Context,
module_map: &mut UniqueMap<ModuleIdent, E::ModuleDefinition>,
package_name: Option<Symbol>,
module_address: Option<Spanned<Address>>,
module_def: P::ModuleDefinition,
) {
assert!(context.address.is_none());
let (mident, mod_) = module_(context, package_name, module_address, module_def);
if let Err((mident, old_loc)) = module_map.add(mident, mod_) {
duplicate_module(context, module_map, mident, old_loc)
}
context.address = None;
context.current_module = None;
context.in_deprecated_code = false;
}
fn set_sender_address(
context: &mut Context,
module_name: &ModuleName,
sender: Option<Spanned<Address>>,
) {
context.address = Some(match sender {
Some(sp!(_, addr)) => addr,
None => {
let loc = module_name.loc();
let msg = format!(
"Invalid module declaration. The module does not have a specified address. Either \
declare it inside of an 'address <address> {{' block or declare it with an \
address 'module <address>::{}''",
module_name
);
context
.env
.add_diag(diag!(Declarations::InvalidModule, (loc, msg)));
Address::Numerical(None, sp(loc, NumericalAddress::DEFAULT_ERROR_ADDRESS))
},
})
}
// This is a hack to recognize APTOS StdLib, Framework, and Token libs to avoid warnings on some old errors.
// This will be removed after library attributes are cleaned up.
// (See https://github.com/aptos-labs/aptos-core/issues/9410)
fn module_is_in_aptos_libs(module_address: Option<Spanned<Address>>) -> bool {
const APTOS_STDLIB_NAME: &str = "aptos_std";
static APTOS_STDLIB_NUMERICAL_ADDRESS: Lazy<NumericalAddress> =
Lazy::new(|| NumericalAddress::parse_str("0x1").unwrap());
const APTOS_FRAMEWORK_NAME: &str = "aptos_framework";
static APTOS_FRAMEWORK_NUMERICAL_ADDRESS: Lazy<NumericalAddress> =
Lazy::new(|| NumericalAddress::parse_str("0x1").unwrap());
const APTOS_TOKEN_NAME: &str = "aptos_token";
static APTOS_TOKEN_NUMERICAL_ADDRESS: Lazy<NumericalAddress> =
Lazy::new(|| NumericalAddress::parse_str("0x3").unwrap());
const APTOS_TOKEN_OBJECTS_NAME: &str = "aptos_token_objects";
static APTOS_TOKEN_OBJECTS_NUMERICAL_ADDRESS: Lazy<NumericalAddress> =
Lazy::new(|| NumericalAddress::parse_str("0x4").unwrap());
match &module_address {
Some(spanned_address) => {
let address = spanned_address.value;
match address {
Address::Numerical(optional_name, spanned_numerical_address) => match optional_name
{
Some(spanned_symbol) => {
((&spanned_symbol.value as &str) == APTOS_STDLIB_NAME
&& (spanned_numerical_address.value == *APTOS_STDLIB_NUMERICAL_ADDRESS))
|| ((&spanned_symbol.value as &str) == APTOS_FRAMEWORK_NAME
&& (spanned_numerical_address.value
== *APTOS_FRAMEWORK_NUMERICAL_ADDRESS))
|| ((&spanned_symbol.value as &str) == APTOS_TOKEN_NAME
&& (spanned_numerical_address.value
== *APTOS_TOKEN_NUMERICAL_ADDRESS))
|| ((&spanned_symbol.value as &str) == APTOS_TOKEN_OBJECTS_NAME
&& (spanned_numerical_address.value
== *APTOS_TOKEN_OBJECTS_NUMERICAL_ADDRESS))
},
None => false,
},
Address::NamedUnassigned(_) => false,
}
},
None => false,
}
}
fn module_(
context: &mut Context,
package_name: Option<Symbol>,
module_address: Option<Spanned<Address>>,
mdef: P::ModuleDefinition,
) -> (ModuleIdent, E::ModuleDefinition) {
let P::ModuleDefinition {
attributes,
loc,
address,
is_spec_module: _,
name,
members,
} = mdef;
let attributes = flatten_attributes(context, AttributePosition::Module, attributes);
assert!(context.address.is_none());
assert!(address.is_none());
set_sender_address(context, &name, module_address);
let _ = check_restricted_name_all_cases(context, NameCase::Module, &name.0);
if name.value().starts_with(|c| c == '_') {
let msg = format!(
"Invalid module name '{}'. Module names cannot start with '_'",
name,
);
context
.env
.add_diag(diag!(Declarations::InvalidName, (name.loc(), msg)));
}
let name_loc = name.0.loc;
let current_module = sp(name_loc, ModuleIdent_::new(*context.cur_address(), name));
if context
.module_deprecation_attribute_locs
.contains_key(¤t_module)
{
context.in_deprecated_code = true;
}
if context.env.flags().warn_of_deprecation_use_in_aptos_libs() {
context.in_aptos_libs = false;
} else {
context.in_aptos_libs = module_is_in_aptos_libs(module_address);
}
let mut new_scope = AliasMapBuilder::new();
module_self_aliases(&mut new_scope, ¤t_module);
// Make a copy of the original UseDecls, to be passed on to the expansion AST before they are
// processed here.
let use_decls = members
.iter()
.filter_map(|member| {
if let ModuleMember::Use(decl) = member {
Some(decl.clone())
} else {
None
}
})
.collect();
let members = members
.into_iter()
.filter_map(|member| aliases_from_member(context, &mut new_scope, ¤t_module, member))
.collect::<Vec<_>>();
let old_aliases = context.aliases.add_and_shadow_all(new_scope);
assert!(
old_aliases.is_empty(),
"ICE there should be no aliases entering a module"
);
context.set_current_module(Some(current_module));
let mut friends = UniqueMap::new();
let mut functions = UniqueMap::new();
let mut constants = UniqueMap::new();
let mut structs = UniqueMap::new();
let mut specs = vec![];
for member in members {
match member {
P::ModuleMember::Use(_) => unreachable!(),
P::ModuleMember::Friend(f) => friend(context, &mut friends, f),
P::ModuleMember::Function(mut f) => {
if !context.is_source_definition && !f.inline {
f.body.value = P::FunctionBody_::Native
}
function(context, &mut functions, f)
},
P::ModuleMember::Constant(c) => constant(context, &mut constants, c),
P::ModuleMember::Struct(s) => struct_def(context, &mut structs, s),
P::ModuleMember::Spec(s) => specs.push(spec(context, s)),
}
}
context.set_to_outer_scope(old_aliases);
let def = E::ModuleDefinition {
package_name,
attributes,
loc,
is_source_module: context.is_source_definition,
dependency_order: 0,
immediate_neighbors: UniqueMap::new(),
used_addresses: BTreeSet::new(),
friends,
structs,
constants,
functions,
specs,
use_decls,
};
(current_module, def)
}
fn script(
context: &mut Context,
scripts: &mut Vec<E::Script>,
package_name: Option<Symbol>,
pscript: P::Script,
) {
scripts.push(script_(context, package_name, pscript))
}
fn script_(context: &mut Context, package_name: Option<Symbol>, pscript: P::Script) -> E::Script {
assert!(context.address.is_none());
assert!(context.is_source_definition);
let P::Script {
attributes,
loc,
uses: puses,
constants: pconstants,
function: pfunction,
specs: pspecs,
} = pscript;
let attributes = flatten_attributes(context, AttributePosition::Script, attributes);
let new_scope = uses(context, puses.clone());
let old_aliases = context.aliases.add_and_shadow_all(new_scope);
assert!(
old_aliases.is_empty(),
"ICE there should be no aliases entering a script"
);
context.set_current_module(None);
context.in_aptos_libs = false;
let mut constants = UniqueMap::new();
for c in pconstants {
// TODO remove after Self rework
check_valid_module_member_name(context, ModuleMemberKind::Constant, c.name.0);
constant(context, &mut constants, c);
}
// TODO remove after Self rework
check_valid_module_member_name(context, ModuleMemberKind::Function, pfunction.name.0);
let (function_name, function) = function_(context, pfunction);
match &function.visibility {
E::Visibility::Public(loc) | E::Visibility::Package(loc) | E::Visibility::Friend(loc) => {
let msg = format!(
"Invalid '{}' visibility modifier. \
Script functions are not callable from other Move functions.",
function.visibility,
);
context
.env
.add_diag(diag!(Declarations::UnnecessaryItem, (*loc, msg)));
},
E::Visibility::Internal => (),
}
match &function.body {
sp!(_, E::FunctionBody_::Defined(_)) => (),
sp!(loc, E::FunctionBody_::Native) => {
context.env.add_diag(diag!(
Declarations::InvalidScript,
(
*loc,
"Invalid 'native' function. 'script' functions must have a defined body"
)
));
},
}
let specs = specs(context, pspecs);
context.set_to_outer_scope(old_aliases);
E::Script {
package_name,
attributes,
loc,
immediate_neighbors: UniqueMap::new(),
used_addresses: BTreeSet::new(),
constants,
function_name,
function,
specs,
use_decls: puses,
}
}
/// If attributes contains a `#[deprecated]` attribute, then returns the location of the attribute.
fn deprecated_attribute_location(attributes: &[P::Attributes]) -> Option<Loc> {
attributes
.iter()
.flat_map(|attrs| &attrs.value)
.filter_map(|attr| {
let sp!(nloc, sym) = match &attr.value {
P::Attribute_::Name(n)
| P::Attribute_::Assigned(n, _)
| P::Attribute_::Parameterized(n, _) => *n,
};
match KnownAttribute::resolve(sym) {
Some(KnownAttribute::Deprecation(_dep)) => Some(nloc),
_ => None,
}
})
.next()
}
fn flatten_attributes(
context: &mut Context,
attr_position: AttributePosition,
attributes: Vec<P::Attributes>,
) -> E::Attributes {
let all_attrs = attributes
.into_iter()
.flat_map(|attrs| attrs.value)
.flat_map(|attr| attribute(context, attr_position, attr))
.collect::<Vec<_>>();
unique_attributes(context, attr_position, false, all_attrs)
}
fn unique_attributes(
context: &mut Context,
attr_position: AttributePosition,
is_nested: bool,
attributes: impl IntoIterator<Item = E::Attribute>,
) -> E::Attributes {
let mut attr_map = UniqueMap::new();
for sp!(loc, attr_) in attributes {
let sp!(nloc, sym) = match &attr_ {
E::Attribute_::Name(n)
| E::Attribute_::Assigned(n, _)
| E::Attribute_::Parameterized(n, _) => *n,
};
let name_ = match KnownAttribute::resolve(sym) {
None => {
let flags = &context.env.flags();
if !flags.skip_attribute_checks() {
let known_attributes = &context.env.get_known_attributes();
if !is_nested && !known_attributes.contains(sym.as_str()) {
let msg = format!("Attribute name '{}' is unknown (use --{} CLI option to ignore); known attributes are '{:?}'.",
sym.as_str(),
SKIP_ATTRIBUTE_CHECKS, known_attributes);
context
.env
.add_diag(diag!(Declarations::UnknownAttribute, (nloc, msg)));
} else if is_nested && known_attributes.contains(sym.as_str()) {
let msg = format!(
"Attribute '{}' is not expected in a nested attribute position.",
sym.as_str()
);
context
.env
.add_diag(diag!(Declarations::InvalidAttribute, (nloc, msg)));
};
}
E::AttributeName_::Unknown(sym)
},
Some(known) => {
debug_assert!(known.name() == sym.as_str());
if is_nested {
let msg = format!(
"Attribute '{}' is not expected in a nested attribute position",
sym.as_str()
);
context
.env
.add_diag(diag!(Declarations::InvalidAttribute, (nloc, msg)));
continue;
}
let expected_positions = known.expected_positions();
if !expected_positions.contains(&attr_position) {
let msg = format!(
"Attribute '{}' is not expected with a {}",
known.name(),
attr_position
);
let all_expected = expected_positions
.iter()
.map(|p| format!("{}", p))
.collect::<Vec<_>>()
.join(", ");
let expected_msg = format!(
"Expected to be used with one of the following: {}",
all_expected
);
context.env.add_diag(diag!(
Declarations::InvalidAttribute,
(nloc, msg),
(nloc, expected_msg)
));
continue;
}
E::AttributeName_::Known(known)
},
};
if let Err((_, old_loc)) = attr_map.add(sp(nloc, name_), sp(loc, attr_)) {
let msg = format!("Duplicate attribute '{}' attached to the same item", name_);
context.env.add_diag(diag!(
Declarations::DuplicateItem,
(loc, msg),
(old_loc, "Attribute previously given here"),
));
}
}
attr_map
}
fn attribute(
context: &mut Context,
attr_position: AttributePosition,
sp!(loc, attribute_): P::Attribute,
) -> Option<E::Attribute> {
use E::Attribute_ as EA;
use P::Attribute_ as PA;
Some(sp(loc, match attribute_ {
PA::Name(n) => EA::Name(n),
PA::Assigned(n, v) => EA::Assigned(n, Box::new(attribute_value(context, *v)?)),
PA::Parameterized(n, sp!(_, pattrs_)) => {
let attrs = pattrs_
.into_iter()
.map(|a| attribute(context, attr_position, a))
.collect::<Option<Vec<_>>>()?;
EA::Parameterized(n, unique_attributes(context, attr_position, true, attrs))
},
}))
}
fn check_module_name(context: &mut Context, ident_loc: &Loc, mident: &ModuleIdent) {
match context.module_members.get(mident) {
None => {
context.env.add_diag(diag!(
NameResolution::UnboundModule,
(*ident_loc, format!("Unbound module '{}'", mident))
));
},
Some(_module) => {
check_for_deprecated_module_use(context, mident);
},
}
}
fn attribute_value(
context: &mut Context,
sp!(loc, avalue_): P::AttributeValue,
) -> Option<E::AttributeValue> {
use E::AttributeValue_ as EV;
use P::{AttributeValue_ as PV, LeadingNameAccess_ as LN, NameAccessChain_ as PN};
Some(sp(loc, match avalue_ {
PV::Value(v) => EV::Value(value(context, v)?),
PV::ModuleAccess(sp!(ident_loc, PN::Two(sp!(aloc, LN::AnonymousAddress(a)), n))) => {
let addr = Address::Numerical(None, sp(aloc, a));
let mident = sp(ident_loc, ModuleIdent_::new(addr, ModuleName(n)));
check_module_name(context, &ident_loc, &mident);
EV::Module(mident)
},
// bit wonky, but this is the only spot currently where modules and expressions exist
// in the same namespace.
// TODO consider if we want to just force all of these checks into the well-known
// attribute setup
PV::ModuleAccess(sp!(ident_loc, PN::One(n)))
if context.aliases.module_alias_get(&n).is_some() =>
{
let sp!(_, mident_) = context.aliases.module_alias_get(&n).unwrap();
let mident = sp(ident_loc, mident_);
check_module_name(context, &ident_loc, &mident);
EV::Module(mident)
},
PV::ModuleAccess(sp!(ident_loc, PN::Two(sp!(aloc, LN::Name(n1)), n2)))
if context
.named_address_mapping
.as_ref()
.map(|m| m.contains_key(&n1.value))
.unwrap_or(false) =>
{
let addr = address(context, false, sp(aloc, LN::Name(n1)));
let mident = sp(ident_loc, ModuleIdent_::new(addr, ModuleName(n2)));
check_module_name(context, &ident_loc, &mident);
EV::Module(mident)
},
PV::ModuleAccess(ma) => EV::ModuleAccess(name_access_chain(
context,
Access::Type,
ma,
Some(DeprecatedItem::Module),
)?),
}))
}
//**************************************************************************************************
// Aliases
//**************************************************************************************************
/// Process the PackageDefinition refs provided by the defs iterator,
/// adding all symbol definitions to members, which records
/// moduleId->SpannedSymbol->ModuleMemberInfo. Also add a record
/// for each deprecated module to module_deprecation_attribute_locs.
fn all_module_members<'a>(
compilation_env: &mut CompilationEnv,
named_addr_maps: &NamedAddressMaps,
members: &mut UniqueMap<ModuleIdent, ModuleMembers>,
module_deprecation_attribute_locs: &mut BTreeMap<ModuleIdent, Loc>,
always_add: bool,
defs: impl IntoIterator<Item = &'a P::PackageDefinition>,
) {
for P::PackageDefinition {
named_address_map,
def,
..
} in defs
{
let named_addr_map = named_addr_maps.get(*named_address_map);
match def {
P::Definition::Module(m) => {
let addr = match &m.address {
Some(a) => {
address_(
compilation_env,
named_addr_map,
/* suggest_declaration */ true,
*a,
)
},
// Error will be handled when the module is compiled
None => {
Address::Numerical(None, sp(m.loc, NumericalAddress::DEFAULT_ERROR_ADDRESS))
},
};
let mident = sp(m.name.loc(), ModuleIdent_::new(addr, m.name));
module_members(members, always_add, m, &mident);
if let Some(loc) = deprecated_attribute_location(&m.attributes) {
module_deprecation_attribute_locs.insert(mident, loc);
}
},
P::Definition::Address(addr_def) => {
let addr = address_(
compilation_env,
named_addr_map,
/* suggest_declaration */ false,
addr_def.addr,
);
for m in &addr_def.modules {
let mident = sp(m.name.loc(), ModuleIdent_::new(addr, m.name));
module_members(members, always_add, m, &mident);
if let Some(loc) = deprecated_attribute_location(&addr_def.attributes) {
module_deprecation_attribute_locs.insert(mident, loc);
} else if let Some(loc) = deprecated_attribute_location(&m.attributes) {
module_deprecation_attribute_locs.insert(mident, loc);
}
}
},
P::Definition::Script(_) => (),
}
}
}
/// Record ModuleMemberInfo about a specified member name, including
/// info about any deprecation found in attributes.
fn record_module_member_info(
cur_members: &mut BTreeMap<Spanned<Symbol>, ModuleMemberInfo>,
name: &Spanned<Symbol>,
attributes: &[P::Attributes],
member_kind: ModuleMemberKind,
) {
cur_members.insert(*name, ModuleMemberInfo {
kind: member_kind,
deprecation: deprecated_attribute_location(attributes),
});
}
/// Record ModuleMemberInfo about a specified member name, skipping
/// deprecation info (as for a spec member).
fn record_module_member_info_without_deprecation(
cur_members: &mut BTreeMap<Spanned<Symbol>, ModuleMemberInfo>,
name: &Spanned<Symbol>,
member_kind: ModuleMemberKind,
) {
cur_members.insert(*name, ModuleMemberInfo {
kind: member_kind,
deprecation: None,
});
}
/// Specified module with identifier mident and definition m,
/// add MemberInfo about each defined member to the members map.
/// This currently includes ModuleMemberKind and deprecation info.
/// If always_add is not false, then a module is processed only if it
/// is already present in the map (as for a module in the stdlibs).
fn module_members(
members: &mut UniqueMap<ModuleIdent, ModuleMembers>,
always_add: bool,
m: &P::ModuleDefinition,
mident: &ModuleIdent,
) {
if !always_add && members.contains_key(mident) {
return;
}