Skip to content

codegen

Classes:

ArxLLVMLiteIRVisitor

Bases: LLVMLiteIRVisitor

LLVMLiteIR

LLVMLiteIR()

Bases: LLVMLiteIR

Methods:

Source code in src/arx/codegen.py
42
43
44
45
46
47
def __init__(self) -> None:
    """
    title: Initialize LLVMIR.
    """
    super().__init__()
    self.translator: ArxLLVMLiteIRVisitor = ArxLLVMLiteIRVisitor()

build

build(
    node: AST,
    output_file: str,
    link: bool = True,
    link_mode: Literal["auto", "pie", "no-pie"] = "auto",
) -> None

-

Transpile the ASTx to LLVM-IR and build it to an executable file.

Source code in src/arx/codegen.py
 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
def build(
    self,
    node: astx.AST,
    output_file: str,
    link: bool = True,
    link_mode: Literal["auto", "pie", "no-pie"] = "auto",
) -> None:
    """
    title: >-
      Transpile the ASTx to LLVM-IR and build it to an executable file.
    parameters:
      node:
        type: astx.AST
      output_file:
        type: str
      link:
        type: bool
      link_mode:
        type: Literal[auto, pie, no-pie]
    """
    self.translator = ArxLLVMLiteIRVisitor()
    result = self.translator.translate(node)

    result_mod = llvm.parse_assembly(result)
    result_object = self.translator.target_machine.emit_object(result_mod)

    with tempfile.NamedTemporaryFile(suffix="", delete=True) as temp_file:
        self.tmp_path = temp_file.name

    file_path_o = f"{self.tmp_path}.o"
    with open(file_path_o, "wb") as file_handler:
        file_handler.write(result_object)

    self.output_file = output_file

    if not link:
        with open(self.output_file, "wb") as file_handler:
            file_handler.write(result_object)
        return

    if link_mode not in self.LINK_MODES:
        raise ValueError(
            "Invalid link mode. Expected one of: auto, pie, no-pie."
        )

    # fix xh typing
    clang: Callable[..., Any] = xh.clang
    clang_args = [file_path_o]
    if link_mode == "pie":
        clang_args.append("-pie")
    elif link_mode == "no-pie":
        clang_args.append("-no-pie")
    clang_args.extend(["-o", self.output_file])
    clang(*clang_args)
    os.chmod(self.output_file, 0o755)