-
Notifications
You must be signed in to change notification settings - Fork 199
/
ast.rs
1824 lines (1709 loc) · 52.4 KB
/
ast.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
// SPDX-License-Identifier: Apache-2.0
use super::symtable::Symtable;
use crate::abi::anchor::discriminator;
use crate::codegen::cfg::{ControlFlowGraph, Instr};
use crate::diagnostics::Diagnostics;
use crate::sema::yul::ast::{InlineAssembly, YulFunction};
use crate::sema::Recurse;
use crate::{codegen, Target};
use indexmap::IndexMap;
use num_bigint::BigInt;
use num_rational::BigRational;
use once_cell::unsync::OnceCell;
pub use solang_parser::diagnostics::*;
use solang_parser::pt;
use solang_parser::pt::{CodeLocation, FunctionTy, OptionalCodeLocation};
use std::cell::RefCell;
use std::{
collections::HashSet,
collections::{BTreeMap, HashMap},
fmt, hash,
path::PathBuf,
sync::Arc,
};
use tiny_keccak::{Hasher, Keccak};
#[derive(PartialEq, Eq, Clone, Hash, Debug)]
pub enum Type {
Address(bool),
Bool,
Int(u16),
Uint(u16),
Rational,
Bytes(u8),
DynamicBytes,
String,
Array(Box<Type>, Vec<ArrayLength>),
/// The usize is an index into enums in the namespace
Enum(usize),
/// The usize is an index into contracts in the namespace
Struct(StructType),
Mapping(Mapping),
/// The usize is an index into contracts in the namespace
Contract(usize),
Ref(Box<Type>),
/// Reference to storage, first bool is true for immutables
StorageRef(bool, Box<Type>),
InternalFunction {
mutability: Mutability,
params: Vec<Type>,
returns: Vec<Type>,
},
ExternalFunction {
mutability: Mutability,
params: Vec<Type>,
returns: Vec<Type>,
},
/// User type definitions, e.g. `type Foo is int128;`. The usize
/// is an index into user_types in the namespace.
UserType(usize),
/// There is no way to declare value in Solidity (should there be?)
Value,
Void,
Unreachable,
/// DynamicBytes and String are lowered to a vector.
Slice(Box<Type>),
/// We could not resolve this type
Unresolved,
/// When we advance a pointer, it cannot be any of the previous types.
/// e.g. Type::Bytes is a pointer to struct.vector. When we advance it, it is a pointer
/// to latter's data region.
BufferPointer,
/// The function selector (or discriminator) type is 4 bytes on Polkadot and 8 bytes on Solana
FunctionSelector,
}
#[derive(Eq, Clone, Debug)]
pub struct Mapping {
pub key: Box<Type>,
pub key_name: Option<pt::Identifier>,
pub value: Box<Type>,
pub value_name: Option<pt::Identifier>,
}
// Ensure the key_name and value_name is not used for comparison or hashing
impl PartialEq for Mapping {
fn eq(&self, other: &Mapping) -> bool {
self.key == other.key && self.value == other.value
}
}
impl hash::Hash for Mapping {
fn hash<H: hash::Hasher>(&self, hasher: &mut H) {
self.key.hash(hasher);
self.value.hash(hasher);
}
}
#[derive(PartialEq, Eq, Clone, Hash, Debug)]
pub enum ArrayLength {
Fixed(BigInt),
Dynamic,
/// Fixed length arrays, any length permitted. This is useful for when we
/// do not want dynamic length, but want to permit any length. For example
/// the create_program_address() call takes any number of seeds as its
/// first argument, and we don't want to allocate a dynamic array for
/// this parameter as this would be wasteful to allocate a vector for
/// this argument.
AnyFixed,
}
impl ArrayLength {
/// Get the length, if fixed
pub fn array_length(&self) -> Option<&BigInt> {
match self {
ArrayLength::Fixed(len) => Some(len),
_ => None,
}
}
}
pub trait RetrieveType {
/// Return the type for this expression. This assumes the expression has a single value,
/// panics will occur otherwise
fn ty(&self) -> Type;
}
impl Type {
pub fn get_type_size(&self) -> u16 {
match self {
Type::Int(n) | Type::Uint(n) => *n,
Type::Bool => 1,
_ => unimplemented!("size of type not known"),
}
}
pub fn unwrap_user_type(self, ns: &Namespace) -> Type {
if let Type::UserType(type_no) = self {
ns.user_types[type_no].ty.clone()
} else {
self
}
}
}
#[derive(PartialEq, Eq, Clone, Debug, Copy, Hash)]
pub enum StructType {
UserDefined(usize),
AccountInfo,
AccountMeta,
ExternalFunction,
SolParameters,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct StructDecl {
pub tags: Vec<Tag>,
pub name: String,
pub loc: pt::Loc,
pub contract: Option<String>,
pub fields: Vec<Parameter>,
// List of offsets of the fields, last entry is the offset for the struct overall size
pub offsets: Vec<BigInt>,
// Same, but now in storage
pub storage_offsets: Vec<BigInt>,
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct EventDecl {
pub tags: Vec<Tag>,
pub name: String,
pub loc: pt::Loc,
pub contract: Option<usize>,
pub fields: Vec<Parameter>,
pub signature: String,
pub anonymous: bool,
pub used: bool,
}
impl EventDecl {
pub fn symbol_name(&self, ns: &Namespace) -> String {
match &self.contract {
Some(c) => format!("{}.{}", ns.contracts[*c].name, self.name),
None => self.name.to_string(),
}
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct ErrorDecl {
pub tags: Vec<Tag>,
pub name: String,
pub loc: pt::Loc,
pub contract: Option<usize>,
pub fields: Vec<Parameter>,
pub used: bool,
}
impl ErrorDecl {
pub fn symbol_name(&self, ns: &Namespace) -> String {
match &self.contract {
Some(c) => format!("{}.{}", ns.contracts[*c].name, self.name),
None => self.name.to_string(),
}
}
}
impl fmt::Display for StructDecl {
/// Make the struct name into a string for printing. The struct can be declared either
/// inside or outside a contract.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.contract {
Some(c) => write!(f, "{}.{}", c, self.name),
None => write!(f, "{}", self.name),
}
}
}
#[derive(Debug)]
pub struct EnumDecl {
pub tags: Vec<Tag>,
pub name: String,
pub contract: Option<String>,
pub loc: pt::Loc,
pub ty: Type,
pub values: IndexMap<String, pt::Loc>,
}
impl fmt::Display for EnumDecl {
/// Make the enum name into a string for printing. The enum can be declared either
/// inside or outside a contract.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.contract {
Some(c) => write!(f, "{}.{}", c, self.name),
None => write!(f, "{}", self.name),
}
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Parameter {
pub loc: pt::Loc,
/// The name can empty (e.g. in an event field or unnamed parameter/return)
pub id: Option<pt::Identifier>,
pub ty: Type,
/// Yul function parameters may not have a type identifier
pub ty_loc: Option<pt::Loc>,
/// Event fields may indexed, which means they are sent to the log
pub indexed: bool,
/// Some builtin structs have readonly fields
pub readonly: bool,
/// A recursive struct may contain itself which make the struct infinite size in memory.
pub infinite_size: bool,
/// Is this struct field recursive. Recursive does not mean infinite size in all cases:
/// `struct S { S[] s }` is recursive but not of infinite size.
pub recursive: bool,
pub annotation: Option<ParameterAnnotation>,
}
#[derive(Debug, Eq, Clone, PartialEq)]
pub struct ParameterAnnotation {
pub loc: pt::Loc,
pub id: pt::Identifier,
}
impl Parameter {
pub fn name_as_str(&self) -> &str {
if let Some(name) = &self.id {
name.name.as_str()
} else {
""
}
}
}
#[derive(PartialEq, Eq, Clone, Hash, Debug)]
pub enum Mutability {
Payable(pt::Loc),
Nonpayable(pt::Loc),
View(pt::Loc),
Pure(pt::Loc),
}
impl Mutability {
pub fn is_default(&self) -> bool {
matches!(self, Mutability::Nonpayable(_))
}
}
impl fmt::Display for Mutability {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Mutability::Pure(_) => write!(f, "pure"),
Mutability::View(_) => write!(f, "view"),
Mutability::Nonpayable(_) => write!(f, "nonpayable"),
Mutability::Payable(_) => write!(f, "payable"),
}
}
}
#[derive(Debug)]
pub struct Function {
pub tags: Vec<Tag>,
/// The location of the prototype (not body)
pub loc: pt::Loc,
pub name: String,
pub contract_no: Option<usize>,
pub ty: pt::FunctionTy,
pub signature: String,
pub mutability: Mutability,
pub visibility: pt::Visibility,
pub params: Arc<Vec<Parameter>>,
pub returns: Arc<Vec<Parameter>>,
/// Constructor arguments for base contracts, only present on constructors
pub bases: BTreeMap<usize, (pt::Loc, usize, Vec<Expression>)>,
/// Modifiers for functions
pub modifiers: Vec<Expression>,
pub is_virtual: bool,
/// Is this function an acccesor function created by a public variable
pub is_accessor: bool,
pub is_override: Option<(pt::Loc, Vec<usize>)>,
/// The selector (known as discriminator on Solana/Anchor)
pub selector: Option<(pt::Loc, Vec<u8>)>,
/// Was the function declared with a body
pub has_body: bool,
/// The resolved body (if any)
pub body: Vec<Statement>,
pub symtable: Symtable,
/// What events are emitted by the body of this function
pub emits_events: Vec<usize>,
/// For overloaded functions this is the mangled (unique) name.
pub mangled_name: String,
/// Solana constructors may have seeds specified using @seed tags
pub annotations: Vec<ConstructorAnnotation>,
/// Which contracts should we use the mangled name in?
pub mangled_name_contracts: HashSet<usize>,
/// This indexmap stores the accounts this functions needs to be called on Solana
/// The string is the account's name
pub solana_accounts: RefCell<IndexMap<String, SolanaAccount>>,
}
/// This struct represents a Solana account. There is no name field, because
/// it is stored in a IndexMap<String, SolanaAccount> (see above)
#[derive(Clone, Copy, Debug)]
pub struct SolanaAccount {
pub loc: pt::Loc,
pub is_signer: bool,
pub is_writer: bool,
/// Has the compiler automatically generated this account entry?
pub generated: bool,
}
#[derive(Debug)]
pub enum ConstructorAnnotation {
Seed(Expression),
Payer(pt::Loc, String),
Space(Expression),
Bump(Expression),
}
impl CodeLocation for ConstructorAnnotation {
fn loc(&self) -> pt::Loc {
match self {
ConstructorAnnotation::Seed(expr)
| ConstructorAnnotation::Space(expr)
| ConstructorAnnotation::Bump(expr) => expr.loc(),
ConstructorAnnotation::Payer(loc, _) => *loc,
}
}
}
/// This trait provides a single interface for fetching paramenters, returns and the symbol table
/// for both yul and solidity functions
pub trait FunctionAttributes {
fn get_symbol_table(&self) -> &Symtable;
fn get_parameters(&self) -> &Vec<Parameter>;
fn get_returns(&self) -> &Vec<Parameter>;
}
impl FunctionAttributes for Function {
fn get_symbol_table(&self) -> &Symtable {
&self.symtable
}
fn get_parameters(&self) -> &Vec<Parameter> {
&self.params
}
fn get_returns(&self) -> &Vec<Parameter> {
&self.returns
}
}
impl Function {
pub fn new(
loc: pt::Loc,
name: String,
contract_no: Option<usize>,
tags: Vec<Tag>,
ty: pt::FunctionTy,
mutability: Option<pt::Mutability>,
visibility: pt::Visibility,
params: Vec<Parameter>,
returns: Vec<Parameter>,
ns: &Namespace,
) -> Self {
let signature = match ty {
pt::FunctionTy::Fallback => String::from("@fallback"),
pt::FunctionTy::Receive => String::from("@receive"),
_ => ns.signature(&name, ¶ms),
};
let mutability = match mutability {
None => Mutability::Nonpayable(loc),
Some(pt::Mutability::Payable(loc)) => Mutability::Payable(loc),
Some(pt::Mutability::Pure(loc)) => Mutability::Pure(loc),
Some(pt::Mutability::View(loc)) => Mutability::View(loc),
Some(pt::Mutability::Constant(loc)) => Mutability::View(loc),
};
let mangled_name = signature
.replace('(', "_")
.replace(')', "")
.replace(',', "_")
.replace("[]", "Array")
.replace('[', "Array")
.replace(']', "");
Function {
tags,
loc,
name,
contract_no,
ty,
signature,
mutability,
visibility,
params: Arc::new(params),
returns: Arc::new(returns),
bases: BTreeMap::new(),
modifiers: Vec::new(),
selector: None,
is_virtual: false,
is_accessor: false,
has_body: false,
is_override: None,
body: Vec::new(),
symtable: Symtable::new(),
emits_events: Vec::new(),
mangled_name,
annotations: Vec::new(),
mangled_name_contracts: HashSet::new(),
solana_accounts: IndexMap::new().into(),
}
}
/// Generate selector for this function
pub fn selector(&self, ns: &Namespace, contract_no: &usize) -> Vec<u8> {
if let Some((_, selector)) = &self.selector {
selector.clone()
} else if ns.target == Target::Solana {
match self.ty {
FunctionTy::Constructor => discriminator("global", "new"),
_ => {
let discriminator_image = if self.mangled_name_contracts.contains(contract_no) {
&self.mangled_name
} else {
&self.name
};
discriminator("global", discriminator_image.as_str())
}
}
} else {
let mut res = [0u8; 32];
let mut hasher = Keccak::v256();
hasher.update(self.signature.as_bytes());
hasher.finalize(&mut res);
res[..4].to_vec()
}
}
/// Is this a constructor
pub fn is_constructor(&self) -> bool {
self.ty == pt::FunctionTy::Constructor
}
/// Does this function have the payable state
pub fn is_payable(&self) -> bool {
matches!(self.mutability, Mutability::Payable(_))
}
/// Does this function have an @payer annotation?
pub fn has_payer_annotation(&self) -> bool {
self.annotations
.iter()
.any(|note| matches!(note, ConstructorAnnotation::Payer(..)))
}
/// Does this function have an @seed annotation?
pub fn has_seed_annotation(&self) -> bool {
self.annotations
.iter()
.any(|note| matches!(note, ConstructorAnnotation::Seed(..)))
}
/// Does this function have the pure state
pub fn is_pure(&self) -> bool {
matches!(self.mutability, Mutability::Pure(_))
}
/// Is this function visible externally, based on it's visibilty modifiers.
///
/// Due to inheritance, this alone does not determine whether a function is
/// externally callable in the final contract artifact; for that, use
/// `Namespace::function_externally_callable()` instead.
pub fn is_public(&self) -> bool {
matches!(
self.visibility,
pt::Visibility::Public(_) | pt::Visibility::External(_)
)
}
/// Is this function accessable only from same contract
pub fn is_private(&self) -> bool {
matches!(self.visibility, pt::Visibility::Private(_))
}
/// Print the function type, contract name, and name
pub fn print_name(&self, ns: &Namespace) -> String {
if let Some(contract_no) = &self.contract_no {
format!(
"{} {}.{}",
self.ty, ns.contracts[*contract_no].name, self.name
)
} else {
format!("{} {}", self.ty, self.name)
}
}
}
impl From<&pt::Type> for Type {
fn from(p: &pt::Type) -> Type {
match p {
pt::Type::Bool => Type::Bool,
pt::Type::Address => Type::Address(false),
pt::Type::AddressPayable => Type::Address(true),
pt::Type::Payable => Type::Address(true),
pt::Type::Int(n) => Type::Int(*n),
pt::Type::Uint(n) => Type::Uint(*n),
pt::Type::Bytes(n) => Type::Bytes(*n),
pt::Type::String => Type::String,
pt::Type::Rational => Type::Rational,
pt::Type::DynamicBytes => Type::DynamicBytes,
// needs special casing
pt::Type::Function { .. } | pt::Type::Mapping { .. } => unimplemented!(),
}
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct UserTypeDecl {
pub tags: Vec<Tag>,
pub loc: pt::Loc,
pub name: String,
pub ty: Type,
pub contract: Option<String>,
}
impl fmt::Display for UserTypeDecl {
/// Make the user type name into a string for printing. The user type can
/// be declared either inside or outside a contract.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.contract {
Some(c) => write!(f, "{}.{}", c, self.name),
None => write!(f, "{}", self.name),
}
}
}
#[derive(Debug)]
pub struct Variable {
pub tags: Vec<Tag>,
pub name: String,
pub loc: pt::Loc,
pub ty: Type,
pub visibility: pt::Visibility,
pub constant: bool,
pub immutable: bool,
pub initializer: Option<Expression>,
pub assigned: bool,
pub read: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Symbol {
Enum(pt::Loc, usize),
Function(Vec<(pt::Loc, usize)>),
Variable(pt::Loc, Option<usize>, usize),
Struct(pt::Loc, StructType),
Event(Vec<(pt::Loc, usize)>),
Error(pt::Loc, usize),
Contract(pt::Loc, usize),
Import(pt::Loc, usize),
UserType(pt::Loc, usize),
}
impl CodeLocation for Symbol {
fn loc(&self) -> pt::Loc {
match self {
Symbol::Enum(loc, _)
| Symbol::Variable(loc, ..)
| Symbol::Struct(loc, _)
| Symbol::Contract(loc, _)
| Symbol::Import(loc, _)
| Symbol::Error(loc, _)
| Symbol::UserType(loc, _) => *loc,
Symbol::Event(items) | Symbol::Function(items) => items[0].0,
}
}
}
impl Symbol {
/// Is this symbol for an event
pub fn is_event(&self) -> bool {
matches!(self, Symbol::Event(_))
}
/// Does this symbol have an accessor function
pub fn has_accessor(&self, ns: &Namespace) -> bool {
if let Symbol::Variable(_, Some(contract_no), var_no) = self {
matches!(
ns.contracts[*contract_no].variables[*var_no].visibility,
pt::Visibility::Public(_)
)
} else {
false
}
}
/// Is this a private symbol
pub fn is_private_variable(&self, ns: &Namespace) -> bool {
match self {
Symbol::Variable(_, Some(contract_no), var_no) => {
let visibility = &ns.contracts[*contract_no].variables[*var_no].visibility;
matches!(visibility, pt::Visibility::Private(_))
}
_ => false,
}
}
}
/// Any Solidity file, either the main file or anything that was imported
#[derive(Clone, Debug)]
pub struct File {
/// The on-disk filename
pub path: PathBuf,
/// Used for offset to line-column conversions
pub line_starts: Vec<usize>,
/// Indicates the file number in FileResolver.files
pub cache_no: Option<usize>,
/// Index into FileResolver.import_paths. This is `None` when this File was
/// created not during `parse_and_resolve` (e.g., builtins)
pub import_no: Option<usize>,
}
/// When resolving a Solidity file, this holds all the resolved items
#[derive(Debug)]
pub struct Namespace {
pub target: Target,
pub files: Vec<File>,
pub enums: Vec<EnumDecl>,
pub structs: Vec<StructDecl>,
pub events: Vec<EventDecl>,
pub errors: Vec<ErrorDecl>,
pub contracts: Vec<Contract>,
/// Global using declarations
pub using: Vec<Using>,
/// All type declarations
pub user_types: Vec<UserTypeDecl>,
/// All functions
pub functions: Vec<Function>,
/// Yul functions
pub yul_functions: Vec<YulFunction>,
/// Global constants
pub constants: Vec<Variable>,
/// address length in bytes
pub address_length: usize,
/// value length in bytes
pub value_length: usize,
pub diagnostics: Diagnostics,
/// There is a separate namespace for functions and non-functions
pub function_symbols: HashMap<(usize, Option<usize>, String), Symbol>,
/// Symbol key is file_no, contract, identifier
pub variable_symbols: HashMap<(usize, Option<usize>, String), Symbol>,
// each variable in the symbol table should have a unique number
pub next_id: usize,
/// For a variable reference at a location, give the constant value
/// This for use by the language server to show the value of a variable at a location
pub var_constants: HashMap<pt::Loc, codegen::Expression>,
/// Overrides for hover in the language server
pub hover_overrides: HashMap<pt::Loc, String>,
}
#[derive(Debug)]
pub struct Layout {
pub slot: BigInt,
pub contract_no: usize,
pub var_no: usize,
pub ty: Type,
}
#[derive(Debug)]
pub struct Base {
pub loc: pt::Loc,
pub contract_no: usize,
pub constructor: Option<(usize, Vec<Expression>)>,
}
#[derive(Debug)]
pub struct Using {
pub list: UsingList,
pub ty: Option<Type>,
pub file_no: Option<usize>,
}
#[derive(Debug)]
pub enum UsingList {
Library(usize),
Functions(Vec<UsingFunction>),
}
/// Using binding for a function, optionally for an operator
#[derive(Debug)]
pub struct UsingFunction {
pub loc: pt::Loc,
pub function_no: usize,
pub oper: Option<pt::UserDefinedOperator>,
}
#[derive(Debug)]
pub struct Contract {
pub tags: Vec<Tag>,
pub loc: pt::Loc,
pub ty: pt::ContractTy,
pub name: String,
pub bases: Vec<Base>,
pub using: Vec<Using>,
pub layout: Vec<Layout>,
pub fixed_layout_size: BigInt,
pub functions: Vec<usize>,
pub all_functions: BTreeMap<usize, usize>,
pub virtual_functions: HashMap<String, usize>,
pub yul_functions: Vec<usize>,
pub variables: Vec<Variable>,
/// List of contracts this contract instantiates
pub creates: Vec<usize>,
/// List of events this contract may emit
pub emits_events: Vec<usize>,
pub initializer: Option<usize>,
pub default_constructor: Option<(Function, usize)>,
pub cfg: Vec<ControlFlowGraph>,
/// Compiled program. Only available after emit.
pub code: OnceCell<Vec<u8>>,
/// Can the contract be instantiated, i.e. not abstract, no errors, etc.
pub instantiable: bool,
/// Account of deployed program code on Solana
pub program_id: Option<Vec<u8>>,
}
impl Contract {
// Is this a concrete contract, which can be instantiated
pub fn is_concrete(&self) -> bool {
matches!(self.ty, pt::ContractTy::Contract(_))
}
// Is this an interface
pub fn is_interface(&self) -> bool {
matches!(self.ty, pt::ContractTy::Interface(_))
}
// Is this an library
pub fn is_library(&self) -> bool {
matches!(self.ty, pt::ContractTy::Library(_))
}
/// Does the constructor require arguments. Should be false is there is no constructor
pub fn constructor_needs_arguments(&self, ns: &Namespace) -> bool {
self.have_constructor(ns) && self.no_args_constructor(ns).is_none()
}
/// Does the contract have a constructor defined
pub fn have_constructor(&self, ns: &Namespace) -> bool {
self.functions
.iter()
.any(|func_no| ns.functions[*func_no].is_constructor())
}
/// Return the constructor with no arguments
pub fn no_args_constructor(&self, ns: &Namespace) -> Option<usize> {
self.functions
.iter()
.find(|func_no| {
let func = &ns.functions[**func_no];
func.is_constructor() && func.params.is_empty()
})
.cloned()
}
}
#[derive(PartialEq, Eq, Clone, Debug)]
pub enum Expression {
BoolLiteral {
loc: pt::Loc,
value: bool,
},
BytesLiteral {
loc: pt::Loc,
ty: Type,
value: Vec<u8>,
},
CodeLiteral {
loc: pt::Loc,
contract_no: usize,
// runtime code rather than deployer (evm only)
runtime: bool,
},
NumberLiteral {
loc: pt::Loc,
ty: Type,
value: BigInt,
},
RationalNumberLiteral {
loc: pt::Loc,
ty: Type,
value: BigRational,
},
StructLiteral {
loc: pt::Loc,
ty: Type,
values: Vec<Expression>,
},
ArrayLiteral {
loc: pt::Loc,
ty: Type,
dimensions: Vec<u32>,
values: Vec<Expression>,
},
ConstArrayLiteral {
loc: pt::Loc,
ty: Type,
dimensions: Vec<u32>,
values: Vec<Expression>,
},
Add {
loc: pt::Loc,
ty: Type,
/// Do not check for overflow, i.e. in `unchecked {}` block
unchecked: bool,
left: Box<Expression>,
right: Box<Expression>,
},
Subtract {
loc: pt::Loc,
ty: Type,
/// Do not check for overflow, i.e. in `unchecked {}` block
unchecked: bool,
left: Box<Expression>,
right: Box<Expression>,
},
Multiply {
loc: pt::Loc,
ty: Type,
/// Do not check for overflow, i.e. in `unchecked {}` block
unchecked: bool,
left: Box<Expression>,
right: Box<Expression>,
},
Divide {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
Modulo {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
Power {
loc: pt::Loc,
ty: Type,
/// Do not check for overflow, i.e. in `unchecked {}` block
unchecked: bool,
base: Box<Expression>,
exp: Box<Expression>,
},
BitwiseOr {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
BitwiseAnd {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
BitwiseXor {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
ShiftLeft {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
},
ShiftRight {
loc: pt::Loc,
ty: Type,
left: Box<Expression>,
right: Box<Expression>,
sign: bool,
},
Variable {
loc: pt::Loc,
ty: Type,
var_no: usize,
},
ConstantVariable {
loc: pt::Loc,
ty: Type,
contract_no: Option<usize>,
var_no: usize,
},
StorageVariable {
loc: pt::Loc,
ty: Type,
contract_no: usize,
var_no: usize,
},
Load {
loc: pt::Loc,
ty: Type,
expr: Box<Expression>,
},
GetRef {
loc: pt::Loc,
ty: Type,
expr: Box<Expression>,
},
StorageLoad {
loc: pt::Loc,
ty: Type,
expr: Box<Expression>,
},
ZeroExt {
loc: pt::Loc,
to: Type,
expr: Box<Expression>,
},
SignExt {
loc: pt::Loc,
to: Type,
expr: Box<Expression>,
},
Trunc {
loc: pt::Loc,
to: Type,
expr: Box<Expression>,
},
CheckingTrunc {
loc: pt::Loc,
to: Type,
expr: Box<Expression>,
},
Cast {
loc: pt::Loc,
to: Type,
expr: Box<Expression>,
},
BytesCast {
loc: pt::Loc,
from: Type,
to: Type,
expr: Box<Expression>,
},
PreIncrement {
loc: pt::Loc,
ty: Type,
/// Do not check for overflow, i.e. in `unchecked {}` block