Skip to content

variables

Classes:

VariableVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: InlineVariableDeclaration) -> None
Source code in src/irx/builder/lowering/variables.py
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
@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)
    if self.named_values.get(symbol_key):
        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.ClassType):
        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")
    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)