#!/usr/bin/env python3
"""warp-crate: any Rust crate as a C library the native warp's FFI loads (card ffi-rust-crate-adapter, notes/crate_adapter.md).

A crate manifest (lib/crates/<name>.warp) is a lib/native file whose foreign lines also say which Rust item answers:

    crate: "regex@1"
    regex_new(pattern: text): handle(regex::Regex) from 'rs_regex' = regex::Regex::new
    regex_is_match(re: handle, haystack: text): bool from 'rs_regex' = regex::Regex::is_match

warp-crate generates a cdylib wrapping each item in an `extern "C"` function of the foreign line's name, builds it with
cargo, caches it under ~/.cache/warp/crates (by crate, manifest, toolchain and target) and writes
  lib/lib<library>.so      the C library the native warp dlopens (LD_LIBRARY_PATH or DYLD_LIBRARY_PATH)
  native/<library>.warp    the manifest without its `= rust` parts: plain foreign lines and warp words (`use <library>`)
Nothing in the native warp knows a crate. Commands:
  warp-crate build <manifest.warp>...   generate, build (cached) and install; prints the library and native file
  warp-crate source <manifest.warp>     print the generated Rust
  warp-crate wasm <manifest.warp> [out] the crate as a WebAssembly module for `use cargo <crate>`, natively and in the
                                        page (decision cargo-semver-version): free functions on numbers, bool and text,
                                        its warp words in a warp.words section (notes/wasm_words.md); default out
                                        lib/crates/<crate>.wasm
  warp-crate scan <crate@version>       draft manifest lines for the crate's public functions, methods, Default
                                        constructors and public fields (rustdoc JSON)
A config struct (card use-cargo-config-structs) crosses as a handle: `= crate::Config::default` makes one (any path call),
`= crate::Config.width` reads its public field, `= crate::Config.width=` sets it from the line's second parameter, and a
parameter `clone(crate::Config)` hands an item the handle's value by value (a clone, the handle stays the caller's).
  warp-crate dirs                       print the cache, library and native folders
Precompiled crates (card precompiled-crates, notes/crate_adapter.md "Plan: precompiled crates"), so `use rs_regex`
works without cargo: CI (.github/workflows/crates.yml) builds lib/crates/*.warp per target and publishes the libraries
with the index crates.json as assets of the release `crates`; a shipped build's key leaves the toolchain out (only the C
ABI crosses).
  warp-crate fetch <name>...            the shipped build of lib/crates/<name>.warp (name `regex` or `rs_regex`) for
                                        this target: downloaded, sha256 checked, installed as `build` installs; a
                                        local build where none is shipped and cargo is there
  warp-crate publish <dir> <manifest.warp>...  build and put each library and native file in <dir>, with its index
                                        entries for this target, crates-<target>.json
  warp-crate index <dir>                merge <dir>/crates-*.json into the index <dir>/crates.json
WARP_CRATES_URL names where fetch finds the index and the files (default the release `crates` of pannous/warp).
"""
import hashlib, json, os, platform, re, shutil, subprocess, sys, urllib.request
from pathlib import Path

GENERATOR_VERSION = "1"
HERE = Path(__file__).resolve().parent
RUNTIME = HERE / "crate_adapter" / "runtime.rs"
CACHE = Path.home() / ".cache" / "warp" / "crates"  # the native warp looks there too (extensions/c_imports crates_cache)
LIB_DIR, NATIVE_DIR, TARGET_DIR = CACHE / "lib", CACHE / "native", CACHE / "target"
DYLIB = ("lib", ".dylib") if sys.platform == "darwin" else ("lib", ".so")
MANIFESTS = HERE.parent / "lib" / "crates"
RELEASE_URL = os.environ.get("WARP_CRATES_URL", "https://github.com/pannous/warp/releases/download/crates")
INDEX = "crates.json"
# this machine's target triple, known without rustc (fetch runs where there is none); the targets CI builds
TARGETS = {("linux", "x86_64"): "x86_64-unknown-linux-gnu", ("linux", "aarch64"): "aarch64-unknown-linux-gnu",
	("linux", "arm64"): "aarch64-unknown-linux-gnu", ("darwin", "arm64"): "aarch64-apple-darwin",
	("darwin", "x86_64"): "x86_64-apple-darwin"}

# a manifest type → [the foreign line's type, the C parameter type, the C result type]
BYTES = ("bytes", "bytes_vec")
NUMBERS = {"i32": "i32", "int": "i32", "i64": "i64", "long": "i64", "f64": "f64", "float": "f64", "f32": "f32"}
FOREIGN = re.compile(r"^\s*(?P<name>\w+)\s*\((?P<params>(?:[^()]|\([^()]*\))*)\)\s*:\s*(?P<result>[\w:()]+)\s+from\s+'(?P<library>\w+)'\s*=\s*(?P<rust>\S.*?)\s*$")
SETTING = re.compile(r'^\s*(crate|library|features|default_features|uses)\s*:\s*(.*?)\s*$')
HANDLE = re.compile(r"^handle(?:\((?P<rust>[\w:<>, ]+)\))?$")
CLONE = re.compile(r"^clone\((?P<rust>[\w:<>, ]+)\)$")  # a handle whose value an item takes by value: a clone of it
FIELD = re.compile(r"^(?P<owner>(?:\w+::)*[A-Z]\w*)\.(?P<field>\w+)(?P<set>=?)$")  # crate::Config.width, .width= to set
STEP = re.compile(r"(\?\.|\*\.|\.)(\w+)")
# what a crate built as a WebAssembly module crosses (warp-crate wasm, notes/wasm_words.md)
WASM_CROSSED = (*NUMBERS, "bool", "text", "string", "void")
WASM_TARGET = "wasm32-unknown-unknown"
WORDS_SECTION = "warp.words"


def fail(message):
	sys.exit(f"warp-crate: {message}")


def top_level_split(text):
	"""`a: i64, b: handle(x::Map<K, V>)` → its parameters, at the commas outside brackets"""
	parts, depth, current = [], 0, ""
	for letter in text:
		depth += letter in "(<[" and 1 or (letter in ")>]" and -1 or 0)
		if letter == "," and depth == 0:
			parts.append(current)
			current = ""
		else:
			current += letter
	return parts + [current]


class Function:
	def __init__(self, line_number, name, params, result, library, rust):
		self.line_number, self.name, self.library = line_number, name, library
		self.params = []  # [(name, type)]
		for written in [p for p in top_level_split(params) if p.strip()]:
			if ":" not in written:
				fail(f"line {line_number}: the parameter {written.strip()!r} of {name} has no type")
			pname, ptype = (part.strip() for part in written.split(":", 1))
			self.params.append((pname, ptype))
		self.result = result
		self.rust = rust.strip()

	def wasm_check(self):
		for written in [t for _, t in self.params] + [self.result]:
			if written not in WASM_CROSSED:
				fail(f"line {self.line_number}: {self.name}: a WebAssembly module crosses numbers, bool and text, not {written!r} "
					"(objects wait for a handle design, decision samples-modules-wasm)")

	def wasm_rust(self, lib):
		"""the raw export <lib>__<name>: a text parameter as its bytes' place and length in the module's memory, a text
		result as one i64 (place << 32 | length)"""
		self.wasm_check()
		params, args = [], []
		for pname, ptype in self.params:
			if ptype in NUMBERS:
				params.append(f"p_{pname}: {NUMBERS[ptype]}")
				args.append(f"p_{pname} as _")
			elif ptype == "bool":
				params.append(f"p_{pname}: i32")
				args.append(f"p_{pname} != 0")
			else:
				params.append(f"p_{pname}_at: i32, p_{pname}_length: i32")
				args.append(f"text_in(p_{pname}_at, p_{pname}_length)" + (".to_string()" if ptype == "string" else ""))
		call = f"{self.rust}({', '.join(args)})"
		results = {"bool": ("i32", f"{call} as i32"), "void": ("()", call)}
		returns, body = results.get(self.result) or ((NUMBERS[self.result], f"{call} as _") if self.result in NUMBERS else ("i64", f"text_out({call})"))
		arrow = "" if returns == "()" else f" -> {returns}"
		return f"#[no_mangle]\npub unsafe extern \"C\" fn {lib}__{self.name}({', '.join(params)}){arrow} {{\n\t{body}\n}}"

	def warp_word(self, lib):
		"""the warp word over the raw export, one line: texts copied in and out through the module's memory"""
		warp_types = {"bool": "bool", "void": "nothing", "text": "text", "string": "text"}
		params = ", ".join(f"{n}: {warp_types.get(t, 'float' if t in ('f32', 'f64', 'float') else 'int')}" for n, t in self.params)
		args = ", ".join(f"{lib}__text_in({n}), byte_size({n})" if t in ("text", "string") else n for n, t in self.params)
		call = f"{lib}__{self.name}({args})"
		body = f"{lib}__text_out({call})" if self.result in ("text", "string") else f"{call} != 0" if self.result == "bool" else call
		return f"{self.name}({params}): {warp_types.get(self.result, 'float' if self.result in ('f32', 'f64', 'float') else 'int')} := {body}"

	def foreign_type(self, written):
		if written in NUMBERS:
			return NUMBERS[written]
		if written in ("bool", "text", "void"):
			return written
		if written in ("hex", "string"):
			return "text"
		if written in BYTES:
			return "bytes"
		if written == "list" or HANDLE.match(written) or CLONE.match(written):
			return "handle"
		fail(f"line {self.line_number}: {self.name}: the type {written!r} is not one warp-crate crosses "
			"(i32 i64 f32 f64 bool text string bytes bytes_vec hex list handle handle(rust::Type) clone(rust::Type) void)")

	def wrapped(self):
		"""Whether the result comes back through a handle the shim keeps (a list, bytes): then the C function is
		<name>_handle and a warp word <name> reads the handle into a warp list and frees it"""
		return self.result in ("list", "bytes")

	def c_name(self):
		return f"{self.name}_handle" if self.wrapped() else self.name

	def foreign_line(self):
		params = []
		for n, t in self.params:
			params.append(f"{n}: {self.foreign_type(t)}")
			if t in BYTES:
				params.append(f"{n}_size: length")
		result = "handle" if self.wrapped() else self.foreign_type(self.result)
		return f"{self.c_name()}({', '.join(params)}): {result} from '{self.library}'"

	def native_lines(self):
		"""The foreign line, and for a handle-wrapped result the warp word over it"""
		lines = [self.foreign_line()]
		if self.wrapped():
			warp_types = {"text": "text", "string": "text", "i32": "int", "int": "int", "i64": "int", "long": "int",
				"f32": "float", "f64": "float", "float": "float"}
			params = ", ".join(f"{n}: {warp_types.get(t, 'int' if HANDLE.match(t) else 'any')}" for n, t in self.params)
			args = ", ".join(n for n, _ in self.params)
			take = "texts" if self.result == "list" else "bytes"
			lines.append(f"{self.name}({params}) := {self.library}_take_{take}({self.c_name()}({args}))")
		return lines

	def field(self):
		"""(owner, field, sets) of a field item: `crate::Config.width` reads the field, `crate::Config.width=` sets it"""
		found = FIELD.match(self.rust)
		return (found.group("owner"), found.group("field"), found.group("set") == "=") if found else None

	def owner(self):
		"""`regex::Regex` of the path `regex::Regex::is_match` (or the field `crate::Config.width`), when that names a type's method"""
		if self.field():
			return self.field()[0]
		path = re.split(r"(?=\?\.|\*\.|\.\w)", self.rust, maxsplit=1)[0]
		segments = path.split("::")
		return "::".join(segments[:-1]) if len(segments) > 1 and segments[-2][:1].isupper() else None

	def handle_type(self, index, written):
		found = HANDLE.match(written)
		if found and found.group("rust"):
			return found.group("rust")
		if index == 0 and self.owner():
			return self.owner()
		fail(f"line {self.line_number}: {self.name}: say the Rust type of the handle {written!r}: handle(crate::Type)")

	def rust_source(self):
		c_params, lets, args = [], [], []
		for index, (pname, ptype) in enumerate(self.params):
			var = f"p_{pname}"
			if ptype in NUMBERS:
				c_params.append(f"{var}: {NUMBERS[ptype]}")
				args.append(f"{var} as _")
			elif ptype == "bool":
				c_params.append(f"{var}: i32")
				args.append(f"{var} != 0")
			elif ptype in ("text", "string"):
				c_params.append(f"{var}: *const c_char")
				args.append(f"text_in({var})" + (".to_string()" if ptype == "string" else ""))
			elif ptype in BYTES:
				c_params.append(f"{var}: *const u8, {var}_size: usize")
				args.append(f"bytes_in({var}, {var}_size)" + (".to_vec()" if ptype == "bytes_vec" else ""))
			elif CLONE.match(ptype):
				rust_type = CLONE.match(ptype).group("rust")
				c_params.append(f"{var}: *mut {rust_type}")
				lets.append(f"let {var} = handle_in({var}, {json.dumps(self.name)})?.clone();")
				args.append(var)
			elif HANDLE.match(ptype):
				rust_type = self.handle_type(index, ptype)
				c_params.append(f"{var}: *mut {rust_type}")
				if self.rust == "drop":
					args.append(var)
				else:
					lets.append(f"let {var} = handle_in({var}, {json.dumps(self.name)})?;")
					args.append(var)
			else:
				fail(f"line {self.line_number}: {self.name}: a parameter of type {ptype!r} is not crossed")
		result = self.result
		if self.rust == "drop":
			if len(self.params) != 1 or not HANDLE.match(self.params[0][1]):
				fail(f"line {self.line_number}: {self.name}: `= drop` takes one handle")
			body = f"if !p_{self.params[0][0]}.is_null() {{ drop(Box::from_raw(p_{self.params[0][0]})) }}; Some(())"
			c_result = "()"
		elif self.field() and self.field()[2]:
			_, field, _ = self.field()
			if len(self.params) != 2 or not HANDLE.match(self.params[0][1]) or result != "void":
				fail(f"line {self.line_number}: {self.name}: a field setter `= Type.{field}=` takes the handle and the value, and gives void")
			value = f"{args[1]}.into()" if CLONE.match(self.params[1][1]) else f"FieldIn::field_in({args[1].removesuffix(' as _')})"
			body = f"p_{self.params[0][0]}.{field} = {value}; Some(())"
			c_result = "()"
		else:
			path, *_ = re.split(r"(?=\?\.|\*\.|\.\w)", self.rust, maxsplit=1)
			expression = f"{path}({', '.join(args)})"
			if self.field():
				if len(self.params) != 1 or not HANDLE.match(self.params[0][1]):
					fail(f"line {self.line_number}: {self.name}: a field `= Type.{self.field()[1]}` takes the one handle it reads")
				path, expression = self.rust, f"{args[0]}.{self.field()[1]}.clone()"
			for kind, method in STEP.findall(self.rust[len(path):]):
				expression += {"?.": f".map(|v| v.{method}())", "*.": f".into_iter().map(|v| v.{method}())", ".": f".{method}()"}[kind]
			if result in NUMBERS or result == "bool":
				c_result = NUMBERS.get(result, "bool")
				body = f"Some(<_ as Out<{c_result}>>::out({expression}))"
			elif result in ("text", "string"):
				c_result = "*const c_char"
				body = f"Some(<_ as Out<*const c_char>>::out({expression}))"
			elif result == "hex":
				c_result = "*const c_char"
				body = f"Some(hex_out({expression}))"
			elif result == "list":
				c_result = "*mut TextList"
				body = f"Some(list_out({expression}))"
			elif result == "bytes":
				c_result = "*mut ByteList"
				body = f"Some(bytes_out({expression}))"
			elif HANDLE.match(result):
				rust_type = HANDLE.match(result).group("rust") or self.owner()
				if not rust_type:
					fail(f"line {self.line_number}: {self.name}: say the Rust type of the handle result: handle(crate::Type)")
				c_result = f"*mut {rust_type}"
				body = f"Some(<_ as HandleOut<{rust_type}>>::handle_out({expression}))"
			elif result == "void":
				c_result = "()"
				body = f"Some(<_ as Out<()>>::out({expression}))"
			else:
				fail(f"line {self.line_number}: {self.name}: a result of type {result!r} is not crossed")
		returns = "" if c_result == "()" else f" -> {c_result}"
		lines = [f"/// {self.foreign_line()} = {self.rust}", "#[no_mangle]",
			f"pub unsafe extern \"C\" fn {self.c_name()}({', '.join(c_params)}){returns} {{",
			f"\tguarded(|| {{"] + [f"\t\t{line}" for line in lets] + [f"\t\t{body}", "\t})", "}"]
		return "\n".join(lines)


class Manifest:
	def __init__(self, path):
		self.path = Path(path)
		self.text = self.path.read_text()
		self.settings = {"features": "", "default_features": "yes", "uses": ""}
		self.functions, self.native_lines = [], []
		for number, line in enumerate(self.text.splitlines(), 1):
			setting, foreign = SETTING.match(line), FOREIGN.match(line)
			if setting:
				self.settings[setting.group(1)] = setting.group(2).strip().strip('"').strip("'")
				self.native_lines.append(f"// {line.strip()}")
			elif foreign:
				function = Function(number, **foreign.groupdict())
				self.functions.append(function)
				self.native_lines += function.native_lines()
			elif re.search(r"\bfrom\s+'\w+'\s*=", line) and not line.lstrip().startswith("//"):
				fail(f"{path}:{number}: not a foreign line warp-crate reads: {line.strip()}")
			else:
				self.native_lines.append(line)
		if "crate" not in self.settings:
			fail(f"{path}: no `crate: \"name@version\"` line")
		self.crate, _, self.version = self.settings["crate"].partition("@")
		self.version = self.version or "*"
		self.library = self.settings.get("library") or "rs_" + self.crate.replace("-", "_")
		for function in self.functions:
			if function.library != self.library:
				fail(f"line {function.line_number}: {function.name} is from '{function.library}', the manifest's library is '{self.library}'")
		self.native_lines += self.helper_lines()

	def helper_lines(self):
		lib = self.library
		return ["", f"// generated by scripts/warp-crate for every crate library: the last failure, lists of texts",
			f"{lib}_last_error(): text from '{lib}'", f"{lib}_list_count(list: handle): i64 from '{lib}'",
			f"{lib}_list_text(list: handle, index: i64): text from '{lib}'", f"{lib}_list_free(list: handle): void from '{lib}'",
			f"{lib}_bytes_count(bytes: handle): i64 from '{lib}'", f"{lib}_bytes_at(bytes: handle, index: i64): i32 from '{lib}'",
			f"{lib}_bytes_free(bytes: handle): void from '{lib}'",
			"// a list or bytes result the shim kept as a handle: a warp list, the handle freed",
			f"{lib}_take_texts(list: int) := {{",
			"\tfound = []", "\ti = 0", f"\twhile i < {lib}_list_count(list) {{", f"\t\tfound += [{lib}_list_text(list, i)]", "\t\ti += 1", "\t}",
			f"\t{lib}_list_free(list)", "\tfound", "}",
			f"{lib}_take_bytes(bytes: int) := {{",
			"\tfound = []", "\ti = 0", f"\twhile i < {lib}_bytes_count(bytes) {{", f"\t\tfound += [{lib}_bytes_at(bytes, i)]", "\t\ti += 1", "\t}",
			f"\t{lib}_bytes_free(bytes)", "\tfound", "}"]

	def rust_source(self):
		lib = self.library
		uses = [u.strip() for u in self.settings["uses"].split(",") if u.strip()]
		parts = [f"// Generated by scripts/warp-crate from {self.path.name} ({self.crate} {self.version}); do not edit.",
			RUNTIME.read_text()] + [f"#[allow(unused_imports)]\nuse {u};" for u in uses]
		parts += [function.rust_source() for function in self.functions]
		parts.append(f"""#[no_mangle]
pub unsafe extern "C" fn {lib}_last_error() -> *const c_char {{
	last_error()
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_list_count(list: *mut TextList) -> i64 {{
	list.as_ref().map_or(-1, |list| list.0.len() as i64)
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_list_text(list: *mut TextList, index: i64) -> *const c_char {{
	match list.as_ref().and_then(|list| usize::try_from(index).ok().and_then(|i| list.0.get(i))) {{
		Some(text) => keep_text(text),
		None => std::ptr::null(),
	}}
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_list_free(list: *mut TextList) {{
	if !list.is_null() {{
		drop(Box::from_raw(list))
	}}
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_bytes_count(bytes: *mut ByteList) -> i64 {{
	bytes.as_ref().map_or(-1, |bytes| bytes.0.len() as i64)
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_bytes_at(bytes: *mut ByteList, index: i64) -> i32 {{
	bytes.as_ref().and_then(|bytes| usize::try_from(index).ok().and_then(|i| bytes.0.get(i))).map_or(-1, |byte| i32::from(*byte))
}}
#[no_mangle]
pub unsafe extern "C" fn {lib}_bytes_free(bytes: *mut ByteList) {{
	if !bytes.is_null() {{
		drop(Box::from_raw(bytes))
	}}
}}""")
		return "\n\n".join(parts) + "\n"

	def wasm_words(self):
		"""the warp.words section: the module's words in warp, over its raw exports (notes/wasm_words.md)"""
		lib = self.library
		return "\n".join([f"// {self.crate}'s words (scripts/warp-crate wasm {self.path.name}): texts cross through its memory",
			f"{lib}__text_in(t: text): int := {{ codes = t.bytes; at = {lib}__alloc(#codes); for i in 0 ..< #codes {{ {lib}__store(at + i, codes[i]) }}; at }}",
			f"{lib}__text_out(packed: int): text := {{ at = packed >> 32; from_utf8([{lib}__load(at + i) for i in 0 ..< packed % 4294967296]) }}"]
			+ [function.warp_word(lib) for function in self.functions]) + "\n"

	def wasm_rust_source(self):
		lib = self.library
		words = self.wasm_words().encode()
		uses = [u.strip() for u in self.settings["uses"].split(",") if u.strip()]
		return "\n".join([f"// Generated by scripts/warp-crate wasm from {self.path.name} ({self.crate} {self.version}); do not edit.",
			"#![allow(clippy::missing_safety_doc)]"] + [f"#[allow(unused_imports)]\nuse {u};" for u in uses] + [
			"// the module's memory as the warp words reach it: room for a text, a byte written, a byte read",
			f"#[no_mangle]\npub extern \"C\" fn {lib}__alloc(length: i32) -> i32 {{\n\tBox::leak(vec![0u8; length.max(1) as usize].into_boxed_slice()).as_mut_ptr() as i32\n}}",
			f"#[no_mangle]\npub unsafe extern \"C\" fn {lib}__store(at: i32, byte: i32) {{\n\t*(at as *mut u8) = byte as u8\n}}",
			f"#[no_mangle]\npub unsafe extern \"C\" fn {lib}__load(at: i32) -> i32 {{\n\t*(at as *const u8) as i32\n}}",
			"#[allow(dead_code)]\nunsafe fn text_in(at: i32, length: i32) -> &'static str {\n\tstd::str::from_utf8_unchecked(std::slice::from_raw_parts(at as *const u8, length as usize))\n}",
			"#[allow(dead_code)]\nfn text_out(text: impl AsRef<str>) -> i64 {\n\tlet bytes = Box::leak(text.as_ref().as_bytes().to_vec().into_boxed_slice());\n\t((bytes.as_ptr() as i64) << 32) | bytes.len() as i64\n}"]
			+ [function.wasm_rust(lib) for function in self.functions]
			+ [f"#[link_section = \"{WORDS_SECTION}\"]\n#[used]\nstatic WARP_WORDS: [u8; {len(words)}] = [{', '.join(map(str, words))}];"]) + "\n"

	def cargo_toml(self):
		features = [f.strip() for f in self.settings["features"].split(",") if f.strip()]
		dependency = {"version": self.version}
		if features:
			dependency["features"] = features
		if self.settings["default_features"] in ("no", "false"):
			dependency["default-features"] = False
		inline = ", ".join(f"{k} = {json.dumps(v).lower() if isinstance(v, bool) else json.dumps(v)}" for k, v in dependency.items())
		return f"""[package]
name = "{self.library}"
version = "0.0.0"
edition = "2021"
publish = false

[lib]
name = "{self.library}"
path = "lib.rs"
crate-type = ["cdylib"]

[dependencies]
{self.crate} = {{ {inline} }}

[profile.release]
opt-level = 3
panic = "unwind"
strip = true

[workspace]
"""


def toolchain():
	return subprocess.run(["rustc", "-vV"], capture_output=True, text=True, check=True).stdout


def target():
	machine = platform.machine().lower()
	found = TARGETS.get((sys.platform.replace("linux2", "linux"), "x86_64" if machine == "amd64" else machine))
	return found or fail(f"no shipped crates for {sys.platform} {machine}: build them with cargo (warp-crate build)")


def shipped_key(manifest):
	"""a shipped build's key: generator, manifest (its source and Cargo.toml: crate, version, features) and target"""
	source, cargo = manifest.rust_source(), manifest.cargo_toml()
	return hashlib.sha256("\0".join([GENERATOR_VERSION, source, cargo, target()]).encode()).hexdigest()[:16]


def built(manifest):
	"""the cache entry holding the manifest's library, built with cargo once: [entry, library file]"""
	source, cargo = manifest.rust_source(), manifest.cargo_toml()
	key = hashlib.sha256("\0".join([GENERATOR_VERSION, source, cargo, toolchain()]).encode()).hexdigest()[:16]
	entry = CACHE / manifest.library / f"{manifest.crate}-{manifest.version.replace('*', 'any')}-{key}"
	library_file = DYLIB[0] + manifest.library + DYLIB[1]
	if not (entry / library_file).exists():
		entry.mkdir(parents=True, exist_ok=True)
		(entry / "lib.rs").write_text(source)
		(entry / "Cargo.toml").write_text(cargo)
		env = dict(os.environ, CARGO_TARGET_DIR=str(TARGET_DIR), CARGO_NET_OFFLINE=os.environ.get("CARGO_NET_OFFLINE", "false"))
		print(f"warp-crate: building {manifest.crate} {manifest.version} as {manifest.library} ({entry})", file=sys.stderr)
		done = subprocess.run(["cargo", "build", "--release", "--quiet", "--manifest-path", str(entry / "Cargo.toml")], env=env)
		if done.returncode != 0:
			fail(f"cargo could not build {manifest.library} from {manifest.path} (its source: {entry / 'lib.rs'})")
		shutil.copy2(TARGET_DIR / "release" / library_file, entry / library_file)
		locked = (entry / "Cargo.lock").read_text() if (entry / "Cargo.lock").exists() else ""
		resolved = re.search(rf'name = "{re.escape(manifest.crate)}"\nversion = "([^"]+)"', locked)
		(entry / "resolved").write_text((resolved.group(1) if resolved else "?") + "\n")
	return entry, library_file


def native_text(manifest, resolved):
	return f"// Generated by scripts/warp-crate from {manifest.path.name}: {manifest.crate} {resolved} as lib{manifest.library}\n" + "\n".join(manifest.native_lines).rstrip() + "\n"


def installed(library, library_file, native):
	"""the library and the native file put where the native warp finds them; prints both"""
	LIB_DIR.mkdir(parents=True, exist_ok=True)
	NATIVE_DIR.mkdir(parents=True, exist_ok=True)
	placed = LIB_DIR / library_file
	temporary = placed.with_suffix(".tmp")
	shutil.copy2(library, temporary)
	os.replace(temporary, placed)  # a running the native warp keeps its mapped copy
	native_file = NATIVE_DIR / native.name
	shutil.copy2(native, native_file)
	print(f"{placed}\n{native_file}")


def wasm_built(manifest, out):
	"""the crate as a WebAssembly core module with its warp.words section (`use cargo <crate>`), built once into the cache,
	copied to out (default lib/crates/<crate>.wasm, which `use cargo` finds beside the manifest)"""
	source, cargo = manifest.wasm_rust_source(), manifest.cargo_toml()
	key = hashlib.sha256("\0".join([GENERATOR_VERSION, WASM_TARGET, source, cargo, toolchain()]).encode()).hexdigest()[:16]
	entry = CACHE / "wasm" / f"{manifest.crate}-{manifest.version.replace('*', 'any')}-{key}"
	module = entry / f"{manifest.crate}.wasm"
	if not module.exists():
		entry.mkdir(parents=True, exist_ok=True)
		(entry / "lib.rs").write_text(source)
		(entry / "Cargo.toml").write_text(cargo)
		env = dict(os.environ, CARGO_TARGET_DIR=str(TARGET_DIR), CARGO_NET_OFFLINE=os.environ.get("CARGO_NET_OFFLINE", "false"))
		print(f"warp-crate: building {manifest.crate} {manifest.version} for {WASM_TARGET} ({entry})", file=sys.stderr)
		done = subprocess.run(["cargo", "build", "--release", "--quiet", "--target", WASM_TARGET, "--manifest-path", str(entry / "Cargo.toml")], env=env)
		if done.returncode != 0:
			fail(f"cargo could not build {manifest.crate} for {WASM_TARGET} from {manifest.path} (its source: {entry / 'lib.rs'}; rustup target add {WASM_TARGET})")
		shutil.copy2(TARGET_DIR / WASM_TARGET / "release" / f"{manifest.library}.wasm", module)
	out = Path(out) if out else manifest.path.with_name(f"{manifest.crate}.wasm")
	shutil.copy2(module, out)
	print(out)


def build(manifest):
	entry, library_file = built(manifest)
	native = entry / f"{manifest.library}.warp"
	native.write_text(native_text(manifest, (entry / "resolved").read_text().strip()))
	installed(entry / library_file, library_file, native)


def sha256_of(path):
	return hashlib.sha256(Path(path).read_bytes()).hexdigest()


def publish(folder, manifests):
	"""each manifest built, its library (named for the target) and native file in the folder, and the target's index
	entries beside them, which `index` merges"""
	folder = Path(folder)
	folder.mkdir(parents=True, exist_ok=True)
	entries = []
	for manifest in manifests:
		entry, library_file = built(manifest)
		resolved = (entry / "resolved").read_text().strip()
		shipped = f"{manifest.library}-{target()}{DYLIB[1]}"
		shutil.copy2(entry / library_file, folder / shipped)
		# per target too: each target's build resolves the crate on its own
		native = folder / f"{manifest.library}-{target()}.warp"
		native.write_text(native_text(manifest, resolved))
		entries.append({"name": manifest.path.stem, "library": manifest.library, "crate": manifest.crate, "version": resolved,
			"key": shipped_key(manifest), "target": target(), "file": shipped, "sha256": sha256_of(folder / shipped),
			"native": native.name, "native_sha256": sha256_of(native)})
	(folder / f"crates-{target()}.json").write_text(json.dumps(entries, indent=1) + "\n")
	print(folder / f"crates-{target()}.json")


def index(folder):
	"""the targets' entries in one index, crates.json, sorted so a merge of the same builds is the same file"""
	folder = Path(folder)
	entries = [entry for part in sorted(folder.glob("crates-*.json")) for entry in json.loads(part.read_text())]
	entries.sort(key=lambda entry: (entry["name"], entry["target"]))
	(folder / INDEX).write_text(json.dumps({"generator": GENERATOR_VERSION, "crates": entries}, indent=1) + "\n")
	print(folder / INDEX)


def downloaded(name, expected_sha256):
	"""a file of the release, checked against its sha256; ø where it can't be had"""
	try:
		with urllib.request.urlopen(f"{RELEASE_URL}/{name}", timeout=60) as response:
			data = response.read()
	except OSError as error:
		print(f"warp-crate: could not download {RELEASE_URL}/{name}: {error}", file=sys.stderr)
		return None
	if expected_sha256 is not None and hashlib.sha256(data).hexdigest() != expected_sha256:
		fail(f"{RELEASE_URL}/{name} is not the file the index names (sha256 {hashlib.sha256(data).hexdigest()}, expected {expected_sha256})")
	return data


def manifest_named(name):
	"""lib/crates/<name>.warp, by its file name (`regex`) or its library (`rs_regex`)"""
	for path in sorted(MANIFESTS.glob("*.warp")):
		manifest = Manifest(path)
		if name in (path.stem, manifest.library):
			return manifest
	fail(f"no crate manifest {name} in {MANIFESTS}")


def fetch(name):
	"""the shipped build of the manifest for this target, else a local build where cargo is there"""
	manifest = manifest_named(name)
	key, here = shipped_key(manifest), target()
	listed = downloaded(INDEX, None)
	shipped = [entry for entry in json.loads(listed)["crates"] if entry["library"] == manifest.library and entry["target"] == here] if listed else []
	matching = [entry for entry in shipped if entry["key"] == key]
	if matching:
		entry = matching[0]
		folder = CACHE / manifest.library / f"shipped-{key}"
		folder.mkdir(parents=True, exist_ok=True)
		library = downloaded(entry["file"], entry["sha256"])
		native = downloaded(entry["native"], entry["native_sha256"])
		if library is not None and native is not None:
			library_file = DYLIB[0] + manifest.library + DYLIB[1]
			(folder / library_file).write_bytes(library)
			(folder / f"{manifest.library}.warp").write_bytes(native)
			return installed(folder / library_file, library_file, folder / f"{manifest.library}.warp")
	why = "is not shipped" if not shipped else ("is shipped for another version of its manifest" if not matching else "could not be downloaded")
	if shutil.which("cargo"):
		print(f"warp-crate: {manifest.library} for {here} {why}: building it with cargo", file=sys.stderr)
		return build(manifest)
	fail(f"{manifest.library} ({manifest.crate}) for {here} {why}, and there is no cargo to build it")


# ---------- scan: draft manifest lines from rustdoc JSON ----------
PRIMITIVES = {"i8": "i32", "i16": "i32", "i32": "i32", "u8": "i32", "u16": "i32", "u32": "i64", "i64": "i64", "u64": "i64",
	"isize": "i64", "usize": "i64", "f32": "f32", "f64": "f64", "bool": "bool", "char": "i32"}


# words warp reads as its own, renamed when rustdoc gives them as parameter names
WARP_WORDS = {"match", "if", "then", "else", "while", "for", "in", "is", "as", "not", "and", "or", "use", "import", "return", "it"}


def scan(spec):
	crate, _, version = spec.partition("@")
	work = CACHE / "scan" / f"{crate}-{version or 'any'}"
	work.mkdir(parents=True, exist_ok=True)
	(work / "Cargo.toml").write_text(f'[package]\nname = "scan"\nversion = "0.0.0"\nedition = "2021"\n[lib]\npath = "lib.rs"\n[dependencies]\n{crate} = "{version or "*"}"\n[workspace]\n')
	(work / "lib.rs").write_text("")
	env = dict(os.environ, CARGO_TARGET_DIR=str(TARGET_DIR), RUSTC_BOOTSTRAP="1", CARGO_NET_OFFLINE=os.environ.get("CARGO_NET_OFFLINE", "false"))
	done = subprocess.run(["cargo", "rustdoc", "--quiet", "-p", crate, "--lib", "--manifest-path", str(work / "Cargo.toml"),
		"--", "-Z", "unstable-options", "--output-format", "json"], env=env)
	if done.returncode != 0:
		fail(f"rustdoc could not describe {spec}")
	doc = json.loads((TARGET_DIR / "doc" / f"{crate.replace('-', '_')}.json").read_text())
	index, library = doc["index"], "rs_" + crate.replace("-", "_")
	prefix = crate.replace("-", "_")
	print(f'crate: "{crate}@{version or "*"}"')

	def mapped(ty, owner, is_result, field=False):
		"""the manifest type of a Rust type, None when it does not cross; a field's (field) also as an Option of it and,
		read, a struct as a handle of its clone"""
		if not isinstance(ty, dict):
			return None
		if "primitive" in ty:
			return PRIMITIVES.get(ty["primitive"])
		if "borrowed_ref" in ty:
			inner = ty["borrowed_ref"]["type"]
			if inner == {"primitive": "str"}:
				return "text"
			if "slice" in inner and inner["slice"] == {"primitive": "u8"}:
				return "bytes"
			if inner == {"generic": "Self"} and not is_result:
				return "handle"
			named = inner.get("resolved_path") if isinstance(inner, dict) else None
			if named and not is_result and not named.get("args", {}) and (named.get("path") or "")[:1].isupper():
				return f"handle({prefix}::{named['path'].split('::')[-1]})"
			return None
		if ty == {"generic": "Self"}:
			# a method taking self by value (a builder's) takes a clone of the handle's value
			return f"handle({owner})" if is_result else (f"clone({owner})" if owner else None)
		path = ty.get("resolved_path")
		if path:
			name = path.get("path") or path.get("name", "")
			last = name.split("::")[-1]
			args = ((path.get("args") or {}).get("angle_bracketed") or {}).get("args", [])
			first = args[0].get("type") if args and isinstance(args[0], dict) else None
			if last == "String":
				return "text"
			if last == "Vec" and first == {"primitive": "u8"}:
				return "bytes" if is_result else "bytes_vec"
			if last in ("Option", "Result") and first is not None:
				return mapped(first, owner, is_result, field) if is_result or (field and last == "Option") else None
			if is_result and owner and last == owner.split("::")[-1]:
				return f"handle({owner})"
			if is_result and field and not args and last[:1].isupper():
				return f"handle({prefix}::{last})"
			# a struct by value (a config handed to a constructor): a clone of a handle's value
			if not is_result and not args and last[:1].isupper():
				return f"clone({prefix}::{last})"
		return None

	def line(name, function, rust_path, owner):
		sig = function["sig"] if "sig" in function else function["decl"]
		params, cross = [], True
		for pname, ptype in sig["inputs"]:
			mapped_type = mapped(ptype, owner, False)
			if mapped_type is None or (function.get("generics", {}).get("params") and mapped_type != "handle"):
				cross = mapped_type is not None and cross
			own = (owner or "it").split("::")[-1].lower()
			pname = pname + "_" if pname in WARP_WORDS else pname
			params.append(f"{own if pname == 'self' else pname}: {mapped_type or '?'}")
			cross = cross and mapped_type is not None
		output = sig.get("output")
		result = "void" if output is None else mapped(output, owner, True)
		text = f"{name}({', '.join(params)}): {result or '?'} from '{library}' = {rust_path}"
		print(text if cross and result else f"// skipped: {text}")

	def fields(name, struct, owner):
		"""a getter and a setter line for each public field of a plain struct (a config struct's)"""
		plain = struct.get("kind", {}).get("plain", {}) if isinstance(struct.get("kind"), dict) else {}
		own = name.lower()
		for field_id in plain.get("fields", []):
			field = index.get(str(field_id))
			if not field or field.get("visibility") != "public" or "struct_field" not in field["inner"]:
				continue
			fname, ftype = field["name"], field["inner"]["struct_field"]
			getter, setter = mapped(ftype, owner, True, True), mapped(ftype, owner, False, True)
			get_line = f"{own}_{fname}({own}: handle): {getter or '?'} from '{library}' = {owner}.{fname}"
			set_line = f"{own}_set_{fname}({own}: handle, {fname}: {setter or '?'}): void from '{library}' = {owner}.{fname}="
			print(get_line if getter and getter not in ("bytes",) else f"// skipped: {get_line}")
			print(set_line if setter else f"// skipped: {set_line}")

	def implements(struct, trait):
		for impl_id in struct.get("impls", []):
			found = (index.get(str(impl_id), {}).get("inner", {}).get("impl", {}).get("trait") or {})
			if (found.get("path") or found.get("name") or "").split("::")[-1] == trait:
				return True
		return False

	def public_items(module_id, seen):
		"""(name, item) of a module's public items, through `pub use` re-exports and globs"""
		if module_id in seen:
			return
		seen.add(module_id)
		for item_id in index[str(module_id)]["inner"]["module"]["items"]:
			item = index.get(str(item_id))
			if not item or item.get("visibility") != "public":
				continue
			used = item["inner"].get("use")
			if used:
				target = index.get(str(used.get("id")))
				if target is None:
					continue
				if used.get("is_glob") and "module" in target["inner"]:
					yield from public_items(used["id"], seen)
				elif not used.get("is_glob"):
					yield used["name"], target
			else:
				yield item["name"], item

	for name, item in public_items(doc["root"], set()):
		inner = item["inner"]
		if "function" in inner:
			line(name, inner["function"], f"{prefix}::{name}", None)
		if "struct" in inner and not inner["struct"].get("generics", {}).get("params"):
			owner = f"{prefix}::{name}"
			print(f"{name.lower()}_free({name.lower()}: handle({owner})): void from '{library}' = drop")
			if implements(inner["struct"], "Default"):
				print(f"{name.lower()}_default(): handle({owner}) from '{library}' = {owner}::default")
			fields(name, inner["struct"], owner)
			for impl_id in inner["struct"].get("impls", []):
				impl = index.get(str(impl_id), {}).get("inner", {}).get("impl", {})
				if impl.get("trait") is not None or impl.get("is_synthetic") or impl.get("synthetic") or impl.get("blanket_impl"):
					continue
				for method_id in impl.get("items", []):
					method = index.get(str(method_id))
					if method and method.get("visibility") == "public" and "function" in method["inner"]:
						line(f"{name.lower()}_{method['name']}", method["inner"]["function"], f"{owner}::{method['name']}", owner)


def main(argv):
	if len(argv) < 2 or argv[1] in ("-h", "--help", "help"):
		print(__doc__)
		return
	command, rest = argv[1], argv[2:]
	if command == "build" and rest:
		for path in rest:
			build(Manifest(path))
	elif command == "wasm" and len(rest) in (1, 2):
		wasm_built(Manifest(rest[0]), rest[1] if len(rest) == 2 else None)
	elif command == "source" and len(rest) == 1:
		sys.stdout.write(Manifest(rest[0]).rust_source())
	elif command == "scan" and len(rest) == 1:
		scan(rest[0])
	elif command == "fetch" and rest:
		for name in rest:
			fetch(name)
	elif command == "publish" and len(rest) >= 2:
		publish(rest[0], [Manifest(path) for path in rest[1:]])
	elif command == "index" and len(rest) == 1:
		index(rest[0])
	elif command == "dirs":
		print(f"cache {CACHE}\nlib {LIB_DIR}\nnative {NATIVE_DIR}")
	else:
		fail(f"unknown command {' '.join(argv[1:])!r}; see warp-crate --help")


if __name__ == "__main__":
	main(sys.argv)
