#!/usr/bin/env python3
"""Build a STITCH++ Swift harness inside the project image.

harness/*.swift become the executable target `worker` of a generated package in <out>/app/pkg,
with the Stitch package and stitch.toml [swift] dependencies. A generated main.swift registers
every `let NAME = endpoint(...)` / `stitchInit` and passes the closures' argument names.
Everything is compiled with ASan and SanitizerCoverage and linked with libstitch_swift_rt.a
(the C/C++ runtime) and libstitch_engine.a. Writes
  <out>/app/worker      fuzzer (STITCH_SWIFT_ENGINE=1: the engine in this process) and reproducer
  <out>/fuzzer, <out>/repro, <out>/manifest.json
stitch.toml [swift]: dependencies = ['.package(path: "/src")']                      (SwiftPM expressions)
                     products = ['.product(name: "SwiftSoup", package: "src")']
"""
import argparse
import json
import os
import re
import shutil
import subprocess
import sys
import tomllib
from pathlib import Path

STUB_RE = re.compile(r"^\s*(?:public\s+|internal\s+)?let\s+(\w+)\s*=\s*(?:Stitch\.)?(endpoint|stitchInit)\b", re.M)
NAMES_RE = re.compile(r'endpoint\(\s*"([^"]+)"[^{]*\{\s*\(([^)]*)\)', re.S)
SAN = ["-Xswiftc", "-sanitize=address", "-Xcc", "-fsanitize=address"]
COV = ["-Xswiftc", "-sanitize-coverage=edge,trace-pc-guard,trace-cmp", "-Xcc", "-fsanitize-coverage=trace-pc-guard,trace-cmp"]
ASAN = ("export ASAN_OPTIONS=${ASAN_OPTIONS:-abort_on_error=1:detect_leaks=0:symbolize=1:allocator_may_return_null=1:"
        "handle_abort=1:handle_sigtrap=1:handle_sigill=1:detect_stack_use_after_return=0}")


def arg_names(params):
    """'(a: Str<4, X>, b: Borrow<Doc>)' -> ['a', 'b'] (labels before the first ':' of each top-level part)"""
    out, depth, cur = [], 0, ""
    for ch in params + ",":
        if ch in "<([":
            depth += 1
        elif ch in ">)]":
            depth -= 1
        if ch == "," and depth == 0:
            if cur.strip():
                out.append(cur.split(":")[0].strip().split()[-1])
            cur = ""
        else:
            cur += ch
    return out


def swift_dict(names):
    """{"a": ["x"]} as a Swift dictionary literal"""
    if not names:
        return "[:]"
    return "[" + ", ".join(f"{json.dumps(k)}: [{', '.join(json.dumps(v) for v in vs)}]" for k, vs in names.items()) + "]"


def package_swift(deps, products):
    return f"""// swift-tools-version:6.0
// Generated by stitch-build.
import PackageDescription

let package = Package(
    name: "StitchHarness",
    dependencies: [
        .package(path: "/stitch/swift/Stitch"),
{''.join(f"        {d},\n" for d in deps)}    ],
    targets: [
        .executableTarget(
            name: "worker",
            dependencies: [
                .product(name: "Stitch", package: "Stitch"),
{''.join(f"                {p},\n" for p in products)}            ],
            path: "Sources/worker",
            swiftSettings: [.swiftLanguageMode(.v5)]
        ),
    ]
)
"""


def compile_pkg(a, proj, pkg, scratch, jobs=None, swiftc=()):
    engine = Path("/stitch/lib/libstitch_engine.a")
    libs = ["/stitch/swift/lib/libstitch_swift_rt.a"] + ([str(engine)] if engine.exists() and not a.coverage else [])
    # stitch_engine_main is weak in the bridge (reproducer images have no engine): pull it in
    force = ["-Xlinker", "--undefined=stitch_engine_main"] if str(engine) in libs else []
    link = force + ["-Xlinker", "--start-group"] + [x for l in libs for x in ("-Xlinker", l)] + ["-Xlinker", "--end-group",
            "-Xlinker", "-lstdc++", "-Xlinker", "-lm"]
    flags = SAN + (["-Xswiftc", "-profile-generate", "-Xswiftc", "-profile-coverage-mapping"] if a.coverage else COV)
    # SwiftPM does not track libraries passed to the linker: remove the binary so it always relinks
    # (a new runtime or engine library otherwise leaves a stale binary)
    (scratch / "release" / "worker").unlink(missing_ok=True)
    cmd = ["swift", "build", "-c", "release", "--package-path", str(pkg), "--scratch-path", str(scratch),
           *(["-j", str(jobs)] if jobs else []), "-Xswiftc", "-g", *[x for f in swiftc for x in ("-Xswiftc", f)], *flags, *link]
    return subprocess.run(cmd, capture_output=True, text=True)


def swift_opts(proj):
    """[swift] build_jobs (parallel compile jobs) and swiftc_flags (e.g. -no-whole-module-optimization:
    big modules otherwise compile in one process that needs a lot of memory)."""
    try:
        sw = tomllib.loads((proj / "stitch.toml").read_text()).get("swift", {})
        return sw.get("build_jobs"), sw.get("swiftc_flags", [])
    except (OSError, tomllib.TOMLDecodeError):
        return None, []


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--project", default="/project")
    ap.add_argument("--out", default=None)
    ap.add_argument("--target", default="all")
    ap.add_argument("--coverage", action="store_true", help="profiling build for `stitch cov` (no sanitizer coverage)")
    ap.add_argument("--try", dest="try_", action="store_true",
                    help="rebuild <out>/app/pkg as it is (stitch try replaced main.swift); binary in /tmp/stitch-try")
    ap.add_argument("--json", action="store_true")
    a = ap.parse_args()
    proj = Path(a.project).resolve()
    cfg = tomllib.loads((proj / "stitch.toml").read_text()) if (proj / "stitch.toml").exists() else {}
    sw = cfg.get("swift", {})
    out = Path(a.out) if a.out else proj / ".stitch" / "build"
    if not out.is_absolute():
        out = proj / out
    out.mkdir(parents=True, exist_ok=True)
    app = out / "app"
    pkg = app / "pkg"
    if a.try_:
        r = compile_pkg(a, proj, pkg, proj / ".stitch" / "swift-build", *swift_opts(proj))
        if r.returncode != 0:
            sys.stderr.write((r.stdout + r.stderr)[-8000:])
            sys.exit(1)
        Path("/tmp/stitch-try/release").mkdir(parents=True, exist_ok=True)
        shutil.copy2(proj / ".stitch" / "swift-build" / "release" / "worker", "/tmp/stitch-try/release/worker")
        sys.exit(0)
    shutil.rmtree(app, ignore_errors=True)
    src = pkg / "Sources" / "worker"
    src.mkdir(parents=True)
    files = sorted(p for p in (proj / "harness").rglob("*.swift") if "data" not in p.relative_to(proj / "harness").parts[:1])
    if not files:
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": "no harness/*.swift files"}]})
    stubs, names = [], {}
    for f in files:
        text = f.read_text()
        if f.name == "main.swift":
            return finish(a, {"ok": False, "errors": [{"file": str(f), "output": "harness/main.swift is generated: rename it"}]})
        shutil.copy2(f, src / f.name)
        stubs += [m.group(1) for m in STUB_RE.finditer(text)]
        for m in NAMES_RE.finditer(text):
            names[m.group(1)] = arg_names(m.group(2))
    if not stubs:
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": "no `let NAME = endpoint(...)` in harness/*.swift"}]})
    (src / "main.swift").write_text(
        "// Generated by stitch-build: registers the stubs, then runs the engine or the reproducer.\n"
        "import Stitch\n#if canImport(Glibc)\nimport Glibc\n#endif\n\n"
        f"exit(stitchMain(argNames: {swift_dict(names)}) {{\n    [{', '.join(stubs)}]\n}})\n")
    (pkg / "Package.swift").write_text(package_swift(sw.get("dependencies", []), sw.get("products", [])))
    scratch = proj / ".stitch" / ("swift-cov" if a.coverage else "swift-build")
    r = compile_pkg(a, proj, pkg, scratch, sw.get("build_jobs"), sw.get("swiftc_flags", []))
    if r.returncode != 0:
        errs = "\n".join(l for l in (r.stdout + r.stderr).splitlines() if not l.startswith(("Fetching", "Computing", "Fetched",
                                                                                           "Creating", "Working copy", "Compiling", "[")))
        return finish(a, {"ok": False, "errors": [{"file": "swift build", "output": errs[-8000:]}]})
    shutil.copy2(scratch / "release" / "worker", app / "worker")
    head = ["#!/bin/sh", 'HERE="$(cd "$(dirname "$0")" && pwd)"', ASAN, "export SWIFT_BACKTRACE=enable=no"]
    (out / "fuzzer").write_text("\n".join(head + ["export STITCH_SWIFT_ENGINE=1", 'exec "$HERE/app/worker" "$@"', ""]))
    # the reproducer demangles Swift names in what it prints (the engine's triage does the same)
    (out / "repro").write_text("\n".join(head + [
        'case " $* " in *" --coverage "*) exec /stitch/bin/stitch-swift-cov "$HERE" "$@";; esac',
        "unset STITCH_SWIFT_ENGINE", 'exec /stitch/bin/stitch-swift-run "$HERE/app/worker" "$@"', ""]))
    for f in ("fuzzer", "repro"):
        (out / f).chmod(0o755)
    if a.coverage:
        return finish(a, {"ok": True, "endpoints": 0, "objects": 0, "datatypes": 0, "errors": []})
    r = subprocess.run([str(out / "repro"), "--manifest"], capture_output=True, text=True, cwd=proj)
    if r.returncode != 0 or not r.stdout.strip():
        return finish(a, {"ok": False, "errors": [{"file": "harness", "output": (r.stderr or r.stdout)[-8000:]}]})
    m = json.loads(r.stdout.strip().splitlines()[-1])
    (out / "manifest.json").write_text(json.dumps(m))
    return finish(a, {"ok": True, "fuzzer": str(out / "fuzzer"), "repro": str(out / "repro"), "endpoints": len(m["endpoints"]),
                      "objects": len(m["objects"]), "datatypes": len(m["datatypes"]), "errors": []})


def finish(a, res):
    if a.json:
        print(json.dumps(res))
    elif res["ok"]:
        print(f"built: {res['endpoints']} endpoints, {res['objects']} object types, {res['datatypes']} datatypes")
    else:
        for e in res["errors"]:
            sys.stderr.write(e["output"] + "\n")
    sys.exit(0 if res["ok"] else 1)


if __name__ == "__main__":
    main()
