-
Notifications
You must be signed in to change notification settings - Fork 200
/
cfg.rs
2179 lines (2036 loc) · 72.1 KB
/
cfg.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::statements::{statement, LoopScopes};
use super::{
constant_folding, dead_storage,
expression::expression,
reaching_definitions, strength_reduce,
vartable::{Vars, Vartable},
vector_to_slice, Options,
};
use crate::codegen::subexpression_elimination::common_sub_expression_elimination;
use crate::codegen::{undefined_variable, Expression, LLVMName};
use crate::sema::ast::{
CallTy, Contract, FunctionAttributes, Namespace, Parameter, RetrieveType, Statement,
StringLocation, StructType, Type,
};
use crate::sema::{contracts::collect_base_args, diagnostics::Diagnostics, Recurse};
use crate::{sema::ast, Target};
use indexmap::IndexMap;
use num_bigint::BigInt;
use num_traits::One;
use parse_display::Display;
use solang_parser::pt::CodeLocation;
use solang_parser::pt::Loc;
use solang_parser::pt::{self, FunctionTy};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::ops::AddAssign;
use std::str;
use std::sync::Arc;
use std::{fmt, fmt::Write};
// IndexMap <ArrayVariable res , res of temp variable>
pub type ArrayLengthVars = IndexMap<usize, usize>;
#[derive(Debug, Clone)]
#[allow(clippy::large_enum_variant)]
pub enum Instr {
/// Set variable
Set {
loc: pt::Loc,
res: usize,
expr: Expression,
},
/// Call internal function, either static dispatch or dynamic dispatch
Call {
res: Vec<usize>,
return_tys: Vec<Type>,
call: InternalCallTy,
args: Vec<Expression>,
},
/// Return
Return { value: Vec<Expression> },
/// Jump unconditionally
Branch { block: usize },
/// Jump conditionally
BranchCond {
cond: Expression,
true_block: usize,
false_block: usize,
},
/// Set array element in memory
Store { dest: Expression, data: Expression },
/// Abort execution
AssertFailure { encoded_args: Option<Expression> },
/// Print to log message
Print { expr: Expression },
/// Load storage (this is an instruction rather than an expression
/// so that it can be moved around by the dead storage pass
LoadStorage {
res: usize,
ty: Type,
storage: Expression,
},
/// Clear storage at slot for ty (might span multiple slots)
ClearStorage { ty: Type, storage: Expression },
/// Set storage value at slot
SetStorage {
ty: Type,
value: Expression,
storage: Expression,
},
/// In storage slot, set the value at the offset
SetStorageBytes {
value: Expression,
storage: Expression,
offset: Expression,
},
/// Push an element onto an array in storage
PushStorage {
res: usize,
ty: Type,
value: Option<Expression>,
storage: Expression,
},
/// Pop an element from an array in storage
PopStorage {
res: Option<usize>,
ty: Type,
storage: Expression,
},
/// Push element on memory array
PushMemory {
res: usize,
ty: Type,
array: usize,
value: Box<Expression>,
},
/// Pop element from memory array. The push builtin returns a reference
/// to the new element which is stored in res.
PopMemory {
res: usize,
ty: Type,
array: usize,
loc: Loc,
},
/// Create contract and call constructor. If creating the contract fails,
/// either store the result in success or abort success.
Constructor {
success: Option<usize>,
res: usize,
contract_no: usize,
constructor_no: Option<usize>,
encoded_args: Expression,
value: Option<Expression>,
gas: Expression,
salt: Option<Expression>,
address: Option<Expression>,
seeds: Option<Expression>,
accounts: Option<Expression>,
loc: Loc,
},
/// Call external functions. If the call fails, set the success failure
/// or abort if this is None
ExternalCall {
success: Option<usize>,
address: Option<Expression>,
accounts: Option<Expression>,
seeds: Option<Expression>,
payload: Expression,
value: Expression,
gas: Expression,
callty: CallTy,
contract_function_no: Option<(usize, usize)>,
flags: Option<Expression>,
},
/// Value transfer; either address.send() or address.transfer()
ValueTransfer {
success: Option<usize>,
address: Expression,
value: Expression,
},
/// Self destruct
SelfDestruct { recipient: Expression },
/// Emit event
EmitEvent {
event_no: usize,
data: Expression,
topics: Vec<Expression>,
},
/// Write Buffer
WriteBuffer {
buf: Expression,
offset: Expression,
value: Expression,
},
/// Copy bytes from source address to destination address
MemCopy {
source: Expression,
destination: Expression,
bytes: Expression,
},
Switch {
cond: Expression,
cases: Vec<(Expression, usize)>,
default: usize,
},
/// Do nothing
Nop,
/// Return AbiEncoded data via an environment system call
ReturnData {
data: Expression,
data_len: Expression,
},
/// Return a code at the end of a function
ReturnCode { code: ReturnCode },
/// For unimplemented code, e.g. unsupported yul builtins. This instruction should
/// only occur for the evm target, for which no emit is implemented yet. Once evm emit
/// is implemented and all yul builtins are supported, this instruction should
/// be removed. We only have this so we can pass evm code through sema/codegen, which is used
/// by the language server and the ethereum solidity tests.
Unimplemented { reachable: bool },
/// This instruction serves to track account accesses through 'tx.accounts.my_account'
/// on Solana, and has no emit implementation. It is exchanged by the proper
/// Expression::Subscript at solana_accounts/account_management.rs
AccountAccess {
loc: pt::Loc,
var_no: usize,
name: String,
},
}
/// This struct defined the return codes that we send to the execution environment when we return
/// from a function.
#[derive(PartialEq, Eq, Hash, Clone, Debug, Display)]
#[display(style = "title case")]
pub enum ReturnCode {
Success,
FunctionSelectorInvalid,
AbiEncodingInvalid,
InvalidDataError,
AccountDataTooSmall,
InvalidProgramId,
}
impl Instr {
pub fn recurse_expressions<T>(
&self,
cx: &mut T,
f: fn(expr: &Expression, ctx: &mut T) -> bool,
) {
match self {
Instr::BranchCond { cond: expr, .. }
| Instr::LoadStorage { storage: expr, .. }
| Instr::ClearStorage { storage: expr, .. }
| Instr::Print { expr }
| Instr::AssertFailure {
encoded_args: Some(expr),
}
| Instr::PopStorage { storage: expr, .. }
| Instr::SelfDestruct { recipient: expr }
| Instr::Set { expr, .. } => {
expr.recurse(cx, f);
}
Instr::PushMemory { value: expr, .. } => {
expr.recurse(cx, f);
}
Instr::SetStorage {
value: item_1,
storage: item_2,
..
}
| Instr::Store {
dest: item_1,
data: item_2,
}
| Instr::ReturnData {
data: item_1,
data_len: item_2,
} => {
item_1.recurse(cx, f);
item_2.recurse(cx, f);
}
Instr::PushStorage { value, storage, .. } => {
if let Some(value) = value {
value.recurse(cx, f);
}
storage.recurse(cx, f);
}
Instr::SetStorageBytes {
value,
storage,
offset,
} => {
value.recurse(cx, f);
storage.recurse(cx, f);
offset.recurse(cx, f);
}
Instr::Return { value: exprs } | Instr::Call { args: exprs, .. } => {
for expr in exprs {
expr.recurse(cx, f);
}
}
Instr::Constructor {
encoded_args,
value,
gas,
salt,
address,
accounts,
..
} => {
encoded_args.recurse(cx, f);
if let Some(expr) = value {
expr.recurse(cx, f);
}
gas.recurse(cx, f);
if let Some(expr) = salt {
expr.recurse(cx, f);
}
if let Some(expr) = address {
expr.recurse(cx, f);
}
if let Some(expr) = accounts {
expr.recurse(cx, f);
}
}
Instr::ExternalCall {
address,
payload,
value,
gas,
..
} => {
if let Some(expr) = address {
expr.recurse(cx, f);
}
payload.recurse(cx, f);
value.recurse(cx, f);
gas.recurse(cx, f);
}
Instr::ValueTransfer { address, value, .. } => {
address.recurse(cx, f);
value.recurse(cx, f);
}
Instr::EmitEvent { data, topics, .. } => {
data.recurse(cx, f);
for expr in topics {
expr.recurse(cx, f);
}
}
Instr::WriteBuffer { offset, value, .. } => {
value.recurse(cx, f);
offset.recurse(cx, f);
}
Instr::MemCopy {
source: from,
destination: to,
bytes,
} => {
from.recurse(cx, f);
to.recurse(cx, f);
bytes.recurse(cx, f);
}
Instr::Switch { cond, cases, .. } => {
cond.recurse(cx, f);
for (case, _) in cases {
case.recurse(cx, f);
}
}
Instr::AssertFailure { encoded_args: None }
| Instr::Nop
| Instr::ReturnCode { .. }
| Instr::Branch { .. }
| Instr::AccountAccess { .. }
| Instr::PopMemory { .. }
| Instr::Unimplemented { .. } => {}
}
}
}
#[derive(Clone, Debug)]
#[allow(clippy::large_enum_variant)]
pub enum InternalCallTy {
Static { cfg_no: usize },
Dynamic(Expression),
Builtin { ast_func_no: usize },
}
#[derive(Clone, PartialEq, Eq)]
pub enum HashTy {
Keccak256,
Ripemd160,
Sha256,
Blake2_256,
Blake2_128,
}
impl fmt::Display for HashTy {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match self {
HashTy::Keccak256 => write!(f, "keccak256"),
HashTy::Ripemd160 => write!(f, "ripemd160"),
HashTy::Sha256 => write!(f, "sha256"),
HashTy::Blake2_128 => write!(f, "blake2_128"),
HashTy::Blake2_256 => write!(f, "blake2_256"),
}
}
}
#[derive(Debug, Clone, Default)]
pub struct BasicBlock {
pub phis: Option<BTreeSet<usize>>,
pub name: String,
pub instr: Vec<Instr>,
pub defs: reaching_definitions::VarDefs,
pub loop_reaching_variables: HashSet<usize>,
pub transfers: Vec<Vec<reaching_definitions::Transfer>>,
}
#[derive(Debug, Clone)]
pub struct ControlFlowGraph {
pub name: String,
pub function_no: ASTFunction,
pub params: Arc<Vec<Parameter>>,
pub returns: Arc<Vec<Parameter>>,
pub vars: Vars,
pub blocks: Vec<BasicBlock>,
pub nonpayable: bool,
pub public: bool,
pub ty: pt::FunctionTy,
pub selector: Vec<u8>,
current: usize,
// A mapping between the res of an array and the res of the temp var holding its length.
pub array_lengths_temps: ArrayLengthVars,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ASTFunction {
SolidityFunction(usize),
YulFunction(usize),
None,
}
impl BasicBlock {
/// Fetch the blocks that can be executed after the block passed as argument
pub fn successors(&self) -> Vec<usize> {
let mut out = Vec::new();
// out cfg has edge as the last instruction in a block
for (i, instr) in self.instr.iter().rev().enumerate() {
match instr {
Instr::Branch { block } => {
assert_eq!(i, 0, "Branch is not last instruction in block");
out.push(*block);
}
Instr::BranchCond {
true_block,
false_block,
..
} => {
assert_eq!(i, 0, "BranchCond is not last instruction in block");
out.push(*true_block);
out.push(*false_block);
}
Instr::Switch { default, cases, .. } => {
assert_eq!(i, 0, "Switch is not last instruction in block");
out.push(*default);
for (_, goto) in cases {
out.push(*goto);
}
}
Instr::AssertFailure { .. }
| Instr::SelfDestruct { .. }
| Instr::ReturnCode { .. }
| Instr::ReturnData { .. }
| Instr::Return { .. }
| Instr::Unimplemented { reachable: false } => {
assert_eq!(i, 0, "instruction should be last in block");
}
_ => {
assert_ne!(i, 0, "instruction should not be last in block");
}
}
}
out
}
}
impl ControlFlowGraph {
pub fn new(name: String, function_no: ASTFunction) -> Self {
let mut cfg = ControlFlowGraph {
name,
function_no,
params: Arc::new(Vec::new()),
returns: Arc::new(Vec::new()),
vars: IndexMap::new(),
blocks: Vec::new(),
nonpayable: false,
public: false,
ty: pt::FunctionTy::Function,
selector: Vec::new(),
current: 0,
array_lengths_temps: IndexMap::new(),
};
cfg.new_basic_block("entry".to_string());
cfg
}
/// Create an empty CFG which will be replaced later
pub fn placeholder() -> Self {
ControlFlowGraph {
name: String::new(),
function_no: ASTFunction::None,
params: Arc::new(Vec::new()),
returns: Arc::new(Vec::new()),
vars: IndexMap::new(),
blocks: Vec::new(),
nonpayable: false,
public: false,
ty: pt::FunctionTy::Function,
selector: Vec::new(),
current: 0,
array_lengths_temps: IndexMap::new(),
}
}
/// Is this a placeholder
pub fn is_placeholder(&self) -> bool {
self.blocks.is_empty()
}
pub fn new_basic_block(&mut self, name: String) -> usize {
let pos = self.blocks.len();
self.blocks.push(BasicBlock {
name,
instr: Vec::new(),
phis: None,
transfers: Vec::new(),
defs: IndexMap::new(),
loop_reaching_variables: HashSet::new(),
});
pos
}
pub fn set_phis(&mut self, block: usize, phis: BTreeSet<usize>) {
if !phis.is_empty() {
self.blocks[block].phis = Some(phis);
}
}
pub fn set_basic_block(&mut self, pos: usize) {
self.current = pos;
}
/// Add an instruction to the CFG
pub fn add(&mut self, vartab: &mut Vartable, ins: Instr) {
if let Instr::Set { res, .. } = ins {
vartab.set_dirty(res);
}
self.blocks[self.current].instr.push(ins);
}
/// Retrieve the basic block being processed
pub fn current_block(&self) -> usize {
self.current
}
/// Function to modify array length temp by inserting an add/sub instruction in the cfg right after a push/pop instruction.
/// The operands of the add/sub instruction are the temp variable, and +/- 1.
pub fn modify_temp_array_length(
&mut self,
loc: pt::Loc,
minus: bool, // If the function is called from pushMemory or popMemory
array_pos: usize, // The res of array that push/pop is performed on
vartab: &mut Vartable,
) {
// If not empty
if self.array_lengths_temps.contains_key(&array_pos) {
let to_add = self.array_lengths_temps[&array_pos];
let add_expr = if minus {
Expression::Subtract {
loc,
ty: Type::Uint(32),
overflowing: true,
left: Box::new(Expression::Variable {
loc,
ty: Type::Uint(32),
var_no: to_add,
}),
right: Box::new(Expression::NumberLiteral {
loc,
ty: Type::Uint(32),
value: BigInt::one(),
}),
}
} else {
Expression::Add {
loc,
ty: Type::Uint(32),
overflowing: true,
left: Box::new(Expression::Variable {
loc,
ty: Type::Uint(32),
var_no: to_add,
}),
right: Box::new(Expression::NumberLiteral {
loc,
ty: Type::Uint(32),
value: BigInt::one(),
}),
}
};
// Add instruction to the cfg
self.add(
vartab,
Instr::Set {
loc,
res: to_add,
expr: add_expr,
},
);
}
}
pub fn expr_to_string(&self, contract: &Contract, ns: &Namespace, expr: &Expression) -> String {
match expr {
Expression::FunctionArg { arg_no, .. } => format!("(arg #{arg_no})"),
Expression::BoolLiteral { value: false, .. } => "false".to_string(),
Expression::BoolLiteral { value: true, .. } => "true".to_string(),
Expression::BytesLiteral {
ty: Type::String,
value,
..
} => {
format!("{}", String::from_utf8_lossy(value))
}
Expression::BytesLiteral { value, .. } => format!("hex\"{}\"", hex::encode(value)),
Expression::NumberLiteral {
ty: ty @ Type::Address(_),
value,
..
} => {
format!("{} {:#x}", ty.to_string(ns), value)
}
Expression::NumberLiteral { ty, value, .. } => {
format!("{} {}", ty.to_string(ns), value)
}
Expression::RationalNumberLiteral { ty, rational, .. } => {
format!("{} {}", ty.to_string(ns), rational)
}
Expression::StructLiteral { values, .. } => format!(
"struct {{ {} }}",
values
.iter()
.map(|e| self.expr_to_string(contract, ns, e))
.collect::<Vec<String>>()
.join(", ")
),
Expression::ConstArrayLiteral {
dimensions, values, ..
} => format!(
"constant {} [ {} ]",
dimensions
.iter()
.map(|d| format!("[{d}]"))
.collect::<String>(),
values
.iter()
.map(|e| self.expr_to_string(contract, ns, e))
.collect::<Vec<String>>()
.join(", ")
),
Expression::ArrayLiteral {
dimensions, values, ..
} => format!(
"{} [ {} ]",
dimensions
.iter()
.map(|d| format!("[{d}]"))
.collect::<String>(),
values
.iter()
.map(|e| self.expr_to_string(contract, ns, e))
.collect::<Vec<String>>()
.join(", ")
),
Expression::Add {
overflowing,
left,
right,
..
} => format!(
"({}{} + {})",
if *overflowing { "overflowing " } else { "" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Subtract {
overflowing,
left,
right,
..
} => format!(
"({}{} - {})",
if *overflowing { "overflowing " } else { "" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::BitwiseOr { left, right, .. } => format!(
"({} | {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::BitwiseAnd { left, right, .. } => format!(
"({} & {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::BitwiseXor { left, right, .. } => format!(
"({} ^ {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::ShiftLeft { left, right, .. } => format!(
"({} << {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::ShiftRight { left, right, .. } => format!(
"({} >> {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Multiply {
overflowing,
left,
right,
..
} => format!(
"({}{} * {})",
if *overflowing { "overflowing " } else { "" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::SignedDivide { left, right, .. } => format!(
"(signed divide {} / {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right),
),
Expression::UnsignedDivide { left, right, .. } => format!(
"(unsigned divide {} / {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right),
),
Expression::SignedModulo { left, right, .. } => format!(
"(signed modulo {} % {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::UnsignedModulo { left, right, .. } => format!(
"(unsigned modulo {} % {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Power {
overflowing,
base,
exp,
..
} => format!(
"({}{} ** {})",
if *overflowing { "overflowing " } else { "" },
self.expr_to_string(contract, ns, base),
self.expr_to_string(contract, ns, exp)
),
Expression::Variable { var_no, .. } => {
if let Some(var) = self.vars.get(var_no) {
format!("%{}", var.id.name)
} else {
panic!("error: non-existing variable {var_no} in CFG");
}
}
Expression::Load { expr, .. } => {
format!("(load {})", self.expr_to_string(contract, ns, expr))
}
Expression::ZeroExt { ty, expr, .. } => format!(
"(zext {} {})",
ty.to_string(ns),
self.expr_to_string(contract, ns, expr)
),
Expression::SignExt { ty, expr, .. } => format!(
"(sext {} {})",
ty.to_string(ns),
self.expr_to_string(contract, ns, expr)
),
Expression::Trunc { ty, expr, .. } => format!(
"(trunc {} {})",
ty.to_string(ns),
self.expr_to_string(contract, ns, expr)
),
Expression::More {
signed,
left,
right,
..
} => format!(
"({} more {} > {})",
if *signed { "signed" } else { "unsigned" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Less {
signed,
left,
right,
..
} => format!(
"({} less {} < {})",
if *signed { "signed" } else { "unsigned" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::MoreEqual {
signed,
left,
right,
..
} => format!(
"({} {} >= {})",
if *signed { "signed" } else { "unsigned" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::LessEqual {
signed,
left,
right,
..
} => format!(
"({} {} <= {})",
if *signed { "signed" } else { "unsigned" },
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Equal { left, right, .. } => format!(
"({} == {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::NotEqual { left, right, .. } => format!(
"({} != {})",
self.expr_to_string(contract, ns, left),
self.expr_to_string(contract, ns, right)
),
Expression::Subscript {
array_ty: ty,
expr,
index,
..
} => format!(
"(subscript {} {}[{}])",
ty.to_string(ns),
self.expr_to_string(contract, ns, expr),
self.expr_to_string(contract, ns, index)
),
Expression::StorageArrayLength { array, elem_ty, .. } => format!(
"(storage array length {}[{}])",
self.expr_to_string(contract, ns, array),
elem_ty.to_string(ns),
),
Expression::StructMember { expr, member, .. } => format!(
"(struct {} field {})",
self.expr_to_string(contract, ns, expr),
member
),
Expression::Not { expr, .. } => {
format!("!{}", self.expr_to_string(contract, ns, expr))
}
Expression::BitwiseNot { expr, .. } => {
format!("~{}", self.expr_to_string(contract, ns, expr))
}
Expression::Negate { expr, .. } => {
format!("-{}", self.expr_to_string(contract, ns, expr))
}
Expression::Poison => "☠".to_string(),
Expression::AllocDynamicBytes {
ty,
size,
initializer: None,
..
} => {
let ty = if let Type::Slice(ty) = ty {
format!("slice {}", ty.to_string(ns))
} else {
ty.to_string(ns)
};
format!(
"(alloc {} len {})",
ty,
self.expr_to_string(contract, ns, size)
)
}
Expression::AllocDynamicBytes {
ty,
size,
initializer: Some(init),
..
} => {
let ty = if let Type::Slice(ty) = ty {
format!("slice {}", ty.to_string(ns))
} else {
ty.to_string(ns)
};
format!(
"(alloc {} {} {})",
ty,
self.expr_to_string(contract, ns, size),
match str::from_utf8(init) {
Ok(s) => format!("\"{}\"", s.escape_debug()),
Err(_) => format!("hex\"{}\"", hex::encode(init)),
}
)
}
Expression::StringCompare { left, right, .. } => format!(
"(strcmp ({}) ({}))",
self.location_to_string(contract, ns, left),
self.location_to_string(contract, ns, right)
),
Expression::StringConcat { left, right, .. } => format!(
"(concat ({}) ({}))",
self.location_to_string(contract, ns, left),
self.location_to_string(contract, ns, right)
),
Expression::Keccak256 { exprs, .. } => format!(
"(keccak256 {})",
exprs
.iter()
.map(|e| self.expr_to_string(contract, ns, e))
.collect::<Vec<String>>()
.join(", ")
),
Expression::InternalFunctionCfg { cfg_no, .. } => {
format!("function {}", contract.cfg[*cfg_no].name)
}
Expression::ReturnData { .. } => "(external call return data)".to_string(),
Expression::Cast { ty, expr, .. } => format!(
"{}({})",
ty.to_string(ns),
self.expr_to_string(contract, ns, expr)
),
Expression::BytesCast { ty, from, expr, .. } => format!(
"{} from:{} ({})",
ty.to_string(ns),
from.to_string(ns),
self.expr_to_string(contract, ns, expr)
),
Expression::Builtin {
kind: builtin,
args,
..
} => format!(
"(builtin {:?} ({}))",
builtin,
args.iter()
.map(|a| self.expr_to_string(contract, ns, a))
.collect::<Vec<String>>()
.join(", ")
),
Expression::FormatString { args: fields, .. } => format!(
"(format string {})",
fields
.iter()
.map(|(spec, a)| format!("({} {})", spec, self.expr_to_string(contract, ns, a)))
.collect::<Vec<String>>()
.join(", ")
),
Expression::Undefined { .. } => "undef".to_string(),
Expression::AdvancePointer {
pointer,
bytes_offset,
} => {
format!(
"(advance ptr: {}, by: {})",
self.expr_to_string(contract, ns, pointer),
self.expr_to_string(contract, ns, bytes_offset)
)
}
Expression::GetRef { expr, .. } => {
format!("(deref {}", self.expr_to_string(contract, ns, expr))
}
_ => panic!("{expr:?}"),
}
}
fn location_to_string(
&self,
contract: &Contract,
ns: &Namespace,
l: &StringLocation<Expression>,
) -> String {
match l {
StringLocation::RunTime(e) => self.expr_to_string(contract, ns, e),
StringLocation::CompileTime(literal) => match str::from_utf8(literal) {
Ok(s) => format!("\"{}\"", s.to_owned()),
Err(_) => format!("hex\"{}\"", hex::encode(literal)),
},