Files
kryon/scripts/generate_android_sources.py
T

165 lines
7.8 KiB
Python

#!/usr/bin/env python3
"""Generate the complete checked Zi graph and its CMake source manifest.
Resolution follows the project, not flat module paths: `ziran ir --project`
namespaces every package's modules, so an application module may share a
name with a Kryon module. Run through scripts/android-build.sh for
`kryon build --profile android`; concurrent ABIs serialize through one lock.
"""
import argparse
import fcntl
import os
from pathlib import Path
import shutil
import subprocess
parser = argparse.ArgumentParser()
parser.add_argument("--ziran", type=Path, required=True)
parser.add_argument("--zi2c", type=Path, required=True)
parser.add_argument("--root", type=Path, required=True)
parser.add_argument("--kryon", type=Path, required=True)
parser.add_argument("--ir", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--manifest", type=Path, required=True)
parser.add_argument("--host", type=Path, help="Explicit NativeActivity host source for a platform test")
parser.add_argument("--entry", type=Path, default=os.environ.get("KRYON_PROJECT_ENTRY", "src/app.zi"),
help="Selected application source (or KRYON_PROJECT_ENTRY)")
parser.add_argument("--package-id", default=os.environ.get("ZIRAN_PACKAGE_ID"),
help="Resolved Kryon identity (or ZIRAN_PACKAGE_ID from ziran tool kryon)")
parser.add_argument("--define", action="append", default=[])
parser.add_argument("--codegen", choices=("c99", "zx"), default="c99")
args = parser.parse_args()
root = args.root.resolve()
kryon = args.kryon.resolve()
entry = (root / args.entry).resolve()
if not entry.is_file() or entry.suffix != ".zi":
parser.error(f"selected application entry is not a Zi source: {entry}")
needs_frame = args.host is None and args.codegen == "c99"
if needs_frame and not args.package_id:
parser.error("--package-id is required unless ZIRAN_PACKAGE_ID is supplied by ziran tool kryon")
entry_module = entry.parent.name if entry.stem == "module" else entry.stem
sources = sorted((root / "src").rglob("*.zi"))
if list((root / "src").rglob("*.c")) or list((root / "src").rglob("*.kry")):
raise SystemExit("Android application implementation must be current Zi")
if not sources:
raise SystemExit("No Zi sources under src/")
host_roots = [
args.host.resolve() if args.host else kryon / "src/backend/android_run.zi",
kryon / "src/backend/android_fopen.zi",
root / "src/main.zi",
root / "src/android_glue.zi",
]
bindings = []
if needs_frame:
host_roots.extend([entry, kryon / "src/backend/frame_entry.zi"])
bindings = ["--bind",
f"{args.package_id}_frame_entry:ProjectFrame={entry_module}:Frame"]
for path in host_roots:
if not path.is_file():
raise SystemExit(f"Missing host source {path}; run scripts/android_scaffold.py")
# `ziran ir --entry` keeps only what its one entry reaches; a native C graph
# has no other root, and `#program_export` alone does not retain a function.
# Android's loader, not main, calls the glue's JNI_OnLoad, which
# cmake/libmain.map.txt exports by name; kryon_android_app's
# --wrap=fopen/fopen64 link android_fopen's wrappers; and a ZX player's
# android_main is called only by the NDK's native_app_glue. This generated
# entry reaches them all: it forwards a valid call straight to the
# application's stable `main(argc, argv)` and names the others only on the
# branch a C argc (never negative) cannot take, so it has no glue side effect.
# Kryon's entries are host capabilities bound to its exports, which keeps a
# called provider. The root is left out of the C inputs, so the host still
# starts the generated C `main` and nothing else.
ROOTS_MODULE, ROOTS_ENTRY = "kryon_android_roots", "KryonAndroidRoots"
kryon_roots = [("__wrap_fopen", "(path: *u8, mode: *u8) -> *void", "(null, null)",
"kryon/android_fopen"),
("__wrap_fopen64", "(path: *u8, mode: *u8) -> *void", "(null, null)",
"kryon/android_fopen")]
if args.codegen == "zx":
kryon_roots.append(("android_main", "(app: *void)", "(null)", "kryon/android_bundle_run"))
roots_source = args.ir.with_name(args.ir.name + "-roots") / (ROOTS_MODULE + ".zi")
roots_text = "\n".join([
"// Generated by kryon scripts/generate_android_sources.py.",
'#import "main"', '#import "android_glue"',
'host_api :: #system_library "host_api";',
*(f"{name} :: {signature} #foreign host_api;" for name, signature, _, _ in kryon_roots),
f"{ROOTS_ENTRY} :: (argc: s32, argv: **u8) -> s32 {{",
" if argc < 0 {",
*(f" unused {name}{call}" if "->" in signature else f" {name}{call}"
for name, signature, call, _ in kryon_roots),
" return JNI_OnLoad(null, null)",
" }",
" return main(argc, argv)",
"}\n"])
for name, _, _, provider in kryon_roots:
bindings.extend(["--bind", f"{ROOTS_MODULE}:{name}={provider}:{name}"])
defines = ["--define", "KRYON_ANDROID_HOST"]
if args.codegen == "zx":
defines.extend(["--define", "KRYON_ZX_APP", "--define", "BUNDLE_NATIVE_RENDERER"])
for name in args.define:
defines.extend(["--define", name])
# Ziran target conditions are independent of the C compiler's preprocessor
# defines. Keep the target attached to both source-to-IR and IR-to-C so Android
# modules never retain a host-Linux branch merely because generation runs on a
# Linux workstation.
cpu_defines = {
"__aarch64__": "arm64",
"__x86_64__": "x64",
"__arm__": "none",
"__i386__": "none",
}
target_cpus = {cpu_defines[name] for name in args.define if name in cpu_defines}
if len(target_cpus) != 1:
parser.error("select exactly one Android CPU define (__aarch64__, __arm__, __x86_64__ or __i386__)")
target = ["--target-os", "android", "--target-cpu", target_cpus.pop()]
if args.ir.exists():
shutil.rmtree(args.ir)
if args.output.exists():
shutil.rmtree(args.output)
args.ir.mkdir(parents=True)
args.output.mkdir(parents=True)
roots_source.parent.mkdir(parents=True, exist_ok=True)
roots_source.write_text(roots_text)
lock_path = root / "build" / "kryon-android-compiler.lock"
lock_path.parent.mkdir(parents=True, exist_ok=True)
with lock_path.open("w") as lock:
fcntl.flock(lock, fcntl.LOCK_EX)
subprocess.run(
[str(args.ziran), "ir", "--project", "--entry", f"{ROOTS_MODULE}:{ROOTS_ENTRY}",
*target, "--root", str(entry.parent), *bindings, *defines, "-o", str(args.ir),
*map(str, host_roots), str(roots_source)],
cwd=root, check=True,
)
# The root only selects what the IR keeps; it never enters native output.
modules = sorted(path for path in args.ir.glob("*.zir") if path.stem != ROOTS_MODULE)
subprocess.run(
[str(args.zi2c), "--no-main", *target, *defines, "--root", str(args.ir),
"-o", str(args.output), *map(str, modules)],
cwd=root, check=True,
)
outputs = sorted(args.output.rglob("*.c"))
if not outputs:
raise SystemExit("Zi compiler emitted no Android native sources")
if not any(path.name == "main.c" for path in outputs):
raise SystemExit("The Android host needs the scaffold's src/main.zi entry")
headers = sorted(args.output.rglob("*.h"))
include_dirs = sorted({args.output, *(p.parent for p in headers)})
lines = ["# Generated from the complete Zi import graph.",
"set(APP_ZIRAN_GENERATED_SOURCES"]
lines.extend(f' "{path}"' for path in outputs)
lines.extend([")", "set(APP_ZIRAN_GENERATED_HEADERS"])
lines.extend(f' "{path}"' for path in headers)
lines.extend([")", "set(APP_ZIRAN_INCLUDE_DIRS"])
lines.extend(f' "{path}"' for path in include_dirs)
lines.append(")\n")
content = "\n".join(lines)
args.manifest.parent.mkdir(parents=True, exist_ok=True)
if not args.manifest.exists() or args.manifest.read_text() != content:
args.manifest.write_text(content)
print(f"Generated {len(outputs)} Android C outputs from maintained Zi sources")