Use f-strings instead of old-style formatting

pull/1107/head
Boyan-MILANOV 3 years ago
parent e270af517f
commit 2fb4587302
  1. 3
      pyproject.toml
  2. 2
      slither/__main__.py
  3. 8
      slither/analyses/data_dependency/data_dependency.py
  4. 2
      slither/core/cfg/node.py
  5. 28
      slither/core/declarations/function.py
  6. 2
      slither/core/declarations/solidity_variables.py
  7. 4
      slither/core/expressions/assignment_operation.py
  8. 4
      slither/core/expressions/binary_operation.py
  9. 6
      slither/core/expressions/unary_operation.py
  10. 6
      slither/core/slither_core.py
  11. 10
      slither/core/solidity_types/elementary_type.py
  12. 10
      slither/core/solidity_types/function_type.py
  13. 2
      slither/core/solidity_types/mapping_type.py
  14. 2
      slither/core/source_mapping/source_mapping.py
  15. 2
      slither/core/variables/local_variable.py
  16. 2
      slither/core/variables/state_variable.py
  17. 8
      slither/detectors/naming_convention/naming_convention.py
  18. 2
      slither/detectors/statements/type_based_tautology.py
  19. 2
      slither/printers/functions/authorization.py
  20. 8
      slither/printers/functions/cfg.py
  21. 24
      slither/printers/inheritance/inheritance_graph.py
  22. 12
      slither/printers/summary/contract.py
  23. 4
      slither/printers/summary/data_depenency.py
  24. 24
      slither/printers/summary/evm.py
  25. 2
      slither/printers/summary/function.py
  26. 2
      slither/printers/summary/function_ids.py
  27. 14
      slither/printers/summary/human_summary.py
  28. 2
      slither/printers/summary/modifier_calls.py
  29. 2
      slither/printers/summary/require_calls.py
  30. 10
      slither/printers/summary/slithir.py
  31. 14
      slither/printers/summary/slithir_ssa.py
  32. 2
      slither/printers/summary/variable_order.py
  33. 6
      slither/slither.py
  34. 16
      slither/slithir/convert.py
  35. 6
      slither/slithir/operations/assignment.py
  36. 21
      slither/slithir/operations/binary.py
  37. 2
      slither/slithir/operations/codesize.py
  38. 2
      slither/slithir/operations/condition.py
  39. 2
      slither/slithir/operations/delete.py
  40. 2
      slither/slithir/operations/event_call.py
  41. 8
      slither/slithir/operations/high_level_call.py
  42. 4
      slither/slithir/operations/index.py
  43. 2
      slither/slithir/operations/init_array.py
  44. 4
      slither/slithir/operations/internal_call.py
  45. 8
      slither/slithir/operations/internal_dynamic_call.py
  46. 2
      slither/slithir/operations/length.py
  47. 6
      slither/slithir/operations/library_call.py
  48. 4
      slither/slithir/operations/low_level_call.py
  49. 4
      slither/slithir/operations/member.py
  50. 4
      slither/slithir/operations/new_array.py
  51. 6
      slither/slithir/operations/new_contract.py
  52. 2
      slither/slithir/operations/new_elementary_type.py
  53. 2
      slither/slithir/operations/new_structure.py
  54. 4
      slither/slithir/operations/phi.py
  55. 4
      slither/slithir/operations/phi_callback.py
  56. 2
      slither/slithir/operations/push.py
  57. 2
      slither/slithir/operations/return_operation.py
  58. 4
      slither/slithir/operations/send.py
  59. 6
      slither/slithir/operations/solidity_call.py
  60. 4
      slither/slithir/operations/transfer.py
  61. 2
      slither/slithir/operations/type_conversion.py
  62. 6
      slither/slithir/operations/unary.py
  63. 4
      slither/slithir/operations/unpack.py
  64. 2
      slither/slithir/tmp_operations/tmp_call.py
  65. 2
      slither/slithir/tmp_operations/tmp_new_array.py
  66. 2
      slither/slithir/tmp_operations/tmp_new_contract.py
  67. 2
      slither/slithir/tmp_operations/tmp_new_elementary_type.py
  68. 2
      slither/slithir/tmp_operations/tmp_new_structure.py
  69. 2
      slither/slithir/utils/ssa.py
  70. 2
      slither/slithir/variables/constant.py
  71. 4
      slither/slithir/variables/local_variable.py
  72. 2
      slither/slithir/variables/reference.py
  73. 2
      slither/slithir/variables/state_variable.py
  74. 2
      slither/slithir/variables/temporary.py
  75. 2
      slither/slithir/variables/tuple.py
  76. 14
      slither/solc_parsing/declarations/function.py
  77. 6
      slither/solc_parsing/expressions/expression_parsing.py
  78. 2
      slither/solc_parsing/expressions/find_variable.py
  79. 4
      slither/solc_parsing/variables/variable_declaration.py
  80. 4
      slither/solc_parsing/yul/parse_yul.py
  81. 40
      slither/tools/similarity/encode.py
  82. 4
      slither/tools/similarity/info.py
  83. 2
      slither/tools/similarity/plot.py
  84. 2
      slither/tools/similarity/test.py
  85. 2
      slither/tools/similarity/train.py
  86. 2
      slither/tools/slither_format/slither_format.py
  87. 2
      slither/tools/upgradeability/__main__.py
  88. 2
      slither/tools/upgradeability/checks/abstract_checks.py
  89. 17
      slither/tools/upgradeability/utils/command_line.py
  90. 2
      slither/utils/colors.py
  91. 28
      slither/utils/command_line.py
  92. 2
      slither/utils/comparable_enum.py
  93. 2
      slither/utils/expression_manipulations.py
  94. 2
      slither/utils/integer_conversion.py
  95. 2
      slither/visitors/expression/constants_folding.py
  96. 6
      slither/visitors/expression/expression.py
  97. 28
      slither/visitors/expression/expression_printer.py
  98. 4
      slither/visitors/slithir/expression_to_slithir.py

@ -18,6 +18,5 @@ logging-fstring-interpolation,
logging-not-lazy,
duplicate-code,
import-error,
unsubscriptable-object,
consider-using-f-string
unsubscriptable-object
"""

@ -208,7 +208,7 @@ def choose_detectors(args, all_detector_classes):
if detector in detectors:
detectors_to_run.append(detectors[detector])
else:
raise Exception("Error: {} is not a detector".format(detector))
raise Exception(f"Error: {detector} is not a detector")
detectors_to_run = sorted(detectors_to_run, key=lambda x: x.IMPACT)
return detectors_to_run

@ -268,15 +268,15 @@ def pprint_dependency(caller_context: Context_types) -> None:
print("#### SSA ####")
context = caller_context.context
for k, values in context[KEY_SSA].items():
print("{} ({}):".format(k, id(k)))
print(f"{k} ({id(k)}):")
for v in values:
print("\t- {}".format(v))
print(f"\t- {v}")
print("#### NON SSA ####")
for k, values in context[KEY_NON_SSA].items():
print("{} ({}):".format(k, hex(id(k))))
print(f"{k} ({hex(id(k))}):")
for v in values:
print("\t- {} ({})".format(v, hex(id(v))))
print(f"\t- {v} ({hex(id(v))})")
# endregion

@ -140,7 +140,7 @@ class NodeType(Enum):
return "END_LOOP"
if self == NodeType.OTHER_ENTRYPOINT:
return "OTHER_ENTRYPOINT"
return "Unknown type {}".format(hex(self.value))
return f"Unknown type {hex(self.value)}"
# endregion

@ -1304,9 +1304,9 @@ class Function(SourceMapping, metaclass=ABCMeta): # pylint: disable=too-many-pu
with open(filename, "w", encoding="utf8") as f:
f.write("digraph{\n")
for node in self.nodes:
f.write('{}[label="{}"];\n'.format(node.node_id, str(node)))
f.write(f'{node.node_id}[label="{str(node)}"];\n')
for son in node.sons:
f.write("{}->{};\n".format(node.node_id, son.node_id))
f.write(f"{node.node_id}->{son.node_id};\n")
f.write("}\n")
@ -1318,20 +1318,18 @@ class Function(SourceMapping, metaclass=ABCMeta): # pylint: disable=too-many-pu
"""
def description(node):
desc = "{}\n".format(node)
desc += "id: {}".format(node.node_id)
desc = f"{node}\n"
desc += f"id: {node.node_id}"
if node.dominance_frontier:
desc += "\ndominance frontier: {}".format(
[n.node_id for n in node.dominance_frontier]
)
desc += f"\ndominance frontier: {[n.node_id for n in node.dominance_frontier]}"
return desc
with open(filename, "w", encoding="utf8") as f:
f.write("digraph{\n")
for node in self.nodes:
f.write('{}[label="{}"];\n'.format(node.node_id, description(node)))
f.write(f'{node.node_id}[label="{description(node)}"];\n')
if node.immediate_dominator:
f.write("{}->{};\n".format(node.immediate_dominator.node_id, node.node_id))
f.write(f"{node.immediate_dominator.node_id}->{node.node_id};\n")
f.write("}\n")
@ -1356,22 +1354,22 @@ class Function(SourceMapping, metaclass=ABCMeta): # pylint: disable=too-many-pu
content = ""
content += "digraph{\n"
for node in self.nodes:
label = "Node Type: {} {}\n".format(str(node.type), node.node_id)
label = f"Node Type: {str(node.type)} {node.node_id}\n"
if node.expression and not skip_expressions:
label += "\nEXPRESSION:\n{}\n".format(node.expression)
label += f"\nEXPRESSION:\n{node.expression}\n"
if node.irs and not skip_expressions:
label += "\nIRs:\n" + "\n".join([str(ir) for ir in node.irs])
content += '{}[label="{}"];\n'.format(node.node_id, label)
content += f'{node.node_id}[label="{label}"];\n'
if node.type in [NodeType.IF, NodeType.IFLOOP]:
true_node = node.son_true
if true_node:
content += '{}->{}[label="True"];\n'.format(node.node_id, true_node.node_id)
content += f'{node.node_id}->{true_node.node_id}[label="True"];\n'
false_node = node.son_false
if false_node:
content += '{}->{}[label="False"];\n'.format(node.node_id, false_node.node_id)
content += f'{node.node_id}->{false_node.node_id}[label="False"];\n'
else:
for son in node.sons:
content += "{}->{};\n".format(node.node_id, son.node_id)
content += f"{node.node_id}->{son.node_id};\n"
content += "}\n"
return content

@ -93,7 +93,7 @@ def solidity_function_signature(name):
Returns:
str
"""
return name + " returns({})".format(",".join(SOLIDITY_FUNCTIONS[name]))
return name + f" returns({','.join(SOLIDITY_FUNCTIONS[name])})"
class SolidityVariable(Context):

@ -50,7 +50,7 @@ class AssignmentOperationType(Enum):
if operation_type == "%=":
return AssignmentOperationType.ASSIGN_MODULO
raise SlitherCoreError("get_type: Unknown operation type {})".format(operation_type))
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type})")
def __str__(self) -> str:
if self == AssignmentOperationType.ASSIGN:
@ -75,7 +75,7 @@ class AssignmentOperationType(Enum):
return "/="
if self == AssignmentOperationType.ASSIGN_MODULO:
return "%="
raise SlitherCoreError("str: Unknown operation type {})".format(self))
raise SlitherCoreError(f"str: Unknown operation type {self})")
class AssignmentOperation(ExpressionTyped):

@ -94,7 +94,7 @@ class BinaryOperationType(Enum):
if operation_type == ">>'":
return BinaryOperationType.RIGHT_SHIFT_ARITHMETIC
raise SlitherCoreError("get_type: Unknown operation type {})".format(operation_type))
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type})")
def __str__(self) -> str: # pylint: disable=too-many-branches
if self == BinaryOperationType.POWER:
@ -145,7 +145,7 @@ class BinaryOperationType(Enum):
return ">'"
if self == BinaryOperationType.RIGHT_SHIFT_ARITHMETIC:
return ">>'"
raise SlitherCoreError("str: Unknown operation type {})".format(self))
raise SlitherCoreError(f"str: Unknown operation type {self})")
class BinaryOperation(ExpressionTyped):

@ -41,7 +41,7 @@ class UnaryOperationType(Enum):
return UnaryOperationType.PLUSPLUS_POST
if operation_type == "--":
return UnaryOperationType.MINUSMINUS_POST
raise SlitherCoreError("get_type: Unknown operation type {}".format(operation_type))
raise SlitherCoreError(f"get_type: Unknown operation type {operation_type}")
def __str__(self):
if self == UnaryOperationType.BANG:
@ -62,7 +62,7 @@ class UnaryOperationType(Enum):
]:
return "--"
raise SlitherCoreError("str: Unknown operation type {}".format(self))
raise SlitherCoreError(f"str: Unknown operation type {self}")
@staticmethod
def is_prefix(operation_type):
@ -82,7 +82,7 @@ class UnaryOperationType(Enum):
]:
return False
raise SlitherCoreError("is_prefix: Unknown operation type {}".format(operation_type))
raise SlitherCoreError(f"is_prefix: Unknown operation type {operation_type}")
class UnaryOperation(ExpressionTyped):

@ -155,7 +155,7 @@ class SlitherCore(Context):
for compilation_unit in self._compilation_units:
for c in compilation_unit.contracts:
for f in c.functions:
f.cfg_to_dot(os.path.join(d, "{}.{}.dot".format(c.name, f.name)))
f.cfg_to_dot(os.path.join(d, f"{c.name}.{f.name}.dot"))
# endregion
###################################################################################
@ -261,9 +261,7 @@ class SlitherCore(Context):
if "id" in r:
self._previous_results_ids.add(r["id"])
except json.decoder.JSONDecodeError:
logger.error(
red("Impossible to decode {}. Consider removing the file".format(filename))
)
logger.error(red(f"Impossible to decode {filename}. Consider removing the file"))
def write_results_to_hide(self):
if not self._results_to_hide:

@ -43,8 +43,8 @@ Int = [
"int256",
]
Max_Int = {k: 2 ** (8 * i - 1) - 1 if i > 0 else 2 ** 255 - 1 for i, k in enumerate(Int)}
Min_Int = {k: -(2 ** (8 * i - 1)) if i > 0 else -(2 ** 255) for i, k in enumerate(Int)}
Max_Int = {k: 2 ** (8 * i - 1) - 1 if i > 0 else 2**255 - 1 for i, k in enumerate(Int)}
Min_Int = {k: -(2 ** (8 * i - 1)) if i > 0 else -(2**255) for i, k in enumerate(Int)}
Uint = [
"uint",
@ -82,7 +82,7 @@ Uint = [
"uint256",
]
Max_Uint = {k: 2 ** (8 * i) - 1 if i > 0 else 2 ** 256 - 1 for i, k in enumerate(Uint)}
Max_Uint = {k: 2 ** (8 * i) - 1 if i > 0 else 2**256 - 1 for i, k in enumerate(Uint)}
Min_Uint = {k: 0 for k in Uint}
@ -140,8 +140,8 @@ M = list(range(8, 257, 8))
N = list(range(0, 81))
MN = list(itertools.product(M, N))
Fixed = ["fixed{}x{}".format(m, n) for (m, n) in MN] + ["fixed"]
Ufixed = ["ufixed{}x{}".format(m, n) for (m, n) in MN] + ["ufixed"]
Fixed = [f"fixed{m}x{n}" for (m, n) in MN] + ["fixed"]
Ufixed = [f"ufixed{m}x{n}" for (m, n) in MN] + ["ufixed"]
ElementaryTypeName = ["address", "bool", "string", "var"] + Int + Uint + Byte + Fixed + Ufixed

@ -38,8 +38,8 @@ class FunctionType(Type):
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return "function({}) returns({})".format(params, return_values)
return "function({})".format(params)
return f"function({params}) returns({return_values})"
return f"function({params})"
@property
def parameters_signature(self) -> str:
@ -49,7 +49,7 @@ class FunctionType(Type):
# Use x.type
# x.name may be empty
params = ",".join([str(x.type) for x in self._params])
return "({})".format(params)
return f"({params})"
@property
def signature(self) -> str:
@ -61,8 +61,8 @@ class FunctionType(Type):
params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values])
if return_values:
return "({}) returns({})".format(params, return_values)
return "({})".format(params)
return f"({params}) returns({return_values})"
return f"({params})"
def __eq__(self, other):
if not isinstance(other, FunctionType):

@ -24,7 +24,7 @@ class MappingType(Type):
return 32, True
def __str__(self):
return "mapping({} => {})".format(str(self._from), str(self._to))
return f"mapping({str(self._from)} => {str(self._to)})"
def __eq__(self, other):
if not isinstance(other, MappingType):

@ -128,7 +128,7 @@ class SourceMapping(Context):
if not lines:
lines = ""
elif len(lines) == 1:
lines = "#{}{}".format(line_descr, lines[0])
lines = f"#{line_descr}{lines[0]}"
else:
lines = f"#{line_descr}{lines[0]}-{line_descr}{lines[-1]}"
return lines

@ -58,4 +58,4 @@ class LocalVariable(ChildFunction, Variable):
@property
def canonical_name(self) -> str:
return "{}.{}".format(self.function.canonical_name, self.name)
return f"{self.function.canonical_name}.{self.name}"

@ -58,7 +58,7 @@ class StateVariable(ChildContract, Variable):
@property
def canonical_name(self) -> str:
return "{}.{}".format(self.contract.name, self.name)
return f"{self.contract.name}.{self.name}"
@property
def full_name(self) -> str:

@ -89,14 +89,10 @@ Solidity defines a [naming convention](https://solidity.readthedocs.io/en/v0.4.2
if func.is_constructor:
continue
if not self.is_mixed_case(func.name):
if (
func.visibility
in [
if func.visibility in [
"internal",
"private",
]
and self.is_mixed_case_with_underscore(func.name)
):
] and self.is_mixed_case_with_underscore(func.name):
continue
if func.name.startswith("echidna_") or func.name.startswith("crytic_"):
continue

@ -11,7 +11,7 @@ from slither.core.solidity_types.elementary_type import Int, Uint
def typeRange(t):
bits = int(t.split("int")[1])
if t in Uint:
return 0, (2 ** bits) - 1
return 0, (2**bits) - 1
if t in Int:
v = (2 ** (bits - 1)) - 1
return -v, v

@ -43,7 +43,7 @@ class PrinterWrittenVariablesAndAuthorization(AbstractPrinter):
for contract in self.contracts:
if contract.is_top_level:
continue
txt += "\nContract %s\n" % contract.name
txt += f"\nContract {contract.name}\n"
table = MyPrettyTable(
["Function", "State variables written", "Conditions on msg.sender"]
)

@ -22,12 +22,10 @@ class CFG(AbstractPrinter):
continue
for function in contract.functions + contract.modifiers:
if filename:
new_filename = "{}-{}-{}.dot".format(
filename, contract.name, function.full_name
)
new_filename = f"{filename}-{contract.name}-{function.full_name}.dot"
else:
new_filename = "{}-{}.dot".format(contract.name, function.full_name)
info += "Export {}\n".format(new_filename)
new_filename = f"{contract.name}-{function.full_name}.dot"
info += f"Export {new_filename}\n"
content = function.slithir_cfg_to_dot_str()
with open(new_filename, "w", encoding="utf8") as f:
f.write(content)

@ -26,7 +26,7 @@ def _get_pattern_func(func):
def _get_port_id(var, contract):
return "%s%s" % (var.name, contract.name)
return f"{var.name}{contract.name}"
class PrinterInheritanceGraph(AbstractPrinter):
@ -100,14 +100,10 @@ class PrinterInheritanceGraph(AbstractPrinter):
# Add arrows (number them if there is more than one path so we know order of declaration for inheritance).
if len(contract.immediate_inheritance) == 1:
ret += "%s -> %s;\n" % (contract.name, contract.immediate_inheritance[0])
ret += f"{contract.name} -> {contract.immediate_inheritance[0]};\n"
else:
for i, immediate_inheritance in enumerate(contract.immediate_inheritance):
ret += '%s -> %s [ label="%s" ];\n' % (
contract.name,
immediate_inheritance,
i + 1,
)
ret += f'{contract.name} -> {immediate_inheritance} [ label="{i + 1}" ];\n'
# Functions
visibilities = ["public", "external"]
@ -155,24 +151,24 @@ class PrinterInheritanceGraph(AbstractPrinter):
indirect_shadowing_information = self._get_indirect_shadowing_information(contract)
# Build the node label
ret += '%s[shape="box"' % contract.name
ret += f'{contract.name}[shape="box"'
ret += 'label=< <TABLE border="0">'
ret += '<TR><TD align="center"><B>%s</B></TD></TR>' % contract.name
ret += f'<TR><TD align="center"><B>{contract.name}</B></TD></TR>'
if public_functions:
ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>'
ret += "%s" % public_functions
ret += f"{public_functions}"
if private_functions:
ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>'
ret += "%s" % private_functions
ret += f"{private_functions}"
if modifiers:
ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>'
ret += "%s" % modifiers
ret += f"{modifiers}"
if public_variables:
ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>'
ret += "%s" % public_variables
ret += f"{public_variables}"
if private_variables:
ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>'
ret += "%s" % private_variables
ret += f"{private_variables}"
if indirect_shadowing_information:
ret += (

@ -64,26 +64,22 @@ class ContractSummary(AbstractPrinter):
public = list(collect.items())
for contract, functions in public:
txt += blue(" - From {}\n".format(contract))
txt += blue(f" - From {contract}\n")
functions = sorted(functions, key=lambda f: f.full_name)
for function in functions:
if function.visibility in ["external", "public"]:
txt += green(
" - {} ({})\n".format(function.full_name, function.visibility)
)
txt += green(f" - {function.full_name} ({function.visibility})\n")
if function.visibility in ["internal", "private"]:
txt += magenta(
" - {} ({})\n".format(function.full_name, function.visibility)
)
txt += magenta(f" - {function.full_name} ({function.visibility})\n")
if function.visibility not in [
"external",
"public",
"internal",
"private",
]:
txt += " - {}  ({})\n".format(function.full_name, function.visibility)
txt += f" - {function.full_name}  ({function.visibility})\n"
additional_fields.add(
function, additional_fields={"visibility": function.visibility}

@ -39,7 +39,7 @@ class DataDependency(AbstractPrinter):
for c in self.contracts:
if c.is_top_level:
continue
txt += "\nContract %s\n" % c.name
txt += f"\nContract {c.name}\n"
table = MyPrettyTable(["Variable", "Dependencies"])
for v in c.state_variables:
table.add_row([v.name, _get(v, c)])
@ -48,7 +48,7 @@ class DataDependency(AbstractPrinter):
txt += "\n"
for f in c.functions_and_modifiers_declared:
txt += "\nFunction %s\n" % f.full_name
txt += f"\nFunction {f.full_name}\n"
table = MyPrettyTable(["Variable", "Dependencies"])
for v in f.variables:
table.add_row([v.name, _get(v, f)])

@ -80,7 +80,7 @@ class PrinterEVM(AbstractPrinter):
evm_info = _extract_evm_info(self.slither)
for contract in self.slither.contracts_derived:
txt += blue("Contract {}\n".format(contract.name))
txt += blue(f"Contract {contract.name}\n")
contract_file = self.slither.source_code[
contract.source_mapping["filename_absolute"]
@ -109,19 +109,12 @@ class PrinterEVM(AbstractPrinter):
+ 1
)
txt += green(
"\t\tSource line {}: {}\n".format(
node_source_line,
contract_file_lines[node_source_line - 1].rstrip(),
)
f"\t\tSource line {node_source_line}: {contract_file_lines[node_source_line - 1].rstrip()}\n"
)
txt += magenta("\t\tEVM Instructions:\n")
node_pcs = contract_pcs.get(node_source_line, [])
for pc in node_pcs:
txt += magenta(
"\t\t\t0x{:x}: {}\n".format(
int(pc), contract_cfg.get_instruction_at(pc)
)
)
txt += magenta(f"\t\t\t{hex(pc)}: {contract_cfg.get_instruction_at(pc)}\n")
for modifier in contract.modifiers:
txt += blue(f"\tModifier {modifier.canonical_name}\n")
@ -132,19 +125,12 @@ class PrinterEVM(AbstractPrinter):
+ 1
)
txt += green(
"\t\tSource line {}: {}\n".format(
node_source_line,
contract_file_lines[node_source_line - 1].rstrip(),
)
f"\t\tSource line {node_source_line}: {contract_file_lines[node_source_line - 1].rstrip()}\n"
)
txt += magenta("\t\tEVM Instructions:\n")
node_pcs = contract_pcs.get(node_source_line, [])
for pc in node_pcs:
txt += magenta(
"\t\t\t0x{:x}: {}\n".format(
int(pc), contract_cfg.get_instruction_at(pc)
)
)
txt += magenta(f"\t\t\t{hex(pc)}: {contract_cfg.get_instruction_at(pc)}\n")
self.info(txt)
res = self.generate_output(txt)

@ -36,7 +36,7 @@ class FunctionSummary(AbstractPrinter):
if c.is_top_level:
continue
(name, inheritance, var, func_summaries, modif_summaries) = c.get_summary()
txt = "\nContract %s" % name
txt = f"\nContract {name}"
txt += "\nContract vars: " + str(var)
txt += "\nInheritance:: " + str(inheritance)
table = MyPrettyTable(

@ -23,7 +23,7 @@ class FunctionIds(AbstractPrinter):
txt = ""
all_tables = []
for contract in self.slither.contracts_derived:
txt += "\n{}:\n".format(contract.name)
txt += f"\n{contract.name}:\n"
table = MyPrettyTable(["Name", "ID"])
for function in contract.functions:
if function.visibility in ["public", "external"]:

@ -126,17 +126,17 @@ class PrinterHumanSummary(AbstractPrinter):
medium,
high,
) = self._get_detectors_result()
txt = "Number of optimization issues: {}\n".format(green(optimization))
txt += "Number of informational issues: {}\n".format(green(informational))
txt += "Number of low issues: {}\n".format(green(low))
txt = f"Number of optimization issues: {green(optimization)}\n"
txt += f"Number of informational issues: {green(informational)}\n"
txt += f"Number of low issues: {green(low)}\n"
if medium > 0:
txt += "Number of medium issues: {}\n".format(yellow(medium))
txt += f"Number of medium issues: {yellow(medium)}\n"
else:
txt += "Number of medium issues: {}\n".format(green(medium))
txt += f"Number of medium issues: {green(medium)}\n"
if high > 0:
txt += "Number of high issues: {}\n".format(red(high))
txt += f"Number of high issues: {red(high)}\n"
else:
txt += "Number of high issues: {}\n\n".format(green(high))
txt += f"Number of high issues: {green(high)}\n\n"
return txt, all_results, optimization, informational, low, medium, high

@ -25,7 +25,7 @@ class Modifiers(AbstractPrinter):
all_tables = []
for contract in self.slither.contracts_derived:
txt = "\nContract %s" % contract.name
txt = f"\nContract {contract.name}"
table = MyPrettyTable(["Function", "Modifiers"])
for function in contract.functions:
modifiers = function.modifiers

@ -35,7 +35,7 @@ class RequireOrAssert(AbstractPrinter):
all_tables = []
all_txt = ""
for contract in self.slither.contracts_derived:
txt = "\nContract %s" % contract.name
txt = f"\nContract {contract.name}"
table = MyPrettyTable(["Function", "require or assert"])
for function in contract.functions:
require = function.all_slithir_operations()

@ -9,14 +9,14 @@ def _print_function(function: Function) -> str:
txt = ""
for node in function.nodes:
if node.expression:
txt += "\t\tExpression: {}\n".format(node.expression)
txt += f"\t\tExpression: {node.expression}\n"
txt += "\t\tIRs:\n"
for ir in node.irs:
txt += "\t\t\t{}\n".format(ir)
txt += f"\t\t\t{ir}\n"
elif node.irs:
txt += "\t\tIRs:\n"
for ir in node.irs:
txt += "\t\t\t{}\n".format(ir)
txt += f"\t\t\t{ir}\n"
return txt
@ -38,12 +38,12 @@ class PrinterSlithIR(AbstractPrinter):
for contract in compilation_unit.contracts:
if contract.is_top_level:
continue
txt += "Contract {}\n".format(contract.name)
txt += f"Contract {contract.name}\n"
for function in contract.functions:
txt += f'\tFunction {function.canonical_name} {"" if function.is_shadowed else "(*)"}\n'
txt += _print_function(function)
for modifier in contract.modifiers:
txt += "\tModifier {}\n".format(modifier.canonical_name)
txt += f"\tModifier {modifier.canonical_name}\n"
txt += _print_function(modifier)
if compilation_unit.functions_top_level:
txt += "Top level functions"

@ -23,26 +23,26 @@ class PrinterSlithIRSSA(AbstractPrinter):
for contract in self.contracts:
if contract.is_top_level:
continue
txt += "Contract {}".format(contract.name) + "\n"
txt += f"Contract {contract.name}" + "\n"
for function in contract.functions:
txt += "\tFunction {}".format(function.canonical_name) + "\n"
txt += f"\tFunction {function.canonical_name}" + "\n"
for node in function.nodes:
if node.expression:
txt += "\t\tExpression: {}".format(node.expression) + "\n"
txt += f"\t\tExpression: {node.expression}" + "\n"
if node.irs_ssa:
txt += "\t\tIRs:" + "\n"
for ir in node.irs_ssa:
txt += "\t\t\t{}".format(ir) + "\n"
txt += f"\t\t\t{ir}" + "\n"
for modifier in contract.modifiers:
txt += "\tModifier {}".format(modifier.canonical_name) + "\n"
txt += f"\tModifier {modifier.canonical_name}" + "\n"
for node in modifier.nodes:
txt += str(node) + "\n"
if node.expression:
txt += "\t\tExpression: {}".format(node.expression) + "\n"
txt += f"\t\tExpression: {node.expression}" + "\n"
if node.irs_ssa:
txt += "\t\tIRs:" + "\n"
for ir in node.irs_ssa:
txt += "\t\t\t{}".format(ir) + "\n"
txt += f"\t\t\t{ir}" + "\n"
self.info(txt)
res = self.generate_output(txt)
return res

@ -25,7 +25,7 @@ class VariableOrder(AbstractPrinter):
all_tables = []
for contract in self.slither.contracts_derived:
txt += "\n{}:\n".format(contract.name)
txt += f"\n{contract.name}:\n"
table = MyPrettyTable(["Name", "Type", "Slot", "Offset"])
for variable in contract.state_variables_ordered:
if not variable.is_constant:

@ -23,13 +23,11 @@ def _check_common_things(thing_name, cls, base_cls, instances_list):
if not issubclass(cls, base_cls) or cls is base_cls:
raise Exception(
"You can't register {!r} as a {}. You need to pass a class that inherits from {}".format(
cls, thing_name, base_cls.__name__
)
f"You can't register {cls!r} as a {thing_name}. You need to pass a class that inherits from {base_cls.__name__}"
)
if any(type(obj) == cls for obj in instances_list): # pylint: disable=unidiomatic-typecheck
raise Exception("You can't register {!r} twice.".format(cls))
raise Exception(f"You can't register {cls!r} twice.")
def _update_file_scopes(candidates: ValuesView[FileScope]):

@ -170,10 +170,10 @@ def _fits_under_integer(val: int, can_be_int: bool, can_be_uint) -> List[str]:
assert can_be_int | can_be_uint
while n <= 256:
if can_be_uint:
if val <= 2 ** n - 1:
if val <= 2**n - 1:
ret.append(f"uint{n}")
if can_be_int:
if val <= (2 ** n) / 2 - 1:
if val <= (2**n) / 2 - 1:
ret.append(f"int{n}")
n = n + 8
return ret
@ -214,7 +214,7 @@ def _find_function_from_parameter(ir: Call, candidates: List[Function]) -> Optio
type_args: List[str]
for idx, arg in enumerate(arguments):
if isinstance(arg, (list,)):
type_args = ["{}[{}]".format(get_type(arg[0].type), len(arg))]
type_args = [f"{get_type(arg[0].type)}[{len(arg)}]"]
elif isinstance(arg, Function):
type_args = [arg.signature_str]
else:
@ -771,7 +771,7 @@ def propagate_types(ir, node: "Node"): # pylint: disable=too-many-locals
# temporary operation; they will be removed
pass
else:
raise SlithIRError("Not handling {} during type propagation".format(type(ir)))
raise SlithIRError(f"Not handling {type(ir)} during type propagation")
return None
@ -1043,7 +1043,7 @@ def extract_tmp_call(ins: TmpCall, contract: Optional[Contract]): # pylint: dis
internalcall.set_expression(ins.expression)
return internalcall
raise Exception("Not extracted {} {}".format(type(ins.called), ins))
raise Exception(f"Not extracted {type(ins.called)} {ins}")
# endregion
@ -1102,7 +1102,7 @@ def convert_to_low_level(ir):
new_ir.set_expression(ir.expression)
new_ir.set_node(ir.node)
return new_ir
raise SlithIRError("Incorrect conversion to low level {}".format(ir))
raise SlithIRError(f"Incorrect conversion to low level {ir}")
def can_be_solidity_func(ir) -> bool:
@ -1123,7 +1123,7 @@ def convert_to_solidity_func(ir):
:param ir:
:return:
"""
call = SolidityFunction("abi.{}()".format(ir.function_name))
call = SolidityFunction(f"abi.{ir.function_name}()")
new_ir = SolidityCall(call, ir.nbr_arguments, ir.lvalue, ir.type_call)
new_ir.arguments = ir.arguments
new_ir.set_expression(ir.expression)
@ -1497,7 +1497,7 @@ def convert_type_of_high_and_internal_level_call(ir: Operation, contract: Option
if can_be_solidity_func(ir):
return convert_to_solidity_func(ir)
if not func:
to_log = "Function not found {}".format(ir.function_name)
to_log = f"Function not found {ir.function_name}"
logger.error(to_log)
ir.function = func
if isinstance(func, Function):

@ -41,7 +41,5 @@ class Assignment(OperationWithLValue):
points = self.lvalue.points_to
while isinstance(points, ReferenceVariable):
points = points.points_to
return "{} (->{}) := {}({})".format(self.lvalue, points, self.rvalue, self.rvalue.type)
return "{}({}) := {}({})".format(
self.lvalue, self.lvalue.type, self.rvalue, self.rvalue.type
)
return f"{self.lvalue} (->{points}) := {self.rvalue}({self.rvalue.type})"
return f"{self.lvalue}({self.lvalue.type}) := {self.rvalue}({self.rvalue.type})"

@ -86,7 +86,7 @@ class BinaryType(Enum):
if operation_type == "||":
return BinaryType.OROR
raise SlithIRError("get_type: Unknown operation type {})".format(operation_type))
raise SlithIRError(f"get_type: Unknown operation type {operation_type})")
def can_be_checked_for_overflow(self):
return self in [
@ -137,7 +137,7 @@ class BinaryType(Enum):
return "&&"
if self == BinaryType.OROR:
return "||"
raise SlithIRError("str: Unknown operation type {} {})".format(self, type(self)))
raise SlithIRError(f"str: Unknown operation type {self} {type(self)})")
class Binary(OperationWithLValue):
@ -186,17 +186,6 @@ class Binary(OperationWithLValue):
points = self.lvalue.points_to
while isinstance(points, ReferenceVariable):
points = points.points_to
return "{}(-> {}) = {} {} {}".format(
str(self.lvalue),
points,
self.variable_left,
self.type_str,
self.variable_right,
)
return "{}({}) = {} {} {}".format(
str(self.lvalue),
self.lvalue.type,
self.variable_left,
self.type_str,
self.variable_right,
)
return f"{str(self.lvalue)}(-> {points}) = {self.variable_left} {self.type_str} {self.variable_right}"
return f"{str(self.lvalue)}({self.lvalue.type}) = {self.variable_left} {self.type_str} {self.variable_right}"

@ -21,4 +21,4 @@ class CodeSize(OperationWithLValue):
return self._value
def __str__(self):
return "{} -> CODESIZE {}".format(self.lvalue, self.value)
return f"{self.lvalue} -> CODESIZE {self.value}"

@ -23,4 +23,4 @@ class Condition(Operation):
return self._value
def __str__(self):
return "CONDITION {}".format(self.value)
return f"CONDITION {self.value}"

@ -24,4 +24,4 @@ class Delete(OperationWithLValue):
return self._variable
def __str__(self):
return "{} = delete {} ".format(self.lvalue, self.variable)
return f"{self.lvalue} = delete {self.variable} "

@ -17,4 +17,4 @@ class EventCall(Call):
def __str__(self):
args = [str(a) for a in self.arguments]
return "Emit {}({})".format(self.name, ".".join(args))
return f"Emit {self.name}({'.'.join(args)})"

@ -144,9 +144,9 @@ class HighLevelCall(Call, OperationWithLValue):
value = ""
gas = ""
if self.call_value:
value = "value:{}".format(self.call_value)
value = f"value:{self.call_value}"
if self.call_gas:
gas = "gas:{}".format(self.call_gas)
gas = f"gas:{self.call_gas}"
arguments = []
if self.arguments:
arguments = self.arguments
@ -155,9 +155,9 @@ class HighLevelCall(Call, OperationWithLValue):
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(self.lvalue, ",".join(str(x) for x in self.lvalue.type))
lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = "
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
lvalue = f"{self.lvalue}({self.lvalue.type}) = "
return txt.format(
lvalue,
self.destination,

@ -37,6 +37,4 @@ class Index(OperationWithLValue):
return self._type
def __str__(self):
return "{}({}) -> {}[{}]".format(
self.lvalue, self.lvalue.type, self.variable_left, self.variable_right
)
return f"{self.lvalue}({self.lvalue.type}) -> {self.variable_left}[{self.variable_right}]"

@ -38,4 +38,4 @@ class InitArray(OperationWithLValue):
return str(elem)
init_values = convert(self.init_values)
return "{}({}) = {}".format(self.lvalue, self.lvalue.type, init_values)
return f"{self.lvalue}({self.lvalue.type}) = {init_values}"

@ -70,9 +70,9 @@ class InternalCall(Call, OperationWithLValue): # pylint: disable=too-many-insta
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(self.lvalue, ",".join(str(x) for x in self.lvalue.type))
lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = "
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
lvalue = f"{self.lvalue}({self.lvalue.type}) = "
if self.is_modifier_call:
txt = "{}MODIFIER_CALL, {}({})"
else:

@ -62,14 +62,14 @@ class InternalDynamicCall(
gas = ""
args = [str(a) for a in self.arguments]
if self.call_value:
value = "value:{}".format(self.call_value)
value = f"value:{self.call_value}"
if self.call_gas:
gas = "gas:{}".format(self.call_gas)
gas = f"gas:{self.call_gas}"
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(self.lvalue, ",".join(str(x) for x in self.lvalue.type))
lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = "
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
lvalue = f"{self.lvalue}({self.lvalue.type}) = "
txt = "{}INTERNAL_DYNAMIC_CALL {}({}) {} {}"
return txt.format(lvalue, self.function.name, ",".join(args), value, gas)

@ -21,4 +21,4 @@ class Length(OperationWithLValue):
return self._value
def __str__(self):
return "{} -> LENGTH {}".format(self.lvalue, self.value)
return f"{self.lvalue} -> LENGTH {self.value}"

@ -27,16 +27,16 @@ class LibraryCall(HighLevelCall):
def __str__(self):
gas = ""
if self.call_gas:
gas = "gas:{}".format(self.call_gas)
gas = f"gas:{self.call_gas}"
arguments = []
if self.arguments:
arguments = self.arguments
if not self.lvalue:
lvalue = ""
elif isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(self.lvalue, ",".join(str(x) for x in self.lvalue.type))
lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = "
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
lvalue = f"{self.lvalue}({self.lvalue.type}) = "
txt = "{}LIBRARY_CALL, dest:{}, function:{}, arguments:{} {}"
function_name = self.function_name

@ -90,9 +90,9 @@ class LowLevelCall(Call, OperationWithLValue): # pylint: disable=too-many-insta
value = ""
gas = ""
if self.call_value:
value = "value:{}".format(self.call_value)
value = f"value:{self.call_value}"
if self.call_gas:
gas = "gas:{}".format(self.call_gas)
gas = f"gas:{self.call_gas}"
arguments = []
if self.arguments:
arguments = self.arguments

@ -66,6 +66,4 @@ class Member(OperationWithLValue):
self._gas = gas
def __str__(self):
return "{}({}) -> {}.{}".format(
self.lvalue, self.lvalue.type, self.variable_left, self.variable_right
)
return f"{self.lvalue}({self.lvalue.type}) -> {self.variable_left}.{self.variable_right}"

@ -26,6 +26,4 @@ class NewArray(Call, OperationWithLValue):
def __str__(self):
args = [str(a) for a in self.arguments]
return "{} = new {}{}({})".format(
self.lvalue, self.array_type, "[]" * self.depth, ",".join(args)
)
return f"{self.lvalue} = new {self.array_type}{'[]' * self.depth}({','.join(args)})"

@ -88,8 +88,8 @@ class NewContract(Call, OperationWithLValue): # pylint: disable=too-many-instan
def __str__(self):
options = ""
if self.call_value:
options = "value:{} ".format(self.call_value)
options = f"value:{self.call_value} "
if self.call_salt:
options += "salt:{} ".format(self.call_salt)
options += f"salt:{self.call_salt} "
args = [str(a) for a in self.arguments]
return "{} = new {}({}) {}".format(self.lvalue, self.contract_name, ",".join(args), options)
return f"{self.lvalue} = new {self.contract_name}({','.join(args)}) {options}"

@ -23,4 +23,4 @@ class NewElementaryType(Call, OperationWithLValue):
def __str__(self):
args = [str(a) for a in self.arguments]
return "{} = new {}({})".format(self.lvalue, self._type, ",".join(args))
return f"{self.lvalue} = new {self._type}({','.join(args)})"

@ -29,4 +29,4 @@ class NewStructure(Call, OperationWithLValue):
def __str__(self):
args = [str(a) for a in self.arguments]
return "{} = new {}({})".format(self.lvalue, self.structure_name, ",".join(args))
return f"{self.lvalue} = new {self.structure_name}({','.join(args)})"

@ -33,6 +33,4 @@ class Phi(OperationWithLValue):
return self._nodes
def __str__(self):
return "{}({}) := \u03D5({})".format(
self.lvalue, self.lvalue.type, [str(v) for v in self._rvalues]
)
return "{self.lvalue}({self.lvalue.type}) := \u03D5({[str(v) for v in self._rvalues]})"

@ -39,6 +39,4 @@ class PhiCallback(Phi):
return self._nodes
def __str__(self):
return "{}({}) := \u03D5({})".format(
self.lvalue, self.lvalue.type, [v.ssa_name for v in self._rvalues]
)
return f"{self.lvalue}({self.lvalue.type}) := \u03D5({[v.ssa_name for v in self._rvalues]})"

@ -24,4 +24,4 @@ class Push(OperationWithLValue):
return self._value
def __str__(self):
return "PUSH {} in {}".format(self.value, self.lvalue)
return f"PUSH {self.value} in {self.lvalue}"

@ -51,4 +51,4 @@ class Return(Operation):
return self._unroll(self._values)
def __str__(self):
return "RETURN {}".format(",".join(["{}".format(x) for x in self.values]))
return f"RETURN {','.join([f'{x}' for x in self.values])}"

@ -31,8 +31,8 @@ class Send(Call, OperationWithLValue):
return self._destination
def __str__(self):
value = "value:{}".format(self.call_value)
return str(self.lvalue) + " = SEND dest:{} {}".format(self.destination, value)
value = f"value:{self.call_value}"
return str(self.lvalue) + f" = SEND dest:{self.destination} {value}"
#

@ -43,7 +43,7 @@ class SolidityCall(Call, OperationWithLValue):
lvalue = ""
if self.lvalue:
if isinstance(self.lvalue.type, (list,)):
lvalue = "{}({}) = ".format(self.lvalue, ",".join(str(x) for x in self.lvalue.type))
lvalue = f"{self.lvalue}({','.join(str(x) for x in self.lvalue.type)}) = "
else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type)
return lvalue + "SOLIDITY_CALL {}({})".format(self.function.full_name, args)
lvalue = f"{self.lvalue}({self.lvalue.type}) = "
return lvalue + f"SOLIDITY_CALL {self.function.full_name}({args})"

@ -27,5 +27,5 @@ class Transfer(Call):
return self._destination
def __str__(self):
value = "value:{}".format(self.call_value)
return "Transfer dest:{} {}".format(self.destination, value)
value = f"value:{self.call_value}"
return f"Transfer dest:{self.destination} {value}"

@ -28,4 +28,4 @@ class TypeConversion(OperationWithLValue):
return [self.variable]
def __str__(self):
return str(self.lvalue) + " = CONVERT {} to {}".format(self.variable, self.type)
return str(self.lvalue) + f" = CONVERT {self.variable} to {self.type}"

@ -19,7 +19,7 @@ class UnaryType(Enum):
return UnaryType.BANG
if operation_type == "~":
return UnaryType.TILD
raise SlithIRError("get_type: Unknown operation type {}".format(operation_type))
raise SlithIRError(f"get_type: Unknown operation type {operation_type}")
def __str__(self):
if self == UnaryType.BANG:
@ -27,7 +27,7 @@ class UnaryType(Enum):
if self == UnaryType.TILD:
return "~"
raise SlithIRError("str: Unknown operation type {}".format(self))
raise SlithIRError(f"str: Unknown operation type {self}")
class Unary(OperationWithLValue):
@ -56,4 +56,4 @@ class Unary(OperationWithLValue):
return str(self._type)
def __str__(self):
return "{} = {} {} ".format(self.lvalue, self.type_str, self.rvalue)
return f"{self.lvalue} = {self.type_str} {self.rvalue} "

@ -26,6 +26,4 @@ class Unpack(OperationWithLValue):
return self._idx
def __str__(self):
return "{}({})= UNPACK {} index: {} ".format(
self.lvalue, self.lvalue.type, self.tuple, self.index
)
return f"{self.lvalue}({self.lvalue.type})= UNPACK {self.tuple} index: {self.index} "

@ -95,4 +95,4 @@ class TmpCall(OperationWithLValue): # pylint: disable=too-many-instance-attribu
self._ori = ori
def __str__(self):
return str(self.lvalue) + " = TMPCALL{} ".format(self.nbr_arguments) + str(self._called)
return str(self.lvalue) + f" = TMPCALL{self.nbr_arguments} " + str(self._called)

@ -23,4 +23,4 @@ class TmpNewArray(OperationWithLValue):
return self._depth
def __str__(self):
return "{} = new {}{}".format(self.lvalue, self.array_type, "[]" * self._depth)
return f"{self.lvalue} = new {self.array_type}{'[]' * self._depth}"

@ -34,4 +34,4 @@ class TmpNewContract(OperationWithLValue):
return []
def __str__(self):
return "{} = new {}".format(self.lvalue, self.contract_name)
return f"{self.lvalue} = new {self.contract_name}"

@ -18,4 +18,4 @@ class TmpNewElementaryType(OperationWithLValue):
return self._type
def __str__(self):
return "{} = new {}".format(self.lvalue, self._type)
return f"{self.lvalue} = new {self._type}"

@ -16,4 +16,4 @@ class TmpNewStructure(OperationWithLValue):
return []
def __str__(self):
return "{} = tmpnew {}".format(self.lvalue, self.contract_name)
return f"{self.lvalue} = tmpnew {self.contract_name}"

@ -822,7 +822,7 @@ def copy_ir(ir, *instances):
value = get_variable(ir, lambda x: x.value, *instances)
return Length(value, lvalue)
raise SlithIRError("Impossible ir copy on {} ({})".format(ir, type(ir)))
raise SlithIRError(f"Impossible ir copy on {ir} ({type(ir)})")
# endregion

@ -74,4 +74,4 @@ class Constant(SlithIRVariable):
return self.value < other
def __repr__(self):
return "%s" % (str(self.value))
return f"{str(self.value)}"

@ -69,5 +69,5 @@ class LocalIRVariable(
@property
def ssa_name(self):
if self.is_storage:
return "{}_{} (-> {})".format(self._name, self.index, [v.name for v in self.refers_to])
return "{}_{}".format(self._name, self.index)
return f"{self._name}_{self.index} (-> {[v.name for v in self.refers_to]})"
return f"{self._name}_{self.index}"

@ -57,7 +57,7 @@ class ReferenceVariable(ChildNode, Variable):
@property
def name(self):
return "REF_{}".format(self.index)
return f"REF_{self.index}"
# overide of core.variables.variables
# reference can have Function has a type

@ -43,4 +43,4 @@ class StateIRVariable(
@property
def ssa_name(self):
return "{}_{}".format(self._name, self.index)
return f"{self._name}_{self.index}"

@ -27,7 +27,7 @@ class TemporaryVariable(ChildNode, Variable):
@property
def name(self):
return "TMP_{}".format(self.index)
return f"TMP_{self.index}"
def __str__(self):
return self.name

@ -28,7 +28,7 @@ class TupleVariable(ChildNode, SlithIRVariable):
@property
def name(self):
return "TUPLE_{}".format(self.index)
return f"TUPLE_{self.index}"
def __str__(self):
return self.name

@ -148,8 +148,8 @@ class FunctionSolc(CallerContextExpression):
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 += "_scope_{}".format(
self._counter_scope_local_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]
@ -661,7 +661,7 @@ class FunctionSolc(CallerContextExpression):
externalCall = statement.get("externalCall", None)
if externalCall is None:
raise ParsingError("Try/Catch not correctly parsed by Slither %s" % statement)
raise ParsingError(f"Try/Catch not correctly parsed by Slither {statement}")
catch_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope
)
@ -678,7 +678,7 @@ class FunctionSolc(CallerContextExpression):
block = statement.get("block", None)
if block is None:
raise ParsingError("Catch not correctly parsed by Slither %s" % statement)
raise ParsingError(f"Catch not correctly parsed by Slither {statement}")
try_scope = Scope(node.underlying_node.scope.is_checked, False, node.underlying_node.scope)
try_node = self._new_node(NodeType.CATCH, statement["src"], try_scope)
@ -1011,7 +1011,7 @@ class FunctionSolc(CallerContextExpression):
link_underlying_nodes(node, new_node)
node = new_node
else:
raise ParsingError("Statement not parsed %s" % name)
raise ParsingError(f"Statement not parsed {name}")
return node
@ -1124,7 +1124,7 @@ class FunctionSolc(CallerContextExpression):
# We start with -1 as counter to catch this corner case
end_node = self._find_end_loop(node, [], -1)
if not end_node:
raise ParsingError("Break in no-loop context {}".format(node.function))
raise ParsingError(f"Break in no-loop context {node.function}")
for son in node.sons:
son.remove_father(node)
@ -1135,7 +1135,7 @@ class FunctionSolc(CallerContextExpression):
start_node = self._find_start_loop(node, [])
if not start_node:
raise ParsingError("Continue in no-loop context {}".format(node.node_id))
raise ParsingError(f"Continue in no-loop context {node.node_id}")
for son in node.sons:
son.remove_father(node)

@ -510,7 +510,7 @@ def parse_expression(expression: Dict, caller_context: CallerContextExpression)
super_name = parse_super_name(expression, is_compact_ast)
var, was_created = find_variable(super_name, caller_context, is_super=True)
if var is None:
raise VariableNotFound("Variable not found: {}".format(super_name))
raise VariableNotFound(f"Variable not found: {super_name}")
if was_created:
var.set_offset(src, caller_context.compilation_unit)
sup = SuperIdentifier(var)
@ -567,7 +567,7 @@ def parse_expression(expression: Dict, caller_context: CallerContextExpression)
elif type_name[caller_context.get_key()] == "FunctionTypeName":
array_type = parse_type(type_name, caller_context)
else:
raise ParsingError("Incorrect type array {}".format(type_name))
raise ParsingError(f"Incorrect type array {type_name}")
array = NewArray(depth, array_type)
array.set_offset(src, caller_context.compilation_unit)
return array
@ -646,4 +646,4 @@ def parse_expression(expression: Dict, caller_context: CallerContextExpression)
raise ParsingError("IdentifierPath not currently supported for the legacy ast")
raise ParsingError("Expression not parsed %s" % name)
raise ParsingError(f"Expression not parsed {name}")

@ -407,4 +407,4 @@ def find_variable(
if ret:
return ret, False
raise VariableNotFound("Variable not found: {} (context {})".format(var_name, contract))
raise VariableNotFound(f"Variable not found: {var_name} (context {contract})")

@ -65,7 +65,7 @@ class VariableDeclarationSolc:
elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, variable_data.get("value", None))
else:
raise ParsingError("Incorrect variable declaration type {}".format(nodeType))
raise ParsingError(f"Incorrect variable declaration type {nodeType}")
else:
nodeType = variable_data["name"]
@ -89,7 +89,7 @@ class VariableDeclarationSolc:
elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, False)
else:
raise ParsingError("Incorrect variable declaration type {}".format(nodeType))
raise ParsingError(f"Incorrect variable declaration type {nodeType}")
@property
def underlying_variable(self) -> Variable:

@ -455,7 +455,7 @@ def convert_yul_switch(
expression_ast = ast["expression"]
# this variable stores the result of the expression so we don't accidentally compute it more than once
switch_expr_var = "switch_expr_{}".format(ast["src"].replace(":", "_"))
switch_expr_var = f"switch_expr_{ast['src'].replace(':', '_')}"
rewritten_switch = {
"nodeType": "YulBlock",
@ -851,7 +851,7 @@ def vars_to_typestr(rets: List[Expression]) -> str:
return ""
if len(rets) == 1:
return str(rets[0].type)
return "tuple({})".format(",".join(str(ret.type) for ret in rets))
return f"tuple({','.join(str(ret.type) for ret in rets)})"
def vars_to_val(vars_to_convert):

@ -142,35 +142,35 @@ def ntype(_type): # pylint: disable=too-many-branches
def encode_ir(ir): # pylint: disable=too-many-branches
# operations
if isinstance(ir, Assignment):
return "({}):=({})".format(encode_ir(ir.lvalue), encode_ir(ir.rvalue))
return f"({encode_ir(ir.lvalue)}):=({encode_ir(ir.rvalue)})"
if isinstance(ir, Index):
return "index({})".format(ntype(ir.index_type))
return f"index({ntype(ir.index_type)})"
if isinstance(ir, Member):
return "member" # .format(ntype(ir._type))
if isinstance(ir, Length):
return "length"
if isinstance(ir, Binary):
return "binary({})".format(str(ir.type))
return f"binary({str(ir.type)})"
if isinstance(ir, Unary):
return "unary({})".format(str(ir.type))
return f"unary({str(ir.type)})"
if isinstance(ir, Condition):
return "condition({})".format(encode_ir(ir.value))
return f"condition({encode_ir(ir.value)})"
if isinstance(ir, NewStructure):
return "new_structure"
if isinstance(ir, NewContract):
return "new_contract"
if isinstance(ir, NewArray):
return "new_array({})".format(ntype(ir.array_type))
return f"new_array({ntype(ir.array_type)})"
if isinstance(ir, NewElementaryType):
return "new_elementary({})".format(ntype(ir.type))
return f"new_elementary({ntype(ir.type)})"
if isinstance(ir, Push):
return "push({},{})".format(encode_ir(ir.value), encode_ir(ir.lvalue))
return f"push({encode_ir(ir.value)},{encode_ir(ir.lvalue)})"
if isinstance(ir, Delete):
return "delete({},{})".format(encode_ir(ir.lvalue), encode_ir(ir.variable))
return f"delete({encode_ir(ir.lvalue)},{encode_ir(ir.variable)})"
if isinstance(ir, SolidityCall):
return "solidity_call({})".format(ir.function.full_name)
return f"solidity_call({ir.function.full_name})"
if isinstance(ir, InternalCall):
return "internal_call({})".format(ntype(ir.type_call))
return f"internal_call({ntype(ir.type_call)})"
if isinstance(ir, EventCall): # is this useful?
return "event"
if isinstance(ir, LibraryCall):
@ -182,13 +182,13 @@ def encode_ir(ir): # pylint: disable=too-many-branches
if isinstance(ir, LowLevelCall): # TODO: improve
return "low_level_call"
if isinstance(ir, TypeConversion):
return "type_conversion({})".format(ntype(ir.type))
return f"type_conversion({ntype(ir.type)})"
if isinstance(ir, Return): # this can be improved using values
return "return" # .format(ntype(ir.type))
if isinstance(ir, Transfer):
return "transfer({})".format(encode_ir(ir.call_value))
return f"transfer({encode_ir(ir.call_value)})"
if isinstance(ir, Send):
return "send({})".format(encode_ir(ir.call_value))
return f"send({encode_ir(ir.call_value)})"
if isinstance(ir, Unpack): # TODO: improve
return "unpack"
if isinstance(ir, InitArray): # TODO: improve
@ -198,19 +198,19 @@ def encode_ir(ir): # pylint: disable=too-many-branches
# variables
if isinstance(ir, Constant):
return "constant({})".format(ntype(ir.type))
return f"constant({ntype(ir.type)})"
if isinstance(ir, SolidityVariableComposed):
return "solidity_variable_composed({})".format(ir.name)
return f"solidity_variable_composed({ir.name})"
if isinstance(ir, SolidityVariable):
return "solidity_variable{}".format(ir.name)
return f"solidity_variable{ir.name}"
if isinstance(ir, TemporaryVariable):
return "temporary_variable"
if isinstance(ir, ReferenceVariable):
return "reference({})".format(ntype(ir.type))
return f"reference({ntype(ir.type)})"
if isinstance(ir, LocalVariable):
return "local_solc_variable({})".format(ir.location)
return f"local_solc_variable({ir.location})"
if isinstance(ir, StateVariable):
return "state_solc_variable({})".format(ntype(ir.type))
return f"state_solc_variable({ntype(ir.type)})"
if isinstance(ir, LocalVariableInitFromTuple):
return "local_variable_init_tuple"
if isinstance(ir, TupleVariable):

@ -40,7 +40,7 @@ def info(args):
x = (filename, contract, fname)
y = " ".join(irs[x])
to_log = "Function {} in contract {} is encoded as:".format(fname, contract)
to_log = f"Function {fname} in contract {contract} is encoded as:"
logger.info(to_log)
logger.info(y)
if model is not None:
@ -48,7 +48,7 @@ def info(args):
logger.info(fvector)
except Exception: # pylint: disable=broad-except
to_log = "Error in %s" % args.filename
to_log = f"Error in {args.filename}"
logger.error(to_log)
logger.error(traceback.format_exc())
sys.exit(-1)

@ -80,6 +80,6 @@ def plot(args): # pylint: disable=too-many-locals
plt.savefig("plot.png", bbox_inches="tight")
except Exception: # pylint: disable=broad-except
logger.error("Error in %s" % args.filename)
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)

@ -47,6 +47,6 @@ def test(args):
logger.info(format_table.format(*(list(x) + [score])))
except Exception: # pylint: disable=broad-except
logger.error("Error in %s" % args.filename)
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)

@ -49,6 +49,6 @@ def train(args): # pylint: disable=too-many-locals
logger.info("Done!")
except Exception: # pylint: disable=broad-except
logger.error("Error in %s" % args.filename)
logger.error(f"Error in {args.filename}")
logger.error(traceback.format_exc())
sys.exit(-1)

@ -102,7 +102,7 @@ def choose_detectors(detectors_to_run, detectors_to_exclude):
continue
cls_detectors_to_run.append(all_detectors[d])
else:
raise Exception("Error: {} is not a detector".format(d))
raise Exception(f"Error: {d} is not a detector")
return cls_detectors_to_run

@ -187,7 +187,7 @@ def main():
v1_name = args.ContractName
v1_contracts = variable1.get_contract_from_name(v1_name)
if len(v1_contracts) != 1:
info = "Contract {} not found in {}".format(v1_name, variable1.filename)
info = f"Contract {v1_name} not found in {variable1.filename}"
logger.error(red(info))
if args.json:
output_to_json(args.json, str(info), json_results)

@ -134,7 +134,7 @@ class AbstractCheck(metaclass=abc.ABCMeta):
info = "\n"
for result in all_results:
info += result["description"]
info += "Reference: {}".format(self.WIKI)
info += f"Reference: {self.WIKI}"
self._log(info)
return all_results

@ -18,10 +18,10 @@ def output_wiki(detector_classes, filter_wiki):
exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
recommendation = detector.WIKI_RECOMMENDATION
print("\n## {}".format(title))
print(f"\n## {title}")
print("### Configuration")
print("* Check: `{}`".format(argument))
print("* Severity: `{}`".format(impact))
print(f"* Check: `{argument}`")
print(f"* Severity: `{impact}`")
print("\n### Description")
print(description)
if exploit_scenario:
@ -64,7 +64,7 @@ def output_to_markdown(detector_classes, _filter_wiki):
def extract_help(cls):
if cls.WIKI == "":
return cls.HELP
return "[{}]({})".format(cls.HELP, cls.WIKI)
return f"[{cls.HELP}]({cls.WIKI})"
detectors_list = []
for detector in detector_classes:
@ -80,14 +80,7 @@ def output_to_markdown(detector_classes, _filter_wiki):
idx = 1
for (argument, help_info, impact, proxy, v2) in detectors_list:
print(
"{} | `{}` | {} | {} | {} | {}".format(
idx,
argument,
help_info,
classification_txt[impact],
"X" if proxy else "",
"X" if v2 else "",
)
f"{idx} | `{argument}` | {help_info} | {classification_txt[impact]} | {'X' if proxy else ''} | {'X' if v2 else ''}"
)
idx = idx + 1

@ -14,7 +14,7 @@ class Colors: # pylint: disable=too-few-public-methods
def colorize(color: Colors, txt: str) -> str:
if Colors.COLORIZATION_ENABLED:
return "{}{}{}".format(color, txt, Colors.END)
return f"{color}{txt}{Colors.END}"
return txt

@ -68,19 +68,15 @@ def read_config_file(args):
for key, elem in config.items():
if key not in defaults_flag_in_config:
logger.info(
yellow(
"{} has an unknown key: {} : {}".format(args.config_file, key, elem)
)
yellow(f"{args.config_file} has an unknown key: {key} : {elem}")
)
continue
if getattr(args, key) == defaults_flag_in_config[key]:
setattr(args, key, elem)
except json.decoder.JSONDecodeError as e:
logger.error(
red("Impossible to read {}, please check the file {}".format(args.config_file, e))
)
logger.error(red(f"Impossible to read {args.config_file}, please check the file {e}"))
else:
logger.error(red("File {} is not a file or does not exist".format(args.config_file)))
logger.error(red(f"File {args.config_file} is not a file or does not exist"))
logger.error(yellow("Falling back to the default settings..."))
@ -88,7 +84,7 @@ def output_to_markdown(detector_classes, printer_classes, filter_wiki):
def extract_help(cls):
if cls.WIKI == "":
return cls.HELP
return "[{}]({})".format(cls.HELP, cls.WIKI)
return f"[{cls.HELP}]({cls.WIKI})"
detectors_list = []
print(filter_wiki)
@ -110,11 +106,7 @@ def output_to_markdown(detector_classes, printer_classes, filter_wiki):
)
idx = 1
for (argument, help_info, impact, confidence) in detectors_list:
print(
"{} | `{}` | {} | {} | {}".format(
idx, argument, help_info, classification_txt[impact], confidence
)
)
print(f"{idx} | `{argument}` | {help_info} | {classification_txt[impact]} | {confidence}")
idx = idx + 1
print()
@ -128,7 +120,7 @@ def output_to_markdown(detector_classes, printer_classes, filter_wiki):
printers_list = sorted(printers_list, key=lambda element: (element[0]))
idx = 1
for (argument, help_info) in printers_list:
print("{} | `{}` | {}".format(idx, argument, help_info))
print(f"{idx} | `{argument}` | {help_info}")
idx = idx + 1
@ -214,11 +206,11 @@ def output_wiki(detector_classes, filter_wiki):
exploit_scenario = detector.WIKI_EXPLOIT_SCENARIO
recommendation = detector.WIKI_RECOMMENDATION
print("\n## {}".format(title))
print(f"\n## {title}")
print("### Configuration")
print("* Check: `{}`".format(check))
print("* Severity: `{}`".format(impact))
print("* Confidence: `{}`".format(confidence))
print(f"* Check: `{check}`")
print(f"* Severity: `{impact}`")
print(f"* Confidence: `{confidence}`")
print("\n### Description")
print(description)
if exploit_scenario:

@ -20,7 +20,7 @@ class ComparableEnum(Enum):
return False
def __repr__(self):
return "%s" % (str(self.value))
return f"{str(self.value)}"
def __hash__(self):
return hash(self.value)

@ -135,5 +135,5 @@ class SplitTernaryExpression:
else:
raise SlitherException(
"Ternary operation not handled {}({})".format(expression, type(expression))
f"Ternary operation not handled {expression}({type(expression)})"
)

@ -23,6 +23,6 @@ def convert_string_to_int(val: Union[str, int]) -> int:
f"{base}e{expo} is too large to fit in any Solidity integer size"
)
return 0
return int(Decimal(base) * Decimal(10 ** expo))
return int(Decimal(base) * Decimal(10**expo))
return int(Decimal(val))

@ -43,7 +43,7 @@ class ConstantFolding(ExpressionVisitor):
left = get_val(expression.expression_left)
right = get_val(expression.expression_right)
if expression.type == BinaryOperationType.POWER:
set_val(expression, left ** right)
set_val(expression, left**right)
elif expression.type == BinaryOperationType.MULTIPLICATION:
set_val(expression, left * right)
elif expression.type == BinaryOperationType.DIVISION:

@ -90,7 +90,7 @@ class ExpressionVisitor:
pass
else:
raise SlitherError("Expression not handled: {}".format(expression))
raise SlitherError(f"Expression not handled: {expression}")
self._post_visit(expression)
@ -209,7 +209,7 @@ class ExpressionVisitor:
pass
else:
raise SlitherError("Expression not handled: {}".format(expression))
raise SlitherError(f"Expression not handled: {expression}")
# pre_expression_name
@ -310,7 +310,7 @@ class ExpressionVisitor:
pass
else:
raise SlitherError("Expression not handled: {}".format(expression))
raise SlitherError(f"Expression not handled: {expression}")
# post_expression_name

@ -21,26 +21,26 @@ class ExpressionPrinter(ExpressionVisitor):
def _post_assignement_operation(self, expression):
left = get(expression.expression_left)
right = get(expression.expression_right)
val = "{} {} {}".format(left, expression.type, right)
val = f"{left} {expression.type} {right}"
set_val(expression, val)
def _post_binary_operation(self, expression):
left = get(expression.expression_left)
right = get(expression.expression_right)
val = "{} {} {}".format(left, expression.type, right)
val = f"{left} {expression.type} {right}"
set_val(expression, val)
def _post_call_expression(self, expression):
called = get(expression.called)
arguments = [get(x) for x in expression.arguments if x]
val = "{}({})".format(called, ",".join(arguments))
arguments = ",".join([get(x) for x in expression.arguments if x])
val = f"{called}({arguments})"
set_val(expression, val)
def _post_conditional_expression(self, expression):
if_expr = get(expression.if_expression)
else_expr = get(expression.else_expression)
then_expr = get(expression.then_expression)
val = "if {} then {} else {}".format(if_expr, else_expr, then_expr)
val = f"if {if_expr} then {else_expr} else {then_expr}"
set_val(expression, val)
def _post_elementary_type_name_expression(self, expression):
@ -52,7 +52,7 @@ class ExpressionPrinter(ExpressionVisitor):
def _post_index_access(self, expression):
left = get(expression.expression_left)
right = get(expression.expression_right)
val = "{}[{}]".format(left, right)
val = f"{left}[{right}]"
set_val(expression, val)
def _post_literal(self, expression):
@ -61,41 +61,41 @@ class ExpressionPrinter(ExpressionVisitor):
def _post_member_access(self, expression):
expr = get(expression.expression)
member_name = str(expression.member_name)
val = "{}.{}".format(expr, member_name)
val = f"{expr}.{member_name}"
set_val(expression, val)
def _post_new_array(self, expression):
array = str(expression.array_type)
depth = expression.depth
val = "new {}{}".format(array, "[]" * depth)
val = f"new {array}{'[]' * depth}"
set_val(expression, val)
def _post_new_contract(self, expression):
contract = str(expression.contract_name)
val = "new {}".format(contract)
val = f"new {contract}"
set_val(expression, val)
def _post_new_elementary_type(self, expression):
t = str(expression.type)
val = "new {}".format(t)
val = f"new {t}"
set_val(expression, val)
def _post_tuple_expression(self, expression):
expressions = [get(e) for e in expression.expressions if e]
val = "({})".format(",".join(expressions))
val = f"({','.join(expressions)})"
set_val(expression, val)
def _post_type_conversion(self, expression):
t = str(expression.type)
expr = get(expression.expression)
val = "{}({})".format(t, expr)
val = f"{t}({expr})"
set_val(expression, val)
def _post_unary_operation(self, expression):
t = str(expression.type)
expr = get(expression.expression)
if expression.is_prefix:
val = "{}{}".format(t, expr)
val = f"{t}{expr}"
else:
val = "{}{}".format(expr, t)
val = f"{expr}{t}"
set_val(expression, val)

@ -321,7 +321,7 @@ class ExpressionToSlithIR(ExpressionVisitor):
set_val(expression, val)
def _post_conditional_expression(self, expression):
raise Exception("Ternary operator are not convertible to SlithIR {}".format(expression))
raise Exception(f"Ternary operator are not convertible to SlithIR {expression}")
def _post_elementary_type_name_expression(self, expression):
set_val(expression, expression.type)
@ -517,4 +517,4 @@ class ExpressionToSlithIR(ExpressionVisitor):
self._result.append(operation)
set_val(expression, lvalue)
else:
raise SlithIRError("Unary operation to IR not supported {}".format(expression))
raise SlithIRError(f"Unary operation to IR not supported {expression}")

Loading…
Cancel
Save