This repository was archived by the owner on May 4, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 690
/
Copy pathmodel.rs
3859 lines (3425 loc) · 129 KB
/
model.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
//! Provides a model for a set of Move modules (and scripts, which
//! are handled like modules). The model allows to access many different aspects of the Move
//! code: all declared functions and types, their associated bytecode, their source location,
//! their source text, and the specification fragments.
//!
//! The environment is nested into a hierarchy:
//!
//! - A `GlobalEnv` which gives access to all modules plus other information on global level,
//! and is the owner of all related data.
//! - A `ModuleEnv` which is a reference to the data of some module in the environment.
//! - A `StructEnv` which is a reference to the data of some struct in a module.
//! - A `FunctionEnv` which is a reference to the data of some function in a module.
use std::{
any::{Any, TypeId},
cell::RefCell,
collections::{BTreeMap, BTreeSet, VecDeque},
ffi::OsStr,
fmt::{self, Formatter},
rc::Rc,
};
use codespan::{ByteIndex, ByteOffset, ColumnOffset, FileId, Files, LineOffset, Location, Span};
use codespan_reporting::{
diagnostic::{Diagnostic, Label, Severity},
term::{emit, termcolor::WriteColor, Config},
};
use itertools::Itertools;
#[allow(unused_imports)]
use log::{info, warn};
use num::{BigUint, One, ToPrimitive};
use serde::{Deserialize, Serialize};
pub use move_binary_format::file_format::{AbilitySet, Visibility as FunctionVisibility};
use move_binary_format::{
access::ModuleAccess,
binary_views::BinaryIndexedView,
file_format::{
AddressIdentifierIndex, Bytecode, CodeOffset, Constant as VMConstant, ConstantPoolIndex,
FunctionDefinitionIndex, FunctionHandleIndex, SignatureIndex, SignatureToken,
StructDefinitionIndex, StructFieldInformation, StructHandleIndex, Visibility,
},
normalized::Type as MType,
views::{
FieldDefinitionView, FunctionDefinitionView, FunctionHandleView, SignatureTokenView,
StructDefinitionView, StructHandleView,
},
CompiledModule,
};
use move_bytecode_source_map::{mapping::SourceMapping, source_map::SourceMap};
use move_command_line_common::{address::NumericalAddress, files::FileHash};
use move_core_types::{
account_address::AccountAddress,
identifier::{IdentStr, Identifier},
language_storage,
value::MoveValue,
};
use move_disassembler::disassembler::{Disassembler, DisassemblerOptions};
use crate::{
ast::{
Attribute, ConditionKind, Exp, ExpData, GlobalInvariant, ModuleName, PropertyBag,
PropertyValue, Spec, SpecBlockInfo, SpecFunDecl, SpecVarDecl, Value,
},
intrinsics::IntrinsicsAnnotation,
pragmas::{
DELEGATE_INVARIANTS_TO_CALLER_PRAGMA, DISABLE_INVARIANTS_IN_BODY_PRAGMA, FRIEND_PRAGMA,
INTRINSIC_PRAGMA, OPAQUE_PRAGMA, VERIFY_PRAGMA,
},
symbol::{Symbol, SymbolPool},
ty::{PrimitiveType, Type, TypeDisplayContext, TypeUnificationAdapter, Variance},
};
// =================================================================================================
/// # Constants
/// A name we use to represent a script as a module.
pub const SCRIPT_MODULE_NAME: &str = "<SELF>";
/// Names used in the bytecode/AST to represent the main function of a script
pub const SCRIPT_BYTECODE_FUN_NAME: &str = "<SELF>";
/// A prefix used for structs which are backing specification ("ghost") memory.
pub const GHOST_MEMORY_PREFIX: &str = "Ghost$";
// =================================================================================================
/// # Locations
/// A location, consisting of a FileId and a span in this file.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
pub struct Loc {
file_id: FileId,
span: Span,
}
impl Loc {
pub fn new(file_id: FileId, span: Span) -> Loc {
Loc { file_id, span }
}
pub fn span(&self) -> Span {
self.span
}
pub fn file_id(&self) -> FileId {
self.file_id
}
// Delivers a location pointing to the end of this one.
pub fn at_end(&self) -> Loc {
if self.span.end() > ByteIndex(0) {
Loc::new(
self.file_id,
Span::new(self.span.end() - ByteOffset(1), self.span.end()),
)
} else {
self.clone()
}
}
// Delivers a location pointing to the start of this one.
pub fn at_start(&self) -> Loc {
Loc::new(
self.file_id,
Span::new(self.span.start(), self.span.start() + ByteOffset(1)),
)
}
/// Creates a location which encloses all the locations in the provided slice,
/// which must not be empty. All locations are expected to be in the same file.
pub fn enclosing(locs: &[&Loc]) -> Loc {
assert!(!locs.is_empty());
let loc = locs[0];
let mut start = loc.span.start();
let mut end = loc.span.end();
for l in locs.iter().skip(1) {
if l.file_id() == loc.file_id() {
start = std::cmp::min(start, l.span().start());
end = std::cmp::max(end, l.span().end());
}
}
Loc::new(loc.file_id(), Span::new(start, end))
}
/// Returns true if the other location is enclosed by this location.
pub fn is_enclosing(&self, other: &Loc) -> bool {
self.file_id == other.file_id && GlobalEnv::enclosing_span(self.span, other.span)
}
}
impl Default for Loc {
fn default() -> Self {
let mut files = Files::new();
let dummy_id = files.add(String::new(), String::new());
Loc::new(dummy_id, Span::default())
}
}
/// Alias for the Loc variant of MoveIR. This uses a `&static str` instead of `FileId` for the
/// file name.
pub type MoveIrLoc = move_ir_types::location::Loc;
// =================================================================================================
/// # Identifiers
///
/// Identifiers are opaque values used to reference entities in the environment.
///
/// We have two kinds of ids: those based on an index, and those based on a symbol. We use
/// the symbol based ids where we do not have control of the definition index order in bytecode
/// (i.e. we do not know in which order move-compiler enters functions and structs into file format),
/// and index based ids where we do have control (for modules, SpecFun and SpecVar).
///
/// In any case, ids are opaque in the sense that if someone has a StructId or similar in hand,
/// it is known to be defined in the environment, as it has been obtained also from the environment.
/// Raw index type used in ids. 16 bits are sufficient currently.
pub type RawIndex = u16;
/// Identifier for a module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct ModuleId(RawIndex);
/// Identifier for a named constant, relative to module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct NamedConstantId(Symbol);
/// Identifier for a structure/resource, relative to module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct StructId(Symbol);
/// Identifier for a field of a structure, relative to struct.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct FieldId(Symbol);
/// Identifier for a Move function, relative to module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct FunId(Symbol);
/// Identifier for a schema.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct SchemaId(Symbol);
/// Identifier for a specification function, relative to module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct SpecFunId(RawIndex);
/// Identifier for a specification variable, relative to module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct SpecVarId(RawIndex);
/// Identifier for a node in the AST, relative to a module. This is used to associate attributes
/// with the node, like source location and type.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct NodeId(usize);
/// A global id. Instances of this type represent unique identifiers relative to `GlobalEnv`.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct GlobalId(usize);
/// Identifier for an intrinsic declaration, relative globally in `GlobalEnv`.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct IntrinsicId(usize);
/// Some identifier qualified by a module.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
pub struct QualifiedId<Id> {
pub module_id: ModuleId,
pub id: Id,
}
/// Some identifier qualified by a module and a type instantiation.
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone)]
pub struct QualifiedInstId<Id> {
pub module_id: ModuleId,
pub inst: Vec<Type>,
pub id: Id,
}
impl NamedConstantId {
pub fn new(sym: Symbol) -> Self {
Self(sym)
}
pub fn symbol(self) -> Symbol {
self.0
}
}
impl FunId {
pub fn new(sym: Symbol) -> Self {
Self(sym)
}
pub fn symbol(self) -> Symbol {
self.0
}
}
impl SchemaId {
pub fn new(sym: Symbol) -> Self {
Self(sym)
}
pub fn symbol(self) -> Symbol {
self.0
}
}
impl StructId {
pub fn new(sym: Symbol) -> Self {
Self(sym)
}
pub fn symbol(self) -> Symbol {
self.0
}
}
impl FieldId {
pub fn new(sym: Symbol) -> Self {
Self(sym)
}
pub fn symbol(self) -> Symbol {
self.0
}
}
impl SpecFunId {
pub fn new(idx: usize) -> Self {
Self(idx as RawIndex)
}
pub fn as_usize(self) -> usize {
self.0 as usize
}
}
impl SpecVarId {
pub fn new(idx: usize) -> Self {
Self(idx as RawIndex)
}
pub fn as_usize(self) -> usize {
self.0 as usize
}
}
impl NodeId {
pub fn new(idx: usize) -> Self {
Self(idx)
}
pub fn as_usize(self) -> usize {
self.0 as usize
}
}
impl ModuleId {
pub fn new(idx: usize) -> Self {
Self(idx as RawIndex)
}
pub fn to_usize(self) -> usize {
self.0 as usize
}
}
impl ModuleId {
pub fn qualified<Id>(self, id: Id) -> QualifiedId<Id> {
QualifiedId {
module_id: self,
id,
}
}
pub fn qualified_inst<Id>(self, id: Id, inst: Vec<Type>) -> QualifiedInstId<Id> {
QualifiedInstId {
module_id: self,
inst,
id,
}
}
}
impl GlobalId {
pub fn new(idx: usize) -> Self {
Self(idx)
}
pub fn as_usize(self) -> usize {
self.0
}
}
impl IntrinsicId {
pub fn new(idx: usize) -> Self {
Self(idx)
}
pub fn as_usize(self) -> usize {
self.0
}
}
impl<Id: Clone> QualifiedId<Id> {
pub fn instantiate(self, inst: Vec<Type>) -> QualifiedInstId<Id> {
let QualifiedId { module_id, id } = self;
QualifiedInstId {
module_id,
inst,
id,
}
}
}
impl<Id: Clone> QualifiedInstId<Id> {
pub fn instantiate(self, params: &[Type]) -> Self {
if params.is_empty() {
self
} else {
let Self {
module_id,
inst,
id,
} = self;
Self {
module_id,
inst: Type::instantiate_vec(inst, params),
id,
}
}
}
pub fn instantiate_ref(&self, params: &[Type]) -> Self {
let res = self.clone();
res.instantiate(params)
}
pub fn to_qualified_id(&self) -> QualifiedId<Id> {
let Self { module_id, id, .. } = self;
module_id.qualified(id.to_owned())
}
}
impl QualifiedInstId<StructId> {
pub fn to_type(&self) -> Type {
Type::Struct(self.module_id, self.id, self.inst.to_owned())
}
}
// =================================================================================================
/// # Verification Scope
/// Defines what functions to verify.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub enum VerificationScope {
/// Verify only public functions.
Public,
/// Verify all functions.
All,
/// Verify only one function.
Only(String),
/// Verify only functions from the given module.
OnlyModule(String),
/// Verify no functions
None,
}
impl Default for VerificationScope {
fn default() -> Self {
Self::Public
}
}
impl VerificationScope {
/// Whether verification is exclusive to only one function or module. If set, this overrides
/// all implicitly included verification targets via invariants and friends.
pub fn is_exclusive(&self) -> bool {
matches!(
self,
VerificationScope::Only(_) | VerificationScope::OnlyModule(_)
)
}
/// Returns the target function if verification is exclusive to one function.
pub fn get_exclusive_verify_function_name(&self) -> Option<&String> {
match self {
VerificationScope::Only(s) => Some(s),
_ => None,
}
}
}
// =================================================================================================
/// # Global Environment
/// Global environment for a set of modules.
#[derive(Debug)]
pub struct GlobalEnv {
/// A Files database for the codespan crate which supports diagnostics.
source_files: Files<String>,
/// A map of FileId in the Files database to information about documentation comments in a file.
/// The comments are represented as map from ByteIndex into string, where the index is the
/// start position of the associated language item in the source.
doc_comments: BTreeMap<FileId, BTreeMap<ByteIndex, String>>,
/// A mapping from file hash to file name and associated FileId. Though this information is
/// already in `source_files`, we can't get it out of there so need to book keep here.
file_hash_map: BTreeMap<FileHash, (String, FileId)>,
/// A mapping from file id to associated alias map.
file_alias_map: BTreeMap<FileId, Rc<BTreeMap<Symbol, NumericalAddress>>>,
/// Bijective mapping between FileId and a plain int. FileId's are themselves wrappers around
/// ints, but the inner representation is opaque and cannot be accessed. This is used so we
/// can emit FileId's to generated code and read them back.
file_id_to_idx: BTreeMap<FileId, u16>,
file_idx_to_id: BTreeMap<u16, FileId>,
/// A set indicating whether a file id is a target or a dependency.
file_id_is_dep: BTreeSet<FileId>,
/// A special constant location representing an unknown location.
/// This uses a pseudo entry in `source_files` to be safely represented.
unknown_loc: Loc,
/// An equivalent of the MoveIrLoc to the above location. Used to map back and force between
/// them.
unknown_move_ir_loc: MoveIrLoc,
/// A special constant location representing an opaque location.
/// In difference to an `unknown_loc`, this is a well-known but undisclosed location.
internal_loc: Loc,
/// Accumulated diagnosis. In a RefCell so we can add to it without needing a mutable GlobalEnv.
/// The boolean indicates whether the diag was reported.
diags: RefCell<Vec<(Diagnostic<FileId>, bool)>>,
/// Pool of symbols -- internalized strings.
symbol_pool: SymbolPool,
/// A counter for allocating node ids.
next_free_node_id: RefCell<usize>,
/// A map from node id to associated information of the expression.
exp_info: RefCell<BTreeMap<NodeId, ExpInfo>>,
/// List of loaded modules, in order they have been provided using `add`.
pub module_data: Vec<ModuleData>,
/// A counter for issuing global ids.
global_id_counter: RefCell<usize>,
/// A map of global invariants.
global_invariants: BTreeMap<GlobalId, GlobalInvariant>,
/// A map from global memories to global invariants which refer to them.
global_invariants_for_memory: BTreeMap<QualifiedInstId<StructId>, BTreeSet<GlobalId>>,
/// A set containing spec functions which are called/used in specs. Note that these
/// are represented without type instantiation because we assume the backend can handle
/// generics in the expression language.
pub used_spec_funs: BTreeSet<QualifiedId<SpecFunId>>,
/// An annotation of all intrinsic declarations
pub intrinsics: IntrinsicsAnnotation,
/// A type-indexed container for storing extension data in the environment.
extensions: RefCell<BTreeMap<TypeId, Box<dyn Any>>>,
/// The address of the standard and extension libaries.
stdlib_address: Option<BigUint>,
extlib_address: Option<BigUint>,
}
/// Struct a helper type for implementing fmt::Display depending on GlobalEnv
pub struct EnvDisplay<'a, T> {
pub env: &'a GlobalEnv,
pub val: &'a T,
}
impl GlobalEnv {
/// Creates a new environment.
pub fn new() -> Self {
let mut source_files = Files::new();
let mut file_hash_map = BTreeMap::new();
let mut file_id_to_idx = BTreeMap::new();
let mut file_idx_to_id = BTreeMap::new();
let mut fake_loc = |content: &str| {
let file_id = source_files.add(content, content.to_string());
let file_hash = FileHash::new(content);
file_hash_map.insert(file_hash, (content.to_string(), file_id));
let file_idx = file_id_to_idx.len() as u16;
file_id_to_idx.insert(file_id, file_idx);
file_idx_to_id.insert(file_idx, file_id);
Loc::new(
file_id,
Span::from(ByteIndex(0_u32)..ByteIndex(content.len() as u32)),
)
};
let unknown_loc = fake_loc("<unknown>");
let unknown_move_ir_loc = MoveIrLoc::new(FileHash::new("<unknown>"), 0, 0);
let internal_loc = fake_loc("<internal>");
GlobalEnv {
source_files,
doc_comments: Default::default(),
unknown_loc,
unknown_move_ir_loc,
internal_loc,
file_hash_map,
file_alias_map: BTreeMap::new(),
file_id_to_idx,
file_idx_to_id,
file_id_is_dep: BTreeSet::new(),
diags: RefCell::new(vec![]),
symbol_pool: SymbolPool::new(),
next_free_node_id: Default::default(),
exp_info: Default::default(),
module_data: vec![],
global_id_counter: RefCell::new(0),
global_invariants: Default::default(),
global_invariants_for_memory: Default::default(),
used_spec_funs: BTreeSet::new(),
intrinsics: Default::default(),
extensions: Default::default(),
stdlib_address: None,
extlib_address: None,
}
}
/// Creates a display container for the given value. There must be an implementation
/// of fmt::Display for an instance to work in formatting.
pub fn display<'a, T>(&'a self, val: &'a T) -> EnvDisplay<'a, T> {
EnvDisplay { env: self, val }
}
/// Stores extension data in the environment. This can be arbitrary data which is
/// indexed by type. Used by tools which want to store their own data in the environment,
/// like a set of tool dependent options/flags. This can also be used to update
/// extension data.
pub fn set_extension<T: Any>(&self, x: T) {
let id = TypeId::of::<T>();
self.extensions
.borrow_mut()
.insert(id, Box::new(Rc::new(x)));
}
/// Retrieves extension data from the environment. Use as in `env.get_extension::<T>()`.
/// An Rc<T> is returned because extension data is stored in a RefCell and we can't use
/// lifetimes (`&'a T`) to control borrowing.
pub fn get_extension<T: Any>(&self) -> Option<Rc<T>> {
let id = TypeId::of::<T>();
self.extensions
.borrow()
.get(&id)
.and_then(|d| d.downcast_ref::<Rc<T>>().cloned())
}
/// Retrieves a clone of the extension data from the environment. Use as in `env.get_cloned_extension::<T>()`.
pub fn get_cloned_extension<T: Any + Clone>(&self) -> T {
let id = TypeId::of::<T>();
let d = self
.extensions
.borrow_mut()
.remove(&id)
.expect("extension defined")
.downcast_ref::<Rc<T>>()
.cloned()
.unwrap();
Rc::try_unwrap(d).unwrap_or_else(|d| d.as_ref().clone())
}
/// Updates extension data. If they are no outstanding references to this extension it
/// is updated in place, otherwise it will be cloned before the update.
pub fn update_extension<T: Any + Clone>(&self, f: impl FnOnce(&mut T)) {
let id = TypeId::of::<T>();
let d = self
.extensions
.borrow_mut()
.remove(&id)
.expect("extension defined")
.downcast_ref::<Rc<T>>()
.cloned()
.unwrap();
let mut curr = Rc::try_unwrap(d).unwrap_or_else(|d| d.as_ref().clone());
f(&mut curr);
self.set_extension(curr);
}
/// Checks whether there is an extension of type `T`.
pub fn has_extension<T: Any>(&self) -> bool {
let id = TypeId::of::<T>();
self.extensions.borrow().contains_key(&id)
}
/// Clear extension data from the environment (return the data if it is previously set).
/// Use as in `env.clear_extension::<T>()` and an `Rc<T>` is returned if the extension data is
/// previously stored in the environment.
pub fn clear_extension<T: Any>(&self) -> Option<Rc<T>> {
let id = TypeId::of::<T>();
self.extensions
.borrow_mut()
.remove(&id)
.and_then(|d| d.downcast::<Rc<T>>().ok())
.map(|boxed| *boxed)
}
/// Create a new global id unique to this environment.
pub fn new_global_id(&self) -> GlobalId {
let mut counter = self.global_id_counter.borrow_mut();
let id = GlobalId::new(*counter);
*counter += 1;
id
}
/// Returns a reference to the symbol pool owned by this environment.
pub fn symbol_pool(&self) -> &SymbolPool {
&self.symbol_pool
}
/// Adds a source to this environment, returning a FileId for it.
pub fn add_source(
&mut self,
file_hash: FileHash,
address_aliases: Rc<BTreeMap<Symbol, NumericalAddress>>,
file_name: &str,
source: &str,
is_dep: bool,
) -> FileId {
let file_id = self.source_files.add(file_name, source.to_string());
self.stdlib_address =
self.resolve_std_address_alias(self.stdlib_address.clone(), "std", &address_aliases);
self.extlib_address = self.resolve_std_address_alias(
self.extlib_address.clone(),
"Extensions",
&address_aliases,
);
self.file_alias_map.insert(file_id, address_aliases);
self.file_hash_map
.insert(file_hash, (file_name.to_string(), file_id));
let file_idx = self.file_id_to_idx.len() as u16;
self.file_id_to_idx.insert(file_id, file_idx);
self.file_idx_to_id.insert(file_idx, file_id);
if is_dep {
self.file_id_is_dep.insert(file_id);
}
file_id
}
fn resolve_std_address_alias(
&self,
def: Option<BigUint>,
name: &str,
aliases: &BTreeMap<Symbol, NumericalAddress>,
) -> Option<BigUint> {
let name_sym = self.symbol_pool().make(name);
if let Some(a) = aliases.get(&name_sym) {
let addr = BigUint::from_bytes_be(a.as_ref());
if matches!(&def, Some(other_addr) if &addr != other_addr) {
self.error(
&self.unknown_loc,
&format!(
"Ambiguous definition of standard address alias `{}` (`0x{} != 0x{}`).\
This alias currently must be unique across all packages.",
name,
addr,
def.unwrap()
),
);
}
Some(addr)
} else {
def
}
}
/// Find all target modules and return in a vector
pub fn get_target_modules(&self) -> Vec<ModuleEnv> {
let mut target_modules: Vec<ModuleEnv> = vec![];
for module_env in self.get_modules() {
if module_env.is_target() {
target_modules.push(module_env);
}
}
target_modules
}
/// Adds documentation for a file.
pub fn add_documentation(&mut self, file_id: FileId, docs: BTreeMap<ByteIndex, String>) {
self.doc_comments.insert(file_id, docs);
}
/// Adds diagnostic to the environment.
pub fn add_diag(&self, diag: Diagnostic<FileId>) {
self.diags.borrow_mut().push((diag, false));
}
/// Adds an error to this environment, without notes.
pub fn error(&self, loc: &Loc, msg: &str) {
self.diag(Severity::Error, loc, msg)
}
/// Adds an error to this environment, with notes.
pub fn error_with_notes(&self, loc: &Loc, msg: &str, notes: Vec<String>) {
self.diag_with_notes(Severity::Error, loc, msg, notes)
}
/// Adds a diagnostic of given severity to this environment.
pub fn diag(&self, severity: Severity, loc: &Loc, msg: &str) {
let diag = Diagnostic::new(severity)
.with_message(msg)
.with_labels(vec![Label::primary(loc.file_id, loc.span)]);
self.add_diag(diag);
}
/// Adds a diagnostic of given severity to this environment, with notes.
pub fn diag_with_notes(&self, severity: Severity, loc: &Loc, msg: &str, notes: Vec<String>) {
let diag = Diagnostic::new(severity)
.with_message(msg)
.with_labels(vec![Label::primary(loc.file_id, loc.span)]);
let diag = diag.with_notes(notes);
self.add_diag(diag);
}
/// Adds a diagnostic of given severity to this environment, with secondary labels.
pub fn diag_with_labels(
&self,
severity: Severity,
loc: &Loc,
msg: &str,
labels: Vec<(Loc, String)>,
) {
let diag = Diagnostic::new(severity)
.with_message(msg)
.with_labels(vec![Label::primary(loc.file_id, loc.span)]);
let labels = labels
.into_iter()
.map(|(l, m)| Label::secondary(l.file_id, l.span).with_message(m))
.collect_vec();
let diag = diag.with_labels(labels);
self.add_diag(diag);
}
/// Checks whether any of the diagnostics contains string.
pub fn has_diag(&self, pattern: &str) -> bool {
self.diags
.borrow()
.iter()
.any(|(d, _)| d.message.contains(pattern))
}
/// Clear all accumulated diagnosis.
pub fn clear_diag(&self) {
self.diags.borrow_mut().clear();
}
/// Returns the unknown location.
pub fn unknown_loc(&self) -> Loc {
self.unknown_loc.clone()
}
/// Returns a Move IR version of the unknown location which is guaranteed to map to the
/// regular unknown location via `to_loc`.
pub fn unknown_move_ir_loc(&self) -> MoveIrLoc {
self.unknown_move_ir_loc
}
/// Returns the internal location.
pub fn internal_loc(&self) -> Loc {
self.internal_loc.clone()
}
/// Converts a Loc as used by the move-compiler compiler to the one we are using here.
/// TODO: move-compiler should use FileId as well so we don't need this here. There is already
/// a todo in their code to remove the current use of `&'static str` for file names in Loc.
pub fn to_loc(&self, loc: &MoveIrLoc) -> Loc {
let file_id = self.get_file_id(loc.file_hash()).unwrap_or_else(|| {
panic!(
"Unable to find source file '{}' in the environment",
loc.file_hash()
)
});
Loc {
file_id,
span: Span::new(loc.start(), loc.end()),
}
}
/// Returns the file id for a file name, if defined.
pub fn get_file_id(&self, fhash: FileHash) -> Option<FileId> {
self.file_hash_map.get(&fhash).map(|(_, id)| id).cloned()
}
/// Maps a FileId to an index which can be mapped back to a FileId.
pub fn file_id_to_idx(&self, file_id: FileId) -> u16 {
*self
.file_id_to_idx
.get(&file_id)
.expect("file_id undefined")
}
/// Maps a an index which was obtained by `file_id_to_idx` back to a FileId.
pub fn file_idx_to_id(&self, file_idx: u16) -> FileId {
*self
.file_idx_to_id
.get(&file_idx)
.expect("file_idx undefined")
}
/// Returns file name and line/column position for a location, if available.
pub fn get_file_and_location(&self, loc: &Loc) -> Option<(String, Location)> {
self.get_location(loc).map(|line_column| {
(
self.source_files
.name(loc.file_id())
.to_string_lossy()
.to_string(),
line_column,
)
})
}
/// Returns line/column position for a location, if available.
pub fn get_location(&self, loc: &Loc) -> Option<Location> {
self.source_files
.location(loc.file_id(), loc.span().start())
.ok()
}
/// Return the source text for the given location.
pub fn get_source(&self, loc: &Loc) -> Result<&str, codespan_reporting::files::Error> {
self.source_files.source_slice(loc.file_id, loc.span)
}
/// Return the source file name for `file_id`
pub fn get_file(&self, file_id: FileId) -> &OsStr {
self.source_files.name(file_id)
}
/// Return the source file names.
pub fn get_source_file_names(&self) -> Vec<String> {
self.file_hash_map
.iter()
.filter_map(|(_, (k, _))| {
if k.eq("<internal>") || k.eq("<unknown>") {
None
} else {
Some(k.clone())
}
})
.collect()
}
/// Return the source file ids.
pub fn get_source_file_ids(&self) -> Vec<FileId> {
self.file_hash_map
.iter()
.filter_map(|(_, (k, id))| {
if k.eq("<internal>") || k.eq("<unknown>") {
None
} else {
Some(*id)
}
})
.collect()
}
// Gets the number of source files in this environment.
pub fn get_file_count(&self) -> usize {
self.file_hash_map.len()
}
/// Returns true if diagnostics have error severity or worse.
pub fn has_errors(&self) -> bool {
self.error_count() > 0
}
/// Returns the number of diagnostics.
pub fn diag_count(&self, min_severity: Severity) -> usize {
self.diags
.borrow()
.iter()
.filter(|(d, _)| d.severity >= min_severity)
.count()
}
/// Returns the number of errors.
pub fn error_count(&self) -> usize {
self.diag_count(Severity::Error)
}
/// Returns true if diagnostics have warning severity or worse.
pub fn has_warnings(&self) -> bool {
self.diags
.borrow()
.iter()
.any(|(d, _)| d.severity >= Severity::Warning)
}
/// Writes accumulated diagnostics of given or higher severity.
pub fn report_diag<W: WriteColor>(&self, writer: &mut W, severity: Severity) {
self.report_diag_with_filter(writer, |d| d.severity >= severity)
}
/// Writes accumulated diagnostics that pass through `filter`
pub fn report_diag_with_filter<W: WriteColor, F: Fn(&Diagnostic<FileId>) -> bool>(
&self,
writer: &mut W,
filter: F,
) {
let mut shown = BTreeSet::new();
for (diag, reported) in self
.diags
.borrow_mut()
.iter_mut()
.filter(|(d, _)| filter(d))
{
if !*reported {
// Avoid showing the same message twice. This can happen e.g. because of
// duplication of expressions via schema inclusion.
if shown.insert(format!("{:?}", diag)) {
emit(writer, &Config::default(), &self.source_files, diag)
.expect("emit must not fail");
}
*reported = true;
}
}
}
/// Adds a global invariant to this environment.
pub fn add_global_invariant(&mut self, inv: GlobalInvariant) {
let id = inv.id;
for memory in &inv.mem_usage {
self.global_invariants_for_memory
.entry(memory.clone())
.or_insert_with(BTreeSet::new)
.insert(id);
}
self.global_invariants.insert(id, inv);
}
/// Get global invariant by id.
pub fn get_global_invariant(&self, id: GlobalId) -> Option<&GlobalInvariant> {
self.global_invariants.get(&id)
}
/// Return the global invariants which refer to the given memory.
pub fn get_global_invariants_for_memory(
&self,
memory: &QualifiedInstId<StructId>,
) -> BTreeSet<GlobalId> {
let mut inv_ids = BTreeSet::new();
for (key, val) in &self.global_invariants_for_memory {
if key.module_id != memory.module_id || key.id != memory.id {