Snapshot unreviewed LocalMP battle work as rework baseline

Records the uncommitted battle-session work exactly as it was left
(local service matchmaking, settlement, chat, native LocalMP hooks,
battle gui/exe patches) so the following review and rework commits
show every correction as a diff against this state.

This commit is not reviewed and is known to be incomplete: in-game
testing reported wrong settlement rewards, single-country teams,
missing random/fixed supplement slots, misattributed hit messages and
other regressions. Do not merge this branch before the rework lands.
This commit is contained in:
N0VAN0M4LY committed 2026-11-28 03:15:47 +08:00
1 parent aa272fc82b
commit 6a189513b0
97 files changed
+7676 -396

No files matched your search

+309
View File
@@ -0,0 +1,309 @@
"""Offline Quirrel bytecode & lexical-scope verifier for `gui-patches/`.
`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 the target script's real `gui.vromfs.bin` imports runs the full `SQParser` +
`CodeGenVisitor` pipeline 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 .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
}
function readText(p) {
let f = io.file(p, "rb")
let s = f.readblob(f.len()).as_string()
f.close()
return s
}
let manifestPath = __argv[0]
let lines = readText(manifestPath).split("\\n")
local failed = 0
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)
bindings[n] <- (n in typeMap) ? typeMap[n] : proxy
foreach (cn in classNames)
bindings[cn] <- DummyClass
let src = readText(filePath)
try {
compilestring(src, display, bindings)
} catch (e) {
print($"COMPILE_ERROR {display}: {e}\\n")
failed++
}
}
if (failed > 0)
throw $"Quirrel bytecode check failed on {failed} file(s)"
"""
@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())
patch_files = sorted(patches_dir.rglob("patch.json"))
touched_files: list[str] = []
errors: list[str] = []
for patch_path in patch_files:
raw = json.loads(patch_path.read_text(encoding="utf-8"))
target = raw["file"].lower()
if target not in archive.files:
errors.append(f"{raw['id']}: missing file {target} in gui.vromfs.bin")
continue
current = archive.files[target].decode("utf-8")
find_text = raw["edit"]["find"]
first = current.find(find_text)
if first == -1:
errors.append(f"{raw['id']}: target snippet not found in {target}")
continue
if current.find(find_text, first + len(find_text)) != -1:
errors.append(f"{raw['id']}: target snippet appears more than once in {target}")
continue
replace_text = raw["edit"]["replace"].replace("{{LOCAL_ENDPOINT}}", endpoint)
if "`" in replace_text:
errors.append(f"{raw['id']}: backtick string syntax is unsupported by 2.61.0.37 Quirrel VM; use $\"...\" or +")
continue
updated = current[:first] + replace_text + current[first + len(find_text):]
archive.put(target, updated.encode("utf-8"))
if target not in touched_files:
touched_files.append(target)
if errors:
return GuiCheckReport(len(patch_files), 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_path in patch_files:
raw = json.loads(patch_path.read_text(encoding="utf-8"))
target = raw["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 = _declared_locals(raw["edit"]["replace"]) - _declared_locals(raw["edit"]["find"])
collisions = sorted(new_locals & reserved)
if collisions:
errors.append(f"{raw['id']}: local binding(s) {collisions} conflict with module imports in {target}")
if errors:
return GuiCheckReport(len(patch_files), 0, tuple(errors))
with tempfile.TemporaryDirectory(prefix="wto-gui-check-") as tmp:
tmp_dir = Path(tmp)
harness_path = tmp_dir / "harness.nut"
harness_path.write_text(HARNESS_SOURCE, encoding="utf-8")
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")
proc = subprocess.run(
[str(sq_exe), str(harness_path), str(manifest_path)],
capture_output=True,
text=True,
encoding="utf-8",
errors="replace",
)
if proc.returncode != 0:
out = (proc.stdout + "\n" + proc.stderr).strip()
for line in out.splitlines():
if line.strip():
errors.append(line.strip())
return GuiCheckReport(len(patch_files), len(touched_files), tuple(errors))
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)
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))
for ret_match in re.finditer(r"return\s+(?:freeze\s*\(\s*)?\{([^{}]*(?:\{[^{}]*\}[^{}]*)*)\}", text, re.DOTALL):
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))
elif stripped.isidentifier():
keys.add(stripped)
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