Skip to content

main

Classes:

Functions:

ArxMain dataclass

ArxMain(
    input_files: list[str] = list(),
    output_file: str = "",
    is_lib: bool = False,
    link_mode: Literal["auto", "pie", "no-pie"] = "auto",
)

Methods:

compile

compile(show_llvm_ir: bool = False) -> bool
Source code in packages/arx/src/arx/main.py
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
def compile(self, show_llvm_ir: bool = False) -> bool:
    """
    title: Compile the given input file.
    parameters:
      show_llvm_ir:
        type: bool
    returns:
      type: bool
    """
    _ = show_llvm_ir
    tree_ast = self._get_codegen_astx()
    ir = ArxBuilder()
    self.output_file = self._resolve_output_file()
    emits_executable = not self.is_lib and self._has_main_entry(tree_ast)

    if isinstance(tree_ast, astx.Module) and self._module_has_imports(
        tree_ast
    ):
        root, resolver = self._build_multimodule_context(tree_ast)
        ir.build_modules(
            root,
            resolver,
            output_file=self.output_file,
            link=emits_executable,
            link_mode=self.link_mode,
        )
        return emits_executable

    ir.build(
        tree_ast,
        output_file=self.output_file,
        link=emits_executable,
        link_mode=self.link_mode,
    )
    return emits_executable

run

run(**kwargs: Any) -> None
Source code in packages/arx/src/arx/main.py
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
def run(self, **kwargs: Any) -> None:
    """
    title: Compile the given source code.
    parameters:
      kwargs:
        type: Any
        variadic: keyword
    """
    self.input_files = kwargs.get("input_files", [])
    output_file = kwargs.get("output_file")
    self.output_file = output_file.strip() if output_file else ""
    self.is_lib = kwargs.get("is_lib", False)
    link_mode = str(kwargs.get("link_mode", "auto")).strip().lower()
    if link_mode not in {"auto", "pie", "no-pie"}:
        raise ValueError(
            "Invalid link mode. Expected one of: auto, pie, no-pie."
        )
    self.link_mode = cast(
        Literal["auto", "pie", "no-pie"],
        link_mode,
    )

    if kwargs.get("show_ast"):
        return self.show_ast()

    if kwargs.get("show_tokens"):
        return self.show_tokens()

    if kwargs.get("show_llvm_ir"):
        return self.show_llvm_ir()

    if kwargs.get("shell"):
        return self.run_shell()

    emits_executable = self.compile()
    if kwargs.get("run"):
        if emits_executable is False:
            raise ValueError(
                "`--run` requires `fn main` (or disable `--lib`)."
            )
        self.run_binary()

run_binary

run_binary() -> None
Source code in packages/arx/src/arx/main.py
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
def run_binary(self) -> None:
    """
    title: Run the generated binary.
    """
    binary_path = Path(self.output_file)
    if not binary_path.is_absolute():
        binary_path = Path.cwd() / binary_path
    result = subprocess.run([str(binary_path)], check=False)
    if result.returncode != 0:
        raise SystemExit(result.returncode)

run_shell

run_shell() -> None
Source code in packages/arx/src/arx/main.py
1065
1066
1067
1068
1069
def run_shell(self) -> None:
    """
    title: Open arx in shell mode.
    """
    raise Exception("Arx Shell is not implemented yet.")

run_tests

run_tests(**kwargs: Any) -> int
Source code in packages/arx/src/arx/main.py
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
def run_tests(self, **kwargs: Any) -> int:
    """
    title: Collect and execute compiled tests from configured paths.
    parameters:
      kwargs:
        type: Any
        variadic: keyword
    returns:
      type: int
    """
    name_filter = str(kwargs.get("name_filter", "")).strip()
    fail_fast = bool(kwargs.get("fail_fast", False))
    keep_artifacts = bool(kwargs.get("keep_artifacts", False))
    list_only = bool(kwargs.get("list_only", False))

    link_mode = str(kwargs.get("link_mode", "auto")).strip().lower()
    if link_mode not in {"auto", "pie", "no-pie"}:
        raise ValueError(
            "Invalid link mode. Expected one of: auto, pie, no-pie."
        )
    self.link_mode = cast(
        Literal["auto", "pie", "no-pie"],
        link_mode,
    )

    testing_module = importlib.import_module("arx.testing")
    runner_cls = testing_module.ArxTestRunner
    settings_module = importlib.import_module("arx.settings")
    try:
        runner_kwargs = self._build_test_runner_kwargs(kwargs)
    except settings_module.ArxProjectError as err:
        print(
            f"ERROR: invalid [tests] configuration: {err}",
            file=sys.stderr,
        )
        return 2

    runner = runner_cls(
        **runner_kwargs,
        name_filter=name_filter,
        fail_fast=fail_fast,
        keep_artifacts=keep_artifacts,
        list_only=list_only,
        link_mode=self.link_mode,
    )
    summary = runner.run()
    return int(summary.exit_code)

show_ast

show_ast() -> None
Source code in packages/arx/src/arx/main.py
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
def show_ast(self) -> None:
    """
    title: Print the AST for the given input file.
    """
    tree_ast = self._get_astx()
    try:
        print(repr(tree_ast))
    except Exception:
        try:
            if hasattr(tree_ast, "to_json"):
                print(tree_ast.to_json())
                return
        except Exception:
            pass

        if isinstance(tree_ast, astx.AST):
            print(self._format_ast_fallback(tree_ast))
            return

        # Fallback for nodes whose repr visualizer path is not supported.
        print(str(tree_ast))

show_llvm_ir

show_llvm_ir() -> None
Source code in packages/arx/src/arx/main.py
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
def show_llvm_ir(self) -> None:
    """
    title: Compile into LLVM IR the given input file.
    """
    tree_ast = self._get_codegen_astx()
    ir = ArxBuilder()

    if isinstance(tree_ast, astx.Module) and self._module_has_imports(
        tree_ast
    ):
        root, resolver = self._build_multimodule_context(tree_ast)
        print(ir.translate_modules(root, resolver))
        return

    print(ir.translate(tree_ast))

show_tokens

show_tokens() -> None
Source code in packages/arx/src/arx/main.py
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
def show_tokens(self) -> None:
    """
    title: Print the AST for the given input file.
    """
    lexer = Lexer()

    for input_file in self.input_files:
        ArxIO.file_to_buffer(input_file)
        tokens = lexer.lex()
        for token in tokens:
            print(token)

FileImportResolver dataclass

FileImportResolver(
    input_files: tuple[str, ...],
    cache: dict[str, ParsedModule] = dict(),
    _source_root_cache: dict[Path, Path | None] = dict(),
)

get_bundled_stdlib_root

get_bundled_stdlib_root() -> Path
Source code in packages/arx/src/arx/main.py
28
29
30
31
32
33
34
def get_bundled_stdlib_root() -> Path:
    """
    title: Return the bundled stdlib root shipped inside the arx package.
    returns:
      type: Path
    """
    return (Path(__file__).resolve().parent / STDLIB_NAMESPACE).resolve()

get_module_name_from_file_path

get_module_name_from_file_path(filepath: str) -> str
Source code in packages/arx/src/arx/main.py
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def get_module_name_from_file_path(filepath: str) -> str:
    """
    title: Return the module name from the source file name.
    parameters:
      filepath:
        type: str
    returns:
      type: str
    """
    file_path = Path(filepath)
    source_root = _find_project_source_root(file_path.parent)
    if source_root is not None:
        module_name = _module_name_from_source_root(file_path, source_root)
        if module_name is not None:
            return module_name
    return file_path.stem