lemmascript 0.6.4 → 0.6.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -5
- package/package.json +1 -1
- package/tools/dist/config.js +32 -10
- package/tools/dist/dafny-commands.js +102 -17
- package/tools/dist/dafny-emit.js +121 -24
- package/tools/dist/extract.js +44 -5
- package/tools/dist/lean-emit.js +27 -18
- package/tools/dist/lsc.js +56 -4
- package/tools/dist/run-log.js +197 -0
- package/tools/dist/runs-command.js +377 -0
- package/tools/dist/transform.js +1 -2
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# LemmaScript (Tech Preview)
|
|
2
2
|
|
|
3
|
-
A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet
|
|
3
|
+
A verification toolchain for TypeScript. Write ordinary TypeScript with `//@ ` specification annotations. The toolchain generates verifiable code from your TypeScript — either in Dafny or Lean 4 (with Velvet 2).
|
|
4
4
|
|
|
5
5
|
See [SPEC.md](SPEC.md), [DESIGN.md](DESIGN.md), and [GETTING_STARTED.md](GETTING_STARTED.md).
|
|
6
6
|
|
|
@@ -29,7 +29,7 @@ See the external [case studies](https://github.com/search?q=topic%3Alemmascript+
|
|
|
29
29
|
- **[xyflow-lemmascript](https://github.com/midspiral/xyflow-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [xyflow](https://github.com/xyflow/xyflow)'s core edge and geometry utilities. 9 functions verified: `addEdge` (dedup — never loses edges, adds at most one), `reconnectEdge` (semantic: under a unique-id precondition, the result is in-place — `|result| ≤ |edges|`, no insertion — *and* when a matching edge existed with non-empty new endpoints, the output contains an edge with those endpoints. Uses `//@ assume` to characterize destructuring, `find`, and the constructed edge), `connectionExists`, `getEdgeCenter` (midpoint correctness), `clamp` (bounds), `rectToBox`/`boxToRect` (field arithmetic), `getBoundsOfBoxes` (enclosure), `getOverlappingArea` (non-negative), `areSetsEqual` (subset + same size). 14 Dafny proof obligations. Also adds a new verified feature — a **DAG connection gate**: `canReach` decides reachability soundly *and* completely, and `wouldCreateCycle` gates both new connections and edge reconnections so the graph is proven to stay acyclic, with `isAcyclic` (sound + complete) establishing the base case and a topological-rank witness giving a safe evaluation order (+29 obligations), shown live in a React Flow demo that refuses cycle-closing edges — extending the case study from verifying existing code to adding a verified feature. Dafny only.
|
|
30
30
|
- **[rallly-lemmascript](https://github.com/midspiral/rallly-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [rallly](https://github.com/lukevella/rallly)'s meeting-poll Next.js app. 2 functions: `validateRedirectUrl` (in-place — open-redirect predicate; non-`undefined` outputs start with `/` but not `//`) and `scorePoll` (extracted ranking core — length preservation, score bounds, top-choice characterization, score-formula equality, within-poll monotonicity, tiebreaker injectivity). The injectivity proof surfaced a real spec-level constraint on the existing `(yes + ifNeedBe) * 1000 + yes` encoding: it overflows when an option has ≥ 1000 yes votes. 10 Dafny VCs, 0 errors. Drove four toolchain additions: `s.startsWith()`, `T | null` nullability, `\result` narrowing under `==>`, `Math.max(...arr)` spread. Dafny only.
|
|
31
31
|
- **[opencode-lemmascript](https://github.com/midspiral/opencode-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield verification of [opencode](https://github.com/anomalyco/opencode)'s permission system and unified-diff patch parser. Highlights: (1) `Patch.parsePatch` carries conservation loop invariants over local ghost state — a parser bug here would silently corrupt user files when an AI applies a patch, and (2) the permission-engine work mechanically closes opencode bug #26514 (subagents bypassing Plan Mode's file-edit restrictions). 9 functions verified in-place, 0 errors. Dafny only.
|
|
32
|
-
- **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet
|
|
32
|
+
- **[pi-lemmascript](https://github.com/midspiral/pi-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of the context-compaction cut-point selector in **pi** (the [earendil-works](https://pi.dev) agent harness). When the context window fills, pi discards history before a chosen cut; a provider API rejects a retained prefix containing an orphaned `toolResult` (a tool result whose tool call was cut away). Both selector functions proven: the cut never lets the kept suffix *start with* — nor *split a tool-use/tool-result run* into — an orphaned tool result, even across the backward metadata snap. The no-orphan result forced the session tree's tool-pairing ordering into an explicit `requires`. 4 VCs, 0 errors. Drove five toolchain additions, headlined by an **opaque fall-through type**: a union LemmaScript can't discriminate (here an array-element union of unreachable imports) becomes a single opaque `type` — the field stays present so distinct values stay distinct, and with no constructor or tag predicate it can only be passed through, never unsoundly observed. **Dafny + Lean**: the no-orphan theorem, the changelog semver core, and both tool-output truncators also carry Lean 4 (Velvet 2) proofs from the same annotated source, zero `sorry`; the Lean port drove the backend's brownfield batch (cross-file externs, union destructor lowering, Bool-vs-Prop contexts, `return`-in-loop elimination).
|
|
33
33
|
- **[flue-lemmascript](https://github.com/midspiral/flue-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of pure logic in **Flue** ([withastro/flue](https://github.com/withastro/flue)), Astro's agent harness — crash-recovery and context-compaction functions proven byte-identical. What it drove into the toolchain: native Dafny `continue`, bounds-guarded `noUncheckedIndexedAccess` optional indexing, optional narrowing past an `opt?.disc` guard composing with discriminated-union matching, and object truthiness. Dafny only.
|
|
34
34
|
- **[balanced-match-lemmascript](https://github.com/midspiral/balanced-match-lemmascript/blob/lemmascript/README_LemmaScript.md)** — brownfield, **in-place** verification of [balanced-match](https://github.com/juliangruber/balanced-match), the ~70-line balanced-bracket finder pulled in by `npm`, `webpack`, and most of the JS tooling stack (1B+ downloads/month). The stack-based `range` core is verified by **refinement**: a pure recursive spec `range_spec` mirrors the loop one branch per recursive case, so the single equivalence `range == range_spec` transfers every property automatically — including an unconditional Dyck body-balance theorem for the interior of every returned pair. 2233 VCs, 0 errors under `--isolate-assertions` (registered on the `dafny-slow` track). Dafny only.
|
|
35
35
|
- **[guardians-lemmascript](https://github.com/midspiral/guardians-lemmascript)** — greenfield verification of the core safety argument behind [Guardians](https://github.com/metareflection/guardians) (Erik Meijer, "Guardians of the Agents", CACM Jan 2026), a generate-verify-execute checker for AI-agent workflows. Instead of verifying an app, it proves the agent *guardrail itself sound* — that a static taint/automaton check over the real recursive workflow AST can never admit an unsafe plan. Highlights: taint over **nested conditionals** as a sound branch-union over-approximation; per-source **provenance** with a join (a multi-input tool is tainted if *any* input was); **unbounded loops** discharged by a one-step pre-fixpoint (`sat = t0 ‖ bodyTaint(t0)`) that bounds taint over any iteration count without iterating to a fixpoint; and a **unified capstone** (`verifyWfSound`) — one clean verdict rules out, on *every* path, both a tainted-data-to-sink leak and a security-automaton error. 54 Dafny obligations, 0 errors. The verified cores are reached from a Guardians-style `Workflow`/`Policy` through a thin *unverified* adapter, differentially tested against the real Python Guardians (used as the oracle, not a porting target). Dafny only.
|
|
@@ -56,13 +56,22 @@ git clone https://github.com/midspiral/LemmaScript.git
|
|
|
56
56
|
cd LemmaScript && npm install && npm run build
|
|
57
57
|
```
|
|
58
58
|
|
|
59
|
-
**Lean backend
|
|
59
|
+
**Lean backend:** from the LemmaScript source checkout, clone Velvet 2 as a sibling on the **`lemma2` branch**:
|
|
60
60
|
|
|
61
61
|
```sh
|
|
62
|
-
git clone https://github.com/namin/
|
|
63
|
-
|
|
62
|
+
git clone --branch lemma2 https://github.com/namin/velvet.git ../velvet
|
|
63
|
+
lake build
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
For an existing Velvet checkout, select the branch with:
|
|
67
|
+
|
|
68
|
+
```sh
|
|
69
|
+
git -C ../velvet fetch origin
|
|
70
|
+
git -C ../velvet checkout lemma2
|
|
64
71
|
```
|
|
65
72
|
|
|
73
|
+
The `lemma` branch is for the previous Velvet version. Use the Lean version pinned in `lean-toolchain` (currently 4.34.0); Lake resolves the Mathlib dependency. Velvet 2 does not require a Loom checkout or external Z3/cvc5 binaries. See [SPEC_LEAN.md](SPEC_LEAN.md) for the project layout and proof workflow.
|
|
74
|
+
|
|
66
75
|
## Usage
|
|
67
76
|
|
|
68
77
|
### Dafny backend
|
package/package.json
CHANGED
package/tools/dist/config.js
CHANGED
|
@@ -29,6 +29,26 @@ export const OPTION_SPECS = {
|
|
|
29
29
|
fileOverride: false,
|
|
30
30
|
description: "Directory for Dafny artifacts, relative to lemmascript.json.",
|
|
31
31
|
},
|
|
32
|
+
"string-semantics": {
|
|
33
|
+
type: "enum",
|
|
34
|
+
values: ["unicode-scalar", "javascript-utf16"],
|
|
35
|
+
default: "unicode-scalar",
|
|
36
|
+
fileOverride: true,
|
|
37
|
+
description: "Which model of JavaScript strings a Dafny proof is made under.",
|
|
38
|
+
},
|
|
39
|
+
"dafny-library": {
|
|
40
|
+
type: "enum",
|
|
41
|
+
values: ["stdlib", "local"],
|
|
42
|
+
default: "stdlib",
|
|
43
|
+
fileOverride: true,
|
|
44
|
+
description: "Use Dafny's standard library or generated local helpers for collection operations.",
|
|
45
|
+
},
|
|
46
|
+
"run-log": {
|
|
47
|
+
type: "boolean",
|
|
48
|
+
default: true,
|
|
49
|
+
fileOverride: false,
|
|
50
|
+
description: "Record lsc check and regen runs in .lemmascript/.",
|
|
51
|
+
},
|
|
32
52
|
};
|
|
33
53
|
export const DEFAULT_OPTIONS = Object.freeze(Object.fromEntries(Object.entries(OPTION_SPECS).map(([key, spec]) => [key, spec.default])));
|
|
34
54
|
const KNOWN_KEYS = Object.keys(OPTION_SPECS);
|
|
@@ -39,7 +59,8 @@ function fail(source, message) {
|
|
|
39
59
|
function isKnownKey(key) {
|
|
40
60
|
return Object.hasOwn(OPTION_SPECS, key);
|
|
41
61
|
}
|
|
42
|
-
|
|
62
|
+
/** Validate one option against the registry and return its typed value. */
|
|
63
|
+
export function parseOptionValue(key, raw, source) {
|
|
43
64
|
const spec = OPTION_SPECS[key];
|
|
44
65
|
if (spec.type === "boolean") {
|
|
45
66
|
if (typeof raw !== "boolean")
|
|
@@ -71,7 +92,7 @@ export function validateOptions(raw, source) {
|
|
|
71
92
|
if (!isKnownKey(key)) {
|
|
72
93
|
fail(source, `unknown option '${key}' (known options: ${KNOWN_KEYS.join(", ")})`);
|
|
73
94
|
}
|
|
74
|
-
out[key] =
|
|
95
|
+
out[key] = parseOptionValue(key, value, source);
|
|
75
96
|
}
|
|
76
97
|
return out;
|
|
77
98
|
}
|
|
@@ -83,10 +104,10 @@ function parseDirectiveValue(key, text, source) {
|
|
|
83
104
|
return (text === "true");
|
|
84
105
|
}
|
|
85
106
|
if (spec.type === "enum")
|
|
86
|
-
return
|
|
107
|
+
return parseOptionValue(key, text, source);
|
|
87
108
|
// Config-only today, but keep the diagnostic precise if a future path is
|
|
88
109
|
// made file-overridable.
|
|
89
|
-
return
|
|
110
|
+
return parseOptionValue(key, text, source);
|
|
90
111
|
}
|
|
91
112
|
/**
|
|
92
113
|
* Find comment lines, marking those that occur before any code.
|
|
@@ -183,13 +204,14 @@ export function parseFileOptions(sourceText, source) {
|
|
|
183
204
|
}
|
|
184
205
|
return out;
|
|
185
206
|
}
|
|
186
|
-
/** Apply defaults
|
|
207
|
+
/** Apply defaults, check option compatibility, and freeze the resolved configuration. */
|
|
187
208
|
export function resolveOptions(explicit, source) {
|
|
188
|
-
|
|
189
|
-
//
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
209
|
+
const options = { ...DEFAULT_OPTIONS, ...explicit };
|
|
210
|
+
// Dafny's precompiled standard library uses Unicode-scalar characters.
|
|
211
|
+
if (options["string-semantics"] === "javascript-utf16" && options["dafny-library"] === "stdlib") {
|
|
212
|
+
fail(source, '"string-semantics": "javascript-utf16" is incompatible with "dafny-library": "stdlib"; set "dafny-library": "local" explicitly');
|
|
213
|
+
}
|
|
214
|
+
return Object.freeze(options);
|
|
193
215
|
}
|
|
194
216
|
/** Find `fileName` at or above `fromPath`. */
|
|
195
217
|
export function findUp(fileName, fromPath, fromIsDirectory = false) {
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
import { existsSync, readFileSync, writeFileSync, copyFileSync, unlinkSync } from "fs";
|
|
5
5
|
import { execFileSync } from "child_process";
|
|
6
6
|
import path from "path";
|
|
7
|
+
import { DEFAULT_OPTIONS, parseOptionValue } from "./config.js";
|
|
7
8
|
function writeGen(genPath, text) {
|
|
8
9
|
writeFileSync(genPath, text);
|
|
9
10
|
console.log(`Generated: ${genPath}`);
|
|
@@ -15,13 +16,31 @@ export function dafnyGen(genPath, dfyPath, text) {
|
|
|
15
16
|
console.log(`Created: ${dfyPath}`);
|
|
16
17
|
}
|
|
17
18
|
}
|
|
18
|
-
export function dafnyCheckDiff(genPath, dfyPath) {
|
|
19
|
+
export function dafnyCheckDiff(genPath, dfyPath, log) {
|
|
20
|
+
const ok = additionsOnly(genPath, dfyPath);
|
|
21
|
+
if (!ok)
|
|
22
|
+
log?.finish({ stage: "diff", exit: 1, dfyPath });
|
|
23
|
+
return ok;
|
|
24
|
+
}
|
|
25
|
+
function additionsOnly(genPath, dfyPath) {
|
|
19
26
|
for (const filePath of [genPath, dfyPath]) {
|
|
20
27
|
if (!existsSync(filePath)) {
|
|
21
28
|
console.error(`ERROR: cannot verify additions-only diff; file does not exist: ${filePath}`);
|
|
22
29
|
return false;
|
|
23
30
|
}
|
|
24
31
|
}
|
|
32
|
+
// Proof additions must retain the model chosen by the generated companion.
|
|
33
|
+
try {
|
|
34
|
+
const generated = readStringSemantics(readFileSync(genPath, "utf-8"));
|
|
35
|
+
const proof = readStringSemantics(readFileSync(dfyPath, "utf-8"));
|
|
36
|
+
if (proof !== generated) {
|
|
37
|
+
throw new Error(`proof string-semantics=${proof} differs from generated string-semantics=${generated}`);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
catch (error) {
|
|
41
|
+
console.error(`ERROR: ${path.basename(dfyPath)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
42
|
+
return false;
|
|
43
|
+
}
|
|
25
44
|
let diff = "";
|
|
26
45
|
try {
|
|
27
46
|
diff = execFileSync("git", ["diff", "--no-index", "--minimal", "--no-color", "--no-ext-diff", "--no-textconv", "--text", "--", genPath, dfyPath], { encoding: "utf-8", stdio: ["ignore", "pipe", "pipe"] });
|
|
@@ -61,32 +80,94 @@ export function dafnyCheckDiff(genPath, dfyPath) {
|
|
|
61
80
|
}
|
|
62
81
|
return true;
|
|
63
82
|
}
|
|
64
|
-
|
|
83
|
+
/** Read the saved model, rejecting ambiguous headers before verification. */
|
|
84
|
+
function readStringSemantics(content) {
|
|
85
|
+
const headers = [...content.matchAll(/^\/\/ lsc options:(.*)$/gm)];
|
|
86
|
+
if (headers.length > 1)
|
|
87
|
+
throw new Error("generated header: duplicate lsc options header (string-semantics must be unambiguous)");
|
|
88
|
+
let model = DEFAULT_OPTIONS["string-semantics"];
|
|
89
|
+
let seen = false;
|
|
90
|
+
for (const token of (headers[0]?.[1] ?? "").trim().split(/\s+/).filter(Boolean)) {
|
|
91
|
+
const eq = token.indexOf("=");
|
|
92
|
+
const key = eq < 0 ? token : token.slice(0, eq);
|
|
93
|
+
if (key !== "string-semantics")
|
|
94
|
+
continue;
|
|
95
|
+
if (seen)
|
|
96
|
+
throw new Error("generated header: duplicate string-semantics option");
|
|
97
|
+
seen = true;
|
|
98
|
+
model = parseOptionValue(key, eq < 0 ? "" : token.slice(eq + 1), "generated header");
|
|
99
|
+
}
|
|
100
|
+
return model;
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* Build verifier arguments from the generated file's `// lsc options:` header.
|
|
104
|
+
* Reading the saved string model instead of the current project config keeps
|
|
105
|
+
* verification consistent with generation, even if the config later changes.
|
|
106
|
+
* Always pass `--unicode-char` explicitly. UTF-16 mode also needs
|
|
107
|
+
* `--allow-deprecation` because Dafny 4.11 deprecates `--unicode-char:false`.
|
|
108
|
+
* Other warning categories remain fatal.
|
|
109
|
+
*/
|
|
110
|
+
export function dafnyVerifyArgs(content, timeLimit, extraFlags) {
|
|
111
|
+
let stringSemantics;
|
|
112
|
+
try {
|
|
113
|
+
stringSemantics = readStringSemantics(content);
|
|
114
|
+
}
|
|
115
|
+
catch (error) {
|
|
116
|
+
return { args: [], error: `ERROR: ${error instanceof Error ? error.message : String(error)}` };
|
|
117
|
+
}
|
|
118
|
+
const utf16 = stringSemantics === "javascript-utf16";
|
|
119
|
+
const usesStandardLibrary = content.includes("Std.");
|
|
120
|
+
if (utf16 && usesStandardLibrary) {
|
|
121
|
+
return { args: [], error: "ERROR: this proof combines \"string-semantics\": \"javascript-utf16\" with Dafny's standard library. " +
|
|
122
|
+
"Dafny 4.11 cannot load its Unicode-scalar standard library under --unicode-char:false. " +
|
|
123
|
+
"Set \"dafny-library\": \"local\" in lemmascript.json or add //@ option dafny-library local, " +
|
|
124
|
+
"then run lsc regen to regenerate collection helpers. " +
|
|
125
|
+
"This does not rewrite handwritten Std.* imports or calls; replace those with local proofs or helpers separately." };
|
|
126
|
+
}
|
|
127
|
+
const args = ["verify"];
|
|
128
|
+
if (usesStandardLibrary)
|
|
129
|
+
args.push("--standard-libraries");
|
|
130
|
+
if (timeLimit)
|
|
131
|
+
args.push("--verification-time-limit", String(timeLimit));
|
|
132
|
+
if (extraFlags) {
|
|
133
|
+
for (const tok of extraFlags.split(/\s+/))
|
|
134
|
+
if (tok)
|
|
135
|
+
args.push(tok);
|
|
136
|
+
}
|
|
137
|
+
args.push(utf16 ? "--unicode-char:false" : "--unicode-char:true");
|
|
138
|
+
if (utf16)
|
|
139
|
+
args.push("--allow-deprecation");
|
|
140
|
+
return { args };
|
|
141
|
+
}
|
|
142
|
+
export function dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log) {
|
|
65
143
|
console.log("Running dafny verify...");
|
|
66
144
|
try {
|
|
67
|
-
const
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
args.push("--verification-time-limit", String(timeLimit));
|
|
73
|
-
if (extraFlags) {
|
|
74
|
-
for (const tok of extraFlags.split(/\s+/))
|
|
75
|
-
if (tok)
|
|
76
|
-
args.push(tok);
|
|
145
|
+
const { args, error } = dafnyVerifyArgs(readFileSync(dfyPath, "utf-8"), timeLimit, extraFlags);
|
|
146
|
+
if (error) {
|
|
147
|
+
console.error(error);
|
|
148
|
+
log?.finish({ stage: "resolve", exit: 1, dfyPath });
|
|
149
|
+
return false;
|
|
77
150
|
}
|
|
151
|
+
if (log)
|
|
152
|
+
args.push(...log.dafnyArgs());
|
|
78
153
|
args.push(dfyPath);
|
|
79
154
|
execFileSync("dafny", args, { cwd: dir, stdio: "inherit" });
|
|
155
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath, results: log.readResults() });
|
|
80
156
|
return true;
|
|
81
157
|
}
|
|
82
158
|
catch (e) {
|
|
83
159
|
if (e?.code === "ENOENT") {
|
|
84
160
|
console.error("ERROR: `dafny` not found on PATH — verification never ran. Install Dafny 4.x: https://dafny.org/");
|
|
161
|
+
log?.discard();
|
|
162
|
+
return false;
|
|
85
163
|
}
|
|
164
|
+
// Dafny writes no results when it stops at parsing or resolution.
|
|
165
|
+
const results = log?.readResults() ?? null;
|
|
166
|
+
log?.finish({ stage: results ? "verify" : "resolve", exit: 1, dfyPath, results });
|
|
86
167
|
return false;
|
|
87
168
|
}
|
|
88
169
|
}
|
|
89
|
-
export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false) {
|
|
170
|
+
export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, extraFlags, noVerify = false, log) {
|
|
90
171
|
// 1. Read old gen before overwriting (needed for base seeding)
|
|
91
172
|
const oldGen = existsSync(genPath) ? readFileSync(genPath, "utf-8") : "";
|
|
92
173
|
// 2. Always write new gen so user can inspect latest output
|
|
@@ -95,10 +176,11 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
95
176
|
if (!existsSync(dfyPath)) {
|
|
96
177
|
writeFileSync(dfyPath, text);
|
|
97
178
|
console.log(`Created: ${path.basename(dfyPath)}`);
|
|
98
|
-
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
|
|
179
|
+
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
|
|
99
180
|
console.error(`FAILED: ${path.basename(dfyPath)} verification failed on first run.`);
|
|
100
181
|
process.exit(1);
|
|
101
182
|
}
|
|
183
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath });
|
|
102
184
|
return;
|
|
103
185
|
}
|
|
104
186
|
// 4. Determine anchor: base file if it exists (dirty state), otherwise old gen
|
|
@@ -119,18 +201,19 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
119
201
|
copyFileSync(dfyPath, mergedPath);
|
|
120
202
|
writeFileSync(dfyPath, savedDfy);
|
|
121
203
|
console.error(`CONFLICT: ${path.basename(dfyPath)} — merge had conflicts, dfy restored. See ${path.basename(mergedPath)}`);
|
|
204
|
+
log?.finish({ stage: "conflict", exit: 1, dfyPath });
|
|
122
205
|
process.exit(1);
|
|
123
206
|
}
|
|
124
207
|
throw e;
|
|
125
208
|
}
|
|
126
209
|
}
|
|
127
210
|
// 6. Check gen invariant (unconditional)
|
|
128
|
-
if (!dafnyCheckDiff(genPath, dfyPath)) {
|
|
211
|
+
if (!dafnyCheckDiff(genPath, dfyPath, log)) {
|
|
129
212
|
console.error(`FAILED: ${path.basename(dfyPath)} has modifications to generated lines.`);
|
|
130
213
|
process.exit(1);
|
|
131
214
|
}
|
|
132
215
|
// 7. Verify (skipped under --no-verify: caller verifies separately)
|
|
133
|
-
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags)) {
|
|
216
|
+
if (!noVerify && !dafnyVerify(dfyPath, dir, timeLimit, extraFlags, log)) {
|
|
134
217
|
// The clean merge already incorporated this generation into the proof
|
|
135
218
|
// file. Keep that generation as the next merge anchor even though the
|
|
136
219
|
// verifier rejected the current proof state; otherwise the next regen
|
|
@@ -139,7 +222,9 @@ export function dafnyRegen(genPath, dfyPath, basePath, text, dir, timeLimit, ext
|
|
|
139
222
|
console.error(`FAILED: ${path.basename(dfyPath)} verification failed.`);
|
|
140
223
|
process.exit(1);
|
|
141
224
|
}
|
|
142
|
-
// 8. Success — delete base (gen is now the anchor)
|
|
225
|
+
// 8. Success — delete base (gen is now the anchor). After a verified run
|
|
226
|
+
// dafnyVerify has already recorded the outcome; this records --no-verify.
|
|
143
227
|
if (existsSync(basePath))
|
|
144
228
|
unlinkSync(basePath);
|
|
229
|
+
log?.finish({ stage: "ok", exit: 0, dfyPath });
|
|
145
230
|
}
|
package/tools/dist/dafny-emit.js
CHANGED
|
@@ -4,7 +4,9 @@
|
|
|
4
4
|
import { exactIntegerLiteral, usesName, usesNameInDecl, usesNameInStmts } from "./ir.js";
|
|
5
5
|
import { freshNameWhere, userNames } from "./names.js";
|
|
6
6
|
import { renameFreeVar } from "./transform.js";
|
|
7
|
-
import { DEFAULT_OPTIONS } from "./config.js";
|
|
7
|
+
import { DEFAULT_OPTIONS, resolveOptions } from "./config.js";
|
|
8
|
+
/** Appended to a function's name for the lemma that carries its `//@ ensures`. */
|
|
9
|
+
export const ENSURES_LEMMA_SUFFIX = "_ensures";
|
|
8
10
|
/** Fresh binder for a comprehension wrapping the given subexpressions: `base`
|
|
9
11
|
* verbatim unless one of them references it, then primed until free. A *local*
|
|
10
12
|
* check — a same-named name elsewhere in the module keeps the plain binder. */
|
|
@@ -214,6 +216,29 @@ const OP_MAP = {
|
|
|
214
216
|
"∧": "&&", "∨": "||", "¬": "!", "↔": "<==>",
|
|
215
217
|
"arrayConcat": "+",
|
|
216
218
|
};
|
|
219
|
+
/** Render a JavaScript string without losing its UTF-16 representation.
|
|
220
|
+
*
|
|
221
|
+
* JavaScript iteration by index exposes UTF-16 code units, including unpaired
|
|
222
|
+
* surrogates. Node's UTF-8 file writer would replace an unpaired surrogate if
|
|
223
|
+
* we emitted it literally, so every non-printable/non-ASCII unit is written as
|
|
224
|
+
* a Dafny `\\uXXXX` escape. Under `--unicode-char:false`, each escape denotes
|
|
225
|
+
* exactly one Dafny char and therefore exactly one JavaScript code unit.
|
|
226
|
+
*/
|
|
227
|
+
function escapeDafnyUTF16String(value) {
|
|
228
|
+
let out = "";
|
|
229
|
+
for (let i = 0; i < value.length; i++) {
|
|
230
|
+
const unit = value.charCodeAt(i);
|
|
231
|
+
if (unit === 0x22)
|
|
232
|
+
out += '\\"';
|
|
233
|
+
else if (unit === 0x5c)
|
|
234
|
+
out += "\\\\";
|
|
235
|
+
else if (0x20 <= unit && unit <= 0x7e)
|
|
236
|
+
out += String.fromCharCode(unit);
|
|
237
|
+
else
|
|
238
|
+
out += `\\u${unit.toString(16).toUpperCase().padStart(4, "0")}`;
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
|
217
242
|
function mapOp(op) { return OP_MAP[op] ?? op; }
|
|
218
243
|
// ── Expression emission ─────────────────────────────────────
|
|
219
244
|
function emitScrutinee(s) {
|
|
@@ -247,7 +272,12 @@ function emitExpr(e) {
|
|
|
247
272
|
// Already canonical decimal; Dafny's `int` is mathematical, so no `n` suffix.
|
|
248
273
|
case "bigint": return e.value;
|
|
249
274
|
case "bool": return e.value ? "true" : "false";
|
|
250
|
-
case "str":
|
|
275
|
+
case "str":
|
|
276
|
+
// Under the default profile the literal is written exactly as before;
|
|
277
|
+
// only the UTF-16 profile needs code-unit escapes (DESIGN_STRINGS.md §3).
|
|
278
|
+
return isUtf16()
|
|
279
|
+
? `"${escapeDafnyUTF16String(e.value)}"`
|
|
280
|
+
: `"${e.value.replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n')}"`;
|
|
251
281
|
case "constructor": {
|
|
252
282
|
// Option constructors (Some/None) may appear in inferred positions
|
|
253
283
|
// (e.g. lambda result) without an explicit `optional<T>` in any
|
|
@@ -352,16 +382,24 @@ function emitExpr(e) {
|
|
|
352
382
|
const comp = `seq(|${s}|, ${idx} requires 0 <= ${idx} < |${s}| => ${core})`;
|
|
353
383
|
return bind ? `(var ${s} := ${obj}; ${comp})` : comp;
|
|
354
384
|
}
|
|
355
|
-
if (e.method === "filter")
|
|
356
|
-
|
|
385
|
+
if (e.method === "filter") {
|
|
386
|
+
if (_dafnyLibrary === "stdlib")
|
|
387
|
+
return `Std.Collections.Seq.Filter(${args[0]}, ${obj})`;
|
|
388
|
+
needPreamble("SeqFilter");
|
|
389
|
+
return `SeqFilter(${args[0]}, ${obj})`;
|
|
390
|
+
}
|
|
357
391
|
// filterMap (synthesized in resolve): drop Nones and unwrap to seq<T>.
|
|
358
392
|
if (e.method === "filterSome") {
|
|
359
393
|
needPreamble("SeqFilterSome");
|
|
360
394
|
needPreamble("OptionType");
|
|
361
395
|
return `SeqFilterSome(${obj})`;
|
|
362
396
|
}
|
|
363
|
-
if (e.method === "every")
|
|
364
|
-
|
|
397
|
+
if (e.method === "every") {
|
|
398
|
+
if (_dafnyLibrary === "stdlib")
|
|
399
|
+
return `Std.Collections.Seq.All(${obj}, ${args[0]})`;
|
|
400
|
+
needPreamble("SeqAll");
|
|
401
|
+
return `SeqAll(${obj}, ${args[0]})`;
|
|
402
|
+
}
|
|
365
403
|
if (e.method === "find") {
|
|
366
404
|
needPreamble("OptionType");
|
|
367
405
|
needPreamble("SeqFind");
|
|
@@ -404,9 +442,12 @@ function emitExpr(e) {
|
|
|
404
442
|
}
|
|
405
443
|
return `(exists ${p} :: ${p} in ${obj} && ${body})`;
|
|
406
444
|
}
|
|
407
|
-
// `.reduce(f, init)` →
|
|
445
|
+
// `.reduce(f, init)` → FoldLeft(f, init, xs), using the selected library.
|
|
408
446
|
if (e.method === "reduce" && args.length === 2) {
|
|
409
|
-
|
|
447
|
+
if (_dafnyLibrary === "stdlib")
|
|
448
|
+
return `Std.Collections.Seq.FoldLeft(${args[0]}, ${args[1]}, ${obj})`;
|
|
449
|
+
needPreamble("SeqFoldLeft");
|
|
450
|
+
return `SeqFoldLeft(${args[0]}, ${args[1]}, ${obj})`;
|
|
410
451
|
}
|
|
411
452
|
}
|
|
412
453
|
// String methods
|
|
@@ -932,7 +973,7 @@ function emitDecl(d) {
|
|
|
932
973
|
// Strip constraints like (==) from type params — ghost lemmas don't need them
|
|
933
974
|
const lemmaTP = d.typeParams.length > 0 ? `<${d.typeParams.map(t => t.replace(/\(.*\)/, '')).join(", ")}>` : "";
|
|
934
975
|
lines.push("");
|
|
935
|
-
lines.push(`lemma ${escapeGeneratedName(`${d.name}
|
|
976
|
+
lines.push(`lemma ${escapeGeneratedName(`${d.name}${ENSURES_LEMMA_SUFFIX}`)}${lemmaTP}(${paramList(d.params)})`);
|
|
936
977
|
for (const r of d.requires)
|
|
937
978
|
lines.push(` requires ${emitExpr(r)}`);
|
|
938
979
|
for (const e of d.ensures)
|
|
@@ -1029,6 +1070,11 @@ function needPreamble(key) { _neededPreambles.add(key); }
|
|
|
1029
1070
|
/** Effective JS-clamp semantics for `arr.slice(lo, hi)`, resolved from project
|
|
1030
1071
|
* config plus file directives before emission. */
|
|
1031
1072
|
let _useSafeSlice = false;
|
|
1073
|
+
// Source of generated collection helpers, selected independently of string semantics.
|
|
1074
|
+
let _dafnyLibrary = DEFAULT_OPTIONS["dafny-library"];
|
|
1075
|
+
// The selected model controls literals, character helpers, and verifier flags.
|
|
1076
|
+
let _stringSemantics = DEFAULT_OPTIONS["string-semantics"];
|
|
1077
|
+
function isUtf16() { return _stringSemantics === "javascript-utf16"; }
|
|
1032
1078
|
const POW2 = `function Pow2(n: int): int
|
|
1033
1079
|
requires n >= 0
|
|
1034
1080
|
decreases n
|
|
@@ -1095,6 +1141,25 @@ const SEQ_FILTER_SOME = `function SeqFilterSome<T>(xs: seq<Option<T>>): seq<T>
|
|
|
1095
1141
|
if |xs| == 0 then []
|
|
1096
1142
|
else (if xs[0].Some? then [xs[0].value] else []) + SeqFilterSome(xs[1..])
|
|
1097
1143
|
}`;
|
|
1144
|
+
const SEQ_FILTER = `function SeqFilter<T(!new)>(p: T -> bool, xs: seq<T>): seq<T>
|
|
1145
|
+
ensures |SeqFilter(p, xs)| <= |xs|
|
|
1146
|
+
ensures forall x :: x in SeqFilter(p, xs) <==> x in xs && p(x)
|
|
1147
|
+
decreases |xs|
|
|
1148
|
+
{
|
|
1149
|
+
if |xs| == 0 then []
|
|
1150
|
+
else (if p(xs[0]) then [xs[0]] else []) + SeqFilter(p, xs[1..])
|
|
1151
|
+
}`;
|
|
1152
|
+
const SEQ_ALL = `predicate SeqAll<T>(xs: seq<T>, p: T -> bool)
|
|
1153
|
+
decreases |xs|
|
|
1154
|
+
{
|
|
1155
|
+
|xs| == 0 || (p(xs[0]) && SeqAll(xs[1..], p))
|
|
1156
|
+
}`;
|
|
1157
|
+
const SEQ_FOLD_LEFT = `function SeqFoldLeft<T, A>(f: (A, T) -> A, init: A, xs: seq<T>): A
|
|
1158
|
+
decreases |xs|
|
|
1159
|
+
{
|
|
1160
|
+
if |xs| == 0 then init
|
|
1161
|
+
else SeqFoldLeft(f, f(init, xs[0]), xs[1..])
|
|
1162
|
+
}`;
|
|
1098
1163
|
const SEQ_FIND_INDEX = `function SeqFindIndex<T>(s: seq<T>, p: T -> bool): int
|
|
1099
1164
|
ensures -1 <= SeqFindIndex(s, p) < |s|
|
|
1100
1165
|
ensures SeqFindIndex(s, p) >= 0 ==> p(s[SeqFindIndex(s, p)])
|
|
@@ -1262,15 +1327,16 @@ const SEQ_SORT_BY = `function {:axiom} SeqSortBy<T(==,!new)>(s: seq<T>, cmp: (T,
|
|
|
1262
1327
|
// U+0020, and NOT U+0085 (NEL, which is Cc). See
|
|
1263
1328
|
// https://tc39.es/ecma262/#sec-white-space and
|
|
1264
1329
|
// https://tc39.es/ecma262/#sec-line-terminators.
|
|
1265
|
-
// `\\
|
|
1266
|
-
//
|
|
1330
|
+
// `\\uXXXX` is Dafny's escape form under --unicode-char:false and `\\U{XXXX}`
|
|
1331
|
+
// under :true (each rejects the other); STRING_TRIM_SCALAR derives the latter.
|
|
1332
|
+
// The enumeration below is emitted Dafny source, not a decoded JS string.
|
|
1267
1333
|
const STRING_TRIM = `predicate IsJSWhitespace(c: char)
|
|
1268
1334
|
{
|
|
1269
|
-
c == '\\
|
|
1270
|
-
c == '\\
|
|
1271
|
-
('\\
|
|
1272
|
-
c == '\\
|
|
1273
|
-
c == '\\
|
|
1335
|
+
c == '\\u0009' || c == '\\u000A' || c == '\\u000B' || c == '\\u000C' || c == '\\u000D' ||
|
|
1336
|
+
c == '\\u0020' || c == '\\u00A0' || c == '\\u1680' ||
|
|
1337
|
+
('\\u2000' <= c <= '\\u200A') ||
|
|
1338
|
+
c == '\\u2028' || c == '\\u2029' || c == '\\u202F' || c == '\\u205F' ||
|
|
1339
|
+
c == '\\u3000' || c == '\\uFEFF'
|
|
1274
1340
|
}
|
|
1275
1341
|
|
|
1276
1342
|
function StringTrimLeft(s: string): string
|
|
@@ -1297,6 +1363,9 @@ function StringTrim(s: string): string
|
|
|
1297
1363
|
{
|
|
1298
1364
|
StringTrimRight(StringTrimLeft(s))
|
|
1299
1365
|
}`;
|
|
1366
|
+
// The same predicate and trims under `--unicode-char:true`, which the
|
|
1367
|
+
// `unicode-scalar` profile verifies under: byte-identical to what was always emitted.
|
|
1368
|
+
const STRING_TRIM_SCALAR = STRING_TRIM.replace(/\\u([0-9A-F]{4})/g, "\\U{$1}");
|
|
1300
1369
|
const STRING_TO_LOWER = `function StringToLower(s: string): string
|
|
1301
1370
|
ensures |StringToLower(s)| == |s|
|
|
1302
1371
|
decreases |s|
|
|
@@ -1317,17 +1386,20 @@ const STRING_TO_UPPER = `function StringToUpper(s: string): string
|
|
|
1317
1386
|
var upper := if 'a' <= c <= 'z' then (c - 'a' + 'A') as char else c;
|
|
1318
1387
|
[upper] + StringToUpper(s[1..])
|
|
1319
1388
|
}`;
|
|
1320
|
-
// `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)
|
|
1321
|
-
//
|
|
1322
|
-
//
|
|
1323
|
-
//
|
|
1389
|
+
// `String.fromCharCode(n)` — the inverse of `s.charCodeAt(i)`'s `(s[i] as int)`
|
|
1390
|
+
// in the UTF-16 code-unit model selected by dafny-commands.ts. LemmaScript
|
|
1391
|
+
// currently admits the direct 16-bit range; JavaScript's wider ToUint16 coercion
|
|
1392
|
+
// remains outside the verified subset.
|
|
1324
1393
|
const STRING_FROM_CHAR_CODE = `function StringFromCharCode(n: int): string
|
|
1325
|
-
requires 0 <= n <
|
|
1394
|
+
requires 0 <= n < 0x10000
|
|
1326
1395
|
ensures |StringFromCharCode(n)| == 1
|
|
1327
1396
|
ensures (StringFromCharCode(n)[0] as int) == n
|
|
1328
1397
|
{
|
|
1329
1398
|
[n as char]
|
|
1330
1399
|
}`;
|
|
1400
|
+
// `unicode-scalar` keeps the scalar range that was always required: a surrogate
|
|
1401
|
+
// is refused by precondition rather than admitted as a code unit.
|
|
1402
|
+
const STRING_FROM_CHAR_CODE_SCALAR = STRING_FROM_CHAR_CODE.replace("requires 0 <= n < 0x10000", "requires 0 <= n < 0xD800 || 0xE000 <= n < 0x110000");
|
|
1331
1403
|
// `s.repeat(n)` — n copies of s, concatenated. The per-index ensures is stated
|
|
1332
1404
|
// for the single-character receiver (the common case: padding with one digit).
|
|
1333
1405
|
const STRING_REPEAT = `function StringRepeat(s: string, n: int): string
|
|
@@ -1442,6 +1514,9 @@ const PREAMBLE_CODE = [
|
|
|
1442
1514
|
["SeqIndexOf", SEQ_INDEX_OF],
|
|
1443
1515
|
["SeqFindIndex", SEQ_FIND_INDEX],
|
|
1444
1516
|
["SeqFindLastIndex", SEQ_FIND_LAST_INDEX],
|
|
1517
|
+
["SeqFilter", SEQ_FILTER],
|
|
1518
|
+
["SeqAll", SEQ_ALL],
|
|
1519
|
+
["SeqFoldLeft", SEQ_FOLD_LEFT],
|
|
1445
1520
|
["SeqFilterSome", SEQ_FILTER_SOME],
|
|
1446
1521
|
["SeqFind", SEQ_FIND],
|
|
1447
1522
|
["SeqFindLast", SEQ_FIND_LAST],
|
|
@@ -1452,10 +1527,10 @@ const PREAMBLE_CODE = [
|
|
|
1452
1527
|
["StringSplit", STRING_SPLIT],
|
|
1453
1528
|
["SeqSort", SEQ_SORT],
|
|
1454
1529
|
["SeqSortBy", SEQ_SORT_BY],
|
|
1455
|
-
["StringTrim", STRING_TRIM],
|
|
1530
|
+
["StringTrim", () => isUtf16() ? STRING_TRIM : STRING_TRIM_SCALAR],
|
|
1456
1531
|
["StringToLower", STRING_TO_LOWER],
|
|
1457
1532
|
["StringToUpper", STRING_TO_UPPER],
|
|
1458
|
-
["StringFromCharCode", STRING_FROM_CHAR_CODE],
|
|
1533
|
+
["StringFromCharCode", () => isUtf16() ? STRING_FROM_CHAR_CODE : STRING_FROM_CHAR_CODE_SCALAR],
|
|
1459
1534
|
["StringRepeat", STRING_REPEAT],
|
|
1460
1535
|
["NatToString", NAT_TO_STRING],
|
|
1461
1536
|
["IntToString", INT_TO_STRING],
|
|
@@ -1467,6 +1542,21 @@ const PREAMBLE_CODE = [
|
|
|
1467
1542
|
["Perm", PERM],
|
|
1468
1543
|
["SetFromSeq", SET_FROM_SEQ],
|
|
1469
1544
|
];
|
|
1545
|
+
/**
|
|
1546
|
+
* The names of the functions, predicates, lemmas and methods declared in Dafny
|
|
1547
|
+
* `text`, in order: a declaration starts its line, may carry modifiers
|
|
1548
|
+
* (`ghost`, `opaque`, …) and attributes (`{:axiom}`), and is never in a comment.
|
|
1549
|
+
*/
|
|
1550
|
+
export function declaredNames(text) {
|
|
1551
|
+
const declaration = /^\s*(?:(?:ghost|opaque|static|twostate|least|greatest)\s+)*(?:function|predicate|lemma|method)(?:\s+\{:[^}]*\})*\s+([A-Za-z_][A-Za-z0-9_]*)/gm;
|
|
1552
|
+
return [...text.matchAll(declaration)].map(m => m[1]);
|
|
1553
|
+
}
|
|
1554
|
+
/**
|
|
1555
|
+
* Every function, predicate, lemma and method the preambles declare, so tools reading
|
|
1556
|
+
* Dafny results can tell lsc's own helpers from the user's members. The
|
|
1557
|
+
* profile-dependent entries only change literals, so either variant gives the same names.
|
|
1558
|
+
*/
|
|
1559
|
+
export const DAFNY_HELPER_NAMES = new Set(PREAMBLE_CODE.flatMap(([, code]) => declaredNames(typeof code === "function" ? code() : code)));
|
|
1470
1560
|
// ── Constructor and record helpers ───────────────────────────
|
|
1471
1561
|
let _recordCtors = new Map();
|
|
1472
1562
|
let _structureDecls = new Map();
|
|
@@ -1582,7 +1672,11 @@ function translatePattern(p) {
|
|
|
1582
1672
|
return `${ctorName}(${p.binders.map(escapeName).join(", ")})`;
|
|
1583
1673
|
}
|
|
1584
1674
|
export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
|
|
1675
|
+
// Programmatic callers share the CLI's compatibility checks.
|
|
1676
|
+
options = resolveOptions(options, tsFileName ?? "Dafny emission");
|
|
1585
1677
|
_useSafeSlice = options["safe-slice"];
|
|
1678
|
+
_stringSemantics = options["string-semantics"];
|
|
1679
|
+
_dafnyLibrary = options["dafny-library"];
|
|
1586
1680
|
resetDafnyNameCache();
|
|
1587
1681
|
buildRecordCtorMap(file.decls);
|
|
1588
1682
|
_neededPreambles.clear();
|
|
@@ -1647,10 +1741,13 @@ export function emitDafnyFile(file, tsFileName, options = DEFAULT_OPTIONS) {
|
|
|
1647
1741
|
const lines = [];
|
|
1648
1742
|
if (tsFileName)
|
|
1649
1743
|
lines.push(`// Generated by lsc from ${tsFileName}`);
|
|
1744
|
+
// Record every UTF-16 selection, including strings introduced by helpers.
|
|
1745
|
+
if (isUtf16())
|
|
1746
|
+
lines.push("// lsc options: string-semantics=javascript-utf16");
|
|
1650
1747
|
for (const [key, code] of PREAMBLE_CODE) {
|
|
1651
1748
|
if (_neededPreambles.has(key)) {
|
|
1652
1749
|
lines.push("");
|
|
1653
|
-
lines.push(code);
|
|
1750
|
+
lines.push(typeof code === "function" ? code() : code);
|
|
1654
1751
|
}
|
|
1655
1752
|
}
|
|
1656
1753
|
lines.push(...declLines);
|