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. 4
      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/printers/functions/authorization.py
  19. 8
      slither/printers/functions/cfg.py
  20. 24
      slither/printers/inheritance/inheritance_graph.py
  21. 12
      slither/printers/summary/contract.py
  22. 4
      slither/printers/summary/data_depenency.py
  23. 24
      slither/printers/summary/evm.py
  24. 2
      slither/printers/summary/function.py
  25. 2
      slither/printers/summary/function_ids.py
  26. 14
      slither/printers/summary/human_summary.py
  27. 2
      slither/printers/summary/modifier_calls.py
  28. 2
      slither/printers/summary/require_calls.py
  29. 10
      slither/printers/summary/slithir.py
  30. 14
      slither/printers/summary/slithir_ssa.py
  31. 2
      slither/printers/summary/variable_order.py
  32. 6
      slither/slither.py
  33. 12
      slither/slithir/convert.py
  34. 6
      slither/slithir/operations/assignment.py
  35. 21
      slither/slithir/operations/binary.py
  36. 2
      slither/slithir/operations/codesize.py
  37. 2
      slither/slithir/operations/condition.py
  38. 2
      slither/slithir/operations/delete.py
  39. 2
      slither/slithir/operations/event_call.py
  40. 8
      slither/slithir/operations/high_level_call.py
  41. 4
      slither/slithir/operations/index.py
  42. 2
      slither/slithir/operations/init_array.py
  43. 4
      slither/slithir/operations/internal_call.py
  44. 8
      slither/slithir/operations/internal_dynamic_call.py
  45. 2
      slither/slithir/operations/length.py
  46. 6
      slither/slithir/operations/library_call.py
  47. 4
      slither/slithir/operations/low_level_call.py
  48. 4
      slither/slithir/operations/member.py
  49. 4
      slither/slithir/operations/new_array.py
  50. 6
      slither/slithir/operations/new_contract.py
  51. 2
      slither/slithir/operations/new_elementary_type.py
  52. 2
      slither/slithir/operations/new_structure.py
  53. 4
      slither/slithir/operations/phi.py
  54. 4
      slither/slithir/operations/phi_callback.py
  55. 2
      slither/slithir/operations/push.py
  56. 2
      slither/slithir/operations/return_operation.py
  57. 4
      slither/slithir/operations/send.py
  58. 6
      slither/slithir/operations/solidity_call.py
  59. 4
      slither/slithir/operations/transfer.py
  60. 2
      slither/slithir/operations/type_conversion.py
  61. 6
      slither/slithir/operations/unary.py
  62. 4
      slither/slithir/operations/unpack.py
  63. 2
      slither/slithir/tmp_operations/tmp_call.py
  64. 2
      slither/slithir/tmp_operations/tmp_new_array.py
  65. 2
      slither/slithir/tmp_operations/tmp_new_contract.py
  66. 2
      slither/slithir/tmp_operations/tmp_new_elementary_type.py
  67. 2
      slither/slithir/tmp_operations/tmp_new_structure.py
  68. 2
      slither/slithir/utils/ssa.py
  69. 2
      slither/slithir/variables/constant.py
  70. 4
      slither/slithir/variables/local_variable.py
  71. 2
      slither/slithir/variables/reference.py
  72. 2
      slither/slithir/variables/state_variable.py
  73. 2
      slither/slithir/variables/temporary.py
  74. 2
      slither/slithir/variables/tuple.py
  75. 14
      slither/solc_parsing/declarations/function.py
  76. 6
      slither/solc_parsing/expressions/expression_parsing.py
  77. 2
      slither/solc_parsing/expressions/find_variable.py
  78. 4
      slither/solc_parsing/variables/variable_declaration.py
  79. 4
      slither/solc_parsing/yul/parse_yul.py
  80. 40
      slither/tools/similarity/encode.py
  81. 4
      slither/tools/similarity/info.py
  82. 2
      slither/tools/similarity/plot.py
  83. 2
      slither/tools/similarity/test.py
  84. 2
      slither/tools/similarity/train.py
  85. 2
      slither/tools/slither_format/slither_format.py
  86. 2
      slither/tools/upgradeability/__main__.py
  87. 2
      slither/tools/upgradeability/checks/abstract_checks.py
  88. 17
      slither/tools/upgradeability/utils/command_line.py
  89. 2
      slither/utils/colors.py
  90. 28
      slither/utils/command_line.py
  91. 2
      slither/utils/comparable_enum.py
  92. 2
      slither/utils/expression_manipulations.py
  93. 6
      slither/visitors/expression/expression.py
  94. 28
      slither/visitors/expression/expression_printer.py
  95. 4
      slither/visitors/slithir/expression_to_slithir.py

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

@ -208,7 +208,7 @@ def choose_detectors(args, all_detector_classes):
if detector in detectors: if detector in detectors:
detectors_to_run.append(detectors[detector]) detectors_to_run.append(detectors[detector])
else: 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) detectors_to_run = sorted(detectors_to_run, key=lambda x: x.IMPACT)
return detectors_to_run return detectors_to_run

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

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

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

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

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

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

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

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

@ -140,8 +140,8 @@ M = list(range(8, 257, 8))
N = list(range(0, 81)) N = list(range(0, 81))
MN = list(itertools.product(M, N)) MN = list(itertools.product(M, N))
Fixed = ["fixed{}x{}".format(m, n) for (m, n) in MN] + ["fixed"] Fixed = [f"fixed{m}x{n}" for (m, n) in MN] + ["fixed"]
Ufixed = ["ufixed{}x{}".format(m, n) for (m, n) in MN] + ["ufixed"] Ufixed = [f"ufixed{m}x{n}" for (m, n) in MN] + ["ufixed"]
ElementaryTypeName = ["address", "bool", "string", "var"] + Int + Uint + Byte + Fixed + 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]) params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values]) return_values = ",".join([str(x.type) for x in self._return_values])
if return_values: if return_values:
return "function({}) returns({})".format(params, return_values) return f"function({params}) returns({return_values})"
return "function({})".format(params) return f"function({params})"
@property @property
def parameters_signature(self) -> str: def parameters_signature(self) -> str:
@ -49,7 +49,7 @@ class FunctionType(Type):
# Use x.type # Use x.type
# x.name may be empty # x.name may be empty
params = ",".join([str(x.type) for x in self._params]) params = ",".join([str(x.type) for x in self._params])
return "({})".format(params) return f"({params})"
@property @property
def signature(self) -> str: def signature(self) -> str:
@ -61,8 +61,8 @@ class FunctionType(Type):
params = ",".join([str(x.type) for x in self._params]) params = ",".join([str(x.type) for x in self._params])
return_values = ",".join([str(x.type) for x in self._return_values]) return_values = ",".join([str(x.type) for x in self._return_values])
if return_values: if return_values:
return "({}) returns({})".format(params, return_values) return f"({params}) returns({return_values})"
return "({})".format(params) return f"({params})"
def __eq__(self, other): def __eq__(self, other):
if not isinstance(other, FunctionType): if not isinstance(other, FunctionType):

@ -24,7 +24,7 @@ class MappingType(Type):
return 32, True return 32, True
def __str__(self): 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): def __eq__(self, other):
if not isinstance(other, MappingType): if not isinstance(other, MappingType):

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

@ -58,4 +58,4 @@ class LocalVariable(ChildFunction, Variable):
@property @property
def canonical_name(self) -> str: 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 @property
def canonical_name(self) -> str: def canonical_name(self) -> str:
return "{}.{}".format(self.contract.name, self.name) return f"{self.contract.name}.{self.name}"
@property @property
def full_name(self) -> str: 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: if func.is_constructor:
continue continue
if not self.is_mixed_case(func.name): if not self.is_mixed_case(func.name):
if ( if func.visibility in [
func.visibility
in [
"internal", "internal",
"private", "private",
] ] and self.is_mixed_case_with_underscore(func.name):
and self.is_mixed_case_with_underscore(func.name)
):
continue continue
if func.name.startswith("echidna_") or func.name.startswith("crytic_"): if func.name.startswith("echidna_") or func.name.startswith("crytic_"):
continue continue

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

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

@ -26,7 +26,7 @@ def _get_pattern_func(func):
def _get_port_id(var, contract): def _get_port_id(var, contract):
return "%s%s" % (var.name, contract.name) return f"{var.name}{contract.name}"
class PrinterInheritanceGraph(AbstractPrinter): 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). # 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: 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: else:
for i, immediate_inheritance in enumerate(contract.immediate_inheritance): for i, immediate_inheritance in enumerate(contract.immediate_inheritance):
ret += '%s -> %s [ label="%s" ];\n' % ( ret += f'{contract.name} -> {immediate_inheritance} [ label="{i + 1}" ];\n'
contract.name,
immediate_inheritance,
i + 1,
)
# Functions # Functions
visibilities = ["public", "external"] visibilities = ["public", "external"]
@ -155,24 +151,24 @@ class PrinterInheritanceGraph(AbstractPrinter):
indirect_shadowing_information = self._get_indirect_shadowing_information(contract) indirect_shadowing_information = self._get_indirect_shadowing_information(contract)
# Build the node label # Build the node label
ret += '%s[shape="box"' % contract.name ret += f'{contract.name}[shape="box"'
ret += 'label=< <TABLE border="0">' 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: if public_functions:
ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>' ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>'
ret += "%s" % public_functions ret += f"{public_functions}"
if private_functions: if private_functions:
ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>' ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>'
ret += "%s" % private_functions ret += f"{private_functions}"
if modifiers: if modifiers:
ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>' ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>'
ret += "%s" % modifiers ret += f"{modifiers}"
if public_variables: if public_variables:
ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>' ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>'
ret += "%s" % public_variables ret += f"{public_variables}"
if private_variables: if private_variables:
ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>' ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>'
ret += "%s" % private_variables ret += f"{private_variables}"
if indirect_shadowing_information: if indirect_shadowing_information:
ret += ( ret += (

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

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

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

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

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

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

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

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

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

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

@ -25,7 +25,7 @@ class VariableOrder(AbstractPrinter):
all_tables = [] all_tables = []
for contract in self.slither.contracts_derived: 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"]) table = MyPrettyTable(["Name", "Type", "Slot", "Offset"])
for variable in contract.state_variables_ordered: for variable in contract.state_variables_ordered:
if not variable.is_constant: 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: if not issubclass(cls, base_cls) or cls is base_cls:
raise Exception( raise Exception(
"You can't register {!r} as a {}. You need to pass a class that inherits from {}".format( f"You can't register {cls!r} as a {thing_name}. You need to pass a class that inherits from {base_cls.__name__}"
cls, thing_name, base_cls.__name__
)
) )
if any(type(obj) == cls for obj in instances_list): # pylint: disable=unidiomatic-typecheck 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]): def _update_file_scopes(candidates: ValuesView[FileScope]):

@ -214,7 +214,7 @@ def _find_function_from_parameter(ir: Call, candidates: List[Function]) -> Optio
type_args: List[str] type_args: List[str]
for idx, arg in enumerate(arguments): for idx, arg in enumerate(arguments):
if isinstance(arg, (list,)): 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): elif isinstance(arg, Function):
type_args = [arg.signature_str] type_args = [arg.signature_str]
else: else:
@ -771,7 +771,7 @@ def propagate_types(ir, node: "Node"): # pylint: disable=too-many-locals
# temporary operation; they will be removed # temporary operation; they will be removed
pass pass
else: else:
raise SlithIRError("Not handling {} during type propagation".format(type(ir))) raise SlithIRError(f"Not handling {type(ir)} during type propagation")
return None return None
@ -1043,7 +1043,7 @@ def extract_tmp_call(ins: TmpCall, contract: Optional[Contract]): # pylint: dis
internalcall.set_expression(ins.expression) internalcall.set_expression(ins.expression)
return internalcall return internalcall
raise Exception("Not extracted {} {}".format(type(ins.called), ins)) raise Exception(f"Not extracted {type(ins.called)} {ins}")
# endregion # endregion
@ -1102,7 +1102,7 @@ def convert_to_low_level(ir):
new_ir.set_expression(ir.expression) new_ir.set_expression(ir.expression)
new_ir.set_node(ir.node) new_ir.set_node(ir.node)
return new_ir 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: def can_be_solidity_func(ir) -> bool:
@ -1123,7 +1123,7 @@ def convert_to_solidity_func(ir):
:param ir: :param ir:
:return: :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 = SolidityCall(call, ir.nbr_arguments, ir.lvalue, ir.type_call)
new_ir.arguments = ir.arguments new_ir.arguments = ir.arguments
new_ir.set_expression(ir.expression) 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): if can_be_solidity_func(ir):
return convert_to_solidity_func(ir) return convert_to_solidity_func(ir)
if not func: 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) logger.error(to_log)
ir.function = func ir.function = func
if isinstance(func, Function): if isinstance(func, Function):

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

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

@ -21,4 +21,4 @@ class CodeSize(OperationWithLValue):
return self._value return self._value
def __str__(self): 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 return self._value
def __str__(self): def __str__(self):
return "CONDITION {}".format(self.value) return f"CONDITION {self.value}"

@ -24,4 +24,4 @@ class Delete(OperationWithLValue):
return self._variable return self._variable
def __str__(self): 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): def __str__(self):
args = [str(a) for a in self.arguments] 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 = "" value = ""
gas = "" gas = ""
if self.call_value: if self.call_value:
value = "value:{}".format(self.call_value) value = f"value:{self.call_value}"
if self.call_gas: if self.call_gas:
gas = "gas:{}".format(self.call_gas) gas = f"gas:{self.call_gas}"
arguments = [] arguments = []
if self.arguments: if self.arguments:
arguments = self.arguments arguments = self.arguments
@ -155,9 +155,9 @@ class HighLevelCall(Call, OperationWithLValue):
if not self.lvalue: if not self.lvalue:
lvalue = "" lvalue = ""
elif isinstance(self.lvalue.type, (list,)): 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: else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type) lvalue = f"{self.lvalue}({self.lvalue.type}) = "
return txt.format( return txt.format(
lvalue, lvalue,
self.destination, self.destination,

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

@ -38,4 +38,4 @@ class InitArray(OperationWithLValue):
return str(elem) return str(elem)
init_values = convert(self.init_values) 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: if not self.lvalue:
lvalue = "" lvalue = ""
elif isinstance(self.lvalue.type, (list,)): 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: else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type) lvalue = f"{self.lvalue}({self.lvalue.type}) = "
if self.is_modifier_call: if self.is_modifier_call:
txt = "{}MODIFIER_CALL, {}({})" txt = "{}MODIFIER_CALL, {}({})"
else: else:

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

@ -21,4 +21,4 @@ class Length(OperationWithLValue):
return self._value return self._value
def __str__(self): 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): def __str__(self):
gas = "" gas = ""
if self.call_gas: if self.call_gas:
gas = "gas:{}".format(self.call_gas) gas = f"gas:{self.call_gas}"
arguments = [] arguments = []
if self.arguments: if self.arguments:
arguments = self.arguments arguments = self.arguments
if not self.lvalue: if not self.lvalue:
lvalue = "" lvalue = ""
elif isinstance(self.lvalue.type, (list,)): 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: else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type) lvalue = f"{self.lvalue}({self.lvalue.type}) = "
txt = "{}LIBRARY_CALL, dest:{}, function:{}, arguments:{} {}" txt = "{}LIBRARY_CALL, dest:{}, function:{}, arguments:{} {}"
function_name = self.function_name function_name = self.function_name

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

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

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

@ -88,8 +88,8 @@ class NewContract(Call, OperationWithLValue): # pylint: disable=too-many-instan
def __str__(self): def __str__(self):
options = "" options = ""
if self.call_value: if self.call_value:
options = "value:{} ".format(self.call_value) options = f"value:{self.call_value} "
if self.call_salt: if self.call_salt:
options += "salt:{} ".format(self.call_salt) options += f"salt:{self.call_salt} "
args = [str(a) for a in self.arguments] 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): def __str__(self):
args = [str(a) for a in self.arguments] 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): def __str__(self):
args = [str(a) for a in self.arguments] 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 return self._nodes
def __str__(self): def __str__(self):
return "{}({}) := \u03D5({})".format( return "{self.lvalue}({self.lvalue.type}) := \u03D5({[str(v) for v in self._rvalues]})"
self.lvalue, self.lvalue.type, [str(v) for v in self._rvalues]
)

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

@ -24,4 +24,4 @@ class Push(OperationWithLValue):
return self._value return self._value
def __str__(self): 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) return self._unroll(self._values)
def __str__(self): 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 return self._destination
def __str__(self): def __str__(self):
value = "value:{}".format(self.call_value) value = f"value:{self.call_value}"
return str(self.lvalue) + " = SEND dest:{} {}".format(self.destination, value) return str(self.lvalue) + f" = SEND dest:{self.destination} {value}"
# #

@ -43,7 +43,7 @@ class SolidityCall(Call, OperationWithLValue):
lvalue = "" lvalue = ""
if self.lvalue: if self.lvalue:
if isinstance(self.lvalue.type, (list,)): 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: else:
lvalue = "{}({}) = ".format(self.lvalue, self.lvalue.type) lvalue = f"{self.lvalue}({self.lvalue.type}) = "
return lvalue + "SOLIDITY_CALL {}({})".format(self.function.full_name, args) return lvalue + f"SOLIDITY_CALL {self.function.full_name}({args})"

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

@ -28,4 +28,4 @@ class TypeConversion(OperationWithLValue):
return [self.variable] return [self.variable]
def __str__(self): 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 return UnaryType.BANG
if operation_type == "~": if operation_type == "~":
return UnaryType.TILD 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): def __str__(self):
if self == UnaryType.BANG: if self == UnaryType.BANG:
@ -27,7 +27,7 @@ class UnaryType(Enum):
if self == UnaryType.TILD: if self == UnaryType.TILD:
return "~" return "~"
raise SlithIRError("str: Unknown operation type {}".format(self)) raise SlithIRError(f"str: Unknown operation type {self}")
class Unary(OperationWithLValue): class Unary(OperationWithLValue):
@ -56,4 +56,4 @@ class Unary(OperationWithLValue):
return str(self._type) return str(self._type)
def __str__(self): 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 return self._idx
def __str__(self): def __str__(self):
return "{}({})= UNPACK {} index: {} ".format( return f"{self.lvalue}({self.lvalue.type})= UNPACK {self.tuple} index: {self.index} "
self.lvalue, self.lvalue.type, self.tuple, self.index
)

@ -95,4 +95,4 @@ class TmpCall(OperationWithLValue): # pylint: disable=too-many-instance-attribu
self._ori = ori self._ori = ori
def __str__(self): 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 return self._depth
def __str__(self): 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 [] return []
def __str__(self): 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 return self._type
def __str__(self): 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 [] return []
def __str__(self): 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) value = get_variable(ir, lambda x: x.value, *instances)
return Length(value, lvalue) 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 # endregion

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

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

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

@ -43,4 +43,4 @@ class StateIRVariable(
@property @property
def ssa_name(self): 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 @property
def name(self): def name(self):
return "TMP_{}".format(self.index) return f"TMP_{self.index}"
def __str__(self): def __str__(self):
return self.name return self.name

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

@ -148,8 +148,8 @@ class FunctionSolc(CallerContextExpression):
if local_var_parser.underlying_variable.name: if local_var_parser.underlying_variable.name:
known_variables = [v.name for v in self._function.variables] known_variables = [v.name for v in self._function.variables]
while local_var_parser.underlying_variable.name in known_variables: while local_var_parser.underlying_variable.name in known_variables:
local_var_parser.underlying_variable.name += "_scope_{}".format( local_var_parser.underlying_variable.name += (
self._counter_scope_local_variables f"_scope_{self._counter_scope_local_variables}"
) )
self._counter_scope_local_variables += 1 self._counter_scope_local_variables += 1
known_variables = [v.name for v in self._function.variables] known_variables = [v.name for v in self._function.variables]
@ -661,7 +661,7 @@ class FunctionSolc(CallerContextExpression):
externalCall = statement.get("externalCall", None) externalCall = statement.get("externalCall", None)
if externalCall is 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( catch_scope = Scope(
node.underlying_node.scope.is_checked, False, node.underlying_node.scope node.underlying_node.scope.is_checked, False, node.underlying_node.scope
) )
@ -678,7 +678,7 @@ class FunctionSolc(CallerContextExpression):
block = statement.get("block", None) block = statement.get("block", None)
if block is 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_scope = Scope(node.underlying_node.scope.is_checked, False, node.underlying_node.scope)
try_node = self._new_node(NodeType.CATCH, statement["src"], try_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) link_underlying_nodes(node, new_node)
node = new_node node = new_node
else: else:
raise ParsingError("Statement not parsed %s" % name) raise ParsingError(f"Statement not parsed {name}")
return node return node
@ -1124,7 +1124,7 @@ class FunctionSolc(CallerContextExpression):
# We start with -1 as counter to catch this corner case # We start with -1 as counter to catch this corner case
end_node = self._find_end_loop(node, [], -1) end_node = self._find_end_loop(node, [], -1)
if not end_node: 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: for son in node.sons:
son.remove_father(node) son.remove_father(node)
@ -1135,7 +1135,7 @@ class FunctionSolc(CallerContextExpression):
start_node = self._find_start_loop(node, []) start_node = self._find_start_loop(node, [])
if not start_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: for son in node.sons:
son.remove_father(node) 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) super_name = parse_super_name(expression, is_compact_ast)
var, was_created = find_variable(super_name, caller_context, is_super=True) var, was_created = find_variable(super_name, caller_context, is_super=True)
if var is None: if var is None:
raise VariableNotFound("Variable not found: {}".format(super_name)) raise VariableNotFound(f"Variable not found: {super_name}")
if was_created: if was_created:
var.set_offset(src, caller_context.compilation_unit) var.set_offset(src, caller_context.compilation_unit)
sup = SuperIdentifier(var) sup = SuperIdentifier(var)
@ -567,7 +567,7 @@ def parse_expression(expression: Dict, caller_context: CallerContextExpression)
elif type_name[caller_context.get_key()] == "FunctionTypeName": elif type_name[caller_context.get_key()] == "FunctionTypeName":
array_type = parse_type(type_name, caller_context) array_type = parse_type(type_name, caller_context)
else: else:
raise ParsingError("Incorrect type array {}".format(type_name)) raise ParsingError(f"Incorrect type array {type_name}")
array = NewArray(depth, array_type) array = NewArray(depth, array_type)
array.set_offset(src, caller_context.compilation_unit) array.set_offset(src, caller_context.compilation_unit)
return array 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("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: if ret:
return ret, False 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": elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, variable_data.get("value", None)) self._init_from_declaration(variable_data, variable_data.get("value", None))
else: else:
raise ParsingError("Incorrect variable declaration type {}".format(nodeType)) raise ParsingError(f"Incorrect variable declaration type {nodeType}")
else: else:
nodeType = variable_data["name"] nodeType = variable_data["name"]
@ -89,7 +89,7 @@ class VariableDeclarationSolc:
elif nodeType == "VariableDeclaration": elif nodeType == "VariableDeclaration":
self._init_from_declaration(variable_data, False) self._init_from_declaration(variable_data, False)
else: else:
raise ParsingError("Incorrect variable declaration type {}".format(nodeType)) raise ParsingError(f"Incorrect variable declaration type {nodeType}")
@property @property
def underlying_variable(self) -> Variable: def underlying_variable(self) -> Variable:

@ -455,7 +455,7 @@ def convert_yul_switch(
expression_ast = ast["expression"] expression_ast = ast["expression"]
# this variable stores the result of the expression so we don't accidentally compute it more than once # 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 = { rewritten_switch = {
"nodeType": "YulBlock", "nodeType": "YulBlock",
@ -851,7 +851,7 @@ def vars_to_typestr(rets: List[Expression]) -> str:
return "" return ""
if len(rets) == 1: if len(rets) == 1:
return str(rets[0].type) 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): 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 def encode_ir(ir): # pylint: disable=too-many-branches
# operations # operations
if isinstance(ir, Assignment): 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): if isinstance(ir, Index):
return "index({})".format(ntype(ir.index_type)) return f"index({ntype(ir.index_type)})"
if isinstance(ir, Member): if isinstance(ir, Member):
return "member" # .format(ntype(ir._type)) return "member" # .format(ntype(ir._type))
if isinstance(ir, Length): if isinstance(ir, Length):
return "length" return "length"
if isinstance(ir, Binary): if isinstance(ir, Binary):
return "binary({})".format(str(ir.type)) return f"binary({str(ir.type)})"
if isinstance(ir, Unary): if isinstance(ir, Unary):
return "unary({})".format(str(ir.type)) return f"unary({str(ir.type)})"
if isinstance(ir, Condition): if isinstance(ir, Condition):
return "condition({})".format(encode_ir(ir.value)) return f"condition({encode_ir(ir.value)})"
if isinstance(ir, NewStructure): if isinstance(ir, NewStructure):
return "new_structure" return "new_structure"
if isinstance(ir, NewContract): if isinstance(ir, NewContract):
return "new_contract" return "new_contract"
if isinstance(ir, NewArray): if isinstance(ir, NewArray):
return "new_array({})".format(ntype(ir.array_type)) return f"new_array({ntype(ir.array_type)})"
if isinstance(ir, NewElementaryType): if isinstance(ir, NewElementaryType):
return "new_elementary({})".format(ntype(ir.type)) return f"new_elementary({ntype(ir.type)})"
if isinstance(ir, Push): 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): 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): if isinstance(ir, SolidityCall):
return "solidity_call({})".format(ir.function.full_name) return f"solidity_call({ir.function.full_name})"
if isinstance(ir, InternalCall): 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? if isinstance(ir, EventCall): # is this useful?
return "event" return "event"
if isinstance(ir, LibraryCall): if isinstance(ir, LibraryCall):
@ -182,13 +182,13 @@ def encode_ir(ir): # pylint: disable=too-many-branches
if isinstance(ir, LowLevelCall): # TODO: improve if isinstance(ir, LowLevelCall): # TODO: improve
return "low_level_call" return "low_level_call"
if isinstance(ir, TypeConversion): 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 if isinstance(ir, Return): # this can be improved using values
return "return" # .format(ntype(ir.type)) return "return" # .format(ntype(ir.type))
if isinstance(ir, Transfer): if isinstance(ir, Transfer):
return "transfer({})".format(encode_ir(ir.call_value)) return f"transfer({encode_ir(ir.call_value)})"
if isinstance(ir, Send): 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 if isinstance(ir, Unpack): # TODO: improve
return "unpack" return "unpack"
if isinstance(ir, InitArray): # TODO: improve if isinstance(ir, InitArray): # TODO: improve
@ -198,19 +198,19 @@ def encode_ir(ir): # pylint: disable=too-many-branches
# variables # variables
if isinstance(ir, Constant): if isinstance(ir, Constant):
return "constant({})".format(ntype(ir.type)) return f"constant({ntype(ir.type)})"
if isinstance(ir, SolidityVariableComposed): if isinstance(ir, SolidityVariableComposed):
return "solidity_variable_composed({})".format(ir.name) return f"solidity_variable_composed({ir.name})"
if isinstance(ir, SolidityVariable): if isinstance(ir, SolidityVariable):
return "solidity_variable{}".format(ir.name) return f"solidity_variable{ir.name}"
if isinstance(ir, TemporaryVariable): if isinstance(ir, TemporaryVariable):
return "temporary_variable" return "temporary_variable"
if isinstance(ir, ReferenceVariable): if isinstance(ir, ReferenceVariable):
return "reference({})".format(ntype(ir.type)) return f"reference({ntype(ir.type)})"
if isinstance(ir, LocalVariable): if isinstance(ir, LocalVariable):
return "local_solc_variable({})".format(ir.location) return f"local_solc_variable({ir.location})"
if isinstance(ir, StateVariable): if isinstance(ir, StateVariable):
return "state_solc_variable({})".format(ntype(ir.type)) return f"state_solc_variable({ntype(ir.type)})"
if isinstance(ir, LocalVariableInitFromTuple): if isinstance(ir, LocalVariableInitFromTuple):
return "local_variable_init_tuple" return "local_variable_init_tuple"
if isinstance(ir, TupleVariable): if isinstance(ir, TupleVariable):

@ -40,7 +40,7 @@ def info(args):
x = (filename, contract, fname) x = (filename, contract, fname)
y = " ".join(irs[x]) 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(to_log)
logger.info(y) logger.info(y)
if model is not None: if model is not None:
@ -48,7 +48,7 @@ def info(args):
logger.info(fvector) logger.info(fvector)
except Exception: # pylint: disable=broad-except 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(to_log)
logger.error(traceback.format_exc()) logger.error(traceback.format_exc())
sys.exit(-1) sys.exit(-1)

@ -80,6 +80,6 @@ def plot(args): # pylint: disable=too-many-locals
plt.savefig("plot.png", bbox_inches="tight") plt.savefig("plot.png", bbox_inches="tight")
except Exception: # pylint: disable=broad-except 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()) logger.error(traceback.format_exc())
sys.exit(-1) sys.exit(-1)

@ -47,6 +47,6 @@ def test(args):
logger.info(format_table.format(*(list(x) + [score]))) logger.info(format_table.format(*(list(x) + [score])))
except Exception: # pylint: disable=broad-except 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()) logger.error(traceback.format_exc())
sys.exit(-1) sys.exit(-1)

@ -49,6 +49,6 @@ def train(args): # pylint: disable=too-many-locals
logger.info("Done!") logger.info("Done!")
except Exception: # pylint: disable=broad-except 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()) logger.error(traceback.format_exc())
sys.exit(-1) sys.exit(-1)

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

@ -187,7 +187,7 @@ def main():
v1_name = args.ContractName v1_name = args.ContractName
v1_contracts = variable1.get_contract_from_name(v1_name) v1_contracts = variable1.get_contract_from_name(v1_name)
if len(v1_contracts) != 1: 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)) logger.error(red(info))
if args.json: if args.json:
output_to_json(args.json, str(info), json_results) output_to_json(args.json, str(info), json_results)

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

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

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

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

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

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

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

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

@ -321,7 +321,7 @@ class ExpressionToSlithIR(ExpressionVisitor):
set_val(expression, val) set_val(expression, val)
def _post_conditional_expression(self, expression): 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): def _post_elementary_type_name_expression(self, expression):
set_val(expression, expression.type) set_val(expression, expression.type)
@ -517,4 +517,4 @@ class ExpressionToSlithIR(ExpressionVisitor):
self._result.append(operation) self._result.append(operation)
set_val(expression, lvalue) set_val(expression, lvalue)
else: else:
raise SlithIRError("Unary operation to IR not supported {}".format(expression)) raise SlithIRError(f"Unary operation to IR not supported {expression}")

Loading…
Cancel
Save