Skip to content

lowering

Modules:

Classes:

ArrayVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: ArrayInt32ArrayLength) -> None
Source code in packages/irx/src/irx/builder/lowering/array.py
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
@VisitorCore.visit.dispatch
def visit(self, node: astx.ArrayInt32ArrayLength) -> None:
    """
    title: Visit ArrayInt32ArrayLength nodes.
    parameters:
      node:
        type: astx.ArrayInt32ArrayLength
    """
    builder_new = self.require_runtime_symbol(
        "array", "irx_arrow_array_builder_int32_new"
    )
    append_int32 = self.require_runtime_symbol(
        "array", "irx_arrow_array_builder_append_int32"
    )
    finish_builder = self.require_runtime_symbol(
        "array", "irx_arrow_array_builder_finish"
    )
    array_length = self.require_runtime_symbol(
        "array", "irx_arrow_array_length"
    )
    release_array = self.require_runtime_symbol(
        "array", "irx_arrow_array_release"
    )

    builder_slot = self._llvm.ir_builder.alloca(
        self._llvm.ARRAY_BUILDER_HANDLE_TYPE,
        name="array_builder_slot",
    )
    self._llvm.ir_builder.call(builder_new, [builder_slot])
    builder_handle = self._llvm.ir_builder.load(
        builder_slot, "array_builder"
    )

    for item in node.values:
        self.visit_child(item)
        value = safe_pop(self.result_stack)
        if value is None:
            raise Exception("Array helper expected an integer value")
        if not is_int_type(value.type):
            raise Exception(
                "Array 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, "array_i32_promote"
            )
        elif value.type.width > self._llvm.INT32_TYPE.width:
            value = self._llvm.ir_builder.trunc(
                value, self._llvm.INT32_TYPE, "array_i32_trunc"
            )

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

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

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

BinaryOpVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: BitXorBinOp) -> None
Source code in packages/irx/src/irx/builder/lowering/binary_ops.py
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
@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.")

BufferVisitorMixin

Bases: VisitorMixinBase

Methods:

lower_buffer_byte_offset

lower_buffer_byte_offset(
    view: Value,
    indices: list[Value],
    *,
    index_nodes: list[AST],
    bounds_policy: BufferIndexBoundsPolicy = DEFAULT,
) -> Value
Source code in packages/irx/src/irx/builder/lowering/buffer.py
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
def lower_buffer_byte_offset(
    self,
    view: ir.Value,
    indices: list[ir.Value],
    *,
    index_nodes: list[astx.AST],
    bounds_policy: BufferIndexBoundsPolicy = (
        BufferIndexBoundsPolicy.DEFAULT
    ),
) -> ir.Value:
    """
    title: Lower one buffer view indexed access to a byte offset.
    parameters:
      view:
        type: ir.Value
      indices:
        type: list[ir.Value]
      index_nodes:
        type: list[astx.AST]
      bounds_policy:
        type: BufferIndexBoundsPolicy
    returns:
      type: ir.Value
    """
    _ = bounds_policy
    if view.type != self._llvm.BUFFER_VIEW_TYPE:
        raise Exception("buffer view indexing requires a BufferViewType")
    if len(indices) != len(index_nodes):
        raise Exception("buffer view index lowering arity mismatch")

    strides = self._extract_buffer_view_strides(view)
    total_offset = self._extract_buffer_view_offset_bytes(view)

    for axis, (index, index_node) in enumerate(
        zip(indices, index_nodes, strict=True)
    ):
        index64 = self._normalize_buffer_index_value(index, index_node)
        stride_ptr = self._llvm.ir_builder.gep(
            strides,
            [ir.Constant(self._llvm.INT64_TYPE, axis)],
            name=f"irx_buffer_index_stride_ptr_{axis}",
        )
        stride = self._llvm.ir_builder.load(
            stride_ptr,
            name=f"irx_buffer_index_stride_{axis}",
        )
        scaled_index = self._llvm.ir_builder.mul(
            index64,
            stride,
            name=f"irx_buffer_index_scaled_{axis}",
        )
        total_offset = self._llvm.ir_builder.add(
            total_offset,
            scaled_index,
            name=f"irx_buffer_index_offset_{axis}",
        )

    return total_offset

lower_buffer_element_pointer

lower_buffer_element_pointer(
    view: Value,
    indices: list[Value],
    element_type: DataType,
    *,
    index_nodes: list[AST],
    bounds_policy: BufferIndexBoundsPolicy = DEFAULT,
) -> Value
Source code in packages/irx/src/irx/builder/lowering/buffer.py
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
def lower_buffer_element_pointer(
    self,
    view: ir.Value,
    indices: list[ir.Value],
    element_type: astx.DataType,
    *,
    index_nodes: list[astx.AST],
    bounds_policy: BufferIndexBoundsPolicy = (
        BufferIndexBoundsPolicy.DEFAULT
    ),
) -> ir.Value:
    """
    title: Lower a buffer view indexed access to a typed element pointer.
    parameters:
      view:
        type: ir.Value
      indices:
        type: list[ir.Value]
      element_type:
        type: astx.DataType
      index_nodes:
        type: list[astx.AST]
      bounds_policy:
        type: BufferIndexBoundsPolicy
    returns:
      type: ir.Value
    """
    element_llvm_type = self._llvm_type_for_ast_type(element_type)
    if element_llvm_type is None:
        raise Exception(
            "buffer view indexing has unsupported element type"
        )

    data = self._extract_buffer_view_data(view)
    total_offset = self.lower_buffer_byte_offset(
        view,
        indices,
        index_nodes=index_nodes,
        bounds_policy=bounds_policy,
    )
    byte_ptr = self._llvm.ir_builder.gep(
        data,
        [total_offset],
        name="irx_buffer_index_byte_ptr",
    )
    element_ptr_type = element_llvm_type.as_pointer()
    if byte_ptr.type == element_ptr_type:
        return byte_ptr
    return self._llvm.ir_builder.bitcast(
        byte_ptr,
        element_ptr_type,
        name="irx_buffer_index_element_ptr",
    )

visit

visit(node: BufferViewRelease) -> None
Source code in packages/irx/src/irx/builder/lowering/buffer.py
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
@VisitorCore.visit.dispatch
def visit(self, node: astx.BufferViewRelease) -> None:
    """
    title: Visit BufferViewRelease nodes.
    parameters:
      node:
        type: astx.BufferViewRelease
    """
    release = self.require_runtime_symbol(
        "buffer",
        "irx_buffer_view_release",
    )
    view_ptr = self._buffer_view_pointer_for_call(
        node.view,
        name="irx_buffer_release_view",
    )
    result = self._llvm.ir_builder.call(
        release,
        [view_ptr],
        name="irx_buffer_release_status",
    )
    self.result_stack.append(result)

CollectionVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: CollectionCount) -> None
Source code in packages/irx/src/irx/builder/lowering/collections.py
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
@VisitorCore.visit.dispatch
def visit(self, node: astx.CollectionCount) -> None:
    """
    title: Visit CollectionCount nodes.
    parameters:
      node:
        type: astx.CollectionCount
    """
    resolution = self._resolved_collection_method(node)
    if resolution.method is not CollectionMethodKind.COUNT:
        raise TypeError("collection count has invalid semantic method")
    self.result_stack.append(
        self._sequence_or_literal_search(
            base=node.base,
            value=node.value,
            method=CollectionMethodKind.COUNT,
        )
    )

ControlFlowVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: ContinueStmt) -> None
Source code in packages/irx/src/irx/builder/lowering/control_flow.py
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
@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_lowering_error(
            "continue statement used outside an active loop",
            node=node,
            code=DiagnosticCodes.LOWERING_INVALID_CONTROL_FLOW,
            hint=(
                "use `continue` only inside while, for-count, or "
                "for-range loop bodies"
            ),
        )
    self._emit_active_cleanups(self.loop_stack[-1].cleanup_depth)
    self._llvm.ir_builder.branch(self.loop_stack[-1].continue_target)

FunctionVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: FunctionReturn) -> None
Source code in packages/irx/src/irx/builder/lowering/functions.py
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
@VisitorCore.visit.dispatch
def visit(self, node: astx.FunctionReturn) -> None:
    """
    title: Visit FunctionReturn nodes.
    parameters:
      node:
        type: astx.FunctionReturn
    """
    if self._current_generator_frame_ptr is not None:
        cast(Any, self)._emit_generator_stop(node)
        return
    return_resolution = self._semantic_return_resolution(node)
    if return_resolution.returns_void:
        self._emit_active_cleanups()
        self._llvm.ir_builder.ret_void()
        return

    if node.value is not None:
        self.visit_child(node.value)
        retval = require_lowered_value(
            safe_pop(self.result_stack),
            node=node.value,
            context="return expression",
        )
    else:
        retval = None

    if retval is None:
        raise_lowering_internal_error(
            "return expression did not lower to a value",
            node=node,
        )

    retval = self._cast_ast_value(
        retval,
        source_type=self._resolved_ast_type(node.value),
        target_type=return_resolution.expected_type,
    )
    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._emit_active_cleanups()
    self._llvm.ir_builder.ret(retval)

GeneratorVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: GeneratorExpr) -> None
Source code in packages/irx/src/irx/builder/lowering/generators.py
836
837
838
839
840
841
842
843
844
845
846
847
848
@VisitorCore.visit.dispatch
def visit(self, node: astx.GeneratorExpr) -> None:
    """
    title: Visit GeneratorExpr nodes.
    parameters:
      node:
        type: astx.GeneratorExpr
    """
    raise_lowering_error(
        "generator expression lowering is not supported yet",
        node=node,
        code=DiagnosticCodes.LOWERING_INVALID_CONTROL_FLOW,
    )

ListVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: ListAppend) -> None
Source code in packages/irx/src/irx/builder/lowering/list.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
@VisitorCore.visit.dispatch
def visit(self, node: astx.ListAppend) -> None:
    """
    title: Visit ListAppend nodes.
    parameters:
      node:
        type: astx.ListAppend
    """
    append_fn = self.require_runtime_symbol(
        LIST_RUNTIME_FEATURE,
        LIST_APPEND_SYMBOL,
    )
    list_ptr = self._lvalue_address(node.base)

    self.visit_child(node.value)
    value = safe_pop(self.result_stack)
    if value is None:
        raise Exception("dynamic list append requires a value")

    element_type = list_element_type(self._resolved_ast_type(node.base))
    if element_type is None:
        raise Exception(
            "dynamic list append requires a single concrete element type"
        )
    value = self._cast_ast_value(
        value,
        source_type=self._resolved_ast_type(node.value),
        target_type=element_type,
    )

    llvm_element_type = self._list_element_llvm_type(node.base)
    value_ptr = self._llvm.ir_builder.alloca(
        llvm_element_type,
        name="irx_list_append_value",
    )
    self._llvm.ir_builder.store(value, value_ptr)
    raw_value_ptr = self._llvm.ir_builder.bitcast(
        value_ptr,
        self._llvm.INT8_TYPE.as_pointer(),
        name="irx_list_append_bytes",
    )

    result = self._llvm.ir_builder.call(
        append_fn,
        [list_ptr, raw_value_ptr],
        name="irx_list_append_status",
    )
    self.result_stack.append(result)

LiteralVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: LiteralInt16) -> None
Source code in packages/irx/src/irx/builder/lowering/literals.py
739
740
741
742
743
744
745
746
747
748
749
@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: ClassDefStmt) -> None
Source code in packages/irx/src/irx/builder/lowering/modules.py
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
@VisitorCore.visit.dispatch
def visit(self, node: astx.ClassDefStmt) -> None:
    """
    title: Visit ClassDefStmt nodes.
    parameters:
      node:
        type: astx.ClassDefStmt
    """
    class_key = semantic_class_key(node, node.name)
    semantic = getattr(node, "semantic", None)
    resolved_class = getattr(semantic, "resolved_class", None)
    layout = getattr(resolved_class, "layout", None)
    initialization = getattr(resolved_class, "initialization", None)
    if layout is None:
        raise Exception("codegen: unresolved class layout.")
    if initialization is None:
        raise Exception("codegen: unresolved class initialization.")

    field_types: list[ir.Type] = [
        self._llvm.OPAQUE_POINTER_TYPE for _ in layout.header_fields
    ]
    for field in layout.instance_fields:
        llvm_type = self._llvm_type_for_ast_type(field.member.type_)
        if llvm_type is None:
            raise Exception(
                f"codegen: Unknown LLVM type for class field "
                f"'{field.member.name}'."
            )
        field_types.append(llvm_type)

    self._ensure_identified_type(
        class_key,
        semantic_class_name(node, node.name),
        field_types,
    )

    for static_initializer in initialization.static_initializers:
        storage = static_initializer.storage
        llvm_type = self._llvm_type_for_ast_type(storage.member.type_)
        if llvm_type is None:
            raise Exception(
                f"codegen: Unknown LLVM type for static class field "
                f"'{storage.member.name}'."
            )
        initializer = self._literal_global_initializer(
            static_initializer.value,
            llvm_type,
        )
        existing = self._llvm.module.globals.get(storage.global_name)
        if existing is None:
            global_var = ir.GlobalVariable(
                self._llvm.module,
                llvm_type,
                name=storage.global_name,
            )
        else:
            global_var = existing
        global_var.linkage = "internal"
        global_var.global_constant = storage.member.is_constant
        global_var.initializer = initializer

    dispatch_table = self._dispatch_table_initializer(node)
    if dispatch_table is not None:
        dispatch_type, dispatch_initializer = dispatch_table
        dispatch_global = self._llvm.module.globals.get(
            layout.dispatch_global_name
        )
        if dispatch_global is None:
            dispatch_global = ir.GlobalVariable(
                self._llvm.module,
                dispatch_type,
                name=layout.dispatch_global_name,
            )
        dispatch_global.linkage = "internal"
        dispatch_global.global_constant = True
        dispatch_global.initializer = dispatch_initializer

    for method in node.methods:
        if (
            astx.is_template_node(method.prototype)
            or bool(getattr(method.prototype, "is_abstract", False))
            or bool(getattr(method, "is_abstract", False))
        ):
            continue
        self.visit(method)

SystemVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: PrintExpr) -> None
Source code in packages/irx/src/irx/builder/lowering/system.py
 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
119
120
121
122
123
124
125
126
127
@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_source_type = self._resolved_ast_type(node.message)
    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,
            unsigned=is_unsigned_type(message_source_type)
            or is_boolean_type(message_source_type),
        )
        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 packages/irx/src/irx/builder/lowering/temporal.py
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
287
288
@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)

TensorVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: TensorRelease) -> None
Source code in packages/irx/src/irx/builder/lowering/tensor.py
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
@VisitorCore.visit.dispatch
def visit(self, node: astx.TensorRelease) -> None:
    """
    title: Visit TensorRelease nodes.
    parameters:
      node:
        type: astx.TensorRelease
    """
    release = self.require_runtime_symbol(
        "buffer",
        "irx_buffer_view_release",
    )
    value = self._require_tensor_value(node.base)
    slot = self._llvm.ir_builder.alloca(
        self._llvm.BUFFER_VIEW_TYPE,
        name="irx_tensor_release_view",
    )
    self._llvm.ir_builder.store(value, slot)
    self.result_stack.append(
        self._llvm.ir_builder.call(
            release,
            [slot],
            name="irx_tensor_release_status",
        )
    )

UnaryOpVisitorMixin

Bases: VisitorMixinBase

Methods:

visit

visit(node: UnaryOp) -> None
Source code in packages/irx/src/irx/builder/lowering/unary_ops.py
 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
@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_name = (
            node.operand.name
            if isinstance(node.operand, astx.Identifier)
            else getattr(node.operand, "field_name", "field")
        )
        operand_key = semantic_assignment_key(node, operand_name)

        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)
            and operand_key in self.const_vars
        ):
            raise Exception(
                f"Cannot mutate '{operand_name}': declared as constant"
            )
        target_addr = self._lvalue_address(node.operand)
        self._llvm.ir_builder.store(result, target_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_name = (
            node.operand.name
            if isinstance(node.operand, astx.Identifier)
            else getattr(node.operand, "field_name", "field")
        )
        operand_key = semantic_assignment_key(node, operand_name)
        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)
            and operand_key in self.const_vars
        ):
            raise Exception(
                f"Cannot mutate '{operand_name}': declared as constant"
            )
        target_addr = self._lvalue_address(node.operand)
        self._llvm.ir_builder.store(result, target_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.")
        if not is_int_type(val.type) or val.type.width != 1:
            raise Exception(
                "codegen: unary operator '!' must lower a Boolean operand."
            )

        result = self._llvm.ir_builder.xor(
            val,
            ir.Constant(self._llvm.BOOLEAN_TYPE, 1),
            "nottmp",
        )

        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 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)