-
Notifications
You must be signed in to change notification settings - Fork 982
/
function.py
1708 lines (1463 loc) · 72.5 KB
/
function.py
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
import logging
from typing import Dict, Optional, Union, List, TYPE_CHECKING, Tuple, Set
from slither.core.cfg.node import NodeType, link_nodes, insert_node, Node
from slither.core.cfg.scope import Scope
from slither.core.declarations.contract import Contract
from slither.core.declarations.function import (
Function,
ModifierStatements,
FunctionType,
)
from slither.core.declarations.function_contract import FunctionContract
from slither.core.expressions import AssignmentOperation
from slither.core.source_mapping.source_mapping import Source
from slither.core.variables.local_variable import LocalVariable
from slither.core.variables.local_variable_init_from_tuple import LocalVariableInitFromTuple
from slither.solc_parsing.cfg.node import NodeSolc
from slither.solc_parsing.declarations.caller_context import CallerContextExpression
from slither.solc_parsing.exceptions import ParsingError
from slither.solc_parsing.expressions.expression_parsing import parse_expression
from slither.solc_parsing.variables.local_variable import LocalVariableSolc
from slither.solc_parsing.variables.local_variable_init_from_tuple import (
LocalVariableInitFromTupleSolc,
)
from slither.solc_parsing.variables.variable_declaration import MultipleVariablesDeclaration
from slither.utils.expression_manipulations import SplitTernaryExpression
from slither.visitors.expression.export_values import ExportValues
from slither.visitors.expression.has_conditional import HasConditional
from slither.solc_parsing.yul.parse_yul import YulBlock
if TYPE_CHECKING:
from slither.core.expressions.expression import Expression
from slither.solc_parsing.declarations.contract import ContractSolc
from slither.solc_parsing.slither_compilation_unit_solc import SlitherCompilationUnitSolc
from slither.core.compilation_unit import SlitherCompilationUnit
LOGGER = logging.getLogger("FunctionSolc")
def link_underlying_nodes(node1: NodeSolc, node2: NodeSolc):
link_nodes(node1.underlying_node, node2.underlying_node)
# pylint: disable=too-many-lines,too-many-branches,too-many-locals,too-many-statements,too-many-instance-attributes
class FunctionSolc(CallerContextExpression):
# elems = [(type, name)]
def __init__(
self,
function: Function,
function_data: Dict,
contract_parser: Optional["ContractSolc"],
slither_parser: "SlitherCompilationUnitSolc",
) -> None:
self._slither_parser: "SlitherCompilationUnitSolc" = slither_parser
self._contract_parser = contract_parser
self._function = function
# Only present if compact AST
if self.is_compact_ast:
self._function.name = function_data["name"]
else:
self._function.name = function_data["attributes"][self.get_key()]
if "id" in function_data:
self._function.id = function_data["id"]
self._functionNotParsed = function_data
self._returnsNotParsed: List[dict] = []
self._params_was_analyzed = False
self._content_was_analyzed = False
self._counter_scope_local_variables = 0
# variable renamed will map the solc id
# to the variable. It only works for compact format
# Later if an expression provides the referencedDeclaration attr
# we can retrieve the variable
# It only matters if two variables have the same name in the function
# which is only possible with solc > 0.5
self._variables_renamed: Dict[
int, Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
] = {}
self._analyze_type()
self._node_to_nodesolc: Dict[Node, NodeSolc] = {}
self._node_to_yulobject: Dict[Node, YulBlock] = {}
self._local_variables_parser: List[
Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
] = []
if "documentation" in function_data:
function.has_documentation = True
@property
def underlying_function(self) -> Function:
return self._function
@property
def contract_parser(self) -> Optional["ContractSolc"]:
return self._contract_parser
@property
def slither_parser(self) -> "SlitherCompilationUnitSolc":
return self._slither_parser
@property
def compilation_unit(self) -> "SlitherCompilationUnit":
return self._function.compilation_unit
###################################################################################
###################################################################################
# region AST format
###################################################################################
###################################################################################
def get_key(self) -> str:
return self._slither_parser.get_key()
def get_children(self, key: str) -> str:
if self.is_compact_ast:
return key
return "children"
@property
def is_compact_ast(self):
return self._slither_parser.is_compact_ast
# endregion
###################################################################################
###################################################################################
# region Variables
###################################################################################
###################################################################################
@property
def variables_renamed(
self,
) -> Dict[int, Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]]:
return self._variables_renamed
def _add_local_variable(
self, local_var_parser: Union[LocalVariableSolc, LocalVariableInitFromTupleSolc]
) -> None:
# If two local variables have the same name
# We add a suffix to the new variable
# This is done to prevent collision during SSA translation
# Use of while in case of collision
# In the worst case, the name will be really long
if local_var_parser.underlying_variable.name:
known_variables = [v.name for v in self._function.variables]
while local_var_parser.underlying_variable.name in known_variables:
local_var_parser.underlying_variable.name += (
f"_scope_{self._counter_scope_local_variables}"
)
self._counter_scope_local_variables += 1
known_variables = [v.name for v in self._function.variables]
if local_var_parser.reference_id is not None:
self._variables_renamed[local_var_parser.reference_id] = local_var_parser
self._function.variables_as_dict[
local_var_parser.underlying_variable.name
] = local_var_parser.underlying_variable
self._local_variables_parser.append(local_var_parser)
# endregion
###################################################################################
###################################################################################
# region Analyses
###################################################################################
###################################################################################
@property
def function_not_parsed(self) -> Dict:
return self._functionNotParsed
def _analyze_type(self) -> None:
"""
Analyz the type of the function
Myst be called in the constructor as the name might change according to the function's type
For example both the fallback and the receiver will have an empty name
:return:
"""
if self.is_compact_ast:
attributes = self._functionNotParsed
else:
attributes = self._functionNotParsed["attributes"]
if self._function.name == "":
self._function.function_type = FunctionType.FALLBACK
# 0.6.x introduced the receiver function
# It has also an empty name, so we need to check the kind attribute
if "kind" in attributes:
if attributes["kind"] == "receive":
self._function.function_type = FunctionType.RECEIVE
else:
self._function.function_type = FunctionType.NORMAL
if isinstance(self._function, FunctionContract):
if self._function.name == self._function.contract_declarer.name:
self._function.function_type = FunctionType.CONSTRUCTOR
def _analyze_attributes(self) -> None:
if self.is_compact_ast:
attributes = self._functionNotParsed
else:
attributes = self._functionNotParsed["attributes"]
if "stateMutability" in attributes:
if attributes["stateMutability"] == "payable":
self._function.payable = True
elif attributes["stateMutability"] == "pure":
self._function.pure = True
self._function.view = True
elif attributes["stateMutability"] == "view":
self._function.view = True
if "constant" in attributes:
self._function.view = attributes["constant"]
if "isConstructor" in attributes and attributes["isConstructor"]:
self._function.function_type = FunctionType.CONSTRUCTOR
if "kind" in attributes:
if attributes["kind"] == "constructor":
self._function.function_type = FunctionType.CONSTRUCTOR
if "visibility" in attributes:
self._function.visibility = attributes["visibility"]
# old solc
elif "public" in attributes:
if attributes["public"]:
self._function.visibility = "public"
else:
self._function.visibility = "private"
else:
self._function.visibility = "public"
if "payable" in attributes:
self._function.payable = attributes["payable"]
if "baseFunctions" in attributes:
overrides_ids = attributes["baseFunctions"]
if len(overrides_ids) > 0:
for f_id in overrides_ids:
funcs = self.slither_parser.functions_by_id[f_id]
for f in funcs:
# Do not consider leaf contracts as overrides.
# B is A { function a() override {} } and C is A { function a() override {} } override A.a(), not each other.
if (
f.contract == self._function.contract
or f.contract in self._function.contract.inheritance
):
self._function.overrides.append(f)
f.overridden_by.append(self._function)
# Attaches reference to override specifier e.g. X is referenced by `function a() override(X)`
if "overrides" in attributes and isinstance(attributes["overrides"], dict):
for override in attributes["overrides"].get("overrides", []):
refId = override["referencedDeclaration"]
overridden_contract = self.slither_parser.contracts_by_id.get(refId, None)
if overridden_contract:
overridden_contract.add_reference_from_raw_source(
override["src"], self.compilation_unit
)
if "virtual" in attributes:
self._function.is_virtual = attributes["virtual"]
def analyze_params(self) -> None:
# Can be re-analyzed due to inheritance
if self._params_was_analyzed:
return
self._params_was_analyzed = True
self._analyze_attributes()
if self.is_compact_ast:
params = self._functionNotParsed["parameters"]
returns = self._functionNotParsed["returnParameters"]
else:
children = self._functionNotParsed[self.get_children("children")]
# It uses to be
# params = children[0]
# returns = children[1]
# But from Solidity 0.6.3 to 0.6.10 (included)
# Comment above a function might be added in the children
child_iter = iter(
[child for child in children if child[self.get_key()] == "ParameterList"]
)
params = next(child_iter)
returns = next(child_iter)
if params:
self._parse_params(params)
if returns:
self._parse_returns(returns)
def analyze_content(self) -> None:
if self._content_was_analyzed:
return
self._content_was_analyzed = True
if self.is_compact_ast:
body = self._functionNotParsed.get("body", None)
return_params = self._functionNotParsed.get("returnParameters", None)
if body and body[self.get_key()] == "Block":
self._function.is_implemented = True
self._parse_cfg(body)
for modifier in self._functionNotParsed["modifiers"]:
self._parse_modifier(modifier)
else:
children = self._functionNotParsed[self.get_children("children")]
return_params = children[1]
self._function.is_implemented = False
for child in children[2:]:
if child[self.get_key()] == "Block":
self._function.is_implemented = True
self._parse_cfg(child)
# Parse modifier after parsing all the block
# In the case a local variable is used in the modifier
for child in children[2:]:
if child[self.get_key()] == "ModifierInvocation":
self._parse_modifier(child)
for local_var_parser in self._local_variables_parser:
local_var_parser.analyze(self)
for node_parser in self._node_to_nodesolc.values():
node_parser.analyze_expressions(self)
for yul_parser in self._node_to_yulobject.values():
yul_parser.analyze_expressions()
self._rewrite_ternary_as_if_else()
self._remove_alone_endif()
if return_params:
self._fix_implicit_return(return_params)
if self._function.entry_point:
self._update_reachability(self._function.entry_point)
# endregion
###################################################################################
###################################################################################
# region Nodes
###################################################################################
###################################################################################
def _new_node(
self, node_type: NodeType, src: Union[str, Source], scope: Union[Scope, "Function"]
) -> NodeSolc:
node = self._function.new_node(node_type, src, scope)
node_parser = NodeSolc(node)
self._node_to_nodesolc[node] = node_parser
return node_parser
def _new_yul_block(
self, src: Union[str, Dict], father_scope: Union[Scope, Function]
) -> YulBlock:
scope = Scope(False, True, father_scope)
node = self._function.new_node(NodeType.ASSEMBLY, src, scope)
contract = None
if isinstance(self._function, FunctionContract):
contract = self._function.contract
yul_object = YulBlock(
contract,
node,
[self._function.name, f"asm_{len(self._node_to_yulobject)}"],
scope,
)
self._node_to_yulobject[node] = yul_object
return yul_object
# endregion
###################################################################################
###################################################################################
# region Parsing function
###################################################################################
###################################################################################
def _parse_if(self, if_statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
# IfStatement = 'if' '(' Expression ')' Statement ( 'else' Statement )?
falseStatement = None
if self.is_compact_ast:
condition = if_statement["condition"]
# Note: check if the expression could be directly
# parsed here
condition_node = self._new_node(NodeType.IF, condition["src"], scope)
condition_node.add_unparsed_expression(condition)
link_underlying_nodes(node, condition_node)
true_scope = Scope(scope.is_checked, False, scope)
trueStatement = self._parse_statement(
if_statement["trueBody"], condition_node, true_scope
)
if "falseBody" in if_statement and if_statement["falseBody"]:
false_scope = Scope(scope.is_checked, False, scope)
falseStatement = self._parse_statement(
if_statement["falseBody"], condition_node, false_scope
)
else:
children = if_statement[self.get_children("children")]
condition = children[0]
# Note: check if the expression could be directly
# parsed here
condition_node = self._new_node(NodeType.IF, condition["src"], scope)
condition_node.add_unparsed_expression(condition)
link_underlying_nodes(node, condition_node)
true_scope = Scope(scope.is_checked, False, scope)
trueStatement = self._parse_statement(children[1], condition_node, true_scope)
if len(children) == 3:
false_scope = Scope(scope.is_checked, False, scope)
falseStatement = self._parse_statement(children[2], condition_node, false_scope)
endIf_node = self._new_node(NodeType.ENDIF, if_statement["src"], scope)
link_underlying_nodes(trueStatement, endIf_node)
if falseStatement:
link_underlying_nodes(falseStatement, endIf_node)
else:
link_underlying_nodes(condition_node, endIf_node)
return endIf_node
def _parse_while(self, whilte_statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
# WhileStatement = 'while' '(' Expression ')' Statement
node_startWhile = self._new_node(NodeType.STARTLOOP, whilte_statement["src"], scope)
body_scope = Scope(scope.is_checked, False, scope)
if self.is_compact_ast:
node_condition = self._new_node(
NodeType.IFLOOP, whilte_statement["condition"]["src"], scope
)
node_condition.add_unparsed_expression(whilte_statement["condition"])
statement = self._parse_statement(whilte_statement["body"], node_condition, body_scope)
else:
children = whilte_statement[self.get_children("children")]
expression = children[0]
node_condition = self._new_node(NodeType.IFLOOP, expression["src"], scope)
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition, body_scope)
node_endWhile = self._new_node(NodeType.ENDLOOP, whilte_statement["src"], scope)
link_underlying_nodes(node, node_startWhile)
link_underlying_nodes(node_startWhile, node_condition)
link_underlying_nodes(statement, node_condition)
link_underlying_nodes(node_condition, node_endWhile)
return node_endWhile
def _parse_for_compact_ast(
self, statement: Dict
) -> Tuple[Optional[Dict], Optional[Dict], Optional[Dict], Dict]:
body = statement["body"]
init_expression = statement.get("initializationExpression", None)
condition = statement.get("condition", None)
loop_expression = statement.get("loopExpression", None)
return init_expression, condition, loop_expression, body
def _parse_for_legacy_ast(
self, statement: Dict
) -> Tuple[Optional[Dict], Optional[Dict], Optional[Dict], Dict]:
# if we're using an old version of solc (anything below and including 0.4.11) or if the user
# explicitly enabled compact ast, we might need to make some best-effort guesses
children = statement[self.get_children("children")]
# there should always be at least one, and never more than 4, children
assert 1 <= len(children) <= 4
# the last element of the children array must be the body, since it's mandatory
# however, it might be a single expression
body = children[-1]
if len(children) == 4:
# handle the first trivial case - if there are four children we know exactly what they are
pre, cond, post = children[0], children[1], children[2]
elif len(children) == 1:
# handle the second trivial case - if there is only one child we know there are no expressions
pre, cond, post = None, None, None
else:
attributes = statement.get("attributes", None)
def has_hint(key):
return key in attributes and not attributes[key]
if attributes and any(
map(
has_hint,
["condition", "initializationExpression", "loopExpression"],
)
):
# if we have attribute hints, rely on those
if len(children) == 2:
# we're missing two expressions, find the one we have
if not has_hint("initializationExpression"):
pre, cond, post = children[0], None, None
elif not has_hint("condition"):
pre, cond, post = None, children[0], None
else: # if not has_hint('loopExpression'):
pre, cond, post = None, None, children[0]
else: # len(children) == 3
# we're missing one expression, figure out what it is
if has_hint("initializationExpression"):
pre, cond, post = None, children[0], children[1]
elif has_hint("condition"):
pre, cond, post = children[0], None, children[1]
else: # if has_hint('loopExpression'):
pre, cond, post = children[0], children[1], None
else:
# we don't have attribute hints, and it's impossible to be 100% accurate here
# let's just try our best
first_type = children[0][self.get_key()]
second_type = children[1][self.get_key()]
# VariableDefinitionStatement is used by solc 0.4.0-0.4.6
# it's changed in 0.4.7 to VariableDeclarationStatement
if first_type in ["VariableDefinitionStatement", "VariableDeclarationStatement"]:
# only the pre statement can be a variable declaration
if len(children) == 2:
# only one child apart from body, it must be pre
pre, cond, post = children[0], None, None
else:
# more than one child, figure out which one is the cond
if second_type == "ExpressionStatement":
# only the post can be an expression statement
pre, cond, post = children[0], None, children[1]
else:
# similarly, the post cannot be anything other than an expression statement
pre, cond, post = children[0], children[1], None
elif first_type == "ExpressionStatement":
# the first element can either be pre or post
if len(children) == 2:
# this is entirely ambiguous, so apply a very dumb heuristic:
# if the statement is closer to the start of the body, it's probably the post
# otherwise, it's probably the pre
# this will work in all cases where the formatting isn't completely borked
node_len = int(children[0]["src"].split(":")[1])
node_start = int(children[0]["src"].split(":")[0])
node_end = node_start + node_len
for_start = int(statement["src"].split(":")[0]) + 3 # trim off the 'for'
body_start = int(body["src"].split(":")[0])
dist_start = node_start - for_start
dist_end = body_start - node_end
if dist_start > dist_end:
pre, cond, post = None, None, children[0]
else:
pre, cond, post = children[0], None, None
else:
# more than one child, we must be the pre
pre, cond, post = children[0], children[1], None
else:
# the first element must be the cond
if len(children) == 2:
pre, cond, post = None, children[0], None
else:
pre, cond, post = None, children[0], children[1]
return pre, cond, post, body
def _parse_for(self, statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
# ForStatement = 'for' '(' (SimpleStatement)? ';' (Expression)? ';' (ExpressionStatement)? ')' Statement
if self.is_compact_ast:
pre, cond, post, body = self._parse_for_compact_ast(statement)
else:
pre, cond, post, body = self._parse_for_legacy_ast(statement)
node_startLoop = self._new_node(NodeType.STARTLOOP, statement["src"], scope)
node_endLoop = self._new_node(NodeType.ENDLOOP, statement["src"], scope)
last_scope = scope
if pre:
pre_scope = Scope(scope.is_checked, False, last_scope)
last_scope = pre_scope
node_init_expression = self._parse_statement(pre, node, pre_scope)
link_underlying_nodes(node_init_expression, node_startLoop)
else:
link_underlying_nodes(node, node_startLoop)
if cond:
cond_scope = Scope(scope.is_checked, False, last_scope)
last_scope = cond_scope
node_condition = self._new_node(NodeType.IFLOOP, cond["src"], cond_scope)
node_condition.add_unparsed_expression(cond)
link_underlying_nodes(node_startLoop, node_condition)
node_beforeBody = node_condition
else:
node_condition = None
node_beforeBody = node_startLoop
body_scope = Scope(scope.is_checked, False, last_scope)
last_scope = body_scope
node_body = self._parse_statement(body, node_beforeBody, body_scope)
if post:
node_loopexpression = self._parse_statement(post, node_body, last_scope)
link_underlying_nodes(node_loopexpression, node_beforeBody)
else:
# node_loopexpression = None
link_underlying_nodes(node_body, node_beforeBody)
if node_condition:
link_underlying_nodes(node_condition, node_endLoop)
else:
link_underlying_nodes(
node_startLoop, node_endLoop
) # this is an infinite loop but we can't break our cfg
return node_endLoop
def _parse_dowhile(self, do_while_statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
node_startDoWhile = self._new_node(NodeType.STARTLOOP, do_while_statement["src"], scope)
condition_scope = Scope(scope.is_checked, False, scope)
if self.is_compact_ast:
node_condition = self._new_node(
NodeType.IFLOOP, do_while_statement["condition"]["src"], condition_scope
)
node_condition.add_unparsed_expression(do_while_statement["condition"])
statement = self._parse_statement(
do_while_statement["body"], node_condition, condition_scope
)
else:
children = do_while_statement[self.get_children("children")]
# same order in the AST as while
expression = children[0]
node_condition = self._new_node(NodeType.IFLOOP, expression["src"], condition_scope)
node_condition.add_unparsed_expression(expression)
statement = self._parse_statement(children[1], node_condition, condition_scope)
body_scope = Scope(scope.is_checked, False, condition_scope)
node_endDoWhile = self._new_node(NodeType.ENDLOOP, do_while_statement["src"], body_scope)
link_underlying_nodes(node, node_startDoWhile)
# empty block, loop from the start to the condition
if not node_condition.underlying_node.sons:
link_underlying_nodes(node_startDoWhile, node_condition)
else:
link_nodes(
node_startDoWhile.underlying_node,
node_condition.underlying_node.sons[0],
)
link_underlying_nodes(statement, node_condition)
link_underlying_nodes(node_condition, node_endDoWhile)
return node_endDoWhile
def _construct_try_expression(self, externalCall: Dict, parameters_list: Dict) -> Dict:
# if the parameters are more than 1 we make the leftHandSide of the Assignment node
# a TupleExpression otherwise an Identifier
# case when there isn't returns(...)
# e.g. external call that doesn't have any return variable
if not parameters_list:
return externalCall
ret: Dict = {"nodeType": "Assignment", "operator": "=", "src": parameters_list["src"]}
parameters = parameters_list.get("parameters", None)
# if the name is "" it means the return variable is not used
if len(parameters) == 1:
if parameters[0]["name"] != "":
self._add_param(parameters[0])
ret["typeDescriptions"] = {
"typeString": parameters[0]["typeName"]["typeDescriptions"]["typeString"]
}
leftHandSide = {
"name": parameters[0]["name"],
"nodeType": "Identifier",
"src": parameters[0]["src"],
"referencedDeclaration": parameters[0]["id"],
"typeDescriptions": parameters[0]["typeDescriptions"],
}
else:
# we don't need an Assignment so we return only the external call
return externalCall
else:
ret["typeDescriptions"] = {"typeString": "tuple()"}
leftHandSide = {
"components": [],
"nodeType": "TupleExpression",
"src": parameters_list["src"],
}
for i, p in enumerate(parameters):
if p["name"] == "":
continue
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": p["src"],
"declarations": [p],
}
self._add_param_init_tuple(new_statement, i)
ident = {
"name": p["name"],
"nodeType": "Identifier",
"src": p["src"],
"referencedDeclaration": p["id"],
"typeDescriptions": p["typeDescriptions"],
}
leftHandSide["components"].append(ident)
ret["leftHandSide"] = leftHandSide
ret["rightHandSide"] = externalCall
return ret
def _parse_try_catch(self, statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
externalCall = statement.get("externalCall", None)
if externalCall is None:
raise ParsingError(f"Try/Catch not correctly parsed by Slither {statement}")
catch_scope = Scope(scope.is_checked, False, scope)
new_node = self._new_node(NodeType.TRY, statement["src"], catch_scope)
clauses = statement.get("clauses", [])
# the first clause is the try scope
returned_variables = clauses[0].get("parameters", None)
constructed_try_expression = self._construct_try_expression(
externalCall, returned_variables
)
new_node.add_unparsed_expression(constructed_try_expression)
link_underlying_nodes(node, new_node)
node = new_node
for index, clause in enumerate(clauses):
# clauses after the first one are related to catch cases
# we set the parameters (e.g. data in this case. catch(string memory data) ...)
# to be initialized so they are not reported by the uninitialized-local-variables detector
if index >= 1:
self._parse_catch(clause, node, catch_scope, True)
else:
# the parameters for the try scope were already added in _construct_try_expression
self._parse_catch(clause, node, catch_scope, False)
return node
def _parse_catch(
self, statement: Dict, node: NodeSolc, scope: Scope, add_param: bool
) -> NodeSolc:
block = statement.get("block", None)
if block is None:
raise ParsingError(f"Catch not correctly parsed by Slither {statement}")
try_scope = Scope(scope.is_checked, False, scope)
try_node = self._new_node(NodeType.CATCH, statement["src"], try_scope)
link_underlying_nodes(node, try_node)
if add_param:
if self.is_compact_ast:
params = statement.get("parameters", None)
else:
params = statement[self.get_children("children")]
if params:
for param in params.get("parameters", []):
assert param[self.get_key()] == "VariableDeclaration"
self._add_param(param, True)
return self._parse_statement(block, try_node, try_scope)
def _parse_variable_definition(self, statement: Dict, node: NodeSolc, scope: Scope) -> NodeSolc:
try:
local_var = LocalVariable()
local_var.set_function(self._function)
local_var.set_offset(statement["src"], self._function.compilation_unit)
local_var_parser = LocalVariableSolc(local_var, statement)
self._add_local_variable(local_var_parser)
# local_var.analyze(self)
new_node = self._new_node(NodeType.VARIABLE, statement["src"], scope)
new_node.underlying_node.add_variable_declaration(local_var)
link_underlying_nodes(node, new_node)
return new_node
except MultipleVariablesDeclaration:
# Custom handling of var (a,b) = .. style declaration
if self.is_compact_ast:
variables = statement["declarations"]
count = len(variables)
if (
statement["initialValue"]["nodeType"] == "TupleExpression"
and len(statement["initialValue"]["components"]) == count
):
inits = statement["initialValue"]["components"]
i = 0
new_node = node
for variable in variables:
if variable is None:
continue
init = inits[i]
src = variable["src"]
i = i + 1
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
"initialValue": init,
}
new_node = self._parse_variable_definition(new_statement, new_node, scope)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
variables = []
i = 0
new_node = node
for variable in statement["declarations"]:
if variable:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
"nodeType": "VariableDefinitionStatement",
"src": src,
"declarations": [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node, scope
)
else:
variables.append(None)
i = i + 1
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
if v is not None:
identifier = {
"nodeType": "Identifier",
"src": v["src"],
"name": v["name"],
"referencedDeclaration": v["id"],
"typeDescriptions": {
"typeString": v["typeDescriptions"]["typeString"]
},
}
var_identifiers.append(identifier)
else:
var_identifiers.append(None)
tuple_expression = {
"nodeType": "TupleExpression",
"src": statement["src"],
"components": var_identifiers,
}
expression = {
"nodeType": "Assignment",
"src": statement["src"],
"operator": "=",
"type": "tuple()",
"leftHandSide": tuple_expression,
"rightHandSide": statement["initialValue"],
"typeDescriptions": {"typeString": "tuple()"},
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"], scope)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
else:
count = 0
children = statement[self.get_children("children")]
child = children[0]
while child[self.get_key()] == "VariableDeclaration":
count = count + 1
child = children[count]
assert len(children) == (count + 1)
tuple_vars = children[count]
variables_declaration = children[0:count]
i = 0
new_node = node
if tuple_vars[self.get_key()] == "TupleExpression":
assert len(tuple_vars[self.get_children("children")]) == count
for variable in variables_declaration:
init = tuple_vars[self.get_children("children")][i]
src = variable["src"]
i = i + 1
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable, init],
}
new_node = self._parse_variable_definition(new_statement, new_node, scope)
else:
# If we have
# var (a, b) = f()
# we can split in multiple declarations, without init
# Then we craft one expression that does the assignment
assert tuple_vars[self.get_key()] in ["FunctionCall", "Conditional"]
variables = []
for variable in variables_declaration:
src = variable["src"]
# Create a fake statement to be consistent
new_statement = {
self.get_key(): "VariableDefinitionStatement",
"src": src,
self.get_children("children"): [variable],
}
variables.append(variable)
new_node = self._parse_variable_definition_init_tuple(
new_statement, i, new_node, scope
)
i = i + 1
var_identifiers = []
# craft of the expression doing the assignement
for v in variables:
identifier = {
self.get_key(): "Identifier",
"src": v["src"],
"attributes": {
"value": v["attributes"][self.get_key()],
"type": v["attributes"]["type"],
},
}
var_identifiers.append(identifier)
expression = {
self.get_key(): "Assignment",
"src": statement["src"],
"attributes": {"operator": "=", "type": "tuple()"},
self.get_children("children"): [
{
self.get_key(): "TupleExpression",
"src": statement["src"],
self.get_children("children"): var_identifiers,
},
tuple_vars,
],
}
node = new_node
new_node = self._new_node(NodeType.EXPRESSION, statement["src"], scope)
new_node.add_unparsed_expression(expression)
link_underlying_nodes(node, new_node)
return new_node
def _parse_variable_definition_init_tuple(
self, statement: Dict, index: int, node: NodeSolc, scope
) -> NodeSolc:
local_var = LocalVariableInitFromTuple()
local_var.set_function(self._function)
local_var.set_offset(statement["src"], self._function.compilation_unit)
local_var_parser = LocalVariableInitFromTupleSolc(local_var, statement, index)
self._add_local_variable(local_var_parser)
new_node = self._new_node(NodeType.VARIABLE, statement["src"], scope)
new_node.underlying_node.add_variable_declaration(local_var)
link_underlying_nodes(node, new_node)
return new_node
def _parse_statement(
self, statement: Dict, node: NodeSolc, scope: Union[Scope, Function]
) -> NodeSolc:
"""
Return:
node
"""