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

CityOfZion / neo3-boa / 8225fc18-870a-447d-90c4-49b96fe75a64

09 Oct 2023 03:52PM UTC coverage: 91.625% (-0.1%) from 91.739%
8225fc18-870a-447d-90c4-49b96fe75a64

push

circleci

Mirella de Medeiros
#86a111f8j - Update CHANGELOG

19988 of 21815 relevant lines covered (91.63%)

0.92 hits per line

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

95.77
/boa3/internal/compiler/codegenerator/codegeneratorvisitor.py
1
import ast
1✔
2
import os.path
1✔
3
from inspect import isclass
1✔
4
from typing import Dict, List, Optional
1✔
5

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

29

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

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

37
    :ivar generator:
38
    """
39

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

43
        self.generator = generator
1✔
44
        self.current_method: Optional[Method] = None
1✔
45
        self.current_class: Optional[UserClass] = None
1✔
46
        self.symbols = generator.symbol_table
1✔
47

48
        self.global_stmts: List[ast.AST] = []
1✔
49
        self._is_generating_initialize = False
1✔
50
        self._root_module: ast.AST = self._tree
1✔
51

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

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

59
        return symbol_table
1✔
60

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

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

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

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

89
            if found_symbol is not None:
1✔
90
                symbol = found_symbol
1✔
91

92
        return GeneratorData(origin_node, symbol_id, symbol, result_type, index, origin_object_type, already_generated)
1✔
93

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

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

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

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

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

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

129
            if not result.already_generated and result.symbol_id is not None:
1✔
130
                if self.is_exception_name(result.symbol_id):
1✔
131
                    self.generator.convert_new_exception()
1✔
132
                else:
133
                    # TODO: validate function calls
134
                    is_internal = hasattr(node, 'is_internal_call') and node.is_internal_call
1✔
135
                    class_type = result.type if isinstance(node, ast.Attribute) else None
1✔
136

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

144
                    elif isinstance(result.index, Package):
1✔
145
                        class_type = None
1✔
146

147
                    self.generator.convert_load_symbol(result.symbol_id, is_internal=is_internal, class_type=class_type)
1✔
148

149
                result.already_generated = True
1✔
150

151
            return result
1✔
152
        else:
153
            index = self.generator.convert_literal(node)
1✔
154
            return self.build_data(node, index=index)
1✔
155

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

166
    def _remove_inserted_opcodes_since(self, last_address: int, last_stack_size: Optional[int] = None):
1✔
167
        self.generator._remove_inserted_opcodes_since(last_address, last_stack_size)
1✔
168

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

172
    def set_filename(self, filename: str):
1✔
173
        if isinstance(filename, str) and os.path.isfile(filename):
1✔
174
            if constants.PATH_SEPARATOR != os.path.sep:
1✔
175
                self.filename = filename.replace(constants.PATH_SEPARATOR, os.path.sep)
×
176
            else:
177
                self.filename = filename
1✔
178

179
    def visit_Module(self, module: ast.Module) -> GeneratorData:
1✔
180
        """
181
        Visitor of the module node
182

183
        Fills module symbol table
184

185
        :param module:
186
        """
187
        global_stmts = [node for node in module.body if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef))]
1✔
188
        function_stmts = module.body[len(global_stmts):]
1✔
189
        mandatory_global_stmts = []
1✔
190
        for stmt in global_stmts:
1✔
191
            if isinstance(stmt, ast.ClassDef):
1✔
192
                class_symbol = self.get_symbol(stmt.name)
1✔
193
                if isinstance(class_symbol, UserClass) and len(class_symbol.class_variables) > 0:
1✔
194
                    mandatory_global_stmts.append(stmt)
1✔
195
            elif not isinstance(stmt, (ast.Import, ast.ImportFrom)):
1✔
196
                mandatory_global_stmts.append(stmt)
1✔
197

198
        for stmt in function_stmts:
1✔
199
            self.visit(stmt)
1✔
200

201
        if self.generator.initialize_static_fields():
1✔
202
            last_symbols = self.symbols  # save to revert in the end and not compromise consequent visits
1✔
203
            class_non_static_stmts = []
1✔
204

205
            for node in global_stmts.copy():
1✔
206
                if isinstance(node, ast.ClassDef):
1✔
207
                    class_origin_module = None
1✔
208
                    if hasattr(node, 'origin'):
1✔
209
                        class_origin_module = node.origin
1✔
210
                        if (node.origin is not self._root_module
1✔
211
                                and hasattr(node.origin, 'symbols')):
212
                            # symbols unique to imports are not included in the symbols
213
                            self.symbols = node.origin.symbols
1✔
214

215
                    class_variables = []
1✔
216
                    class_functions = []
1✔
217
                    for stmt in node.body:
1✔
218
                        if isinstance(stmt, (ast.Assign, ast.AugAssign, ast.AnnAssign)):
1✔
219
                            class_variables.append(stmt)
1✔
220
                        else:
221
                            class_functions.append(stmt)
1✔
222

223
                    if len(class_functions) > 0:
1✔
224
                        if class_origin_module is not None and not hasattr(node, 'origin'):
1✔
225
                            node.origin = class_origin_module
×
226

227
                        cls_fun = node
1✔
228
                        if len(class_variables) > 0:
1✔
229
                            cls_var = node
1✔
230
                            cls_fun = self.clone(node)
1✔
231
                            cls_fun.body = class_functions
1✔
232
                            cls_var.body = class_variables
1✔
233
                        else:
234
                            global_stmts.remove(cls_fun)
1✔
235

236
                        class_non_static_stmts.append(cls_fun)
1✔
237
                    self.symbols = last_symbols  # don't use inner scopes to evaluate the other globals
1✔
238

239
            # to generate the 'initialize' method for Neo
240
            self._log_info(f"Compiling '{constants.INITIALIZE_METHOD_ID}' function")
1✔
241
            self._is_generating_initialize = True
1✔
242
            for stmt in global_stmts:
1✔
243
                cur_tree = self._tree
1✔
244
                cur_filename = self.filename
1✔
245
                if hasattr(stmt, 'origin'):
1✔
246
                    if hasattr(stmt.origin, 'filename'):
1✔
247
                        self.set_filename(stmt.origin.filename)
1✔
248
                    self._tree = stmt.origin
1✔
249

250
                self.visit(stmt)
1✔
251
                self.filename = cur_filename
1✔
252
                self._tree = cur_tree
1✔
253

254
            self._is_generating_initialize = False
1✔
255
            self.generator.end_initialize()
1✔
256

257
            # generate any symbol inside classes that's not variables AFTER generating 'initialize' method
258
            for stmt in class_non_static_stmts:
1✔
259
                cur_tree = self._tree
1✔
260
                if hasattr(stmt, 'origin'):
1✔
261
                    self._tree = stmt.origin
1✔
262
                self.visit(stmt)
1✔
263
                self._tree = cur_tree
1✔
264

265
            self.symbols = last_symbols  # revert in the end to not compromise consequent visits
1✔
266
            self.generator.additional_symbols = None
1✔
267

268
        elif len(function_stmts) > 0 or len(mandatory_global_stmts) > 0:
1✔
269
            # to organize syntax tree nodes from other modules
270
            for stmt in global_stmts:
1✔
271
                if not hasattr(stmt, 'origin'):
1✔
272
                    stmt.origin = module
1✔
273

274
            module.symbols = self._symbols
1✔
275
            self.global_stmts.extend(global_stmts)
1✔
276
        else:
277
            # to generate objects when there are no static variables to generate 'initialize'
278
            for stmt in global_stmts:
1✔
279
                self.visit(stmt)
1✔
280

281
        return self.build_data(module)
1✔
282

283
    def visit_ClassDef(self, node: ast.ClassDef) -> GeneratorData:
1✔
284
        if node.name in self.symbols:
1✔
285
            class_symbol = self.symbols[node.name]
1✔
286
            if isinstance(class_symbol, UserClass):
1✔
287
                self.current_class = class_symbol
1✔
288

289
            if self._is_generating_initialize:
1✔
290
                address = self.generator.bytecode_size
1✔
291
                self.generator.convert_new_empty_array(len(class_symbol.class_variables), class_symbol)
1✔
292
                self.generator.convert_store_variable(node.name, address)
1✔
293
            else:
294
                init_method = class_symbol.constructor_method()
1✔
295
                if isinstance(init_method, Method) and init_method.start_address is None:
1✔
296
                    self.generator.generate_implicit_init_user_class(init_method)
1✔
297

298
        for stmt in node.body:
1✔
299
            self.visit(stmt)
1✔
300

301
        self.current_class = None
1✔
302
        return self.build_data(node)
1✔
303

304
    def visit_FunctionDef(self, function: ast.FunctionDef) -> GeneratorData:
1✔
305
        """
306
        Visitor of the function definition node
307

308
        Generates the Neo VM code for the function
309

310
        :param function: the python ast function definition node
311
        """
312
        method = self._symbols[function.name]
1✔
313

314
        if isinstance(method, Property):
1✔
315
            method = method.getter
1✔
316

317
        if isinstance(method, Method):
1✔
318
            self.current_method = method
1✔
319
            if isinstance(self.current_class, ClassType):
1✔
320
                function_name = self.current_class.identifier + constants.ATTRIBUTE_NAME_SEPARATOR + function.name
1✔
321
            else:
322
                function_name = function.name
1✔
323

324
            self._log_info(f"Compiling '{function_name}' function")
1✔
325

326
            if method.is_public or method.is_called:
1✔
327
                if not isinstance(self.current_class, ClassType) or not self.current_class.is_interface:
1✔
328
                    self.generator.convert_begin_method(method)
1✔
329

330
                    for stmt in function.body:
1✔
331
                        self.visit_to_map(stmt)
1✔
332

333
                    self.generator.convert_end_method(function.name)
1✔
334

335
            self.current_method = None
1✔
336

337
        return self.build_data(function, symbol=method, symbol_id=function.name)
1✔
338

339
    def visit_Return(self, ret: ast.Return) -> GeneratorData:
1✔
340
        """
341
        Visitor of a function return node
342

343
        :param ret: the python ast return node
344
        """
345
        if self.generator.stack_size > 0:
1✔
346
            self.generator.clear_stack(True)
1✔
347

348
        if self.current_method.return_type is not Type.none:
1✔
349
            result = self.visit_to_generate(ret.value)
1✔
350
            if result.type is Type.none and not self.generator.is_none_inserted():
1✔
351
                self.generator.convert_literal(None)
1✔
352
        elif ret.value is not None:
1✔
353
            self.visit_to_generate(ret.value)
1✔
354
            if self.generator.stack_size > 0:
1✔
355
                self.generator.remove_stack_top_item()
1✔
356

357
        self.generator.insert_return()
1✔
358

359
        return self.build_data(ret)
1✔
360

361
    def store_variable(self, *var_ids: VariableGenerationData, value: ast.AST):
1✔
362
        # if the value is None, it is a variable declaration
363
        if value is not None:
1✔
364
            if len(var_ids) == 1:
1✔
365
                # it's a simple assignment
366
                var_id, index, address = var_ids[0]
1✔
367
                if index is None:
1✔
368
                    # if index is None, then it is a variable assignment
369
                    result_data = self.visit_to_generate(value)
1✔
370

371
                    if result_data.type is Type.none and not self.generator.is_none_inserted():
1✔
372
                        self.generator.convert_literal(None)
1✔
373
                    self.generator.convert_store_variable(var_id, address, self.current_class if self.current_method is None else None)
1✔
374
                else:
375
                    # if not, it is an array assignment
376
                    self.generator.convert_load_symbol(var_id)
1✔
377
                    self.visit_to_generate(index)
1✔
378

379
                    aux_index = VMCodeMapping.instance().bytecode_size
1✔
380
                    value_data = self.visit_to_generate(value)
1✔
381
                    value_address = value_data.index if value_data.index is not None else aux_index
1✔
382

383
                    self.generator.convert_set_item(value_address)
1✔
384

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

408
    def visit_AnnAssign(self, ann_assign: ast.AnnAssign) -> GeneratorData:
1✔
409
        """
410
        Visitor of an annotated assignment node
411

412
        :param ann_assign: the python ast variable assignment node
413
        """
414
        var_value_address = self.generator.bytecode_size
1✔
415
        var_data = self.visit(ann_assign.target)
1✔
416
        var_id = var_data.symbol_id
1✔
417
        # filter to find the imported variables
418
        if (var_id not in self.generator.symbol_table
1✔
419
                and hasattr(ann_assign, 'origin')
420
                and isinstance(ann_assign.origin, ast.AST)):
421
            var_id = self._get_unique_name(var_id, ann_assign.origin)
×
422
        self.store_variable(VariableGenerationData(var_id, None, var_value_address), value=ann_assign.value)
1✔
423
        return self.build_data(ann_assign)
1✔
424

425
    def visit_Assign(self, assign: ast.Assign) -> GeneratorData:
1✔
426
        """
427
        Visitor of an assignment node
428

429
        :param assign: the python ast variable assignment node
430
        """
431
        vars_ids: List[VariableGenerationData] = []
1✔
432
        for target in assign.targets:
1✔
433
            var_value_address = self.generator.bytecode_size
1✔
434
            target_data: GeneratorData = self.visit(target)
1✔
435

436
            var_id = target_data.symbol_id
1✔
437
            var_index = target_data.index
1✔
438

439
            # filter to find the imported variables
440
            if (var_id not in self.generator.symbol_table
1✔
441
                    and hasattr(assign, 'origin')
442
                    and isinstance(assign.origin, ast.AST)):
443
                var_id = self._get_unique_name(var_id, assign.origin)
×
444

445
            vars_ids.append(VariableGenerationData(var_id, var_index, var_value_address))
1✔
446

447
        self.store_variable(*vars_ids, value=assign.value)
1✔
448
        return self.build_data(assign)
1✔
449

450
    def visit_AugAssign(self, aug_assign: ast.AugAssign) -> GeneratorData:
1✔
451
        """
452
        Visitor of an augmented assignment node
453

454
        :param aug_assign: the python ast augmented assignment node
455
        """
456
        start_address = self.generator.bytecode_size
1✔
457
        var_data = self.visit(aug_assign.target)
1✔
458
        var_id = var_data.symbol_id
1✔
459
        # filter to find the imported variables
460
        if (var_id not in self.generator.symbol_table
1✔
461
                and hasattr(aug_assign, 'origin')
462
                and isinstance(aug_assign.origin, ast.AST)):
463
            var_id = self._get_unique_name(var_id, aug_assign.origin)
×
464

465
        if isinstance(var_data.type, UserClass):
1✔
466
            self.generator.duplicate_stack_top_item()
1✔
467
        elif hasattr(var_data.origin_object_type, 'identifier') and var_data.already_generated:
1✔
468
            VMCodeMapping.instance().remove_opcodes(start_address)
×
469
            self.generator.convert_load_symbol(var_data.origin_object_type.identifier)
×
470

471
        self.generator.convert_load_symbol(var_id, class_type=var_data.origin_object_type)
1✔
472
        value_address = self.generator.bytecode_size
1✔
473
        self.visit_to_generate(aug_assign.value)
1✔
474
        self.generator.convert_operation(aug_assign.op)
1✔
475
        self.generator.convert_store_variable(var_id, value_address, user_class=var_data.origin_object_type)
1✔
476
        return self.build_data(aug_assign)
1✔
477

478
    def visit_Subscript(self, subscript: ast.Subscript) -> GeneratorData:
1✔
479
        """
480
        Visitor of a subscript node
481

482
        :param subscript: the python ast subscript node
483
        """
484
        if isinstance(subscript.slice, ast.Slice):
1✔
485
            return self.visit_Subscript_Slice(subscript)
1✔
486

487
        return self.visit_Subscript_Index(subscript)
1✔
488

489
    def visit_Subscript_Index(self, subscript: ast.Subscript) -> GeneratorData:
1✔
490
        """
491
        Visitor of a subscript node with index
492

493
        :param subscript: the python ast subscript node
494
        """
495
        index = None
1✔
496
        symbol_id = None
1✔
497
        if isinstance(subscript.ctx, ast.Load):
1✔
498
            # get item
499
            value_data = self.visit_to_generate(subscript.value)
1✔
500
            slice = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
1✔
501
            self.visit_to_generate(slice)
1✔
502

503
            index_is_constant_number = isinstance(slice, ast.Num) and isinstance(slice.n, int)
1✔
504
            self.generator.convert_get_item(index_is_positive=(index_is_constant_number and slice.n >= 0),
1✔
505
                                            test_is_negative_index=not (index_is_constant_number and slice.n < 0))
506

507
            value_type = value_data.type
1✔
508
        else:
509
            # set item
510
            var_data = self.visit(subscript.value)
1✔
511

512
            index = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
1✔
513
            symbol_id = var_data.symbol_id
1✔
514
            value_type = var_data.type
1✔
515

516
        result_type = value_type.item_type if isinstance(value_type, SequenceType) else value_type
1✔
517
        return self.build_data(subscript, result_type=result_type,
1✔
518
                               symbol_id=symbol_id, index=index)
519

520
    def visit_Subscript_Slice(self, subscript: ast.Subscript) -> GeneratorData:
1✔
521
        """
522
        Visitor of a subscript node with slice
523

524
        :param subscript: the python ast subscript node
525
        """
526
        lower_omitted = subscript.slice.lower is None
1✔
527
        upper_omitted = subscript.slice.upper is None
1✔
528
        step_omitted = subscript.slice.step is None
1✔
529

530
        self.visit_to_generate(subscript.value)
1✔
531

532
        step_negative = True if not step_omitted and subscript.slice.step.n < 0 else False
1✔
533

534
        if step_negative:
1✔
535
            # reverse the ByteString or the list
536
            self.generator.convert_array_negative_stride()
1✔
537

538
        addresses = []
1✔
539

540
        for index_number, omitted in [(subscript.slice.lower, lower_omitted), (subscript.slice.upper, upper_omitted)]:
1✔
541
            if not omitted:
1✔
542
                addresses.append(VMCodeMapping.instance().bytecode_size)
1✔
543
                self.visit_to_generate(index_number)
1✔
544

545
                index_is_constant_number = isinstance(index_number, ast.Num) and isinstance(index_number.n, int)
1✔
546
                if index_is_constant_number and index_number.n < 0:
1✔
547
                    self.generator.fix_negative_index(test_is_negative=False)
1✔
548
                elif not index_is_constant_number:
1✔
549
                    self.generator.fix_negative_index()
1✔
550

551
                if step_negative:
1✔
552
                    self.generator.duplicate_stack_item(len(addresses) + 1)  # duplicates the subscript
1✔
553
                    self.generator.fix_index_negative_stride()
1✔
554

555
                self.generator.fix_index_out_of_range(has_another_index_in_stack=len(addresses) == 2)
1✔
556

557
        # if both are explicit
558
        if not lower_omitted and not upper_omitted:
1✔
559
            self.generator.convert_get_sub_sequence()
1✔
560

561
        # only one of them is omitted
562
        elif lower_omitted != upper_omitted:
1✔
563
            # start position is omitted
564
            if lower_omitted:
1✔
565
                self.generator.convert_get_sequence_beginning()
1✔
566
            # end position is omitted
567
            else:
568
                self.generator.convert_get_sequence_ending()
1✔
569
        else:
570
            self.generator.convert_copy()
1✔
571

572
        if not step_omitted:
1✔
573
            self.visit_to_generate(subscript.slice.step)
1✔
574
            self.generator.convert_get_stride()
1✔
575

576
        return self.build_data(subscript)
1✔
577

578
    def _convert_unary_operation(self, operand, op):
1✔
579
        self.visit_to_generate(operand)
1✔
580
        self.generator.convert_operation(op)
1✔
581

582
    def _convert_binary_operation(self, left, right, op):
1✔
583
        self.visit_to_generate(left)
1✔
584
        self.visit_to_generate(right)
1✔
585
        self.generator.convert_operation(op)
1✔
586

587
    def visit_BinOp(self, bin_op: ast.BinOp) -> GeneratorData:
1✔
588
        """
589
        Visitor of a binary operation node
590

591
        :param bin_op: the python ast binary operation node
592
        """
593
        if isinstance(bin_op.op, BinaryOperation):
1✔
594
            self._convert_binary_operation(bin_op.left, bin_op.right, bin_op.op)
1✔
595

596
        return self.build_data(bin_op)
1✔
597

598
    def visit_UnaryOp(self, un_op: ast.UnaryOp) -> GeneratorData:
1✔
599
        """
600
        Visitor of a binary operation node
601

602
        :param un_op: the python ast binary operation node
603
        """
604
        if isinstance(un_op.op, UnaryOperation):
1✔
605
            self._convert_unary_operation(un_op.operand, un_op.op)
1✔
606

607
        return self.build_data(un_op)
1✔
608

609
    def visit_Compare(self, compare: ast.Compare) -> GeneratorData:
1✔
610
        """
611
        Visitor of a compare operation node
612

613
        :param compare: the python ast compare operation node
614
        """
615
        operation_symbol: IOperation = BinaryOp.And
1✔
616
        converted: bool = False
1✔
617
        left = compare.left
1✔
618
        for index, op in enumerate(compare.ops):
1✔
619
            right = compare.comparators[index]
1✔
620
            if isinstance(op, IOperation):
1✔
621
                if isinstance(op, BinaryOperation):
1✔
622
                    self._convert_binary_operation(left, right, op)
1✔
623
                else:
624
                    operand = left
1✔
625
                    if isinstance(operand, ast.NameConstant) and operand.value is None:
1✔
626
                        operand = right
×
627
                    self._convert_unary_operation(operand, op)
1✔
628
                # if it's more than two comparators, must include AND between the operations
629
                if not converted:
1✔
630
                    converted = True
1✔
631
                    operation_symbol = op
1✔
632
                else:
633
                    operation_symbol = BinaryOp.And
1✔
634
                    self.generator.convert_operation(BinaryOp.And)
1✔
635
            left = right
1✔
636

637
        return self.build_data(compare, symbol=operation_symbol, result_type=operation_symbol.result)
1✔
638

639
    def visit_BoolOp(self, bool_op: ast.BoolOp) -> GeneratorData:
1✔
640
        """
641
        Visitor of a compare operation node
642

643
        :param bool_op: the python ast boolean operation node
644
        """
645
        if isinstance(bool_op.op, BinaryOperation):
1✔
646
            left = bool_op.values[0]
1✔
647
            self.visit_to_generate(left)
1✔
648
            for index, right in enumerate(bool_op.values[1:]):
1✔
649
                self.visit_to_generate(right)
1✔
650
                self.generator.convert_operation(bool_op.op)
1✔
651

652
        return self.build_data(bool_op)
1✔
653

654
    def visit_While(self, while_node: ast.While) -> GeneratorData:
1✔
655
        """
656
        Visitor of a while statement node
657

658
        :param while_node: the python ast while statement node
659
        """
660
        start_addr: int = self.generator.convert_begin_while()
1✔
661
        for stmt in while_node.body:
1✔
662
            self.visit_to_map(stmt, generate=True)
1✔
663

664
        test_address: int = VMCodeMapping.instance().bytecode_size
1✔
665
        test_data = self.visit_to_map(while_node.test, generate=True)
1✔
666
        self.generator.convert_end_while(start_addr, test_address)
1✔
667

668
        else_begin_address: int = self.generator.last_code_start_address
1✔
669
        for stmt in while_node.orelse:
1✔
670
            self.visit_to_map(stmt, generate=True)
1✔
671

672
        self.generator.convert_end_loop_else(start_addr, else_begin_address, len(while_node.orelse) > 0)
1✔
673
        return self.build_data(while_node, index=start_addr)
1✔
674

675
    def visit_For(self, for_node: ast.For) -> GeneratorData:
1✔
676
        """
677
        Visitor of for statement node
678

679
        :param for_node: the python ast for node
680
        """
681
        self.visit_to_generate(for_node.iter)
1✔
682
        start_address = self.generator.convert_begin_for()
1✔
683

684
        if isinstance(for_node.target, tuple):
1✔
685
            for target in for_node.target:
×
686
                var_data = self.visit_to_map(target)
×
687
                self.generator.convert_store_variable(var_data.symbol_id)
×
688
        else:
689
            var_data = self.visit(for_node.target)
1✔
690
            self.generator.convert_store_variable(var_data.symbol_id)
1✔
691

692
        for stmt in for_node.body:
1✔
693
            self.visit_to_map(stmt, generate=True)
1✔
694

695
        # TODO: remove when optimizing for generation
696
        if self.current_method is not None:
1✔
697
            self.current_method.remove_instruction(for_node.lineno, for_node.col_offset)
1✔
698

699
        condition_address = self.generator.convert_end_for(start_address)
1✔
700
        self.include_instruction(for_node, condition_address)
1✔
701
        else_begin = self.generator.last_code_start_address
1✔
702

703
        for stmt in for_node.orelse:
1✔
704
            self.visit_to_map(stmt, generate=True)
1✔
705

706
        self.generator.convert_end_loop_else(start_address,
1✔
707
                                             else_begin,
708
                                             has_else=len(for_node.orelse) > 0,
709
                                             is_for=True)
710
        return self.build_data(for_node)
1✔
711

712
    def visit_If(self, if_node: ast.If) -> GeneratorData:
1✔
713
        """
714
        Visitor of if statement node
715

716
        :param if_node: the python ast if statement node
717
        """
718
        test = self.visit_to_map(if_node.test, generate=True)
1✔
719

720
        if not Type.bool.is_type_of(test.type) and test.type is not None:
1✔
721
            self.generator.convert_builtin_method_call(Builtin.Bool)
1✔
722

723
        start_addr: int = self.generator.convert_begin_if()
1✔
724
        for stmt in if_node.body:
1✔
725
            self.visit_to_map(stmt, generate=True)
1✔
726

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

729
        if len(if_node.orelse) > 0:
1✔
730
            start_addr = self.generator.convert_begin_else(start_addr, ends_with_if)
1✔
731
            for stmt in if_node.orelse:
1✔
732
                self.visit_to_map(stmt, generate=True)
1✔
733

734
        self.generator.convert_end_if(start_addr)
1✔
735
        return self.build_data(if_node)
1✔
736

737
    def visit_Expr(self, expr: ast.Expr, generate: bool = False) -> GeneratorData:
1✔
738
        """
739
        Visitor of an expression node
740

741
        :param expr: the python ast expression node
742
        :param generate: if it should convert the value
743
        """
744
        last_stack = self.generator.stack_size
1✔
745
        if generate:
1✔
746
            value = self.visit_to_generate(expr.value)
1✔
747
        else:
748
            value = self.visit(expr.value)
1✔
749

750
        new_stack = self.generator.stack_size
1✔
751
        for x in range(last_stack, new_stack):
1✔
752
            self.generator.remove_stack_top_item()
1✔
753

754
        return value
1✔
755

756
    def visit_IfExp(self, if_node: ast.IfExp) -> GeneratorData:
1✔
757
        """
758
        Visitor of if expression node
759

760
        :param if_node: the python ast if statement node
761
        """
762
        self.visit_to_map(if_node.test, generate=True)
1✔
763

764
        start_addr: int = self.generator.convert_begin_if()
1✔
765
        body_data = self.visit_to_map(if_node.body, generate=True)
1✔
766

767
        start_addr = self.generator.convert_begin_else(start_addr)
1✔
768
        else_data = self.visit_to_map(if_node.orelse, generate=True)
1✔
769

770
        self.generator.convert_end_if(start_addr)
1✔
771
        return self.build_data(if_node, result_type=Type.union.build([body_data.type, else_data.type]))
1✔
772

773
    def visit_Assert(self, assert_node: ast.Assert) -> GeneratorData:
1✔
774
        """
775
        Visitor of the assert node
776

777
        :param assert_node: the python ast assert node
778
        """
779
        self.visit_to_generate(assert_node.test)
1✔
780

781
        if assert_node.msg is not None:
1✔
782
            self.visit_to_generate(assert_node.msg)
1✔
783

784
        self.generator.convert_assert(has_message=assert_node.msg is not None)
1✔
785
        return self.build_data(assert_node)
1✔
786

787
    def visit_Call(self, call: ast.Call) -> GeneratorData:
1✔
788
        """
789
        Visitor of a function call node
790

791
        :param call: the python ast function call node
792
        :returns: The called function return type
793
        """
794
        # the parameters are included into the stack in the reversed order
795
        last_address = VMCodeMapping.instance().bytecode_size
1✔
796
        last_stack = self.generator.stack_size
1✔
797

798
        func_data = self.visit(call.func)
1✔
799
        function_id = func_data.symbol_id
1✔
800
        # if the symbol is not a method, check if it is a class method
801
        if (isinstance(func_data.type, ClassType) and func_data.symbol_id in func_data.type.symbols
1✔
802
                and isinstance(func_data.type.symbols[func_data.symbol_id], IExpression)):
803
            symbol = func_data.type.symbols[func_data.symbol_id]
1✔
804
        else:
805
            symbol = func_data.symbol
1✔
806

807
        if not isinstance(symbol, Method):
1✔
808
            is_internal = hasattr(call, 'is_internal_call') and call.is_internal_call
1✔
809
            _, symbol = self.generator.get_symbol(function_id, is_internal=is_internal)
1✔
810

811
        if self.is_implemented_class_type(symbol):
1✔
812
            self.generator.convert_init_user_class(symbol)
1✔
813
            symbol = symbol.constructor_method()
1✔
814
        args_addresses: List[int] = []
1✔
815

816
        has_cls_or_self_argument = isinstance(symbol, Method) and symbol.has_cls_or_self
1✔
817
        if not has_cls_or_self_argument:
1✔
818
            self._remove_inserted_opcodes_since(last_address, last_stack)
1✔
819

820
        if isinstance(symbol, Method):
1✔
821
            # self or cls is already generated
822
            call_args = (call.args[1:]
1✔
823
                         if has_cls_or_self_argument and len(call.args) == len(symbol.args)
824
                         else call.args)
825
            args_to_generate = [arg for index, arg in enumerate(call_args) if index in symbol.args_to_be_generated()]
1✔
826
            keywords_dict = {keyword.arg: keyword.value for keyword in call.keywords}
1✔
827
            keywords_with_index = {index: keywords_dict[arg_name]
1✔
828
                                   for index, arg_name in enumerate(symbol.args)
829
                                   if arg_name in keywords_dict}
830

831
            for index in keywords_with_index:
1✔
832
                if index < len(args_to_generate):
1✔
833
                    # override default values
834
                    args_to_generate[index] = keywords_with_index[index]
1✔
835
                else:
836
                    # put keywords
837
                    args_to_generate.append(keywords_with_index[index])
1✔
838

839
        else:
840
            args_to_generate = call.args
1✔
841

842
        if isinstance(symbol, IBuiltinMethod):
1✔
843
            reordered_args = []
1✔
844
            for index in symbol.generation_order:
1✔
845
                if 0 <= index < len(args_to_generate):
1✔
846
                    reordered_args.append(args_to_generate[index])
1✔
847

848
            args = reordered_args
1✔
849
        else:
850
            args = reversed(args_to_generate)
1✔
851

852
        args_begin_address = self.generator.last_code_start_address
1✔
853
        for arg in args:
1✔
854
            args_addresses.append(
1✔
855
                VMCodeMapping.instance().bytecode_size
856
            )
857
            self.visit_to_generate(arg)
1✔
858

859
        class_type = None
1✔
860
        if has_cls_or_self_argument:
1✔
861
            num_args = len(args_addresses)
1✔
862
            if self.generator.stack_size > num_args:
1✔
863
                value = self.generator._stack_pop(-num_args - 1)
1✔
864
                self.generator._stack_append(value)
1✔
865
                class_type = value if isinstance(value, UserClass) else None
1✔
866
            end_address = VMCodeMapping.instance().move_to_end(last_address, args_begin_address)
1✔
867
            if not symbol.is_init:
1✔
868
                args_addresses.append(end_address)
1✔
869

870
        if self.is_exception_name(function_id):
1✔
871
            self.generator.convert_new_exception(len(call.args))
1✔
872
        elif isinstance(symbol, type(Builtin.Super)) and len(args_to_generate) == 0:
1✔
873
            self_or_cls_id = list(self.current_method.args)[0]
1✔
874
            self.generator.convert_load_symbol(self_or_cls_id)
1✔
875
        elif isinstance(symbol, IBuiltinMethod):
1✔
876
            self.generator.convert_builtin_method_call(symbol, args_addresses)
1✔
877
        else:
878
            self.generator.convert_load_symbol(function_id, args_addresses,
1✔
879
                                               class_type=class_type)
880

881
        return self.build_data(call, symbol=symbol, symbol_id=function_id,
1✔
882
                               result_type=symbol.type if isinstance(symbol, IExpression) else symbol,
883
                               already_generated=True)
884

885
    def visit_Raise(self, raise_node: ast.Raise) -> GeneratorData:
1✔
886
        """
887
        Visitor of the raise node
888

889
        :param raise_node: the python ast raise node
890
        """
891
        self.visit_to_map(raise_node.exc, generate=True)
1✔
892
        self.generator.convert_raise_exception()
1✔
893
        return self.build_data(raise_node)
1✔
894

895
    def visit_Try(self, try_node: ast.Try) -> GeneratorData:
1✔
896
        """
897
        Visitor of the try node
898

899
        :param try_node: the python ast try node
900
        """
901
        try_address: int = self.generator.convert_begin_try()
1✔
902
        try_end: Optional[int] = None
1✔
903
        for stmt in try_node.body:
1✔
904
            self.visit_to_map(stmt, generate=True)
1✔
905

906
        if len(try_node.handlers) == 1:
1✔
907
            handler = try_node.handlers[0]
1✔
908
            try_end = self.generator.convert_try_except(handler.name)
1✔
909
            for stmt in handler.body:
1✔
910
                self.visit_to_map(stmt, generate=True)
1✔
911

912
        else_address = None
1✔
913
        if len(try_node.orelse) > 0:
1✔
914
            else_start_address = self.generator.convert_begin_else(try_end)
1✔
915
            else_address = self.generator.bytecode_size
1✔
916
            for stmt in try_node.orelse:
1✔
917
                self.visit_to_map(stmt, generate=True)
1✔
918
            self.generator.convert_end_if(else_start_address)
1✔
919

920
        except_end = self.generator.convert_end_try(try_address, try_end, else_address)
1✔
921
        for stmt in try_node.finalbody:
1✔
922
            self.visit_to_map(stmt, generate=True)
1✔
923
        self.generator.convert_end_try_finally(except_end, try_address, len(try_node.finalbody) > 0)
1✔
924

925
        return self.build_data(try_node)
1✔
926

927
    def visit_Name(self, name_node: ast.Name) -> GeneratorData:
1✔
928
        """
929
        Visitor of a name node
930

931
        :param name_node: the python ast name identifier node
932
        :return: the identifier of the name
933
        """
934
        name = name_node.id
1✔
935
        if name not in self._symbols:
1✔
936
            hashed_name = self._get_unique_name(name, self._tree)
1✔
937
            if hashed_name not in self._symbols and hasattr(name_node, 'origin'):
1✔
938
                hashed_name = self._get_unique_name(name, name_node.origin)
1✔
939

940
            if hashed_name in self._symbols:
1✔
941
                name = hashed_name
1✔
942

943
        else:
944
            if name not in self.generator.symbol_table:
1✔
945
                symbol = self._symbols[name]
1✔
946
                for symbol_id, internal_symbol in self.generator.symbol_table.items():
1✔
947
                    if internal_symbol == symbol:
1✔
948
                        name = symbol_id
×
949
                        break
×
950

951
        return self.build_data(name_node, name)
1✔
952

953
    def visit_Starred(self, starred: ast.Starred) -> GeneratorData:
1✔
954
        value_data = self.visit_to_generate(starred.value)
1✔
955
        self.generator.convert_starred_variable()
1✔
956

957
        starred_data = value_data.copy(starred)
1✔
958
        starred_data.already_generated = True
1✔
959
        return starred_data
1✔
960

961
    def visit_Attribute(self, attribute: ast.Attribute) -> GeneratorData:
1✔
962
        """
963
        Visitor of a attribute node
964

965
        :param attribute: the python ast attribute node
966
        :return: the identifier of the attribute
967
        """
968
        last_address = VMCodeMapping.instance().bytecode_size
1✔
969
        last_stack = self.generator.stack_size
1✔
970

971
        _attr, attr = self.generator.get_symbol(attribute.attr)
1✔
972
        value = attribute.value
1✔
973
        value_symbol = None
1✔
974
        value_type = None
1✔
975
        value_data = self.visit(value)
1✔
976
        need_to_visit_again = True
1✔
977

978
        if value_data.symbol_id is not None and not value_data.already_generated:
1✔
979
            value_id = value_data.symbol_id
1✔
980
            if value_data.symbol is not None:
1✔
981
                value_symbol = value_data.symbol
1✔
982
            else:
983
                _, value_symbol = self.generator.get_symbol(value_id)
1✔
984
            value_type = value_symbol.type if hasattr(value_symbol, 'type') else value_symbol
1✔
985

986
            if hasattr(value_type, 'symbols') and attribute.attr in value_type.symbols:
1✔
987
                attr = value_type.symbols[attribute.attr]
1✔
988
            elif isinstance(value_type, Package) and attribute.attr in value_type.inner_packages:
1✔
989
                attr = value_type.inner_packages[attribute.attr]
1✔
990

991
            if isinstance(value_symbol, UserClass):
1✔
992
                if isinstance(attr, Method) and attr.has_cls_or_self:
1✔
993
                    self.generator.convert_load_symbol(value_id)
1✔
994
                    need_to_visit_again = False
1✔
995

996
                if isinstance(attr, Variable):
1✔
997
                    cur_bytesize = self.generator.bytecode_size
1✔
998
                    self.visit_to_generate(attribute.value)
1✔
999
                    self.generator.convert_load_symbol(attribute.attr, class_type=value_symbol)
1✔
1000

1001
                    symbol_id = _attr if isinstance(_attr, str) else None
1✔
1002
                    return self.build_data(attribute,
1✔
1003
                                           already_generated=self.generator.bytecode_size > cur_bytesize,
1004
                                           symbol=attr, symbol_id=symbol_id,
1005
                                           origin_object_type=value_symbol)
1006
        else:
1007
            if isinstance(value, ast.Attribute) and value_data.already_generated:
1✔
1008
                need_to_visit_again = False
1✔
1009
            else:
1010
                need_to_visit_again = value_data.already_generated
1✔
1011
                self._remove_inserted_opcodes_since(last_address, last_stack)
1✔
1012

1013
        # the verification above only verify variables, this one will should work with literals and constants
1014
        if isinstance(value, ast.Constant) and len(attr.args) > 0 and isinstance(attr, IBuiltinMethod) and attr.has_self_argument:
1✔
1015
            attr = attr.build(value_data.type)
×
1016

1017
        if attr is not Type.none and not hasattr(attribute, 'generate_value'):
1✔
1018
            value_symbol_id = (value_symbol.identifier
1✔
1019
                               if self.is_implemented_class_type(value_symbol)
1020
                               else value_data.symbol_id)
1021
            attribute_id = f'{value_symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
1✔
1022
            index = value_type if isinstance(value_type, Package) else None
1✔
1023
            return self.build_data(attribute, symbol_id=attribute_id, symbol=attr, index=index)
1✔
1024

1025
        if isinstance(value, ast.Attribute) and need_to_visit_again:
1✔
1026
            value_data = self.visit(value)
1✔
1027
        elif hasattr(attribute, 'generate_value') and attribute.generate_value:
1✔
1028
            current_bytecode_size = self.generator.bytecode_size
1✔
1029
            if need_to_visit_again:
1✔
1030
                value_data = self.visit_to_generate(attribute.value)
1✔
1031

1032
            result = value_data.type
1✔
1033
            generation_result = value_data.symbol
1✔
1034
            if result is None and value_data.symbol_id is not None:
1✔
1035
                _, result = self.generator.get_symbol(value_data.symbol_id)
1✔
1036
                if isinstance(result, IExpression):
1✔
1037
                    generation_result = result
×
1038
                    result = result.type
×
1039
            elif isinstance(attribute.value, ast.Attribute) and isinstance(value_data.index, int):
1✔
1040
                result = self.get_type(generation_result)
1✔
1041

1042
            if self.is_implemented_class_type(result):
1✔
1043
                class_attr_id = f'{result.identifier}.{attribute.attr}'
1✔
1044
                symbol_id = class_attr_id
1✔
1045
                symbol = None
1✔
1046
                result_type = None
1✔
1047
                symbol_index = None
1✔
1048
                is_load_context_variable_from_class = (isinstance(attribute.ctx, ast.Load) and
1✔
1049
                                                       isinstance(attr, Variable) and
1050
                                                       isinstance(result, UserClass))
1051

1052
                if self.generator.bytecode_size > current_bytecode_size and isinstance(result, UserClass) and not is_load_context_variable_from_class:
1✔
1053
                    # it was generated already, don't convert again
1054
                    generated = False
1✔
1055
                    symbol_id = attribute.attr if isinstance(generation_result, Variable) else class_attr_id
1✔
1056
                    result_type = result
1✔
1057
                else:
1058
                    current_bytecode_size = self.generator.bytecode_size
1✔
1059
                    index = self.generator.convert_class_symbol(result,
1✔
1060
                                                                attribute.attr,
1061
                                                                isinstance(attribute.ctx, ast.Load))
1062
                    generated = self.generator.bytecode_size > current_bytecode_size
1✔
1063
                    symbol = result
1✔
1064
                    if not isinstance(result, UserClass):
1✔
1065
                        if isinstance(index, int):
1✔
1066
                            symbol_index = index
1✔
1067
                        else:
1068
                            symbol_id = index
1✔
1069

1070
                return self.build_data(attribute,
1✔
1071
                                       symbol_id=symbol_id, symbol=symbol,
1072
                                       result_type=result_type, index=symbol_index,
1073
                                       origin_object_type=value_type,
1074
                                       already_generated=generated)
1075

1076
        if value_data is not None and value_symbol is None:
1✔
1077
            value_symbol = value_data.symbol_id
×
1078

1079
        if value_data is not None and value_data.symbol_id is not None:
1✔
1080
            value_id = f'{value_data.symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
1✔
1081
        else:
1082
            value_id = attribute.attr
×
1083

1084
        return self.build_data(attribute, symbol_id=value_id, symbol=value_symbol)
1✔
1085

1086
    def visit_Continue(self, continue_node: ast.Continue) -> GeneratorData:
1✔
1087
        """
1088
        :param continue_node: the python ast continue statement node
1089
        """
1090
        self.generator.convert_loop_continue()
1✔
1091
        return self.build_data(continue_node)
1✔
1092

1093
    def visit_Break(self, break_node: ast.Break) -> GeneratorData:
1✔
1094
        """
1095
        :param break_node: the python ast break statement node
1096
        """
1097
        self.generator.convert_loop_break()
1✔
1098
        return self.build_data(break_node)
1✔
1099

1100
    def visit_Constant(self, constant: ast.Constant) -> GeneratorData:
1✔
1101
        """
1102
        Visitor of constant values node
1103

1104
        :param constant: the python ast constant value node
1105
        """
1106
        index = self.generator.convert_literal(constant.value)
1✔
1107
        result_type = self.get_type(constant.value)
1✔
1108
        return self.build_data(constant, result_type=result_type, index=index, already_generated=True)
1✔
1109

1110
    def visit_NameConstant(self, constant: ast.NameConstant) -> GeneratorData:
1✔
1111
        """
1112
        Visitor of constant names node
1113

1114
        :param constant: the python ast name constant node
1115
        """
1116
        index = self.generator.convert_literal(constant.value)
×
1117
        result_type = self.get_type(constant.value)
×
1118
        return self.build_data(constant, result_type=result_type, index=index, already_generated=True)
×
1119

1120
    def visit_Num(self, num: ast.Num) -> GeneratorData:
1✔
1121
        """
1122
        Visitor of literal number node
1123

1124
        :param num: the python ast number node
1125
        """
1126
        index = self.generator.convert_literal(num.n)
×
1127
        result_type = self.get_type(num.n)
×
1128
        return self.build_data(num, result_type=result_type, index=index, already_generated=True)
×
1129

1130
    def visit_Str(self, string: ast.Str) -> GeneratorData:
1✔
1131
        """
1132
        Visitor of literal string node
1133

1134
        :param string: the python ast string node
1135
        """
1136
        index = self.generator.convert_literal(string.s)
×
1137
        result_type = self.get_type(string.s)
×
1138
        return self.build_data(string, result_type=result_type, index=index, already_generated=True)
×
1139

1140
    def visit_Bytes(self, bts: ast.Bytes) -> GeneratorData:
1✔
1141
        """
1142
        Visitor of literal bytes node
1143

1144
        :param bts: the python ast bytes node
1145
        """
1146
        index = self.generator.convert_literal(bts.s)
×
1147
        result_type = self.get_type(bts.s)
×
1148
        return self.build_data(bts, result_type=result_type, index=index, already_generated=True)
×
1149

1150
    def visit_Tuple(self, tup_node: ast.Tuple) -> GeneratorData:
1✔
1151
        """
1152
        Visitor of literal tuple node
1153

1154
        :param tup_node: the python ast tuple node
1155
        """
1156
        result_type = Type.tuple
1✔
1157
        self._create_array(tup_node.elts, result_type)
1✔
1158
        return self.build_data(tup_node, result_type=result_type, already_generated=True)
1✔
1159

1160
    def visit_List(self, list_node: ast.List) -> GeneratorData:
1✔
1161
        """
1162
        Visitor of literal list node
1163

1164
        :param list_node: the python ast list node
1165
        """
1166
        result_type = Type.list
1✔
1167
        self._create_array(list_node.elts, result_type)
1✔
1168
        return self.build_data(list_node, result_type=result_type, already_generated=True)
1✔
1169

1170
    def visit_Dict(self, dict_node: ast.Dict) -> GeneratorData:
1✔
1171
        """
1172
        Visitor of literal dict node
1173

1174
        :param dict_node: the python ast dict node
1175
        """
1176
        result_type = Type.dict
1✔
1177
        length = min(len(dict_node.keys), len(dict_node.values))
1✔
1178
        self.generator.convert_new_map(result_type)
1✔
1179
        for key_value in range(length):
1✔
1180
            self.generator.duplicate_stack_top_item()
1✔
1181
            self.visit_to_generate(dict_node.keys[key_value])
1✔
1182
            value_data = self.visit_to_generate(dict_node.values[key_value])
1✔
1183
            self.generator.convert_set_item(value_data.index)
1✔
1184

1185
        return self.build_data(dict_node, result_type=result_type, already_generated=True)
1✔
1186

1187
    def visit_Pass(self, pass_node: ast.Pass) -> GeneratorData:
1✔
1188
        """
1189
        Visitor of pass node
1190

1191
        :param pass_node: the python ast dict node
1192
        """
1193
        # only generates if the scope is a function
1194
        result_type = None
1✔
1195
        generated = False
1✔
1196

1197
        if isinstance(self.current_method, Method):
1✔
1198
            self.generator.insert_nop()
1✔
1199
            generated = True
1✔
1200

1201
        return self.build_data(pass_node, result_type=result_type, already_generated=generated)
1✔
1202

1203
    def _create_array(self, values: List[ast.AST], array_type: IType):
1✔
1204
        """
1205
        Creates a new array from a literal sequence
1206

1207
        :param values: list of values of the new array items
1208
        """
1209
        length = len(values)
1✔
1210
        if length > 0:
1✔
1211
            for value in reversed(values):
1✔
1212
                self.visit_to_generate(value)
1✔
1213
        self.generator.convert_new_array(length, array_type)
1✔
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