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

CityOfZion / neo3-boa / 849f9350-0a78-48f9-8c96-4fb6490304cc

04 Oct 2023 11:48AM UTC coverage: 91.907% (-0.1%) from 92.049%
849f9350-0a78-48f9-8c96-4fb6490304cc

Pull #1137

circleci

luc10921
CU-86a0aw4fc - Remove python 3.7, 3.8 & 3.9 from circleCI
Pull Request #1137: Remove python 3.7, 3.8 & 3.9 from circleCI

20010 of 21772 relevant lines covered (91.91%)

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

30

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

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

38
    :ivar generator:
39
    """
40

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

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

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

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

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

60
        return symbol_table
1✔
61

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

150
                result.already_generated = True
1✔
151

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

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

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

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

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

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

184
        Fills module symbol table
185

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

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

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

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

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

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

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

237
                        class_non_static_stmts.append(cls_fun)
1✔
238
                    self.symbols = last_symbols  # don't use inner scopes to evaluate the other globals
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

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

358
        self.generator.insert_return()
1✔
359

360
        return self.build_data(ret)
1✔
361

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

488
        return self.visit_Subscript_Index(subscript)
1✔
489

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

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

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

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

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

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

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

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

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

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

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

539
        addresses = []
1✔
540

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

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

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

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

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

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

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

577
        return self.build_data(subscript)
1✔
578

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

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

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

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

597
        return self.build_data(bin_op)
1✔
598

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

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

608
        return self.build_data(un_op)
1✔
609

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

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

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

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

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

653
        return self.build_data(bool_op)
1✔
654

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

755
        return value
1✔
756

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

860
        class_type = None
1✔
861
        if has_cls_or_self_argument:
1✔
862
            num_args = len(args_addresses)
1✔
863
            if self.generator.stack_size > num_args:
1✔
864
                value = self.generator._stack_pop(-num_args - 1)
1✔
865
                self.generator._stack_append(value)
1✔
866
                class_type = value if isinstance(value, UserClass) else None
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
                                               class_type=class_type)
881

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

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

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

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

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

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

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

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

926
        return self.build_data(try_node)
1✔
927

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1078
        if value_data is not None and value_symbol is None:
1✔
1079
            value_symbol = value_data.symbol_id
×
1080

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

1086
        return self.build_data(attribute, symbol_id=value_id, symbol=value_symbol)
1✔
1087

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

1187
        return self.build_data(dict_node, result_type=result_type, already_generated=True)
1✔
1188

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

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

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

1203
        return self.build_data(pass_node, result_type=result_type, already_generated=generated)
1✔
1204

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

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