Verified full GUI compilation on both supported game versions and confirmed that a deliberate unknown binding fails.
367 lines
14 KiB
Python
367 lines
14 KiB
Python
"""Offline Quirrel bytecode & lexical-scope verifier for `patches/gui/`.
|
|
|
|
`sq.exe --syntax-check` only runs `sq_parsetoast` and skips `CodeGenVisitor`, missing
|
|
`Unknown variable`, forward references, and `Named binding name conflicts with existing
|
|
constant/enum/import`. Driving `sq.exe` via `compilestring(src, chunkname, bindings)`
|
|
with import names from the game archive and stand-ins for their values runs the full
|
|
parser and bytecode generator without executing any game code.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import re
|
|
import subprocess
|
|
import tempfile
|
|
from dataclasses import dataclass
|
|
from pathlib import Path
|
|
|
|
from .exepatch.errors import PatchError
|
|
from .guipatch import GuiVariant, load_gui_patches, select
|
|
from .vromfs import Archive, read_archive
|
|
|
|
MOUNT_PREFIXES: tuple[tuple[str, str], ...] = (
|
|
("%scripts/", "scripts/"),
|
|
("%globalScripts/", "globalscripts/"),
|
|
("%sqstd/", "std/"),
|
|
("%sqStdLibs/", "sqstdlibs/"),
|
|
("%appGlobals/", "globals/"),
|
|
("%gui/", "gui/"),
|
|
("%rGui/", "reactivegui/"),
|
|
("%darg/", "darg/"),
|
|
)
|
|
|
|
MODULE_BUILTINS: tuple[str, ...] = (
|
|
"require",
|
|
"require_optional",
|
|
"persist",
|
|
"keepref",
|
|
"__name__",
|
|
"__filename__",
|
|
"__static_analysis__",
|
|
)
|
|
|
|
HARNESS_SOURCE = """\
|
|
let io = require("io")
|
|
let types = require("types")
|
|
class DummyClass {}
|
|
class Proxy {
|
|
function _get(_k) { return this }
|
|
function _add(_o) { return 0 }
|
|
function _sub(_o) { return 0 }
|
|
function _mul(_o) { return 0 }
|
|
function _div(_o) { return 1 }
|
|
function _modulo(_o) { return 0 }
|
|
function _unm() { return 0 }
|
|
function _cmp(_o) { return 0 }
|
|
}
|
|
let proxy = Proxy()
|
|
let typeMap = {
|
|
String = types.String
|
|
Table = types.Table
|
|
Array = types.Array
|
|
Function = types.Function
|
|
Integer = types.Integer
|
|
Float = types.Float
|
|
Bool = types.Bool
|
|
CtrlsInGui = __CONTROL_MASKS__
|
|
LOGIN_STATE = __LOGIN_MASKS__
|
|
QUEUE_TYPE_BIT = __QUEUE_MASKS__
|
|
}
|
|
function readText(p) {
|
|
let f = io.file(p, "rb")
|
|
let s = f.readblob(f.len()).as_string()
|
|
f.close()
|
|
return s
|
|
}
|
|
let manifestPath = __MANIFEST_PATH__
|
|
let lines = readText(manifestPath).split("\\n")
|
|
foreach (line in lines) {
|
|
let trimmed = line.strip()
|
|
if (trimmed == "")
|
|
continue
|
|
let parts = trimmed.split("\\t")
|
|
let filePath = parts[0]
|
|
let display = parts[1]
|
|
let names = parts.len() > 2 && parts[2] != "" ? parts[2].split(",") : []
|
|
let classNames = parts.len() > 3 && parts[3] != "" ? parts[3].split(",") : []
|
|
let bindings = {}
|
|
foreach (n in names) {
|
|
// These native imports need integer stand-ins for constant folding of masks and shifts.
|
|
let isNativeInteger = n.startswith("GT_") || n.startswith("OBJECTIVE_TYPE_")
|
|
let fallback = isNativeInteger ? 1 : proxy
|
|
bindings[n] <- (n in typeMap) ? typeMap[n] : fallback
|
|
}
|
|
foreach (cn in classNames)
|
|
bindings[cn] <- DummyClass
|
|
let src = readText(filePath)
|
|
try {
|
|
compilestring(src, display, bindings)
|
|
print($"COMPILED {display}\\n")
|
|
} catch (e) {
|
|
print($"COMPILE_ERROR {display}: {e}\\n")
|
|
}
|
|
}
|
|
print("COMPILATION_COMPLETE\\n")
|
|
"""
|
|
|
|
|
|
@dataclass(frozen=True)
|
|
class GuiCheckReport:
|
|
patches_applied: int
|
|
files_checked: int
|
|
errors: tuple[str, ...]
|
|
|
|
|
|
def verify_gui_patches(
|
|
gui_pack_path: Path,
|
|
patches_dir: Path,
|
|
sq_exe: Path,
|
|
endpoint: str = "127.0.0.1:47115",
|
|
) -> GuiCheckReport:
|
|
archive = read_archive(gui_pack_path.read_bytes())
|
|
patches = load_gui_patches(patches_dir)
|
|
touched_files: list[str] = []
|
|
errors: list[str] = []
|
|
|
|
chosen: dict[str, GuiVariant] = {}
|
|
for patch in patches:
|
|
try:
|
|
variant, updated = select(archive.files, patch, endpoint)
|
|
except PatchError as error:
|
|
errors.append(str(error))
|
|
continue
|
|
if any("`" in edit.replace for edit in variant.edits):
|
|
errors.append(f"{patch.identifier}: backtick string syntax is unsupported by the game's Quirrel VM; use $\"...\" or +")
|
|
continue
|
|
target = variant.file.lower()
|
|
chosen[patch.identifier] = variant
|
|
archive.put(target, updated.encode("utf-8"))
|
|
if target not in touched_files:
|
|
touched_files.append(target)
|
|
|
|
if errors:
|
|
return GuiCheckReport(len(patches), 0, tuple(errors))
|
|
|
|
export_cache: dict[str, set[str]] = {}
|
|
native_syms = _collect_all_named_imports(archive)
|
|
stock_archive = read_archive(gui_pack_path.read_bytes())
|
|
|
|
for patch in patches:
|
|
variant = chosen[patch.identifier]
|
|
target = variant.file.lower()
|
|
stock_src = stock_archive.files[target].decode("utf-8")
|
|
imp_names, imp_classes = _resolve_file_bindings(stock_src, stock_archive, export_cache, native_syms)
|
|
reserved = (imp_names | imp_classes) - set(MODULE_BUILTINS)
|
|
new_locals: set[str] = set()
|
|
for edit in variant.edits:
|
|
new_locals |= _declared_locals(edit.replace) - _declared_locals(edit.find)
|
|
collisions = sorted(new_locals & reserved)
|
|
if collisions:
|
|
errors.append(f"{patch.identifier}: local binding(s) {collisions} conflict with module imports in {target}")
|
|
|
|
if errors:
|
|
return GuiCheckReport(len(patches), 0, tuple(errors))
|
|
|
|
export_cache.clear()
|
|
with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp:
|
|
tmp_dir = Path(tmp)
|
|
manifest_lines: list[str] = []
|
|
|
|
for index, rel_path in enumerate(touched_files):
|
|
source = archive.files[rel_path].decode("utf-8")
|
|
names, class_names = _resolve_file_bindings(source, archive, export_cache, native_syms)
|
|
nut_file = tmp_dir / f"check_{index}.nut"
|
|
nut_file.write_bytes(archive.files[rel_path])
|
|
manifest_lines.append(
|
|
f"{nut_file}\t{rel_path}\t{','.join(sorted(names))}\t{','.join(sorted(class_names))}"
|
|
)
|
|
|
|
manifest_path = tmp_dir / "manifest.tsv"
|
|
manifest_path.write_text("\n".join(manifest_lines), encoding="utf-8")
|
|
# The standalone interpreter does not expose __argv as a script binding.
|
|
harness_source = HARNESS_SOURCE.replace(
|
|
"__CONTROL_MASKS__",
|
|
_integer_table_literal(stock_archive, "globalscripts/sharedenums.nut", r"\benum\s+CtrlsInGui"),
|
|
)
|
|
harness_source = harness_source.replace(
|
|
"__LOGIN_MASKS__",
|
|
_integer_table_literal(stock_archive, "globals/login/loginconsts.nut", r"\benum\s+LOGIN_STATE"),
|
|
)
|
|
harness_source = harness_source.replace(
|
|
"__QUEUE_MASKS__",
|
|
_integer_table_literal(stock_archive, "scripts/queue/queuetypebit.nut", r"\breturn\s+freeze\("),
|
|
)
|
|
harness_source = harness_source.replace("__MANIFEST_PATH__", json.dumps(manifest_path.as_posix(), ensure_ascii=False))
|
|
harness_path = tmp_dir / "harness.nut"
|
|
harness_path.write_text(harness_source, encoding="utf-8")
|
|
proc = subprocess.run(
|
|
[str(sq_exe), str(harness_path)],
|
|
capture_output=True,
|
|
text=True,
|
|
encoding="utf-8",
|
|
errors="replace",
|
|
)
|
|
# sq.exe can exit with status zero after a compile or runtime error in the harness.
|
|
confirmations = [
|
|
line for line in proc.stdout.splitlines()
|
|
if line.startswith("COMPILED ") or line == "COMPILATION_COMPLETE"
|
|
]
|
|
expected = [f"COMPILED {path}" for path in touched_files] + ["COMPILATION_COMPLETE"]
|
|
if confirmations != expected:
|
|
errors.append("Quirrel compiler did not confirm bytecode compilation for every modified script")
|
|
if proc.returncode != 0:
|
|
errors.append(f"Quirrel compiler exited with status {proc.returncode}")
|
|
if errors:
|
|
errors.extend(
|
|
line.strip() for line in (proc.stdout + "\n" + proc.stderr).splitlines()
|
|
if line.strip() and line not in confirmations
|
|
)
|
|
|
|
return GuiCheckReport(len(patches), len(touched_files), tuple(errors))
|
|
|
|
|
|
def _integer_table_literal(archive: Archive, file: str, table_start: str) -> str:
|
|
"""Read a stock table of integer flags for constant expressions in the compiler."""
|
|
source = archive.files.get(file, b"").decode("utf-8")
|
|
table = re.search(table_start + r"\s*\{([^{}]*)\}", source)
|
|
if table is None:
|
|
return "{}"
|
|
|
|
fields = re.findall(
|
|
r"^[ \t]*([A-Za-z_][A-Za-z0-9_]*)[ \t]*=[ \t]*"
|
|
r"(0x[0-9a-fA-F]+|[0-9]+)[ \t]*,?[ \t]*(?://[^\r\n]*)?\r?$",
|
|
table[1],
|
|
re.MULTILINE,
|
|
)
|
|
return "{ " + ", ".join(f"{name} = {value}" for name, value in fields) + " }"
|
|
|
|
|
|
def _resolve_vromfs_path(spec: str) -> str | None:
|
|
for prefix, target in MOUNT_PREFIXES:
|
|
if spec.startswith(prefix):
|
|
return (target + spec[len(prefix):]).lower()
|
|
if spec.endswith(".nut"):
|
|
return spec.lstrip("/").lower()
|
|
return None
|
|
|
|
|
|
def _collect_all_named_imports(archive: Archive) -> dict[str, set[str]]:
|
|
by_mod: dict[str, set[str]] = {}
|
|
pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE)
|
|
for content in archive.files.values():
|
|
text = content.decode("utf-8", errors="ignore")
|
|
for match in pattern.finditer(text):
|
|
mod, items = match.group(1), match.group(2)
|
|
if items.strip() == "*":
|
|
continue
|
|
bucket = by_mod.setdefault(mod, set())
|
|
for raw_item in items.replace("\r", " ").replace("\n", " ").split(","):
|
|
token = raw_item.strip()
|
|
if not token:
|
|
continue
|
|
orig = token.split()[0]
|
|
if orig.isidentifier():
|
|
bucket.add(orig)
|
|
return by_mod
|
|
|
|
|
|
def _exports_of_module(spec: str, archive: Archive, cache: dict[str, set[str]], native_syms: dict[str, set[str]]) -> set[str]:
|
|
if spec in cache:
|
|
return cache[spec]
|
|
vpath = _resolve_vromfs_path(spec)
|
|
if not vpath or vpath not in archive.files:
|
|
res = set(native_syms.get(spec, set()))
|
|
cache[spec] = res
|
|
return res
|
|
|
|
cache[spec] = set()
|
|
text = archive.files[vpath].decode("utf-8", errors="ignore")
|
|
keys: set[str] = set(native_syms.get(spec, set()))
|
|
|
|
if vpath == "scripts/dagui_library.nut":
|
|
keys |= _exports_of_module("%globalScripts/logs.nut", archive, cache, native_syms)
|
|
keys |= _exports_of_module("%scripts/sqDagui/daguiNativeApi.nut", archive, cache, native_syms)
|
|
keys |= _exports_of_module("%globalScripts/sharedEnums.nut", archive, cache, native_syms)
|
|
|
|
if vpath == "scripts/sqdagui/daguinativeapi.nut":
|
|
# Its return table merges the native daguiScene exports. The cursor helper is
|
|
# only used through wildcard imports, so it cannot be found in the named imports.
|
|
keys.update(native_syms.get("daguiScene", set()))
|
|
keys.add("get_dagui_mouse_cursor_pos_RC")
|
|
|
|
for arr_match in re.finditer(r"let\s+fields\s*=\s*\[(.*?)\]", text, re.DOTALL):
|
|
for s_match in re.finditer(r'"([A-Za-z_][A-Za-z0-9_]*)"', arr_match.group(1)):
|
|
keys.add(s_match.group(1))
|
|
|
|
# Stock modules also return inline tables and merge a final table into other exports.
|
|
returned_table = re.compile(
|
|
r"\breturn\s*\(?\s*(?:freeze\s*\(\s*)?"
|
|
r"(?:[A-Za-z_]\w*\.__merge\(\s*(?:[A-Za-z_]\w*\s*,\s*)+)?"
|
|
r"\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}",
|
|
re.DOTALL,
|
|
)
|
|
for ret_match in returned_table.finditer(text):
|
|
body = ret_match.group(1)
|
|
for line in body.splitlines():
|
|
stripped = line.strip().rstrip(",")
|
|
if not stripped or stripped.startswith("//"):
|
|
continue
|
|
m_assign = re.match(r"^([A-Za-z_][A-Za-z0-9_]*)\s*=", stripped)
|
|
if m_assign:
|
|
keys.add(m_assign.group(1))
|
|
else:
|
|
fields = [field.strip() for field in stripped.split(",")]
|
|
if all(field.isidentifier() for field in fields):
|
|
keys.update(fields)
|
|
|
|
for m_slot in re.finditer(r'\b(?:export|res)\s*(?:\.\s*([A-Za-z_][A-Za-z0-9_]*)|\[\s*"([A-Za-z_][A-Za-z0-9_]*)"\s*\])\s*<-', text):
|
|
keys.add(m_slot.group(1) or m_slot.group(2))
|
|
|
|
cache[spec] = keys
|
|
return keys
|
|
|
|
|
|
def _resolve_file_bindings(
|
|
source: str,
|
|
archive: Archive,
|
|
cache: dict[str, set[str]],
|
|
native_syms: dict[str, set[str]],
|
|
) -> tuple[set[str], set[str]]:
|
|
names: set[str] = set(MODULE_BUILTINS)
|
|
class_names: set[str] = set()
|
|
used_as_base = set(re.findall(r"\bclass\s*(?:[A-Za-z_][A-Za-z0-9_]*)?\s*\(\s*([A-Za-z_][A-Za-z0-9_]*)\s*\)", source))
|
|
|
|
for match in re.finditer(r'^import\s+"([^"]+)"\s+as\s+([A-Za-z_][A-Za-z0-9_]*)', source, re.MULTILINE):
|
|
alias = match.group(2)
|
|
(class_names if alias in used_as_base else names).add(alias)
|
|
|
|
from_pattern = re.compile(r'^from\s+"([^"]+)"\s+import\s+([^\r\n]+(?:\r?\n\s*,[^\r\n]+)*)', re.MULTILINE)
|
|
for match in from_pattern.finditer(source):
|
|
spec, raw_items = match.group(1), match.group(2).strip()
|
|
if raw_items == "*":
|
|
for sym in _exports_of_module(spec, archive, cache, native_syms):
|
|
(class_names if sym in used_as_base else names).add(sym)
|
|
continue
|
|
for token in raw_items.replace("\r", " ").replace("\n", " ").split(","):
|
|
parts = token.strip().split()
|
|
if not parts:
|
|
continue
|
|
bound = parts[2] if len(parts) >= 3 and parts[1] == "as" else parts[0]
|
|
if bound.isidentifier():
|
|
(class_names if bound in used_as_base else names).add(bound)
|
|
|
|
return names - class_names, class_names
|
|
|
|
|
|
def _declared_locals(snippet: str) -> set[str]:
|
|
found: set[str] = set()
|
|
for m in re.finditer(r"\b(?:let|local)\s+([A-Za-z_][A-Za-z0-9_]*)\s*=", snippet):
|
|
found.add(m.group(1))
|
|
for m in re.finditer(r"\b(?:let|local)\s*\{([^}]+)\}\s*=", snippet):
|
|
for tok in m.group(1).split(","):
|
|
parts = tok.strip().split(":")
|
|
ident = parts[-1].strip()
|
|
if ident.isidentifier():
|
|
found.add(ident)
|
|
return found
|