• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

CityOfZion / neo3-boa / e084b44c-1a5f-4649-92cd-d3ed06099181

05 Mar 2024 05:58PM UTC coverage: 92.023% (-0.08%) from 92.107%
e084b44c-1a5f-4649-92cd-d3ed06099181

push

circleci

Mirella de Medeiros
CU-86drpnc9z - Drop support to Python 3.10

20547 of 22328 relevant lines covered (92.02%)

1.84 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

95.98
/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py
1
import ast
2✔
2
import os.path
2✔
3
from inspect import isclass
2✔
4

5
from boa3.internal import constants
2✔
6
from boa3.internal.analyser.astanalyser import IAstAnalyser
2✔
7
from boa3.internal.compiler.codegenerator.codegenerator import CodeGenerator
2✔
8
from boa3.internal.compiler.codegenerator.generatordata import GeneratorData
2✔
9
from boa3.internal.compiler.codegenerator.variablegenerationdata import VariableGenerationData
2✔
10
from boa3.internal.compiler.codegenerator.vmcodemapping import VMCodeMapping
2✔
11
from boa3.internal.model.builtin.builtin import Builtin
2✔
12
from boa3.internal.model.builtin.method.builtinmethod import IBuiltinMethod
2✔
13
from boa3.internal.model.expression import IExpression
2✔
14
from boa3.internal.model.imports.package import Package
2✔
15
from boa3.internal.model.method import Method
2✔
16
from boa3.internal.model.operation.binary.binaryoperation import BinaryOperation
2✔
17
from boa3.internal.model.operation.binaryop import BinaryOp
2✔
18
from boa3.internal.model.operation.operation import IOperation
2✔
19
from boa3.internal.model.operation.unary.unaryoperation import UnaryOperation
2✔
20
from boa3.internal.model.property import Property
2✔
21
from boa3.internal.model.symbol import ISymbol
2✔
22
from boa3.internal.model.type.classes.classtype import ClassType
2✔
23
from boa3.internal.model.type.classes.userclass import UserClass
2✔
24
from boa3.internal.model.type.collection.sequence.sequencetype import SequenceType
2✔
25
from boa3.internal.model.type.type import IType, Type
2✔
26
from boa3.internal.model.variable import Variable
2✔
27

28

29
class VisitorCodeGenerator(IAstAnalyser):
2✔
30
    """
31
    This class is responsible for walk through the ast.
32

33
    The methods with the name starting with 'visit_' are implementations of methods from the :class:`NodeVisitor` class.
34
    These methods are used to walk through the Python abstract syntax tree.
35

36
    :ivar generator:
37
    """
38

39
    def __init__(self, generator: CodeGenerator, filename: str = None, root: str = None):
2✔
40
        super().__init__(ast.parse(""), filename=filename, root_folder=root, log=True, fail_fast=True)
2✔
41

42
        self.generator = generator
2✔
43
        self.current_method: Method | None = None
2✔
44
        self.current_class: UserClass | None = None
2✔
45
        self.symbols = generator.symbol_table
2✔
46

47
        self.global_stmts: list[ast.AST] = []
2✔
48
        self._is_generating_initialize = False
2✔
49
        self._root_module: ast.AST = self._tree
2✔
50

51
    @property
2✔
52
    def _symbols(self) -> dict[str, ISymbol]:
2✔
53
        symbol_table = self.symbols.copy()
2✔
54

55
        if isinstance(self.current_class, UserClass):
2✔
56
            symbol_table.update(self.current_class.symbols)
2✔
57

58
        return symbol_table
2✔
59

60
    def include_instruction(self, node: ast.AST, address: int):
2✔
61
        if self.current_method is not None and address in VMCodeMapping.instance().code_map:
2✔
62
            bytecode = VMCodeMapping.instance().code_map[address]
2✔
63
            from boa3.internal.model.debuginstruction import DebugInstruction
2✔
64
            self.current_method.include_instruction(DebugInstruction.build(node, bytecode))
2✔
65

66
    def build_data(self, origin_node: ast.AST | None,
2✔
67
                   symbol_id: str | None = None,
68
                   symbol: ISymbol | None = None,
69
                   result_type: IType | None = None,
70
                   index: int | None = None,
71
                   origin_object_type: ISymbol | None = None,
72
                   already_generated: bool = False) -> GeneratorData:
73

74
        if isinstance(symbol, IType) and result_type is None:
2✔
75
            result_type = symbol
2✔
76
            symbol = None
2✔
77

78
        if symbol is None and symbol_id is not None:
2✔
79
            # try to find the symbol if the id is known
80
            if symbol_id in self._symbols:
2✔
81
                found_symbol = self._symbols[symbol_id]
2✔
82
            else:
83
                _, found_symbol = self.generator.get_symbol(symbol_id)
2✔
84
                if found_symbol is Type.none:
2✔
85
                    # generator get_symbol returns Type.none if the symbol is not found
86
                    found_symbol = None
2✔
87

88
            if found_symbol is not None:
2✔
89
                symbol = found_symbol
2✔
90

91
        return GeneratorData(origin_node, symbol_id, symbol, result_type, index, origin_object_type, already_generated)
2✔
92

93
    def visit_and_update_analyser(self, node: ast.AST, target_analyser) -> GeneratorData:
2✔
94
        result = self.visit(node)
2✔
95
        if hasattr(target_analyser, '_update_logs'):
2✔
96
            target_analyser._update_logs(self)
2✔
97
        return result
2✔
98

99
    def visit(self, node: ast.AST) -> GeneratorData:
2✔
100
        result = super().visit(node)
2✔
101
        if not isinstance(result, GeneratorData):
2✔
102
            result = self.build_data(node)
2✔
103
        return result
2✔
104

105
    def visit_to_map(self, node: ast.AST, generate: bool = False) -> GeneratorData:
2✔
106
        address: int = VMCodeMapping.instance().bytecode_size
2✔
107
        if isinstance(node, ast.Expr):
2✔
108
            value = self.visit_Expr(node, generate)
2✔
109
        elif generate:
2✔
110
            value = self.visit_to_generate(node)
2✔
111
        else:
112
            value = self.visit(node)
2✔
113

114
        if not isinstance(node, (ast.For, ast.While, ast.If)):
2✔
115
            # control flow nodes must map each of their instructions
116
            self.include_instruction(node, address)
2✔
117
        return value
2✔
118

119
    def visit_to_generate(self, node) -> GeneratorData:
2✔
120
        """
121
        Visitor to generate the nodes that the primary visitor is used to retrieve value
122

123
        :param node: an ast node
124
        """
125
        if isinstance(node, ast.AST):
2✔
126
            result = self.visit(node)
2✔
127

128
            if not result.already_generated and result.symbol_id is not None:
2✔
129
                if self.is_exception_name(result.symbol_id):
2✔
130
                    self.generator.convert_new_exception()
2✔
131
                else:
132
                    is_internal = hasattr(node, 'is_internal_call') and node.is_internal_call
2✔
133
                    class_type = result.type if isinstance(node, ast.Attribute) else None
2✔
134

135
                    if (self.is_implemented_class_type(result.type)
2✔
136
                            and len(result.symbol_id.split(constants.ATTRIBUTE_NAME_SEPARATOR)) > 1):
137
                        # if the symbol id has the attribute separator and the top item on the stack is a user class,
138
                        # then this value is an attribute from that class
139
                        # change the id for correct generation
140
                        result.symbol_id = result.symbol_id.split(constants.ATTRIBUTE_NAME_SEPARATOR)[-1]
2✔
141

142
                    elif isinstance(result.index, Package):
2✔
143
                        class_type = None
2✔
144

145
                    self.generator.convert_load_symbol(result.symbol_id, is_internal=is_internal, class_type=class_type)
2✔
146

147
                result.already_generated = True
2✔
148

149
            return result
2✔
150
        else:
151
            index = self.generator.convert_literal(node)
2✔
152
            return self.build_data(node, index=index)
2✔
153

154
    def is_exception_name(self, exc_id: str) -> bool:
2✔
155
        global_symbols = globals()
2✔
156
        if exc_id in global_symbols or exc_id in global_symbols['__builtins__']:
2✔
157
            symbol = (global_symbols[exc_id]
2✔
158
                      if exc_id in global_symbols
159
                      else global_symbols['__builtins__'][exc_id])
160
            if isclass(symbol) and issubclass(symbol, BaseException):
2✔
161
                return True
2✔
162
        return False
2✔
163

164
    def is_global_variable(self, variable_id: str) -> bool:
2✔
165
        if self.current_class and variable_id in self.current_class.variables:
2✔
166
            return False
2✔
167
        if self.current_method and (variable_id in self.current_method.args
2✔
168
                                    or variable_id in self.current_method.locals):
169
            return False
2✔
170

171
        return variable_id in self.symbols
2✔
172

173
    def _remove_inserted_opcodes_since(self, last_address: int, last_stack_size: int | None = None):
2✔
174
        self.generator._remove_inserted_opcodes_since(last_address, last_stack_size)
2✔
175

176
    def _get_unique_name(self, name_id: str, node: ast.AST) -> str:
2✔
177
        return '{0}{2}{1}'.format(node.__hash__(), name_id, constants.VARIABLE_NAME_SEPARATOR)
2✔
178

179
    def set_filename(self, filename: str):
2✔
180
        if isinstance(filename, str) and os.path.isfile(filename):
2✔
181
            if constants.PATH_SEPARATOR != os.path.sep:
2✔
182
                self.filename = filename.replace(constants.PATH_SEPARATOR, os.path.sep)
×
183
            else:
184
                self.filename = filename
2✔
185

186
    def visit_Module(self, module: ast.Module) -> GeneratorData:
2✔
187
        """
188
        Visitor of the module node
189

190
        Fills module symbol table
191

192
        :param module:
193
        """
194
        global_stmts = [node for node in module.body if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))]
2✔
195
        function_stmts = module.body[len(global_stmts):]
2✔
196
        mandatory_global_stmts = []
2✔
197
        for stmt in global_stmts:
2✔
198
            if isinstance(stmt, ast.ClassDef):
2✔
199
                class_symbol = self.get_symbol(stmt.name)
2✔
200
                if isinstance(class_symbol, UserClass) and len(class_symbol.class_variables) > 0:
2✔
201
                    mandatory_global_stmts.append(stmt)
2✔
202
            elif not isinstance(stmt, (ast.Import, ast.ImportFrom)):
2✔
203
                mandatory_global_stmts.append(stmt)
2✔
204

205
        for stmt in function_stmts:
2✔
206
            self.visit(stmt)
2✔
207

208
        if self.generator.initialize_static_fields():
2✔
209
            last_symbols = self.symbols  # save to revert in the end and not compromise consequent visits
2✔
210
            class_non_static_stmts = []
2✔
211

212
            for node in global_stmts.copy():
2✔
213
                if isinstance(node, ast.ClassDef):
2✔
214
                    class_origin_module = None
2✔
215
                    if hasattr(node, 'origin'):
2✔
216
                        class_origin_module = node.origin
2✔
217
                        if (node.origin is not self._root_module
2✔
218
                                and hasattr(node.origin, 'symbols')):
219
                            # symbols unique to imports are not included in the symbols
220
                            self.symbols = node.origin.symbols
2✔
221

222
                    class_variables = []
2✔
223
                    class_functions = []
2✔
224
                    for stmt in node.body:
2✔
225
                        if isinstance(stmt, (ast.Assign, ast.AugAssign, ast.AnnAssign)):
2✔
226
                            class_variables.append(stmt)
2✔
227
                        else:
228
                            class_functions.append(stmt)
2✔
229

230
                    if len(class_functions) > 0:
2✔
231
                        if class_origin_module is not None and not hasattr(node, 'origin'):
2✔
232
                            node.origin = class_origin_module
×
233

234
                        cls_fun = node
2✔
235
                        if len(class_variables) > 0:
2✔
236
                            cls_var = node
2✔
237
                            cls_fun = self.clone(node)
2✔
238
                            cls_fun.body = class_functions
2✔
239
                            cls_var.body = class_variables
2✔
240
                        else:
241
                            global_stmts.remove(cls_fun)
2✔
242

243
                        class_non_static_stmts.append(cls_fun)
2✔
244
                    self.symbols = last_symbols  # don't use inner scopes to evaluate the other globals
2✔
245

246
            # to generate the 'initialize' method for Neo
247
            self._log_info(f"Compiling '{constants.INITIALIZE_METHOD_ID}' function")
2✔
248
            self._is_generating_initialize = True
2✔
249
            for stmt in global_stmts:
2✔
250
                cur_tree = self._tree
2✔
251
                cur_filename = self.filename
2✔
252
                if hasattr(stmt, 'origin'):
2✔
253
                    if hasattr(stmt.origin, 'filename'):
2✔
254
                        self.set_filename(stmt.origin.filename)
2✔
255
                    self._tree = stmt.origin
2✔
256

257
                self.visit(stmt)
2✔
258
                self.filename = cur_filename
2✔
259
                self._tree = cur_tree
2✔
260

261
            self._is_generating_initialize = False
2✔
262
            self.generator.end_initialize()
2✔
263

264
            # generate any symbol inside classes that's not variables AFTER generating 'initialize' method
265
            for stmt in class_non_static_stmts:
2✔
266
                cur_tree = self._tree
2✔
267
                if hasattr(stmt, 'origin'):
2✔
268
                    self._tree = stmt.origin
2✔
269
                self.visit(stmt)
2✔
270
                self._tree = cur_tree
2✔
271

272
            self.symbols = last_symbols  # revert in the end to not compromise consequent visits
2✔
273
            self.generator.additional_symbols = None
2✔
274

275
        elif len(function_stmts) > 0 or len(mandatory_global_stmts) > 0:
2✔
276
            # to organize syntax tree nodes from other modules
277
            for stmt in global_stmts:
2✔
278
                if not hasattr(stmt, 'origin'):
2✔
279
                    stmt.origin = module
2✔
280

281
            module.symbols = self._symbols
2✔
282
            self.global_stmts.extend(global_stmts)
2✔
283
        else:
284
            # to generate objects when there are no static variables to generate 'initialize'
285
            for stmt in global_stmts:
2✔
286
                self.visit(stmt)
2✔
287

288
        return self.build_data(module)
2✔
289

290
    def visit_ClassDef(self, node: ast.ClassDef) -> GeneratorData:
2✔
291
        if node.name in self.symbols:
2✔
292
            class_symbol = self.symbols[node.name]
2✔
293
            if isinstance(class_symbol, UserClass):
2✔
294
                self.current_class = class_symbol
2✔
295

296
            if self._is_generating_initialize:
2✔
297
                address = self.generator.bytecode_size
2✔
298
                self.generator.convert_new_empty_array(len(class_symbol.class_variables), class_symbol)
2✔
299
                self.generator.convert_store_variable(node.name, address)
2✔
300
            else:
301
                init_method = class_symbol.constructor_method()
2✔
302
                if isinstance(init_method, Method) and init_method.start_address is None:
2✔
303
                    self.generator.generate_implicit_init_user_class(init_method)
2✔
304

305
        for stmt in node.body:
2✔
306
            self.visit(stmt)
2✔
307

308
        self.current_class = None
2✔
309
        return self.build_data(node)
2✔
310

311
    def visit_FunctionDef(self, function: ast.FunctionDef) -> GeneratorData:
2✔
312
        """
313
        Visitor of the function definition node
314

315
        Generates the Neo VM code for the function
316

317
        :param function: the python ast function definition node
318
        """
319
        method = self._symbols[function.name]
2✔
320

321
        if isinstance(method, Property):
2✔
322
            method = method.getter
2✔
323

324
        if isinstance(method, Method):
2✔
325
            self.current_method = method
2✔
326
            if isinstance(self.current_class, ClassType):
2✔
327
                function_name = self.current_class.identifier + constants.ATTRIBUTE_NAME_SEPARATOR + function.name
2✔
328
            else:
329
                function_name = function.name
2✔
330

331
            self._log_info(f"Compiling '{function_name}' function")
2✔
332

333
            if method.is_public or method.is_called:
2✔
334
                if not isinstance(self.current_class, ClassType) or not self.current_class.is_interface:
2✔
335
                    self.generator.convert_begin_method(method)
2✔
336

337
                    for stmt in function.body:
2✔
338
                        self.visit_to_map(stmt)
2✔
339

340
                    self.generator.convert_end_method(function.name)
2✔
341

342
            self.current_method = None
2✔
343

344
        return self.build_data(function, symbol=method, symbol_id=function.name)
2✔
345

346
    def visit_Return(self, ret: ast.Return) -> GeneratorData:
2✔
347
        """
348
        Visitor of a function return node
349

350
        :param ret: the python ast return node
351
        """
352
        if self.generator.stack_size > 0:
2✔
353
            self.generator.clear_stack(True)
2✔
354

355
        if self.current_method.return_type is not Type.none:
2✔
356
            result = self.visit_to_generate(ret.value)
2✔
357
            if result.type is Type.none and not self.generator.is_none_inserted():
2✔
358
                self.generator.convert_literal(None)
2✔
359
        elif ret.value is not None:
2✔
360
            self.visit_to_generate(ret.value)
2✔
361
            if self.generator.stack_size > 0:
2✔
362
                self.generator.remove_stack_top_item()
2✔
363

364
        self.generator.insert_return()
2✔
365

366
        return self.build_data(ret)
2✔
367

368
    def store_variable(self, *var_ids: VariableGenerationData, value: ast.AST):
2✔
369
        # if the value is None, it is a variable declaration
370
        if value is not None:
2✔
371
            if len(var_ids) == 1:
2✔
372
                # it's a simple assignment
373
                var_id, index, address = var_ids[0]
2✔
374
                if index is None:
2✔
375
                    # if index is None, then it is a variable assignment
376
                    result_data = self.visit_to_generate(value)
2✔
377

378
                    if result_data.type is Type.none and not self.generator.is_none_inserted():
2✔
379
                        self.generator.convert_literal(None)
2✔
380
                    self.generator.convert_store_variable(var_id, address, self.current_class if self.current_method is None else None)
2✔
381
                else:
382
                    # if not, it is an array assignment
383
                    self.generator.convert_load_symbol(var_id)
2✔
384
                    self.visit_to_generate(index)
2✔
385

386
                    aux_index = VMCodeMapping.instance().bytecode_size
2✔
387
                    value_data = self.visit_to_generate(value)
2✔
388
                    value_address = value_data.index if value_data.index is not None else aux_index
2✔
389

390
                    self.generator.convert_set_item(value_address)
2✔
391

392
            elif len(var_ids) > 0:
2✔
393
                # it's a chained assignment
394
                self.visit_to_generate(value)
2✔
395
                for pos, (var_id, index, address) in enumerate(reversed(var_ids)):
2✔
396
                    if index is None:
2✔
397
                        # if index is None, then it is a variable assignment
398
                        if pos < len(var_ids) - 1:
2✔
399
                            self.generator.duplicate_stack_top_item()
2✔
400
                        self.generator.convert_store_variable(var_id, address)
2✔
401
                    else:
402
                        # if not, it is an array assignment
403
                        if pos < len(var_ids) - 1:
2✔
404
                            self.generator.convert_load_symbol(var_id)
2✔
405
                            self.visit_to_generate(index)
2✔
406
                            fix_index = VMCodeMapping.instance().bytecode_size
2✔
407
                            self.generator.duplicate_stack_item(3)
2✔
408
                        else:
409
                            self.visit_to_generate(index)
2✔
410
                            fix_index = VMCodeMapping.instance().bytecode_size
2✔
411
                            self.generator.convert_load_symbol(var_id)
2✔
412
                            self.generator.swap_reverse_stack_items(3)
2✔
413
                        self.generator.convert_set_item(fix_index)
2✔
414

415
    def visit_AnnAssign(self, ann_assign: ast.AnnAssign) -> GeneratorData:
2✔
416
        """
417
        Visitor of an annotated assignment node
418

419
        :param ann_assign: the python ast variable assignment node
420
        """
421
        var_value_address = self.generator.bytecode_size
2✔
422
        var_data = self.visit(ann_assign.target)
2✔
423
        var_id = var_data.symbol_id
2✔
424
        # filter to find the imported variables
425
        if (var_id not in self.generator.symbol_table
2✔
426
                and hasattr(ann_assign, 'origin')
427
                and isinstance(ann_assign.origin, ast.AST)):
428
            var_id = self._get_unique_name(var_id, ann_assign.origin)
×
429

430
        if not (isinstance(var_data.symbol, Variable) and
2✔
431
                self.is_global_variable(var_id) and
432
                not self.generator.store_constant_variable(var_data.symbol)
433
        ):
434
            self.store_variable(VariableGenerationData(var_id, None, var_value_address), value=ann_assign.value)
2✔
435

436
        return self.build_data(ann_assign)
2✔
437

438
    def visit_Assign(self, assign: ast.Assign) -> GeneratorData:
2✔
439
        """
440
        Visitor of an assignment node
441

442
        :param assign: the python ast variable assignment node
443
        """
444
        vars_ids: list[VariableGenerationData] = []
2✔
445
        for target in assign.targets:
2✔
446
            var_value_address = self.generator.bytecode_size
2✔
447
            target_data: GeneratorData = self.visit(target)
2✔
448

449
            var_id = target_data.symbol_id
2✔
450
            var_index = target_data.index
2✔
451

452
            if (
2✔
453
                    isinstance(target_data.symbol, Variable) and
454
                    self.is_global_variable(var_id) and
455
                    not self.generator.store_constant_variable(target_data.symbol)
456
            ):
457
                continue
2✔
458

459
            # filter to find the imported variables
460
            if (var_id not in self.generator.symbol_table
2✔
461
                    and hasattr(assign, 'origin')
462
                    and isinstance(assign.origin, ast.AST)):
463
                var_id = self._get_unique_name(var_id, assign.origin)
×
464

465
            vars_ids.append(VariableGenerationData(var_id, var_index, var_value_address))
2✔
466

467
        if vars_ids:
2✔
468
            self.store_variable(*vars_ids, value=assign.value)
2✔
469
        return self.build_data(assign)
2✔
470

471
    def visit_AugAssign(self, aug_assign: ast.AugAssign) -> GeneratorData:
2✔
472
        """
473
        Visitor of an augmented assignment node
474

475
        :param aug_assign: the python ast augmented assignment node
476
        """
477
        start_address = self.generator.bytecode_size
2✔
478
        var_data = self.visit(aug_assign.target)
2✔
479
        var_id = var_data.symbol_id
2✔
480
        # filter to find the imported variables
481
        if (var_id not in self.generator.symbol_table
2✔
482
                and hasattr(aug_assign, 'origin')
483
                and isinstance(aug_assign.origin, ast.AST)):
484
            var_id = self._get_unique_name(var_id, aug_assign.origin)
×
485

486
        if isinstance(var_data.type, UserClass):
2✔
487
            self.generator.duplicate_stack_top_item()
2✔
488
        elif hasattr(var_data.origin_object_type, 'identifier') and var_data.already_generated:
2✔
489
            VMCodeMapping.instance().remove_opcodes(start_address)
×
490
            self.generator.convert_load_symbol(var_data.origin_object_type.identifier)
×
491

492
        self.generator.convert_load_symbol(var_id, class_type=var_data.origin_object_type)
2✔
493
        value_address = self.generator.bytecode_size
2✔
494
        self.visit_to_generate(aug_assign.value)
2✔
495
        self.generator.convert_operation(aug_assign.op)
2✔
496
        self.generator.convert_store_variable(var_id, value_address, user_class=var_data.origin_object_type)
2✔
497
        return self.build_data(aug_assign)
2✔
498

499
    def visit_Subscript(self, subscript: ast.Subscript) -> GeneratorData:
2✔
500
        """
501
        Visitor of a subscript node
502

503
        :param subscript: the python ast subscript node
504
        """
505
        if isinstance(subscript.slice, ast.Slice):
2✔
506
            return self.visit_Subscript_Slice(subscript)
2✔
507

508
        return self.visit_Subscript_Index(subscript)
2✔
509

510
    def visit_Subscript_Index(self, subscript: ast.Subscript) -> GeneratorData:
2✔
511
        """
512
        Visitor of a subscript node with index
513

514
        :param subscript: the python ast subscript node
515
        """
516
        index = None
2✔
517
        symbol_id = None
2✔
518
        if isinstance(subscript.ctx, ast.Load):
2✔
519
            # get item
520
            value_data = self.visit_to_generate(subscript.value)
2✔
521
            slice = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
2✔
522
            self.visit_to_generate(slice)
2✔
523

524
            index_is_constant_number = isinstance(slice, ast.Num) and isinstance(slice.n, int)
2✔
525
            self.generator.convert_get_item(index_is_positive=(index_is_constant_number and slice.n >= 0),
2✔
526
                                            test_is_negative_index=not (index_is_constant_number and slice.n < 0))
527

528
            value_type = value_data.type
2✔
529
        else:
530
            # set item
531
            var_data = self.visit(subscript.value)
2✔
532

533
            index = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
2✔
534
            symbol_id = var_data.symbol_id
2✔
535
            value_type = var_data.type
2✔
536

537
        result_type = value_type.item_type if isinstance(value_type, SequenceType) else value_type
2✔
538
        return self.build_data(subscript, result_type=result_type,
2✔
539
                               symbol_id=symbol_id, index=index)
540

541
    def visit_Subscript_Slice(self, subscript: ast.Subscript) -> GeneratorData:
2✔
542
        """
543
        Visitor of a subscript node with slice
544

545
        :param subscript: the python ast subscript node
546
        """
547
        lower_omitted = subscript.slice.lower is None
2✔
548
        upper_omitted = subscript.slice.upper is None
2✔
549
        step_omitted = subscript.slice.step is None
2✔
550

551
        self.visit_to_generate(subscript.value)
2✔
552

553
        step_negative = True if not step_omitted and subscript.slice.step.n < 0 else False
2✔
554

555
        if step_negative:
2✔
556
            # reverse the ByteString or the list
557
            self.generator.convert_array_negative_stride()
2✔
558

559
        addresses = []
2✔
560

561
        for index_number, omitted in [(subscript.slice.lower, lower_omitted), (subscript.slice.upper, upper_omitted)]:
2✔
562
            if not omitted:
2✔
563
                addresses.append(VMCodeMapping.instance().bytecode_size)
2✔
564
                self.visit_to_generate(index_number)
2✔
565

566
                index_is_constant_number = isinstance(index_number, ast.Num) and isinstance(index_number.n, int)
2✔
567
                if index_is_constant_number and index_number.n < 0:
2✔
568
                    self.generator.fix_negative_index(test_is_negative=False)
2✔
569
                elif not index_is_constant_number:
2✔
570
                    self.generator.fix_negative_index()
2✔
571

572
                if step_negative:
2✔
573
                    self.generator.duplicate_stack_item(len(addresses) + 1)  # duplicates the subscript
2✔
574
                    self.generator.fix_index_negative_stride()
2✔
575

576
                self.generator.fix_index_out_of_range(has_another_index_in_stack=len(addresses) == 2)
2✔
577

578
        # if both are explicit
579
        if not lower_omitted and not upper_omitted:
2✔
580
            self.generator.convert_get_sub_sequence()
2✔
581

582
        # only one of them is omitted
583
        elif lower_omitted != upper_omitted:
2✔
584
            # start position is omitted
585
            if lower_omitted:
2✔
586
                self.generator.convert_get_sequence_beginning()
2✔
587
            # end position is omitted
588
            else:
589
                self.generator.convert_get_sequence_ending()
2✔
590
        else:
591
            self.generator.convert_copy()
2✔
592

593
        if not step_omitted:
2✔
594
            self.visit_to_generate(subscript.slice.step)
2✔
595
            self.generator.convert_get_stride()
2✔
596

597
        return self.build_data(subscript)
2✔
598

599
    def _convert_unary_operation(self, operand, op):
2✔
600
        self.visit_to_generate(operand)
2✔
601
        self.generator.convert_operation(op)
2✔
602

603
    def _convert_binary_operation(self, left, right, op):
2✔
604
        self.visit_to_generate(left)
2✔
605
        self.visit_to_generate(right)
2✔
606
        self.generator.convert_operation(op)
2✔
607

608
    def visit_BinOp(self, bin_op: ast.BinOp) -> GeneratorData:
2✔
609
        """
610
        Visitor of a binary operation node
611

612
        :param bin_op: the python ast binary operation node
613
        """
614
        if isinstance(bin_op.op, BinaryOperation):
2✔
615
            self._convert_binary_operation(bin_op.left, bin_op.right, bin_op.op)
2✔
616

617
        return self.build_data(bin_op)
2✔
618

619
    def visit_UnaryOp(self, un_op: ast.UnaryOp) -> GeneratorData:
2✔
620
        """
621
        Visitor of a binary operation node
622

623
        :param un_op: the python ast binary operation node
624
        """
625
        if isinstance(un_op.op, UnaryOperation):
2✔
626
            self._convert_unary_operation(un_op.operand, un_op.op)
2✔
627

628
        return self.build_data(un_op, result_type=un_op.op.result)
2✔
629

630
    def visit_Compare(self, compare: ast.Compare) -> GeneratorData:
2✔
631
        """
632
        Visitor of a compare operation node
633

634
        :param compare: the python ast compare operation node
635
        """
636
        operation_symbol: IOperation = BinaryOp.And
2✔
637
        converted: bool = False
2✔
638
        left = compare.left
2✔
639
        for index, op in enumerate(compare.ops):
2✔
640
            right = compare.comparators[index]
2✔
641
            if isinstance(op, IOperation):
2✔
642
                if isinstance(op, BinaryOperation):
2✔
643
                    self._convert_binary_operation(left, right, op)
2✔
644
                else:
645
                    operand = left
2✔
646
                    if isinstance(operand, ast.NameConstant) and operand.value is None:
2✔
647
                        operand = right
×
648
                    self._convert_unary_operation(operand, op)
2✔
649
                # if it's more than two comparators, must include AND between the operations
650
                if not converted:
2✔
651
                    converted = True
2✔
652
                    operation_symbol = op
2✔
653
                else:
654
                    operation_symbol = BinaryOp.And
2✔
655
                    self.generator.convert_operation(BinaryOp.And)
2✔
656
            left = right
2✔
657

658
        return self.build_data(compare, symbol=operation_symbol, result_type=operation_symbol.result)
2✔
659

660
    def visit_BoolOp(self, bool_op: ast.BoolOp) -> GeneratorData:
2✔
661
        """
662
        Visitor of a compare operation node
663

664
        :param bool_op: the python ast boolean operation node
665
        """
666
        if isinstance(bool_op.op, BinaryOperation):
2✔
667
            left = bool_op.values[0]
2✔
668
            self.visit_to_generate(left)
2✔
669
            for index, right in enumerate(bool_op.values[1:]):
2✔
670
                self.visit_to_generate(right)
2✔
671
                self.generator.convert_operation(bool_op.op)
2✔
672

673
        return self.build_data(bool_op)
2✔
674

675
    def visit_While(self, while_node: ast.While) -> GeneratorData:
2✔
676
        """
677
        Visitor of a while statement node
678

679
        :param while_node: the python ast while statement node
680
        """
681
        start_addr: int = self.generator.convert_begin_while()
2✔
682
        for stmt in while_node.body:
2✔
683
            self.visit_to_map(stmt, generate=True)
2✔
684

685
        test_address: int = VMCodeMapping.instance().bytecode_size
2✔
686
        test_data = self.visit_to_map(while_node.test, generate=True)
2✔
687
        self.generator.convert_end_while(start_addr, test_address)
2✔
688

689
        else_begin_address: int = self.generator.last_code_start_address
2✔
690
        for stmt in while_node.orelse:
2✔
691
            self.visit_to_map(stmt, generate=True)
2✔
692

693
        self.generator.convert_end_loop_else(start_addr, else_begin_address, len(while_node.orelse) > 0)
2✔
694
        return self.build_data(while_node, index=start_addr)
2✔
695

696
    def visit_Match(self, match_node: ast.Match) -> GeneratorData:
2✔
697
        case_addresses = []
2✔
698

699
        for index, case in enumerate(match_node.cases):
2✔
700
            # if it's the wildcard to accept all values
701
            if hasattr(case.pattern, 'pattern') and case.pattern.pattern is None:
2✔
702
                for stmt in case.body:
2✔
703
                    self.visit_to_map(stmt, generate=True)
2✔
704
                self.generator.convert_end_if(case_addresses[-1])
2✔
705
            else:
706
                subject = self.visit_to_map(match_node.subject, generate=True)
2✔
707
                if isinstance(case.pattern, ast.MatchSingleton):
2✔
708
                    self.generator.convert_literal(case.pattern.value)
2✔
709
                    pattern_type = self.get_type(case.pattern.value)
2✔
710
                else:
711
                    pattern = self.visit_to_generate(case.pattern.value)
2✔
712
                    pattern_type = pattern.type
2✔
713

714
                self.generator.duplicate_stack_item(2)
2✔
715
                pattern_type.generate_is_instance_type_check(self.generator)
2✔
716

717
                self.generator.swap_reverse_stack_items(3)
2✔
718
                self.generator.convert_operation(BinaryOp.NumEq)
2✔
719
                self.generator.convert_operation(BinaryOp.And)
2✔
720

721
                case_addresses.append(self.generator.convert_begin_if())
2✔
722
                for stmt in case.body:
2✔
723
                    self.visit_to_map(stmt, generate=True)
2✔
724

725
                ends_with_if = len(case.body) > 0 and isinstance(case.body[-1], ast.If)
2✔
726

727
                if index < len(match_node.cases) - 1:
2✔
728
                    case_addresses[index] = self.generator.convert_begin_else(case_addresses[index], ends_with_if)
2✔
729

730
        for case_addr in reversed(range(len(case_addresses))):
2✔
731
            self.generator.convert_end_if(case_addresses[case_addr])
2✔
732

733
        return self.build_data(match_node)
2✔
734

735
    def visit_For(self, for_node: ast.For) -> GeneratorData:
2✔
736
        """
737
        Visitor of for statement node
738

739
        :param for_node: the python ast for node
740
        """
741
        self.visit_to_generate(for_node.iter)
2✔
742
        start_address = self.generator.convert_begin_for()
2✔
743

744
        if isinstance(for_node.target, tuple):
2✔
745
            for target in for_node.target:
×
746
                var_data = self.visit_to_map(target)
×
747
                self.generator.convert_store_variable(var_data.symbol_id)
×
748
        else:
749
            var_data = self.visit(for_node.target)
2✔
750
            self.generator.convert_store_variable(var_data.symbol_id)
2✔
751

752
        for stmt in for_node.body:
2✔
753
            self.visit_to_map(stmt, generate=True)
2✔
754

755
        # TODO: remove when optimizing for generation #864e6me36
756
        if self.current_method is not None:
2✔
757
            self.current_method.remove_instruction(for_node.lineno, for_node.col_offset)
2✔
758

759
        condition_address = self.generator.convert_end_for(start_address)
2✔
760
        self.include_instruction(for_node, condition_address)
2✔
761
        else_begin = self.generator.last_code_start_address
2✔
762

763
        for stmt in for_node.orelse:
2✔
764
            self.visit_to_map(stmt, generate=True)
2✔
765

766
        self.generator.convert_end_loop_else(start_address,
2✔
767
                                             else_begin,
768
                                             has_else=len(for_node.orelse) > 0,
769
                                             is_for=True)
770
        return self.build_data(for_node)
2✔
771

772
    def visit_If(self, if_node: ast.If) -> GeneratorData:
2✔
773
        """
774
        Visitor of if statement node
775

776
        :param if_node: the python ast if statement node
777
        """
778
        test = self.visit_to_map(if_node.test, generate=True)
2✔
779

780
        if not Type.bool.is_type_of(test.type) and test.type is not None:
2✔
781
            self.generator.convert_builtin_method_call(Builtin.Bool)
2✔
782

783
        start_addr: int = self.generator.convert_begin_if()
2✔
784
        for stmt in if_node.body:
2✔
785
            self.visit_to_map(stmt, generate=True)
2✔
786

787
        ends_with_if = len(if_node.body) > 0 and isinstance(if_node.body[-1], ast.If)
2✔
788

789
        if len(if_node.orelse) > 0:
2✔
790
            start_addr = self.generator.convert_begin_else(start_addr, ends_with_if)
2✔
791
            for stmt in if_node.orelse:
2✔
792
                self.visit_to_map(stmt, generate=True)
2✔
793

794
        self.generator.convert_end_if(start_addr)
2✔
795
        return self.build_data(if_node)
2✔
796

797
    def visit_Expr(self, expr: ast.Expr, generate: bool = False) -> GeneratorData:
2✔
798
        """
799
        Visitor of an expression node
800

801
        :param expr: the python ast expression node
802
        :param generate: if it should convert the value
803
        """
804
        last_stack = self.generator.stack_size
2✔
805
        if generate:
2✔
806
            value = self.visit_to_generate(expr.value)
2✔
807
        else:
808
            value = self.visit(expr.value)
2✔
809

810
        new_stack = self.generator.stack_size
2✔
811
        for x in range(last_stack, new_stack):
2✔
812
            self.generator.remove_stack_top_item()
2✔
813

814
        return value
2✔
815

816
    def visit_IfExp(self, if_node: ast.IfExp) -> GeneratorData:
2✔
817
        """
818
        Visitor of if expression node
819

820
        :param if_node: the python ast if statement node
821
        """
822
        self.visit_to_map(if_node.test, generate=True)
2✔
823

824
        start_addr: int = self.generator.convert_begin_if()
2✔
825
        body_data = self.visit_to_map(if_node.body, generate=True)
2✔
826

827
        start_addr = self.generator.convert_begin_else(start_addr)
2✔
828
        else_data = self.visit_to_map(if_node.orelse, generate=True)
2✔
829

830
        self.generator.convert_end_if(start_addr)
2✔
831
        return self.build_data(if_node, result_type=Type.union.build([body_data.type, else_data.type]))
2✔
832

833
    def visit_Assert(self, assert_node: ast.Assert) -> GeneratorData:
2✔
834
        """
835
        Visitor of the assert node
836

837
        :param assert_node: the python ast assert node
838
        """
839
        self.visit_to_generate(assert_node.test)
2✔
840

841
        if assert_node.msg is not None:
2✔
842
            self.visit_to_generate(assert_node.msg)
2✔
843

844
        self.generator.convert_assert(has_message=assert_node.msg is not None)
2✔
845
        return self.build_data(assert_node)
2✔
846

847
    def visit_Call(self, call: ast.Call) -> GeneratorData:
2✔
848
        """
849
        Visitor of a function call node
850

851
        :param call: the python ast function call node
852
        :returns: The called function return type
853
        """
854
        # the parameters are included into the stack in the reversed order
855
        last_address = VMCodeMapping.instance().bytecode_size
2✔
856
        last_stack = self.generator.stack_size
2✔
857

858
        func_data = self.visit(call.func)
2✔
859
        function_id = func_data.symbol_id
2✔
860
        # if the symbol is not a method, check if it is a class method
861
        if (isinstance(func_data.type, ClassType) and func_data.symbol_id in func_data.type.symbols
2✔
862
                and isinstance(func_data.type.symbols[func_data.symbol_id], IExpression)):
863
            symbol = func_data.type.symbols[func_data.symbol_id]
2✔
864
        else:
865
            symbol = func_data.symbol
2✔
866

867
        if not isinstance(symbol, Method):
2✔
868
            is_internal = hasattr(call, 'is_internal_call') and call.is_internal_call
2✔
869
            _, symbol = self.generator.get_symbol(function_id, is_internal=is_internal)
2✔
870

871
        if self.is_implemented_class_type(symbol):
2✔
872
            self.generator.convert_init_user_class(symbol)
2✔
873
            symbol = symbol.constructor_method()
2✔
874
        args_addresses: list[int] = []
2✔
875

876
        has_cls_or_self_argument = isinstance(symbol, Method) and symbol.has_cls_or_self
2✔
877
        if not has_cls_or_self_argument:
2✔
878
            self._remove_inserted_opcodes_since(last_address, last_stack)
2✔
879

880
        if isinstance(symbol, Method):
2✔
881
            # self or cls is already generated
882
            call_args = (call.args[1:]
2✔
883
                         if has_cls_or_self_argument and len(call.args) == len(symbol.args)
884
                         else call.args)
885
            args_to_generate = [arg for index, arg in enumerate(call_args) if index in symbol.args_to_be_generated()]
2✔
886
            keywords_dict = {keyword.arg: keyword.value for keyword in call.keywords}
2✔
887
            keywords_with_index = {index: keywords_dict[arg_name]
2✔
888
                                   for index, arg_name in enumerate(symbol.args)
889
                                   if arg_name in keywords_dict}
890

891
            for index in keywords_with_index:
2✔
892
                if index < len(args_to_generate):
2✔
893
                    # override default values
894
                    args_to_generate[index] = keywords_with_index[index]
2✔
895
                else:
896
                    # put keywords
897
                    args_to_generate.append(keywords_with_index[index])
2✔
898

899
        else:
900
            args_to_generate = call.args
2✔
901

902
        if isinstance(symbol, IBuiltinMethod):
2✔
903
            reordered_args = []
2✔
904
            for index in symbol.generation_order:
2✔
905
                if 0 <= index < len(args_to_generate):
2✔
906
                    reordered_args.append(args_to_generate[index])
2✔
907

908
            args = reordered_args
2✔
909
        else:
910
            args = reversed(args_to_generate)
2✔
911

912
        args_begin_address = self.generator.last_code_start_address
2✔
913
        for arg in args:
2✔
914
            args_addresses.append(
2✔
915
                VMCodeMapping.instance().bytecode_size
916
            )
917
            self.visit_to_generate(arg)
2✔
918

919
        class_type = None
2✔
920
        if has_cls_or_self_argument:
2✔
921
            num_args = len(args_addresses)
2✔
922
            if self.generator.stack_size > num_args:
2✔
923
                value = self.generator._stack_pop(-num_args - 1)
2✔
924
                self.generator._stack_append(value)
2✔
925
                class_type = value if isinstance(value, UserClass) else None
2✔
926
            end_address = VMCodeMapping.instance().move_to_end(last_address, args_begin_address)
2✔
927
            if not symbol.is_init:
2✔
928
                args_addresses.append(end_address)
2✔
929

930
        if self.is_exception_name(function_id):
2✔
931
            self.generator.convert_new_exception(len(call.args))
2✔
932
        elif isinstance(symbol, type(Builtin.Super)) and len(args_to_generate) == 0:
2✔
933
            self_or_cls_id = list(self.current_method.args)[0]
2✔
934
            self.generator.convert_load_symbol(self_or_cls_id)
2✔
935
        elif isinstance(symbol, IBuiltinMethod):
2✔
936
            self.generator.convert_builtin_method_call(symbol, args_addresses)
2✔
937
        else:
938
            self.generator.convert_load_symbol(function_id, args_addresses,
2✔
939
                                               class_type=class_type)
940

941
        return self.build_data(call, symbol=symbol, symbol_id=function_id,
2✔
942
                               result_type=symbol.type if isinstance(symbol, IExpression) else symbol,
943
                               already_generated=True)
944

945
    def visit_Raise(self, raise_node: ast.Raise) -> GeneratorData:
2✔
946
        """
947
        Visitor of the raise node
948

949
        :param raise_node: the python ast raise node
950
        """
951
        self.visit_to_map(raise_node.exc, generate=True)
2✔
952
        self.generator.convert_raise_exception()
2✔
953
        return self.build_data(raise_node)
2✔
954

955
    def visit_Try(self, try_node: ast.Try) -> GeneratorData:
2✔
956
        """
957
        Visitor of the try node
958

959
        :param try_node: the python ast try node
960
        """
961
        try_address: int = self.generator.convert_begin_try()
2✔
962
        try_end: int | None = None
2✔
963
        for stmt in try_node.body:
2✔
964
            self.visit_to_map(stmt, generate=True)
2✔
965

966
        if len(try_node.handlers) == 1:
2✔
967
            handler = try_node.handlers[0]
2✔
968
            try_end = self.generator.convert_try_except(handler.name)
2✔
969
            for stmt in handler.body:
2✔
970
                self.visit_to_map(stmt, generate=True)
2✔
971

972
        else_address = None
2✔
973
        if len(try_node.orelse) > 0:
2✔
974
            else_start_address = self.generator.convert_begin_else(try_end)
2✔
975
            else_address = self.generator.bytecode_size
2✔
976
            for stmt in try_node.orelse:
2✔
977
                self.visit_to_map(stmt, generate=True)
2✔
978
            self.generator.convert_end_if(else_start_address)
2✔
979

980
        except_end = self.generator.convert_end_try(try_address, try_end, else_address)
2✔
981
        for stmt in try_node.finalbody:
2✔
982
            self.visit_to_map(stmt, generate=True)
2✔
983
        self.generator.convert_end_try_finally(except_end, try_address, len(try_node.finalbody) > 0)
2✔
984

985
        return self.build_data(try_node)
2✔
986

987
    def visit_Name(self, name_node: ast.Name) -> GeneratorData:
2✔
988
        """
989
        Visitor of a name node
990

991
        :param name_node: the python ast name identifier node
992
        :return: the identifier of the name
993
        """
994
        name = name_node.id
2✔
995
        if name not in self._symbols:
2✔
996
            hashed_name = self._get_unique_name(name, self._tree)
2✔
997
            if hashed_name not in self._symbols and hasattr(name_node, 'origin'):
2✔
998
                hashed_name = self._get_unique_name(name, name_node.origin)
2✔
999

1000
            if hashed_name in self._symbols:
2✔
1001
                name = hashed_name
2✔
1002

1003
        else:
1004
            if name not in self.generator.symbol_table:
2✔
1005
                symbol = self._symbols[name]
2✔
1006
                for symbol_id, internal_symbol in self.generator.symbol_table.items():
2✔
1007
                    if internal_symbol == symbol:
2✔
1008
                        name = symbol_id
×
1009
                        break
×
1010

1011
        return self.build_data(name_node, name)
2✔
1012

1013
    def visit_Starred(self, starred: ast.Starred) -> GeneratorData:
2✔
1014
        value_data = self.visit_to_generate(starred.value)
2✔
1015
        self.generator.convert_starred_variable()
2✔
1016

1017
        starred_data = value_data.copy(starred)
2✔
1018
        starred_data.already_generated = True
2✔
1019
        return starred_data
2✔
1020

1021
    def visit_Attribute(self, attribute: ast.Attribute) -> GeneratorData:
2✔
1022
        """
1023
        Visitor of a attribute node
1024

1025
        :param attribute: the python ast attribute node
1026
        :return: the identifier of the attribute
1027
        """
1028
        last_address = VMCodeMapping.instance().bytecode_size
2✔
1029
        last_stack = self.generator.stack_size
2✔
1030

1031
        _attr, attr = self.generator.get_symbol(attribute.attr)
2✔
1032
        value = attribute.value
2✔
1033
        value_symbol = None
2✔
1034
        value_type = None
2✔
1035
        value_data = self.visit(value)
2✔
1036
        need_to_visit_again = True
2✔
1037

1038
        if value_data.symbol_id is not None and not value_data.already_generated:
2✔
1039
            value_id = value_data.symbol_id
2✔
1040
            if value_data.symbol is not None:
2✔
1041
                value_symbol = value_data.symbol
2✔
1042
            else:
1043
                _, value_symbol = self.generator.get_symbol(value_id)
2✔
1044
            value_type = value_symbol.type if hasattr(value_symbol, 'type') else value_symbol
2✔
1045

1046
            if hasattr(value_type, 'symbols') and attribute.attr in value_type.symbols:
2✔
1047
                attr = value_type.symbols[attribute.attr]
2✔
1048
            elif isinstance(value_type, Package) and attribute.attr in value_type.inner_packages:
2✔
1049
                attr = value_type.inner_packages[attribute.attr]
2✔
1050

1051
            if isinstance(value_symbol, UserClass):
2✔
1052
                if isinstance(attr, Method) and attr.has_cls_or_self:
2✔
1053
                    self.generator.convert_load_symbol(value_id)
2✔
1054
                    need_to_visit_again = False
2✔
1055

1056
                if isinstance(attr, Variable):
2✔
1057
                    cur_bytesize = self.generator.bytecode_size
2✔
1058
                    self.visit_to_generate(attribute.value)
2✔
1059
                    self.generator.convert_load_symbol(attribute.attr, class_type=value_symbol)
2✔
1060

1061
                    symbol_id = _attr if isinstance(_attr, str) else None
2✔
1062
                    return self.build_data(attribute,
2✔
1063
                                           already_generated=self.generator.bytecode_size > cur_bytesize,
1064
                                           symbol=attr, symbol_id=symbol_id,
1065
                                           origin_object_type=value_symbol)
1066
        else:
1067
            if isinstance(value, ast.Attribute) and value_data.already_generated:
2✔
1068
                need_to_visit_again = False
2✔
1069
            else:
1070
                need_to_visit_again = value_data.already_generated
2✔
1071
                self._remove_inserted_opcodes_since(last_address, last_stack)
2✔
1072

1073
        # the verification above only verify variables, this one will should work with literals and constants
1074
        if isinstance(value, ast.Constant) and len(attr.args) > 0 and isinstance(attr, IBuiltinMethod) and attr.has_self_argument:
2✔
1075
            attr = attr.build(value_data.type)
×
1076

1077
        if attr is not Type.none and not hasattr(attribute, 'generate_value'):
2✔
1078
            value_symbol_id = (value_symbol.identifier
2✔
1079
                               if self.is_implemented_class_type(value_symbol)
1080
                               else value_data.symbol_id)
1081
            attribute_id = f'{value_symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
2✔
1082
            index = value_type if isinstance(value_type, Package) else None
2✔
1083
            return self.build_data(attribute, symbol_id=attribute_id, symbol=attr, index=index)
2✔
1084

1085
        if isinstance(value, ast.Attribute) and need_to_visit_again:
2✔
1086
            value_data = self.visit(value)
2✔
1087
        elif hasattr(attribute, 'generate_value') and attribute.generate_value:
2✔
1088
            current_bytecode_size = self.generator.bytecode_size
2✔
1089
            if need_to_visit_again:
2✔
1090
                value_data = self.visit_to_generate(attribute.value)
2✔
1091

1092
            result = value_data.type
2✔
1093
            generation_result = value_data.symbol
2✔
1094
            if result is None and value_data.symbol_id is not None:
2✔
1095
                _, result = self.generator.get_symbol(value_data.symbol_id)
2✔
1096
                if isinstance(result, IExpression):
2✔
1097
                    generation_result = result
×
1098
                    result = result.type
×
1099
            elif isinstance(attribute.value, ast.Attribute) and isinstance(value_data.index, int):
2✔
1100
                result = self.get_type(generation_result)
2✔
1101

1102
            if self.is_implemented_class_type(result):
2✔
1103
                class_attr_id = f'{result.identifier}.{attribute.attr}'
2✔
1104
                symbol_id = class_attr_id
2✔
1105
                symbol = None
2✔
1106
                result_type = None
2✔
1107
                symbol_index = None
2✔
1108
                is_load_context_variable_from_class = (isinstance(attribute.ctx, ast.Load) and
2✔
1109
                                                       isinstance(attr, Variable) and
1110
                                                       isinstance(result, UserClass))
1111

1112
                if self.generator.bytecode_size > current_bytecode_size and isinstance(result, UserClass) and not is_load_context_variable_from_class:
2✔
1113
                    # it was generated already, don't convert again
1114
                    generated = False
2✔
1115
                    symbol_id = attribute.attr if isinstance(generation_result, Variable) else class_attr_id
2✔
1116
                    result_type = result
2✔
1117
                else:
1118
                    current_bytecode_size = self.generator.bytecode_size
2✔
1119
                    index = self.generator.convert_class_symbol(result,
2✔
1120
                                                                attribute.attr,
1121
                                                                isinstance(attribute.ctx, ast.Load))
1122
                    generated = self.generator.bytecode_size > current_bytecode_size
2✔
1123
                    symbol = result
2✔
1124
                    if not isinstance(result, UserClass):
2✔
1125
                        if isinstance(index, int):
2✔
1126
                            symbol_index = index
2✔
1127
                        else:
1128
                            symbol_id = index
2✔
1129

1130
                return self.build_data(attribute,
2✔
1131
                                       symbol_id=symbol_id, symbol=symbol,
1132
                                       result_type=result_type, index=symbol_index,
1133
                                       origin_object_type=value_type,
1134
                                       already_generated=generated)
1135

1136
        if value_data is not None and value_symbol is None:
2✔
1137
            value_symbol = value_data.symbol_id
×
1138

1139
        if value_data is not None and value_data.symbol_id is not None:
2✔
1140
            value_id = f'{value_data.symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
2✔
1141
        else:
1142
            value_id = attribute.attr
×
1143

1144
        return self.build_data(attribute, symbol_id=value_id, symbol=value_symbol)
2✔
1145

1146
    def visit_Continue(self, continue_node: ast.Continue) -> GeneratorData:
2✔
1147
        """
1148
        :param continue_node: the python ast continue statement node
1149
        """
1150
        self.generator.convert_loop_continue()
2✔
1151
        return self.build_data(continue_node)
2✔
1152

1153
    def visit_Break(self, break_node: ast.Break) -> GeneratorData:
2✔
1154
        """
1155
        :param break_node: the python ast break statement node
1156
        """
1157
        self.generator.convert_loop_break()
2✔
1158
        return self.build_data(break_node)
2✔
1159

1160
    def visit_Constant(self, constant: ast.Constant) -> GeneratorData:
2✔
1161
        """
1162
        Visitor of constant values node
1163

1164
        :param constant: the python ast constant value node
1165
        """
1166
        index = self.generator.convert_literal(constant.value)
2✔
1167
        result_type = self.get_type(constant.value)
2✔
1168
        return self.build_data(constant, result_type=result_type, index=index, already_generated=True)
2✔
1169

1170
    def visit_NameConstant(self, constant: ast.NameConstant) -> GeneratorData:
2✔
1171
        """
1172
        Visitor of constant names node
1173

1174
        :param constant: the python ast name constant node
1175
        """
1176
        index = self.generator.convert_literal(constant.value)
×
1177
        result_type = self.get_type(constant.value)
×
1178
        return self.build_data(constant, result_type=result_type, index=index, already_generated=True)
×
1179

1180
    def visit_Num(self, num: ast.Num) -> GeneratorData:
2✔
1181
        """
1182
        Visitor of literal number node
1183

1184
        :param num: the python ast number node
1185
        """
1186
        index = self.generator.convert_literal(num.n)
×
1187
        result_type = self.get_type(num.n)
×
1188
        return self.build_data(num, result_type=result_type, index=index, already_generated=True)
×
1189

1190
    def visit_Str(self, string: ast.Str) -> GeneratorData:
2✔
1191
        """
1192
        Visitor of literal string node
1193

1194
        :param string: the python ast string node
1195
        """
1196
        index = self.generator.convert_literal(string.s)
×
1197
        result_type = self.get_type(string.s)
×
1198
        return self.build_data(string, result_type=result_type, index=index, already_generated=True)
×
1199

1200
    def visit_Bytes(self, bts: ast.Bytes) -> GeneratorData:
2✔
1201
        """
1202
        Visitor of literal bytes node
1203

1204
        :param bts: the python ast bytes node
1205
        """
1206
        index = self.generator.convert_literal(bts.s)
×
1207
        result_type = self.get_type(bts.s)
×
1208
        return self.build_data(bts, result_type=result_type, index=index, already_generated=True)
×
1209

1210
    def visit_Tuple(self, tup_node: ast.Tuple) -> GeneratorData:
2✔
1211
        """
1212
        Visitor of literal tuple node
1213

1214
        :param tup_node: the python ast tuple node
1215
        """
1216
        result_type = Type.tuple
2✔
1217
        self._create_array(tup_node.elts, result_type)
2✔
1218
        return self.build_data(tup_node, result_type=result_type, already_generated=True)
2✔
1219

1220
    def visit_List(self, list_node: ast.List) -> GeneratorData:
2✔
1221
        """
1222
        Visitor of literal list node
1223

1224
        :param list_node: the python ast list node
1225
        """
1226
        result_type = Type.list
2✔
1227
        self._create_array(list_node.elts, result_type)
2✔
1228
        return self.build_data(list_node, result_type=result_type, already_generated=True)
2✔
1229

1230
    def visit_Dict(self, dict_node: ast.Dict) -> GeneratorData:
2✔
1231
        """
1232
        Visitor of literal dict node
1233

1234
        :param dict_node: the python ast dict node
1235
        """
1236
        result_type = Type.dict
2✔
1237
        length = min(len(dict_node.keys), len(dict_node.values))
2✔
1238
        self.generator.convert_new_map(result_type)
2✔
1239
        for key_value in range(length):
2✔
1240
            self.generator.duplicate_stack_top_item()
2✔
1241
            self.visit_to_generate(dict_node.keys[key_value])
2✔
1242
            value_data = self.visit_to_generate(dict_node.values[key_value])
2✔
1243
            self.generator.convert_set_item(value_data.index)
2✔
1244

1245
        return self.build_data(dict_node, result_type=result_type, already_generated=True)
2✔
1246

1247
    def visit_JoinedStr(self, fstring: ast.JoinedStr) -> GeneratorData:
2✔
1248
        """
1249
        Visitor of an f-string node
1250

1251
        :param string: the python ast string node
1252
        """
1253
        result_type = Type.str
2✔
1254
        index = self.generator.bytecode_size
2✔
1255
        for index, value in enumerate(fstring.values):
2✔
1256
            self.visit_to_generate(value)
2✔
1257
            if index != 0:
2✔
1258
                self.generator.convert_operation(BinaryOp.Concat)
2✔
1259
                if index < len(fstring.values) - 1:
2✔
1260
                    self._remove_inserted_opcodes_since(self.generator.last_code_start_address)
×
1261

1262
        return self.build_data(fstring, result_type=result_type, index=index, already_generated=True)
2✔
1263

1264
    def visit_FormattedValue(self, formatted_value: ast.FormattedValue) -> GeneratorData:
2✔
1265
        """
1266
        Visitor of a formatted_value node
1267

1268
        :param formatted_value: the python ast string node
1269
        """
1270
        generated_value = self.visit_to_generate(formatted_value.value)
2✔
1271
        if generated_value.type == Type.str:
2✔
1272
            return generated_value
2✔
1273

1274
        else:
1275
            match generated_value.type:
2✔
1276
                case Type.bool:
2✔
1277
                    self.generator.convert_builtin_method_call(Builtin.StrBool)
2✔
1278
                case Type.int:
2✔
1279
                    self.generator.convert_builtin_method_call(Builtin.StrInt)
2✔
1280
                case Type.bytes:
2✔
1281
                    self.generator.convert_builtin_method_call(Builtin.StrBytes)
2✔
1282
                case x if Type.sequence.is_type_of(x):
2✔
1283
                    self.generator.convert_builtin_method_call(Builtin.StrSequence)
2✔
1284
                case x if isinstance(x, UserClass):
2✔
1285
                    self.generator.convert_builtin_method_call(Builtin.StrClass.build(x))
2✔
1286

1287
            return self.build_data(formatted_value, result_type=Type.str, already_generated=True)
2✔
1288

1289
    def visit_Pass(self, pass_node: ast.Pass) -> GeneratorData:
2✔
1290
        """
1291
        Visitor of pass node
1292

1293
        :param pass_node: the python ast dict node
1294
        """
1295
        # only generates if the scope is a function
1296
        result_type = None
2✔
1297
        generated = False
2✔
1298

1299
        if isinstance(self.current_method, Method):
2✔
1300
            self.generator.insert_nop()
2✔
1301
            generated = True
2✔
1302

1303
        return self.build_data(pass_node, result_type=result_type, already_generated=generated)
2✔
1304

1305
    def _create_array(self, values: list[ast.AST], array_type: IType):
2✔
1306
        """
1307
        Creates a new array from a literal sequence
1308

1309
        :param values: list of values of the new array items
1310
        """
1311
        length = len(values)
2✔
1312
        if length > 0:
2✔
1313
            for value in reversed(values):
2✔
1314
                self.visit_to_generate(value)
2✔
1315
        self.generator.convert_new_array(length, array_type)
2✔
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc