Skip to content

visitors

Modules:

Classes:

ArrowVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: ArrowInt32ArrayLength) -> None
Source code in src/irx/builders/llvmliteir/visitors/arrow.py
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
@VisitorCore.visit.dispatch  # type: ignore[attr-defined,untyped-decorator]
def visit(self, node: astx.ArrowInt32ArrayLength) -> None:
    """
    title: Visit ArrowInt32ArrayLength nodes.
    parameters:
      node:
        type: astx.ArrowInt32ArrayLength
    """
    builder_new = self.require_runtime_symbol(
        "arrow", "irx_arrow_array_builder_int32_new"
    )
    append_int32 = self.require_runtime_symbol(
        "arrow", "irx_arrow_array_builder_append_int32"
    )
    finish_builder = self.require_runtime_symbol(
        "arrow", "irx_arrow_array_builder_finish"
    )
    array_length = self.require_runtime_symbol(
        "arrow", "irx_arrow_array_length"
    )
    release_array = self.require_runtime_symbol(
        "arrow", "irx_arrow_array_release"
    )

    builder_slot = self._llvm.ir_builder.alloca(
        self._llvm.ARROW_ARRAY_BUILDER_HANDLE_TYPE,
        name="arrow_builder_slot",
    )
    self._llvm.ir_builder.call(builder_new, [builder_slot])
    builder_handle = self._llvm.ir_builder.load(
        builder_slot, "arrow_builder"
    )

    for item in node.values:
        self.visit_child(item)
        value = safe_pop(self.result_stack)
        if value is None:
            raise Exception("Arrow helper expected an integer value")
        if not is_int_type(value.type):
            raise Exception(
                "Arrow helper supports only integer expressions"
            )

        if value.type.width < self._llvm.INT32_TYPE.width:
            value = self._llvm.ir_builder.sext(
                value, self._llvm.INT32_TYPE, "arrow_i32_promote"
            )
        elif value.type.width > self._llvm.INT32_TYPE.width:
            value = self._llvm.ir_builder.trunc(
                value, self._llvm.INT32_TYPE, "arrow_i32_trunc"
            )

        self._llvm.ir_builder.call(append_int32, [builder_handle, value])

    array_slot = self._llvm.ir_builder.alloca(
        self._llvm.ARROW_ARRAY_HANDLE_TYPE,
        name="arrow_array_slot",
    )
    self._llvm.ir_builder.call(
        finish_builder, [builder_handle, array_slot]
    )
    array_handle = self._llvm.ir_builder.load(array_slot, "arrow_array")
    length_i64 = self._llvm.ir_builder.call(
        array_length, [array_handle], "arrow_length"
    )
    self._llvm.ir_builder.call(release_array, [array_handle])

    length_i32 = self._llvm.ir_builder.trunc(
        length_i64, self._llvm.INT32_TYPE, "arrow_length_i32"
    )
    self.result_stack.append(length_i32)

BinaryOpVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: BitXorBinOp) -> None
Source code in src/irx/builders/llvmliteir/visitors/binary_ops.py
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
@VisitorCore.visit.dispatch
def visit(self, node: BitXorBinOp) -> None:
    """
    title: Visit BitXorBinOp nodes.
    parameters:
      node:
        type: BitXorBinOp
    """
    llvm_lhs, llvm_rhs, _unsigned = self._load_binary_operands(
        node,
        unify_numeric=False,
    )
    if self._try_set_binary_op(llvm_lhs, llvm_rhs, node.op_code):
        return
    raise Exception(f"Binary op {node.op_code} not implemented yet.")

ControlFlowVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: ContinueStmt) -> None
Source code in src/irx/builders/llvmliteir/visitors/control_flow.py
382
383
384
385
386
387
388
389
390
391
392
393
@VisitorCore.visit.dispatch
def visit(self, node: astx.ContinueStmt) -> None:
    """
    title: Visit ContinueStmt nodes.
    parameters:
      node:
        type: astx.ContinueStmt
    """
    if not self.loop_stack:
        raise Exception("codegen: Continue statement outside loop.")
    continue_target = self.loop_stack[-1]["continue_target"]
    self._llvm.ir_builder.branch(continue_target)

FunctionVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: FunctionReturn) -> None
Source code in src/irx/builders/llvmliteir/visitors/functions.py
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
@VisitorCore.visit.dispatch
def visit(self, node: astx.FunctionReturn) -> None:
    """
    title: Visit FunctionReturn nodes.
    parameters:
      node:
        type: astx.FunctionReturn
    """
    if node.value is not None:
        self.visit_child(node.value)
        retval = safe_pop(self.result_stack)
    else:
        retval = None

    if retval is not None:
        fn_return_type = (
            self._llvm.ir_builder.function.function_type.return_type
        )
        if is_int_type(fn_return_type) and fn_return_type.width == 1:
            if is_int_type(retval.type) and retval.type.width != 1:
                retval = self._llvm.ir_builder.trunc(retval, ir.IntType(1))
        self._llvm.ir_builder.ret(retval)
        return

    self._llvm.ir_builder.ret_void()

LiteralVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: LiteralInt16) -> None
Source code in src/irx/builders/llvmliteir/visitors/literals.py
508
509
510
511
512
513
514
515
516
517
518
@VisitorCore.visit.dispatch
def visit(self, node: astx.LiteralInt16) -> None:
    """
    title: Visit LiteralInt16 nodes.
    parameters:
      node:
        type: astx.LiteralInt16
    """
    self.result_stack.append(
        ir.Constant(self._llvm.INT16_TYPE, node.value)
    )

ModuleVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: StructDefStmt) -> None
Source code in src/irx/builders/llvmliteir/visitors/modules.py
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
@VisitorCore.visit.dispatch
def visit(self, node: astx.StructDefStmt) -> None:
    """
    title: Visit StructDefStmt nodes.
    parameters:
      node:
        type: astx.StructDefStmt
    """
    struct_type = self._llvm.module.context.get_identified_type(node.name)
    if not struct_type.is_opaque:
        raise ValueError(f"Struct '{node.name}' already defined.")

    field_types: list[ir.Type] = []
    for attr in node.attributes:
        type_str = attr.type_.__class__.__name__.lower()
        field_types.append(self._llvm.get_data_type(type_str))

    struct_type.set_body(*field_types)
    self.struct_types[node.name] = struct_type

SystemVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: PrintExpr) -> None
Source code in src/irx/builders/llvmliteir/visitors/system.py
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
@VisitorCore.visit.dispatch
def visit(self, node: astx.PrintExpr) -> None:
    """
    title: Visit PrintExpr nodes.
    parameters:
      node:
        type: astx.PrintExpr
    """
    self.visit_child(node.message)
    message_value = safe_pop(self.result_stack)
    if message_value is None:
        raise Exception("Invalid message in PrintExpr")

    message_type = message_value.type
    ptr: ir.Value
    if (
        isinstance(message_type, ir.PointerType)
        and message_type.pointee == self._llvm.INT8_TYPE
    ):
        ptr = message_value
    elif is_int_type(message_type):
        int_arg, int_fmt = self._normalize_int_for_printf(message_value)
        int_fmt_gv = self._get_or_create_format_global(int_fmt)
        ptr = self._snprintf_heap(int_fmt_gv, [int_arg])
    elif isinstance(
        message_type, (ir.HalfType, ir.FloatType, ir.DoubleType)
    ):
        if isinstance(message_type, (ir.HalfType, ir.FloatType)):
            float_arg = self._llvm.ir_builder.fpext(
                message_value, self._llvm.DOUBLE_TYPE, "print_to_double"
            )
        else:
            float_arg = message_value
        float_fmt_gv = self._get_or_create_format_global("%.6f")
        ptr = self._snprintf_heap(float_fmt_gv, [float_arg])
    else:
        raise Exception(
            f"Unsupported message type in PrintExpr: {message_type}"
        )

    puts_fn = self.require_runtime_symbol("libc", "puts")
    self._llvm.ir_builder.call(puts_fn, [ptr])
    self.result_stack.append(ir.Constant(self._llvm.INT32_TYPE, 0))

TemporalVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: LiteralDateTime) -> None
Source code in src/irx/builders/llvmliteir/visitors/temporal.py
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
@VisitorCore.visit.dispatch
def visit(self, node: astx.LiteralDateTime) -> None:
    """
    title: Visit LiteralDateTime nodes.
    parameters:
      node:
        type: astx.LiteralDateTime
    """
    hour_minute_count = 2
    hour_minute_second_count = 3
    max_hour = 23
    max_minute_second = 59

    value = node.value.strip()
    if "T" in value:
        date_part, time_part = value.split("T", 1)
    elif " " in value:
        date_part, time_part = value.split(" ", 1)
    else:
        raise ValueError(
            f"LiteralDateTime: invalid format '{node.value}'. "
            "Expected 'YYYY-MM-DDTHH:MM[:SS]' (or space instead of 'T')."
        )

    if "." in time_part:
        raise ValueError(
            "LiteralDateTime: fractional seconds not supported in "
            f"'{node.value}'. Use LiteralTimestamp instead."
        )
    if time_part.endswith("Z") or "+" in time_part or "-" in time_part[2:]:
        raise ValueError(
            "LiteralDateTime: timezone offsets not supported in "
            f"'{node.value}'. Use LiteralTimestamp for timezones."
        )

    try:
        y_str, m_str, d_str = date_part.split("-")
        year = int(y_str)
        month = int(m_str)
        day = int(d_str)
    except Exception as exc:
        raise ValueError(
            f"LiteralDateTime: invalid date part in '{node.value}'. "
            "Expected 'YYYY-MM-DD'."
        ) from exc

    int32_min, int32_max = -(2**31), 2**31 - 1
    if not (int32_min <= year <= int32_max):
        raise ValueError(
            f"LiteralDateTime: year out of 32-bit range in '{node.value}'."
        )

    try:
        parts = time_part.split(":")
        if len(parts) not in (hour_minute_count, hour_minute_second_count):
            raise ValueError("time must be HH:MM or HH:MM:SS")
        hour = int(parts[0])
        minute = int(parts[1])
        second = (
            int(parts[2]) if len(parts) == hour_minute_second_count else 0
        )
    except Exception as exc:
        raise ValueError(
            f"LiteralDateTime: invalid time part in '{node.value}'. "
            "Expected 'HH:MM' or 'HH:MM:SS'."
        ) from exc

    if not (0 <= hour <= max_hour):
        raise ValueError(
            f"LiteralDateTime: hour out of range in '{node.value}'."
        )
    if not (0 <= minute <= max_minute_second):
        raise ValueError(
            f"LiteralDateTime: minute out of range in '{node.value}'."
        )
    if not (0 <= second <= max_minute_second):
        raise ValueError(
            f"LiteralDateTime: second out of range in '{node.value}'."
        )

    try:
        datetime(year, month, day)
        time_value(hour, minute, second)
    except ValueError as exc:
        raise ValueError(
            "LiteralDateTime: invalid calendar date/time in "
            f"'{node.value}'."
        ) from exc

    i32 = self._llvm.INT32_TYPE
    const_dt = ir.Constant(
        self._llvm.DATETIME_TYPE,
        [
            ir.Constant(i32, year),
            ir.Constant(i32, month),
            ir.Constant(i32, day),
            ir.Constant(i32, hour),
            ir.Constant(i32, minute),
            ir.Constant(i32, second),
        ],
    )
    self.result_stack.append(const_dt)

UnaryOpVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: UnaryOp) -> None
Source code in src/irx/builders/llvmliteir/visitors/unary_ops.py
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
@VisitorCore.visit.dispatch  # type: ignore[attr-defined,untyped-decorator]
def visit(self, node: astx.UnaryOp) -> None:
    """
    title: Visit UnaryOp nodes.
    parameters:
      node:
        type: astx.UnaryOp
    """
    if node.op_code == "++":
        self.visit_child(node.operand)
        operand_val = safe_pop(self.result_stack)
        if operand_val is None:
            raise Exception("codegen: Invalid unary operand.")
        operand_key = (
            semantic_symbol_key(node.operand, node.operand.name)
            if isinstance(node.operand, astx.Identifier)
            else ""
        )

        one = ir.Constant(operand_val.type, 1)
        if is_fp_type(operand_val.type):
            result = self._llvm.ir_builder.fadd(operand_val, one, "inctmp")
        else:
            result = self._llvm.ir_builder.add(operand_val, one, "inctmp")

        if isinstance(node.operand, astx.Identifier):
            if operand_key in self.const_vars:
                raise Exception(
                    f"Cannot mutate '{node.operand.name}':"
                    "declared as constant"
                )
            var_addr = self.named_values.get(operand_key)
            if var_addr:
                self._llvm.ir_builder.store(result, var_addr)

        self.result_stack.append(result)
        return

    if node.op_code == "--":
        self.visit_child(node.operand)
        operand_val = safe_pop(self.result_stack)
        if operand_val is None:
            raise Exception("codegen: Invalid unary operand.")
        operand_key = (
            semantic_symbol_key(node.operand, node.operand.name)
            if isinstance(node.operand, astx.Identifier)
            else ""
        )
        one = ir.Constant(operand_val.type, 1)
        if is_fp_type(operand_val.type):
            result = self._llvm.ir_builder.fsub(operand_val, one, "dectmp")
        else:
            result = self._llvm.ir_builder.sub(operand_val, one, "dectmp")

        if isinstance(node.operand, astx.Identifier):
            if operand_key in self.const_vars:
                raise Exception(
                    f"Cannot mutate '{node.operand.name}':"
                    "declared as constant"
                )
            var_addr = self.named_values.get(operand_key)
            if var_addr:
                self._llvm.ir_builder.store(result, var_addr)

        self.result_stack.append(result)
        return

    if node.op_code == "!":
        self.visit_child(node.operand)
        val = safe_pop(self.result_stack)
        if val is None:
            raise Exception("codegen: Invalid unary operand.")

        zero = ir.Constant(val.type, 0)
        is_zero = self._llvm.ir_builder.icmp_signed(
            "==", val, zero, "iszero"
        )

        if isinstance(val.type, ir.IntType) and val.type.width == 1:
            result = is_zero
        else:
            result = self._llvm.ir_builder.zext(
                is_zero, val.type, "nottmp"
            )

        if isinstance(node.operand, astx.Identifier):
            operand_key = semantic_symbol_key(
                node.operand, node.operand.name
            )
            if operand_key in self.const_vars:
                raise Exception(
                    f"Cannot mutate '{node.operand.name}':"
                    "declared as constant"
                )
            addr = self.named_values.get(operand_key)
            if addr:
                self._llvm.ir_builder.store(result, addr)

        self.result_stack.append(result)
        return

    raise Exception(f"Unary operator {node.op_code} not implemented yet.")

VariableVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: InlineVariableDeclaration) -> None
Source code in src/irx/builders/llvmliteir/visitors/variables.py
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
@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()
    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.")
    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, type_str)

    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)