Skip to content

Commit

Permalink
#86dtb6tt0 - Change the usage of typing collections to use `collect…
Browse files Browse the repository at this point in the history
…ions.abc` and update the tests accordingly
  • Loading branch information
Mirella de Medeiros committed May 8, 2024
1 parent 1071dd5 commit e500116
Show file tree
Hide file tree
Showing 138 changed files with 674 additions and 700 deletions.
26 changes: 19 additions & 7 deletions boa3/boa3.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,14 @@ class Boa3:
"""

@staticmethod
def compile(path: str, root_folder: str = None, log_level: str = None,
env: str = None, fail_fast: bool = True,
optimize: bool = True) -> bytes:
def compile(
path: str,
root_folder: str = None,
log_level: str = None,
env: str = None,
fail_fast: bool = True,
optimize: bool = True
) -> bytes:
"""
Load a Python file to be compiled but don't write the result into a file
Expand All @@ -33,10 +38,17 @@ def compile(path: str, root_folder: str = None, log_level: str = None,
)

@staticmethod
def compile_and_save(path: str, output_path: str = None, root_folder: str = None,
show_errors: bool = True, log_level: str = None,
debug: bool = False, env: str = None, fail_fast: bool = True,
optimize: bool = True):
def compile_and_save(
path: str,
output_path: str = None,
root_folder: str = None,
show_errors: bool = True,
log_level: str = None,
debug: bool = False,
env: str = None,
fail_fast: bool = True,
optimize: bool = True
):
"""
Load a Python file to be compiled and save the result into the files.
By default, the resultant .nef file is saved in the same folder of the
Expand Down
26 changes: 16 additions & 10 deletions boa3/internal/analyser/analyser.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import ast
from typing import Self

from boa3.builtin.compile_time import NeoMetadata
from boa3.internal import constants
Expand Down Expand Up @@ -56,11 +55,18 @@ def __init__(self, ast_tree: ast.AST, path: str = None, project_root: str = None
if project_root is not None and os.path.isdir(project_root)
else path)

@staticmethod
def analyse(path: str, log: bool = False, fail_fast: bool = False,
imported_files: dict[str, Analyser] | None = None,
import_stack: list[str] | None = None,
root: str = None, env: str = None, compiler_entry: bool = False) -> Analyser:
@classmethod
def analyse(
cls,
path: str,
log: bool = False,
fail_fast: bool = False,
imported_files: dict[str, Self] | None = None,
import_stack: list[str] | None = None,
root: str = None,
env: str = None,
compiler_entry: bool = False
) -> Self:
"""
Analyses the syntax of the Python code
Expand Down Expand Up @@ -116,7 +122,7 @@ def warnings(self) -> list[CompilerWarning]:
def env(self) -> str:
return self._env

def copy(self) -> Analyser:
def copy(self) -> Self:
copied = Analyser(ast_tree=self.ast_tree, path=self.path, project_root=self.root,
env=self._env, log=self._log, fail_fast=self._fail_fast)

Expand Down Expand Up @@ -146,7 +152,7 @@ def __check_types(self) -> bool:
return not type_analyser.has_errors

def __analyse_modules(self,
imported_files: dict[str, Analyser] | None = None,
imported_files: dict[str, Self] | None = None,
import_stack: list[str] | None = None) -> bool:
"""
Validates the symbols and constructs the symbol table of the ast tree
Expand Down Expand Up @@ -246,5 +252,5 @@ def update_symbol_table_with_imports(self):

self._included_imported_files = True

def get_imports(self) -> list[Analyser]:
def get_imports(self) -> list[Self]:
return list(self._imported_files.values())
13 changes: 11 additions & 2 deletions boa3/internal/analyser/importanalyser.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,17 @@ def _find_package(self, module_origin: str, origin_file: str | None = None):
self.is_builtin_import = True
return

if (os.path.commonpath([self.path, constants.BOA_PACKAGE_PATH]) != constants.BOA_PACKAGE_PATH or
('boa3' in path and constants.PATH_SEPARATOR.join(path[path.index('boa3'):]).startswith('boa3/builtin'))):
def is_boa_package() -> bool:
common_path = os.path.commonpath([self.path, constants.BOA_PACKAGE_PATH])
if common_path == constants.BOA_PACKAGE_PATH:
return True
if 'boa3' not in path:
return False

boa_path = path[path.index('boa3'):]
return len(boa_path) > 1 and boa_path[1] in ('builtin', 'sc')

if not is_boa_package():
# doesn't analyse boa3.builtin packages that aren't included in the imports.compilerbuiltin as an user module
import re

Expand Down
5 changes: 2 additions & 3 deletions boa3/internal/analyser/model/optimizer/Operation.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
from __future__ import annotations

import ast
from enum import Enum, auto
from typing import Self

from boa3.internal.model.operation.operation import IOperation
from boa3.internal.model.operation.operator import Operator
Expand All @@ -20,7 +19,7 @@ def is_symmetric(self) -> bool:
return self._symmetric

@classmethod
def get_operation(cls, op: ast.operator | IOperation) -> Operation | None:
def get_operation(cls, op: ast.operator | IOperation) -> Self | None:
op = op.operator if isinstance(op, IOperation) else op
if op is Operator.Plus or isinstance(op, (ast.Add, ast.UAdd)):
return cls.Add
Expand Down
12 changes: 7 additions & 5 deletions boa3/internal/analyser/model/optimizer/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from __future__ import annotations

from typing import Any
from typing import Any, Self


class ScopeValue:
Expand All @@ -9,14 +7,14 @@ def __init__(self):
self._assigned_variables: set[str] = set()
self._parent_scope: ScopeValue | None = None

def new_scope(self) -> ScopeValue:
def new_scope(self) -> Self:
scope = ScopeValue()
scope._values = self._values.copy()
scope._assigned_variables = self._assigned_variables.copy()
scope._parent_scope = self
return scope

def previous_scope(self) -> ScopeValue | None:
def previous_scope(self) -> Self | None:
return self._parent_scope

def update_values(self, *scopes, is_loop_scope: bool = False):
Expand Down Expand Up @@ -92,5 +90,9 @@ def __init__(self):
def identifier(self) -> str:
return 'undefined'

@property
def is_deprecated(self) -> bool:
return False


Undefined = UndefinedType()
4 changes: 2 additions & 2 deletions boa3/internal/analyser/model/symbolscope.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import annotations
from typing import Self

from boa3.internal.model.symbol import ISymbol

Expand All @@ -11,7 +11,7 @@ def __init__(self, symbols: dict[str, ISymbol] = None):
def symbols(self) -> dict[str, ISymbol]:
return self._symbols.copy()

def copy(self) -> SymbolScope:
def copy(self) -> Self:
return SymbolScope(self._symbols)

def include_symbol(self, symbol_id: str, symbol: ISymbol, reassign_original: bool = True):
Expand Down
25 changes: 20 additions & 5 deletions boa3/internal/analyser/moduleanalyser.py
Original file line number Diff line number Diff line change
Expand Up @@ -1432,16 +1432,31 @@ def visit_Attribute(self, attribute: ast.Attribute) -> ISymbol | str:

if isinstance(value, Variable):
value = value.type

attribute_symbol = None
if hasattr(value, 'symbols') and attribute.attr in value.symbols:
return value.symbols[attribute.attr]
attribute_symbol = value.symbols[attribute.attr]
elif isinstance(value, Package) and attribute.attr in value.inner_packages:
return value.inner_packages[attribute.attr]
attribute_symbol = value.inner_packages[attribute.attr]
elif Builtin.get_symbol(attribute.attr) is not None:
return Builtin.get_symbol(attribute.attr)
attribute_symbol = Builtin.get_symbol(attribute.attr)
elif isinstance(value, UndefinedType):
return value
attribute_symbol = value

attribute_id = '{0}.{1}'.format(value_id, attribute.attr)
if attribute_symbol is not None:
if attribute_symbol.is_deprecated:
self._log_warning(
CompilerWarning.DeprecatedSymbol(
attribute.lineno,
attribute.col_offset,
attribute_id,
attribute_symbol.new_location if hasattr(attribute_symbol, 'new_location') else None
)
)
return attribute_symbol
else:
return '{0}.{1}'.format(value_id, attribute.attr)
return attribute_id

def visit_For(self, for_node: ast.For):
"""
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from __future__ import annotations

__all__ = [
'ExecutionScript'
]

from typing import Self

from boa3.internal.compiler.codegenerator.vmcodemapping import VMCodeMapping
from boa3.internal.neo.vm.VMCode import VMCode
Expand All @@ -21,7 +20,7 @@ def __init__(self, code_map: dict[int, VMCode], tokens: list[MethodToken]):
self._tokens = tokens

@classmethod
def from_code_map(cls, instance: VMCodeMapping) -> ExecutionScript:
def from_code_map(cls, instance: VMCodeMapping) -> Self:
obj = ExecutionScript(instance.code_map, instance._method_tokens.to_list())
return obj

Expand Down
6 changes: 2 additions & 4 deletions boa3/internal/compiler/codegenerator/engine/istack.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,5 @@
from __future__ import annotations

import abc
from typing import TypeVar
from typing import TypeVar, Self

T = TypeVar("T")

Expand All @@ -21,7 +19,7 @@ def append(self, value: T):
def clear(self):
return self._stack.clear()

def copy(self) -> IStack:
def copy(self) -> Self:
new_stack = self.__class__(*self._default_constructor_args())
new_stack._stack = self._stack.copy()
return new_stack
Expand Down
20 changes: 9 additions & 11 deletions boa3/internal/compiler/codegenerator/engine/stackmemento.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
from __future__ import annotations

__all__ = [
'StackMemento',
'NeoStack'
Expand All @@ -11,6 +9,15 @@
from boa3.internal.neo.vm.VMCode import VMCode


class NeoStack(IStack):
def __init__(self):
from boa3.internal.model.type.itype import IType
super().__init__(stack_type=IType)

def _default_constructor_args(self) -> tuple:
return tuple()


class StackMemento:
"""
This class is responsible for managing the simulation of the blockchain stack during the code generation
Expand Down Expand Up @@ -105,12 +112,3 @@ def reverse(self, code: VMCode, start: int = 0, end: int = None, *, rotate: bool
self._current_stack = stack

return stack.reverse(start, end, rotate=rotate)


class NeoStack(IStack):
def __init__(self):
from boa3.internal.model.type.itype import IType
super().__init__(stack_type=IType)

def _default_constructor_args(self) -> tuple:
return tuple()
22 changes: 12 additions & 10 deletions boa3/internal/compiler/codegenerator/generatordata.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from __future__ import annotations

import ast
from typing import Self

from boa3.internal.model.expression import IExpression
from boa3.internal.model.identifiedsymbol import IdentifiedSymbol
Expand Down Expand Up @@ -28,13 +27,16 @@ def __init__(self, origin_node: ast.AST | None,
self.symbol_id: str | None = symbol_id
self.type: IType | None = result_type
self.index: int | None = index
self.origin_object_type: ISymbol | None = origin_object_type
self.origin_object_type: IType | None = origin_object_type
self.already_generated: bool = already_generated

def copy(self, new_origin: ast.AST | None = None) -> GeneratorData:
return GeneratorData(new_origin if isinstance(new_origin, ast.AST) else self.node,
self.symbol_id,
self.symbol,
self.type,
self.index,
self.already_generated)
def copy(self, new_origin: ast.AST | None = None) -> Self:
return GeneratorData(
origin_node=new_origin if isinstance(new_origin, ast.AST) else self.node,
symbol_id=self.symbol_id,
symbol=self.symbol,
result_type=self.type,
index=self.index,
origin_object_type=self.origin_object_type,
already_generated=self.already_generated
)
4 changes: 2 additions & 2 deletions boa3/internal/compiler/codegenerator/vmcodemapping.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import annotations
from typing import Self

from boa3.internal.compiler.codegenerator.methodtokencollection import MethodTokenCollection
from boa3.internal.compiler.codegenerator.vmcodemap import VMCodeMap
Expand All @@ -14,7 +14,7 @@ class VMCodeMapping:
"""
This class is responsible for managing the Neo VM instruction during the bytecode generation.
"""
_instance: VMCodeMapping = None
_instance: Self = None

@classmethod
def instance(cls):
Expand Down
4 changes: 2 additions & 2 deletions boa3/internal/compiler/compiledmetadata.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from __future__ import annotations
from typing import Self

from boa3.builtin.compile_time import NeoMetadata
from boa3.internal import constants
Expand All @@ -9,7 +9,7 @@ class CompiledMetadata:
_instance = None

@classmethod
def instance(cls) -> CompiledMetadata:
def instance(cls) -> Self:
if cls._instance is None:
cls._instance = cls()
return cls._instance
Expand Down
2 changes: 1 addition & 1 deletion boa3/internal/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
BOA_VERSION = _actual_boa_version # for logging only
BOA_LOGGING_NAME = 'neo3-boa-log'
COMPILER_VERSION = BOA_VERSION
BOA_PACKAGE_PATH = os.path.abspath(f'{__file__}/..')
BOA_PACKAGE_PATH = os.path.abspath(f'{__file__}/../..')
DEFAULT_CONTRACT_ENVIRONMENT = 'mainnet'

locale.setlocale(locale.LC_ALL, '')
Expand Down
5 changes: 2 additions & 3 deletions boa3/internal/model/builtin/builtinsymbol.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
from __future__ import annotations

from abc import ABC
from typing import Self

from boa3.internal.model.identifiedsymbol import IdentifiedSymbol


class IBuiltinSymbol(IdentifiedSymbol, ABC):

def build(self, *args, **kwargs) -> IBuiltinSymbol:
def build(self, *args, **kwargs) -> Self:
"""
Creates a symbol instance with the given value as self
Expand Down
6 changes: 2 additions & 4 deletions boa3/internal/model/builtin/contract/neoaccountstatetype.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
from __future__ import annotations

from typing import Any
from typing import Any, Self

from boa3.internal.model.builtin.method.builtinmethod import IBuiltinMethod
from boa3.internal.model.expression import IExpression
Expand Down Expand Up @@ -60,7 +58,7 @@ def constructor_method(self) -> Method | None:
return self._constructor

@classmethod
def build(cls, value: Any = None) -> NeoAccountStateType:
def build(cls, value: Any = None) -> Self:
if value is None or cls._is_type_of(value):
return _NeoAccountState

Expand Down
Loading

0 comments on commit e500116

Please sign in to comment.