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

CityOfZion / neo3-boa / ebd2ce56-e86e-475b-9d6f-8380fd4e71d9

pending completion
ebd2ce56-e86e-475b-9d6f-8380fd4e71d9

Pull #1062

circleci

luc10921
CU-864eek0cd - Default the execution path to the execution directory
Pull Request #1062: Default the execution path to the execution directory

18980 of 20825 relevant lines covered (91.14%)

0.91 hits per line

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

96.02
/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.constants import SYS_VERSION_INFO
1✔
13
from boa3.internal.model.builtin.builtin import Builtin
1✔
14
from boa3.internal.model.builtin.interop.interop import Interop
1✔
15
from boa3.internal.model.builtin.method.builtinmethod import IBuiltinMethod
1✔
16
from boa3.internal.model.expression import IExpression
1✔
17
from boa3.internal.model.imports.package import Package
1✔
18
from boa3.internal.model.method import Method
1✔
19
from boa3.internal.model.operation.binary.binaryoperation import BinaryOperation
1✔
20
from boa3.internal.model.operation.binaryop import BinaryOp
1✔
21
from boa3.internal.model.operation.operation import IOperation
1✔
22
from boa3.internal.model.operation.unary.unaryoperation import UnaryOperation
1✔
23
from boa3.internal.model.property import Property
1✔
24
from boa3.internal.model.symbol import ISymbol
1✔
25
from boa3.internal.model.type.classes.classtype import ClassType
1✔
26
from boa3.internal.model.type.classes.userclass import UserClass
1✔
27
from boa3.internal.model.type.collection.sequence.sequencetype import SequenceType
1✔
28
from boa3.internal.model.type.type import IType, Type
1✔
29
from boa3.internal.model.variable import Variable
1✔
30

31

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

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

39
    :ivar generator:
40
    """
41

42
    def __init__(self, generator: CodeGenerator, filename: str = None):
1✔
43
        super().__init__(ast.parse(""), filename=filename, log=True)
1✔
44

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

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

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

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

61
        return symbol_table
1✔
62

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

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

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

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

91
            if found_symbol is not None:
1✔
92
                symbol = found_symbol
1✔
93

94
        return GeneratorData(origin_node, symbol_id, symbol, result_type, index, origin_object_type, already_generated)
1✔
95

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

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

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

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

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

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

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

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

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

149
                    self.generator.convert_load_symbol(result.symbol_id, is_internal=is_internal, class_type=class_type if self.current_method is None else None)
1✔
150

151
                result.already_generated = True
1✔
152

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

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

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

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

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

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

185
        Fills module symbol table
186

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

200
        for stmt in function_stmts:
1✔
201
            self.visit(stmt)
1✔
202

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

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

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

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

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

238
                        class_non_static_stmts.append(cls_fun)
1✔
239

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

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

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

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

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

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

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

282
        return self.build_data(module)
1✔
283

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

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

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

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

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

309
        Generates the Neo VM code for the function
310

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

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

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

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

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

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

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

336
            self.current_method = None
1✔
337

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

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

344
        :param ret: the python ast return node
345
        """
346
        if self.generator.stack_size > 0:
1✔
347
            self.generator.clear_stack(True)
1✔
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
        self.generator.insert_return()
1✔
353

354
        return self.build_data(ret)
1✔
355

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

366
                    if result_data.type is Type.none and not self.generator.is_none_inserted():
1✔
367
                        self.generator.convert_literal(None)
1✔
368
                    self.generator.convert_store_variable(var_id, address, self.current_class if self.current_method is None else None)
1✔
369
                else:
370
                    # if not, it is an array assignment
371
                    self.generator.convert_load_symbol(var_id)
1✔
372
                    self.visit_to_generate(index)
1✔
373

374
                    aux_index = VMCodeMapping.instance().bytecode_size
1✔
375
                    value_data = self.visit_to_generate(value)
1✔
376
                    value_address = value_data.index if value_data.index is not None else aux_index
1✔
377

378
                    self.generator.convert_set_item(value_address)
1✔
379

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

403
    def visit_AnnAssign(self, ann_assign: ast.AnnAssign) -> GeneratorData:
1✔
404
        """
405
        Visitor of an annotated assignment node
406

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

420
    def visit_Assign(self, assign: ast.Assign) -> GeneratorData:
1✔
421
        """
422
        Visitor of an assignment node
423

424
        :param assign: the python ast variable assignment node
425
        """
426
        vars_ids: List[VariableGenerationData] = []
1✔
427
        for target in assign.targets:
1✔
428
            var_value_address = self.generator.bytecode_size
1✔
429
            target_data: GeneratorData = self.visit(target)
1✔
430

431
            var_id = target_data.symbol_id
1✔
432
            var_index = target_data.index
1✔
433

434
            # filter to find the imported variables
435
            if (var_id not in self.generator.symbol_table
1✔
436
                    and hasattr(assign, 'origin')
437
                    and isinstance(assign.origin, ast.AST)):
438
                var_id = self._get_unique_name(var_id, assign.origin)
×
439

440
            vars_ids.append(VariableGenerationData(var_id, var_index, var_value_address))
1✔
441

442
        self.store_variable(*vars_ids, value=assign.value)
1✔
443
        return self.build_data(assign)
1✔
444

445
    def visit_AugAssign(self, aug_assign: ast.AugAssign) -> GeneratorData:
1✔
446
        """
447
        Visitor of an augmented assignment node
448

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

460
        if isinstance(var_data.type, UserClass):
1✔
461
            self.generator.duplicate_stack_top_item()
1✔
462
        elif hasattr(var_data.origin_object_type, 'identifier') and var_data.already_generated:
1✔
463
            VMCodeMapping.instance().remove_opcodes(start_address)
×
464
            self.generator.convert_load_symbol(var_data.origin_object_type.identifier)
×
465

466
        self.generator.convert_load_symbol(var_id, class_type=var_data.origin_object_type)
1✔
467
        value_address = self.generator.bytecode_size
1✔
468
        self.visit_to_generate(aug_assign.value)
1✔
469
        self.generator.convert_operation(aug_assign.op)
1✔
470
        self.generator.convert_store_variable(var_id, value_address, user_class=var_data.origin_object_type)
1✔
471
        return self.build_data(aug_assign)
1✔
472

473
    def visit_Subscript(self, subscript: ast.Subscript) -> GeneratorData:
1✔
474
        """
475
        Visitor of a subscript node
476

477
        :param subscript: the python ast subscript node
478
        """
479
        if isinstance(subscript.slice, ast.Slice):
1✔
480
            return self.visit_Subscript_Slice(subscript)
1✔
481

482
        return self.visit_Subscript_Index(subscript)
1✔
483

484
    def visit_Subscript_Index(self, subscript: ast.Subscript) -> GeneratorData:
1✔
485
        """
486
        Visitor of a subscript node with index
487

488
        :param subscript: the python ast subscript node
489
        """
490
        index = None
1✔
491
        symbol_id = None
1✔
492
        if isinstance(subscript.ctx, ast.Load):
1✔
493
            # get item
494
            value_data = self.visit_to_generate(subscript.value)
1✔
495
            slice = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
1✔
496
            self.visit_to_generate(slice)
1✔
497

498
            index_is_constant_number = isinstance(slice, ast.Num) and isinstance(slice.n, int)
1✔
499
            self.generator.convert_get_item(index_is_positive=(index_is_constant_number and slice.n >= 0),
1✔
500
                                            test_is_negative_index=not (index_is_constant_number and slice.n < 0))
501

502
            value_type = value_data.type
1✔
503
        else:
504
            # set item
505
            var_data = self.visit(subscript.value)
1✔
506

507
            index = subscript.slice.value if isinstance(subscript.slice, ast.Index) else subscript.slice
1✔
508
            symbol_id = var_data.symbol_id
1✔
509
            value_type = var_data.type
1✔
510

511
        result_type = value_type.item_type if isinstance(value_type, SequenceType) else value_type
1✔
512
        return self.build_data(subscript, result_type=result_type,
1✔
513
                               symbol_id=symbol_id, index=index)
514

515
    def visit_Subscript_Slice(self, subscript: ast.Subscript) -> GeneratorData:
1✔
516
        """
517
        Visitor of a subscript node with slice
518

519
        :param subscript: the python ast subscript node
520
        """
521
        lower_omitted = subscript.slice.lower is None
1✔
522
        upper_omitted = subscript.slice.upper is None
1✔
523
        step_omitted = subscript.slice.step is None
1✔
524

525
        self.visit_to_generate(subscript.value)
1✔
526

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

529
        if step_negative:
1✔
530
            # reverse the ByteString or the list
531
            self.generator.convert_array_negative_stride()
1✔
532

533
        addresses = []
1✔
534

535
        for index_number, omitted in [(subscript.slice.lower, lower_omitted), (subscript.slice.upper, upper_omitted)]:
1✔
536
            if not omitted:
1✔
537
                addresses.append(VMCodeMapping.instance().bytecode_size)
1✔
538
                self.visit_to_generate(index_number)
1✔
539

540
                index_is_constant_number = isinstance(index_number, ast.Num) and isinstance(index_number.n, int)
1✔
541
                if index_is_constant_number and index_number.n < 0:
1✔
542
                    self.generator.fix_negative_index(test_is_negative=False)
1✔
543
                elif not index_is_constant_number:
1✔
544
                    self.generator.fix_negative_index()
1✔
545

546
                if step_negative:
1✔
547
                    self.generator.duplicate_stack_item(len(addresses) + 1)  # duplicates the subscript
1✔
548
                    self.generator.fix_index_negative_stride()
1✔
549

550
                self.generator.fix_index_out_of_range(has_another_index_in_stack=len(addresses) == 2)
1✔
551

552
        # if both are explicit
553
        if not lower_omitted and not upper_omitted:
1✔
554
            self.generator.convert_get_sub_sequence()
1✔
555

556
        # only one of them is omitted
557
        elif lower_omitted != upper_omitted:
1✔
558
            # start position is omitted
559
            if lower_omitted:
1✔
560
                self.generator.convert_get_sequence_beginning()
1✔
561
            # end position is omitted
562
            else:
563
                self.generator.convert_get_sequence_ending()
1✔
564
        else:
565
            self.generator.convert_copy()
1✔
566

567
        if not step_omitted:
1✔
568
            self.visit_to_generate(subscript.slice.step)
1✔
569
            self.generator.convert_get_stride()
1✔
570

571
        return self.build_data(subscript)
1✔
572

573
    def _convert_unary_operation(self, operand, op):
1✔
574
        self.visit_to_generate(operand)
1✔
575
        self.generator.convert_operation(op)
1✔
576

577
    def _convert_binary_operation(self, left, right, op):
1✔
578
        self.visit_to_generate(left)
1✔
579
        self.visit_to_generate(right)
1✔
580
        self.generator.convert_operation(op)
1✔
581

582
    def visit_BinOp(self, bin_op: ast.BinOp) -> GeneratorData:
1✔
583
        """
584
        Visitor of a binary operation node
585

586
        :param bin_op: the python ast binary operation node
587
        """
588
        if isinstance(bin_op.op, BinaryOperation):
1✔
589
            self._convert_binary_operation(bin_op.left, bin_op.right, bin_op.op)
1✔
590

591
        return self.build_data(bin_op)
1✔
592

593
    def visit_UnaryOp(self, un_op: ast.UnaryOp) -> GeneratorData:
1✔
594
        """
595
        Visitor of a binary operation node
596

597
        :param un_op: the python ast binary operation node
598
        """
599
        if isinstance(un_op.op, UnaryOperation):
1✔
600
            self._convert_unary_operation(un_op.operand, un_op.op)
1✔
601

602
        return self.build_data(un_op)
1✔
603

604
    def visit_Compare(self, compare: ast.Compare) -> GeneratorData:
1✔
605
        """
606
        Visitor of a compare operation node
607

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

632
        return self.build_data(compare, symbol=operation_symbol, result_type=operation_symbol.result)
1✔
633

634
    def visit_BoolOp(self, bool_op: ast.BoolOp) -> GeneratorData:
1✔
635
        """
636
        Visitor of a compare operation node
637

638
        :param bool_op: the python ast boolean operation node
639
        """
640
        if isinstance(bool_op.op, BinaryOperation):
1✔
641
            left = bool_op.values[0]
1✔
642
            self.visit_to_generate(left)
1✔
643
            for index, right in enumerate(bool_op.values[1:]):
1✔
644
                self.visit_to_generate(right)
1✔
645
                self.generator.convert_operation(bool_op.op)
1✔
646

647
        return self.build_data(bool_op)
1✔
648

649
    def visit_While(self, while_node: ast.While) -> GeneratorData:
1✔
650
        """
651
        Visitor of a while statement node
652

653
        :param while_node: the python ast while statement node
654
        """
655
        start_addr: int = self.generator.convert_begin_while()
1✔
656
        for stmt in while_node.body:
1✔
657
            self.visit_to_map(stmt, generate=True)
1✔
658

659
        test_address: int = VMCodeMapping.instance().bytecode_size
1✔
660
        test_data = self.visit_to_map(while_node.test, generate=True)
1✔
661
        self.generator.convert_end_while(start_addr, test_address)
1✔
662

663
        else_begin_address: int = self.generator.last_code_start_address
1✔
664
        for stmt in while_node.orelse:
1✔
665
            self.visit_to_map(stmt, generate=True)
1✔
666

667
        self.generator.convert_end_loop_else(start_addr, else_begin_address, len(while_node.orelse) > 0)
1✔
668
        return self.build_data(while_node, index=start_addr)
1✔
669

670
    def visit_For(self, for_node: ast.For) -> GeneratorData:
1✔
671
        """
672
        Visitor of for statement node
673

674
        :param for_node: the python ast for node
675
        """
676
        self.visit_to_generate(for_node.iter)
1✔
677
        start_address = self.generator.convert_begin_for()
1✔
678

679
        if isinstance(for_node.target, tuple):
1✔
680
            for target in for_node.target:
×
681
                var_data = self.visit_to_map(target)
×
682
                self.generator.convert_store_variable(var_data.symbol_id)
×
683
        else:
684
            var_data = self.visit(for_node.target)
1✔
685
            self.generator.convert_store_variable(var_data.symbol_id)
1✔
686

687
        for stmt in for_node.body:
1✔
688
            self.visit_to_map(stmt, generate=True)
1✔
689

690
        # TODO: remove when optimizing for generation
691
        if self.current_method is not None:
1✔
692
            self.current_method.remove_instruction(for_node.lineno, for_node.col_offset)
1✔
693

694
        condition_address = self.generator.convert_end_for(start_address)
1✔
695
        self.include_instruction(for_node, condition_address)
1✔
696
        else_begin = self.generator.last_code_start_address
1✔
697

698
        for stmt in for_node.orelse:
1✔
699
            self.visit_to_map(stmt, generate=True)
1✔
700

701
        self.generator.convert_end_loop_else(start_address,
1✔
702
                                             else_begin,
703
                                             has_else=len(for_node.orelse) > 0,
704
                                             is_for=True)
705
        return self.build_data(for_node)
1✔
706

707
    def visit_If(self, if_node: ast.If) -> GeneratorData:
1✔
708
        """
709
        Visitor of if statement node
710

711
        :param if_node: the python ast if statement node
712
        """
713
        test = self.visit_to_map(if_node.test, generate=True)
1✔
714

715
        if not Type.bool.is_type_of(test.type) and test.type is not None:
1✔
716
            self.generator.convert_builtin_method_call(Builtin.Bool)
1✔
717

718
        start_addr: int = self.generator.convert_begin_if()
1✔
719
        for stmt in if_node.body:
1✔
720
            self.visit_to_map(stmt, generate=True)
1✔
721

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

724
        if len(if_node.orelse) > 0:
1✔
725
            start_addr = self.generator.convert_begin_else(start_addr, ends_with_if)
1✔
726
            for stmt in if_node.orelse:
1✔
727
                self.visit_to_map(stmt, generate=True)
1✔
728

729
        self.generator.convert_end_if(start_addr)
1✔
730
        return self.build_data(if_node)
1✔
731

732
    def visit_Expr(self, expr: ast.Expr, generate: bool = False) -> GeneratorData:
1✔
733
        """
734
        Visitor of an expression node
735

736
        :param expr: the python ast expression node
737
        :param generate: if it should convert the value
738
        """
739
        last_stack = self.generator.stack_size
1✔
740
        if generate:
1✔
741
            value = self.visit_to_generate(expr.value)
1✔
742
        else:
743
            value = self.visit(expr.value)
1✔
744

745
        new_stack = self.generator.stack_size
1✔
746
        for x in range(last_stack, new_stack):
1✔
747
            self.generator.remove_stack_top_item()
1✔
748

749
        return value
1✔
750

751
    def visit_IfExp(self, if_node: ast.IfExp) -> GeneratorData:
1✔
752
        """
753
        Visitor of if expression node
754

755
        :param if_node: the python ast if statement node
756
        """
757
        self.visit_to_map(if_node.test, generate=True)
1✔
758

759
        start_addr: int = self.generator.convert_begin_if()
1✔
760
        body_data = self.visit_to_map(if_node.body, generate=True)
1✔
761

762
        start_addr = self.generator.convert_begin_else(start_addr)
1✔
763
        else_data = self.visit_to_map(if_node.orelse, generate=True)
1✔
764

765
        self.generator.convert_end_if(start_addr)
1✔
766
        return self.build_data(if_node, result_type=Type.union.build([body_data.type, else_data.type]))
1✔
767

768
    def visit_Assert(self, assert_node: ast.Assert) -> GeneratorData:
1✔
769
        """
770
        Visitor of the assert node
771

772
        :param assert_node: the python ast assert node
773
        """
774
        self.visit_to_generate(assert_node.test)
1✔
775

776
        if assert_node.msg is not None:
1✔
777
            self.generator.duplicate_stack_top_item()
1✔
778
            self.generator.insert_not()
1✔
779

780
            # if assert is false, log the message
781
            start_addr: int = self.generator.convert_begin_if()
1✔
782

783
            self.visit_to_generate(assert_node.msg)
1✔
784
            self.generator.convert_builtin_method_call(Interop.Log)
1✔
785

786
            self.generator.convert_end_if(start_addr)
1✔
787

788
        self.generator.convert_assert()
1✔
789
        return self.build_data(assert_node)
1✔
790

791
    def visit_Call(self, call: ast.Call) -> GeneratorData:
1✔
792
        """
793
        Visitor of a function call node
794

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

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

811
        if not isinstance(symbol, Method):
1✔
812
            is_internal = hasattr(call, 'is_internal_call') and call.is_internal_call
1✔
813
            _, symbol = self.generator.get_symbol(function_id, is_internal=is_internal)
1✔
814

815
        if self.is_implemented_class_type(symbol):
1✔
816
            self.generator.convert_init_user_class(symbol)
1✔
817
            symbol = symbol.constructor_method()
1✔
818
        args_addresses: List[int] = []
1✔
819

820
        has_cls_or_self_argument = isinstance(symbol, Method) and symbol.has_cls_or_self
1✔
821
        if not has_cls_or_self_argument:
1✔
822
            self._remove_inserted_opcodes_since(last_address, last_stack)
1✔
823

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

835
            for index in keywords_with_index:
1✔
836
                if index < len(args_to_generate):
1✔
837
                    # override default values
838
                    args_to_generate[index] = keywords_with_index[index]
1✔
839
                else:
840
                    # put keywords
841
                    args_to_generate.append(keywords_with_index[index])
1✔
842

843
        else:
844
            args_to_generate = call.args
1✔
845

846
        if isinstance(symbol, IBuiltinMethod):
1✔
847
            reordered_args = []
1✔
848
            for index in symbol.generation_order:
1✔
849
                if 0 <= index < len(args_to_generate):
1✔
850
                    reordered_args.append(args_to_generate[index])
1✔
851

852
            args = reordered_args
1✔
853
        else:
854
            args = reversed(args_to_generate)
1✔
855

856
        args_begin_address = self.generator.last_code_start_address
1✔
857
        for arg in args:
1✔
858
            args_addresses.append(
1✔
859
                VMCodeMapping.instance().bytecode_size
860
            )
861
            self.visit_to_generate(arg)
1✔
862
        if has_cls_or_self_argument:
1✔
863
            num_args = len(args_addresses)
1✔
864
            if self.generator.stack_size > num_args:
1✔
865
                value = self.generator._stack_pop(-num_args - 1)
1✔
866
                self.generator._stack_append(value)
1✔
867
            end_address = VMCodeMapping.instance().move_to_end(last_address, args_begin_address)
1✔
868
            if not symbol.is_init:
1✔
869
                args_addresses.append(end_address)
1✔
870

871
        if self.is_exception_name(function_id):
1✔
872
            self.generator.convert_new_exception(len(call.args))
1✔
873
        elif isinstance(symbol, type(Builtin.Super)) and len(args_to_generate) == 0:
1✔
874
            self_or_cls_id = list(self.current_method.args)[0]
1✔
875
            self.generator.convert_load_symbol(self_or_cls_id)
1✔
876
        elif isinstance(symbol, IBuiltinMethod):
1✔
877
            self.generator.convert_builtin_method_call(symbol, args_addresses)
1✔
878
        else:
879
            self.generator.convert_load_symbol(function_id, args_addresses)
1✔
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
        return self.build_data(name_node, name)
1✔
943

944
    def visit_Starred(self, starred: ast.Starred) -> GeneratorData:
1✔
945
        value_data = self.visit_to_generate(starred.value)
1✔
946
        self.generator.convert_starred_variable()
1✔
947

948
        starred_data = value_data.copy(starred)
1✔
949
        starred_data.already_generated = True
1✔
950
        return starred_data
1✔
951

952
    def visit_Attribute(self, attribute: ast.Attribute) -> GeneratorData:
1✔
953
        """
954
        Visitor of a attribute node
955

956
        :param attribute: the python ast attribute node
957
        :return: the identifier of the attribute
958
        """
959
        last_address = VMCodeMapping.instance().bytecode_size
1✔
960
        last_stack = self.generator.stack_size
1✔
961

962
        _attr, attr = self.generator.get_symbol(attribute.attr)
1✔
963
        value = attribute.value
1✔
964
        value_symbol = None
1✔
965
        value_type = None
1✔
966
        value_data = self.visit(value)
1✔
967
        need_to_visit_again = True
1✔
968

969
        if value_data.symbol_id is not None and not value_data.already_generated:
1✔
970
            value_id = value_data.symbol_id
1✔
971
            if value_data.symbol is not None:
1✔
972
                value_symbol = value_data.symbol
1✔
973
            else:
974
                _, value_symbol = self.generator.get_symbol(value_id)
1✔
975
            value_type = value_symbol.type if hasattr(value_symbol, 'type') else value_symbol
1✔
976

977
            if hasattr(value_type, 'symbols') and attribute.attr in value_type.symbols:
1✔
978
                attr = value_type.symbols[attribute.attr]
1✔
979
            elif isinstance(value_type, Package) and attribute.attr in value_type.inner_packages:
1✔
980
                attr = value_type.inner_packages[attribute.attr]
1✔
981

982
            if isinstance(value_symbol, UserClass):
1✔
983
                if isinstance(attr, Method) and attr.has_cls_or_self:
1✔
984
                    self.generator.convert_load_symbol(value_id)
1✔
985
                    need_to_visit_again = False
1✔
986

987
                if isinstance(attr, Variable):
1✔
988
                    cur_bytesize = self.generator.bytecode_size
1✔
989
                    self.visit_to_generate(attribute.value)
1✔
990
                    self.generator.convert_load_symbol(attribute.attr, class_type=value_symbol)
1✔
991

992
                    symbol_id = _attr if isinstance(_attr, str) else None
1✔
993
                    return self.build_data(attribute,
1✔
994
                                           already_generated=self.generator.bytecode_size > cur_bytesize,
995
                                           symbol=attr, symbol_id=symbol_id,
996
                                           origin_object_type=value_symbol)
997
        else:
998
            if isinstance(value, ast.Attribute) and value_data.already_generated:
1✔
999
                need_to_visit_again = False
1✔
1000
            else:
1001
                need_to_visit_again = value_data.already_generated
1✔
1002
                self._remove_inserted_opcodes_since(last_address, last_stack)
1✔
1003

1004
        # the verification above only verify variables, this one will should work with literals and constants
1005
        if isinstance(value, (ast.Constant if SYS_VERSION_INFO >= (3, 8) else (ast.Num, ast.Str, ast.Bytes))) \
1✔
1006
                and len(attr.args) > 0 and isinstance(attr, IBuiltinMethod) and attr.has_self_argument:
1007
            attr = attr.build(value_data.type)
1✔
1008

1009
        if attr is not Type.none and not hasattr(attribute, 'generate_value'):
1✔
1010
            value_symbol_id = (value_symbol.identifier
1✔
1011
                               if self.is_implemented_class_type(value_symbol)
1012
                               else value_data.symbol_id)
1013
            attribute_id = f'{value_symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
1✔
1014
            index = value_type if isinstance(value_type, Package) else None
1✔
1015
            return self.build_data(attribute, symbol_id=attribute_id, symbol=attr, index=index)
1✔
1016

1017
        if isinstance(value, ast.Attribute) and need_to_visit_again:
1✔
1018
            value_data = self.visit(value)
1✔
1019
        elif hasattr(attribute, 'generate_value') and attribute.generate_value:
1✔
1020
            current_bytecode_size = self.generator.bytecode_size
1✔
1021
            if need_to_visit_again:
1✔
1022
                value_data = self.visit_to_generate(attribute.value)
1✔
1023

1024
            result = value_data.type
1✔
1025
            generation_result = value_data.symbol
1✔
1026
            if result is None and value_data.symbol_id is not None:
1✔
1027
                _, result = self.generator.get_symbol(value_data.symbol_id)
1✔
1028
                if isinstance(result, IExpression):
1✔
1029
                    generation_result = result
×
1030
                    result = result.type
×
1031
            elif isinstance(attribute.value, ast.Attribute) and isinstance(value_data.index, int):
1✔
1032
                result = self.get_type(generation_result)
1✔
1033

1034
            if self.is_implemented_class_type(result):
1✔
1035
                class_attr_id = f'{result.identifier}.{attribute.attr}'
1✔
1036
                symbol_id = class_attr_id
1✔
1037
                symbol = None
1✔
1038
                result_type = None
1✔
1039
                symbol_index = None
1✔
1040
                is_load_context_variable_from_class = (isinstance(attribute.ctx, ast.Load) and
1✔
1041
                                                       isinstance(attr, Variable) and
1042
                                                       isinstance(result, UserClass))
1043

1044
                if self.generator.bytecode_size > current_bytecode_size and isinstance(result, UserClass) and not is_load_context_variable_from_class:
1✔
1045
                    # it was generated already, don't convert again
1046
                    generated = False
1✔
1047
                    symbol_id = attribute.attr if isinstance(generation_result, Variable) else class_attr_id
1✔
1048
                    result_type = result
1✔
1049
                else:
1050
                    current_bytecode_size = self.generator.bytecode_size
1✔
1051
                    index = self.generator.convert_class_symbol(result,
1✔
1052
                                                                attribute.attr,
1053
                                                                isinstance(attribute.ctx, ast.Load))
1054
                    generated = self.generator.bytecode_size > current_bytecode_size
1✔
1055
                    symbol = result
1✔
1056
                    if not isinstance(result, UserClass):
1✔
1057
                        if isinstance(index, int):
1✔
1058
                            symbol_index = index
1✔
1059
                        else:
1060
                            symbol_id = index
1✔
1061

1062
                return self.build_data(attribute,
1✔
1063
                                       symbol_id=symbol_id, symbol=symbol,
1064
                                       result_type=result_type, index=symbol_index,
1065
                                       already_generated=generated)
1066

1067
        if value_data is not None and value_symbol is None:
1✔
1068
            value_symbol = value_data.symbol_id
×
1069

1070
        if value_data is not None and value_data.symbol_id is not None:
1✔
1071
            value_id = f'{value_data.symbol_id}{constants.ATTRIBUTE_NAME_SEPARATOR}{attribute.attr}'
1✔
1072
        else:
1073
            value_id = attribute.attr
×
1074

1075
        return self.build_data(attribute, symbol_id=value_id, symbol=value_symbol)
1✔
1076

1077
    def visit_Continue(self, continue_node: ast.Continue) -> GeneratorData:
1✔
1078
        """
1079
        :param continue_node: the python ast continue statement node
1080
        """
1081
        self.generator.convert_loop_continue()
1✔
1082
        return self.build_data(continue_node)
1✔
1083

1084
    def visit_Break(self, break_node: ast.Break) -> GeneratorData:
1✔
1085
        """
1086
        :param break_node: the python ast break statement node
1087
        """
1088
        self.generator.convert_loop_break()
1✔
1089
        return self.build_data(break_node)
1✔
1090

1091
    def visit_Constant(self, constant: ast.Constant) -> GeneratorData:
1✔
1092
        """
1093
        Visitor of constant values node
1094

1095
        :param constant: the python ast constant value node
1096
        """
1097
        index = self.generator.convert_literal(constant.value)
1✔
1098
        result_type = self.get_type(constant.value)
1✔
1099
        return self.build_data(constant, result_type=result_type, index=index, already_generated=True)
1✔
1100

1101
    def visit_NameConstant(self, constant: ast.NameConstant) -> GeneratorData:
1✔
1102
        """
1103
        Visitor of constant names node
1104

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

1111
    def visit_Num(self, num: ast.Num) -> GeneratorData:
1✔
1112
        """
1113
        Visitor of literal number node
1114

1115
        :param num: the python ast number node
1116
        """
1117
        index = self.generator.convert_literal(num.n)
×
1118
        result_type = self.get_type(num.n)
×
1119
        return self.build_data(num, result_type=result_type, index=index, already_generated=True)
×
1120

1121
    def visit_Str(self, string: ast.Str) -> GeneratorData:
1✔
1122
        """
1123
        Visitor of literal string node
1124

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

1131
    def visit_Bytes(self, bts: ast.Bytes) -> GeneratorData:
1✔
1132
        """
1133
        Visitor of literal bytes node
1134

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

1141
    def visit_Tuple(self, tup_node: ast.Tuple) -> GeneratorData:
1✔
1142
        """
1143
        Visitor of literal tuple node
1144

1145
        :param tup_node: the python ast tuple node
1146
        """
1147
        result_type = Type.tuple
1✔
1148
        self._create_array(tup_node.elts, result_type)
1✔
1149
        return self.build_data(tup_node, result_type=result_type, already_generated=True)
1✔
1150

1151
    def visit_List(self, list_node: ast.List) -> GeneratorData:
1✔
1152
        """
1153
        Visitor of literal list node
1154

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

1161
    def visit_Dict(self, dict_node: ast.Dict) -> GeneratorData:
1✔
1162
        """
1163
        Visitor of literal dict node
1164

1165
        :param dict_node: the python ast dict node
1166
        """
1167
        result_type = Type.dict
1✔
1168
        length = min(len(dict_node.keys), len(dict_node.values))
1✔
1169
        self.generator.convert_new_map(result_type)
1✔
1170
        for key_value in range(length):
1✔
1171
            self.generator.duplicate_stack_top_item()
1✔
1172
            self.visit_to_generate(dict_node.keys[key_value])
1✔
1173
            value_data = self.visit_to_generate(dict_node.values[key_value])
1✔
1174
            self.generator.convert_set_item(value_data.index)
1✔
1175

1176
        return self.build_data(dict_node, result_type=result_type, already_generated=True)
1✔
1177

1178
    def visit_Pass(self, pass_node: ast.Pass) -> GeneratorData:
1✔
1179
        """
1180
        Visitor of pass node
1181

1182
        :param pass_node: the python ast dict node
1183
        """
1184
        # only generates if the scope is a function
1185
        result_type = None
1✔
1186
        generated = False
1✔
1187

1188
        if isinstance(self.current_method, Method):
1✔
1189
            self.generator.insert_nop()
1✔
1190
            generated = True
1✔
1191

1192
        return self.build_data(pass_node, result_type=result_type, already_generated=generated)
1✔
1193

1194
    def _create_array(self, values: List[ast.AST], array_type: IType):
1✔
1195
        """
1196
        Creates a new array from a literal sequence
1197

1198
        :param values: list of values of the new array items
1199
        """
1200
        length = len(values)
1✔
1201
        if length > 0:
1✔
1202
            for value in reversed(values):
1✔
1203
                self.visit_to_generate(value)
1✔
1204
        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

© 2025 Coveralls, Inc