Skip to content

variables

Classes:

VariableVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: InlineVariableDeclaration) -> None
Source code in packages/irx/src/irx/builder/lowering/variables.py
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
@VisitorCore.visit.dispatch
def visit(self, node: astx.InlineVariableDeclaration) -> None:
    """
    title: Visit InlineVariableDeclaration nodes.
    parameters:
      node:
        type: astx.InlineVariableDeclaration
    """
    symbol_key = semantic_symbol_key(node, node.name)
    existing_storage = self.named_values.get(symbol_key)
    if existing_storage and self._current_generator_frame_ptr is None:
        raise Exception(f"Identifier already declared: {node.name}")

    type_str = node.type_.__class__.__name__.lower()
    llvm_type = self._llvm_type_for_ast_type(node.type_)
    if llvm_type is None:
        raise Exception(
            "codegen: Unknown LLVM type for inline variable "
            f"'{node.name}'."
        )
    if node.value is not None:
        self.visit_child(node.value)
        init_val = safe_pop(self.result_stack)
        if init_val is None:
            raise Exception("Initializer code generation failed.")
        init_val = self._cast_ast_value(
            init_val,
            source_type=self._resolved_ast_type(node.value),
            target_type=node.type_,
        )
    elif isinstance(node.type_, astx.StructType):
        init_val = ir.Constant(llvm_type, None)
    elif isinstance(node.type_, astx.ListType):
        init_val = cast(
            ir.Constant,
            cast(Any, self)._empty_list_value_for_type(node.type_),
        )
    elif isinstance(node.type_, astx.ClassType):
        init_val = ir.Constant(llvm_type, None)
    elif isinstance(node.type_, astx.GeneratorType):
        init_val = ir.Constant(llvm_type, None)
    elif "float" in type_str:
        init_val = ir.Constant(self._llvm.get_data_type(type_str), 0.0)
    else:
        init_val = ir.Constant(self._llvm.get_data_type(type_str), 0)

    if type_str == "string":
        alloca = self.create_entry_block_alloca(node.name, "stringascii")
    elif existing_storage is not None:
        alloca = existing_storage
    else:
        alloca = self.create_entry_block_alloca(node.name, llvm_type)

    self._llvm.ir_builder.store(init_val, alloca)
    if node.mutability == astx.MutabilityKind.constant:
        self.const_vars.add(symbol_key)
    self.named_values[symbol_key] = alloca
    self.result_stack.append(init_val)