Repository navigation
Expand file tree
/
Copy pathprecheck.ts
More file actions
273 lines (262 loc) · 11.3 KB
/
Copy pathprecheck.ts
File metadata and controls
273 lines (262 loc) · 11.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
import { queueCounts } from './queueCounts';
import crypto from 'node:crypto';
import { inspectScopedLeanDeclarations } from '../../src/math/leanSource';
import { LEAN_TASK_DECLARATIONS_MAX } from '../../src/math/leanTask';
import { maskLeanCommentsAndStrings } from '../../src/math/leanSyntax';
import type { WebEnvironment, WebPrecheck, WebPrecheckDiagnostic } from './shared';
import { libraryPackDigest, type LibraryPack } from '../../src/math/libraryPacks';
/** What the runner reports for one compile of the statement; `output` is Lean's `--json` stream. */
export type WebPrecheckOutput = {
output: string;
exitCode: number | null;
timedOut: boolean;
/** Set only after the host's isolated query checked this declaration and its transitive axioms. */
checkedTarget?: string;
};
export type WebPrecheckRunner = (
input: {
environment: WebEnvironment;
source: string;
libraryPack?: LibraryPack;
/** Host-selected immutable candidate context; ordinary editor checks do not supply files. */
sourceFile?: string;
dependencySources?: { file: string; source: string }[];
candidateTarget?: { name: string; expectedType?: string };
},
signal: AbortSignal,
) => Promise<WebPrecheckOutput>;
const maxDiagnostics = 40,
maxMessage = 1_500;
// Lean counts lines from 1 and columns in code points from 0; offsets here are JavaScript string indexes.
function position(source: string, offset: number) {
const before = source.slice(0, offset),
start = before.lastIndexOf('\n') + 1;
return { line: before.split('\n').length, column: [...before.slice(start)].length };
}
/**
* The checks bootstrapLeanTask makes before a run starts, with a position for each, so the editor can point at the
* problem without starting Lean. tests/webPrecheck.test.ts keeps the codes in step with src/math/leanTask.ts.
*/
export function inspectStatement(source: string): WebPrecheckDiagnostic[] {
const found: WebPrecheckDiagnostic[] = [];
const add = (code: string, offset: number, name?: string) =>
found.push({ severity: 'error', code, ...position(source, offset), ...(name ? { name } : {}) });
// With the u flag a surrogate class only matches unpaired halves, which do not survive UTF-8.
const invalid = /[\x00-\x08\x0b\x0c\x0e-\x1f\x7f\ud800-\udfff]/u.exec(source);
if (invalid) {
add('lean_task_input_invalid', invalid.index);
return found;
}
const declarations = inspectScopedLeanDeclarations(source);
if (declarations.length > LEAN_TASK_DECLARATIONS_MAX) {
add('lean_task_declarations_limit', declarations[LEAN_TASK_DECLARATIONS_MAX].startOffset);
return found;
}
const seen = new Set<string>(),
repeats = new Set<number>();
for (const { qualifiedName, startOffset } of declarations) {
if (seen.has(qualifiedName)) {
add('lean_task_declaration_names_ambiguous', startOffset, qualifiedName);
repeats.add(startOffset);
}
seen.add(qualifiedName);
}
const targets = new Set(declarations.filter(item => item.kind === 'theorem').map(item => item.startOffset));
if (!targets.size) add('lean_task_targets_missing', 0);
// Targets are found by their final name component, which a theorem may not share with a differently named declaration.
const local = (name: string) => name.split('.').at(-1)!,
full = new Map<string, Set<string>>();
for (const { name, qualifiedName } of declarations)
full.set(local(name), (full.get(local(name)) ?? new Set()).add(qualifiedName));
const shared = new Set(
declarations
.filter(item => item.kind === 'theorem' && full.get(local(item.name))!.size > 1)
.map(item => local(item.name)),
);
for (const { name, qualifiedName, startOffset } of declarations)
if (shared.has(local(name)) && !repeats.has(startOffset))
add('lean_task_target_name_ambiguous', startOffset, qualifiedName);
for (const keyword of maskLeanCommentsAndStrings(source).matchAll(
/(?<![\p{L}\p{M}\p{N}_'.?!])(?:theorem|lemma)(?![\p{L}\p{M}\p{N}_'.?!])/gu,
))
if (!targets.has(keyword.index)) add('lean_task_declaration_invalid', keyword.index);
return found.slice(0, maxDiagnostics);
}
const isRecord = (value: unknown): value is Record<string, unknown> =>
Boolean(value && typeof value === 'object' && !Array.isArray(value));
const place = (value: unknown) =>
isRecord(value) &&
Number.isSafeInteger(value.line) &&
Number(value.line) >= 1 &&
Number.isSafeInteger(value.column) &&
Number(value.column) >= 0
? { line: Number(value.line), column: Number(value.column) }
: undefined;
/** Reads `lean --json` lines. Sorry warnings become the target count; `#eval` output and silent messages are dropped. */
export function leanDiagnostics(output: string) {
const diagnostics: WebPrecheckDiagnostic[] = [];
let sorries = 0,
errors = 0;
for (const line of output.split('\n')) {
let value: unknown;
try {
value = JSON.parse(line);
} catch {
continue;
}
if (!isRecord(value) || value.isSilent === true || typeof value.data !== 'string') continue;
const severity = value.severity,
at = place(value.pos);
if ((severity !== 'error' && severity !== 'warning') || !at) continue;
if (severity === 'warning' && (value.kind === 'hasSorry' || /^declaration uses [`']sorry[`']$/u.test(value.data))) {
sorries++;
continue;
}
if (severity === 'error') errors++;
if (diagnostics.length >= maxDiagnostics) continue;
const end = place(value.endPos);
diagnostics.push({
severity,
...at,
...(end ? { endLine: end.line, endColumn: end.column } : {}),
message: value.data.length > maxMessage ? `${value.data.slice(0, maxMessage)}…` : value.data,
});
}
// Errors first, each group in source order, so the first entry is the one to fix.
diagnostics.sort(
(a, b) =>
Number(a.severity === 'warning') - Number(b.severity === 'warning') || a.line - b.line || a.column - b.column,
);
return { diagnostics, sorries, errors };
}
/** Turns one compile into a result. A crash without a diagnostic is the service's problem, not the statement's. */
export function precheckResult(environment: WebEnvironment, run: WebPrecheckOutput, targets: number): WebPrecheck {
const { diagnostics, sorries, errors } = leanDiagnostics(run.output);
const base = { environment, targets, sorries, diagnostics };
if (run.timedOut) return { ...base, status: 'timeout' };
if (errors) return { ...base, status: 'errors' };
if (run.exitCode !== 0) return { ...base, status: 'unavailable' };
return { ...base, status: sorries ? 'ready' : 'complete' };
}
export class PrecheckSuperseded extends Error {}
/**
* Compiles statements for the editor. Each editor scope has at most one check in flight (a newer one replaces it), the
* service runs a few at a time with a short queue, and identical statements come from a small cache.
*/
export class WebPrechecker {
private readonly cache = new Map<string, WebPrecheck>();
private readonly inflight = new Map<string, AbortController>();
private readonly recent = new Map<string, number[]>();
private readonly waiting: Array<{ start(): void; createdAt: string }> = [];
private running = 0;
constructor(
private readonly runner: WebPrecheckRunner,
private readonly limits = { concurrency: 2, queue: 6, perMinute: 20, cache: 200 },
) {}
queueState() {
return { running: this.running, waiting: this.waiting.map(item => item.createdAt) };
}
counts() {
return queueCounts(this.queueState(), true);
}
async check(
owner: string,
input: { environment: WebEnvironment; source: string; checkScope?: string; libraryPack?: LibraryPack },
signal: AbortSignal,
): Promise<WebPrecheck> {
signal.throwIfAborted();
const scope = JSON.stringify([owner, input.checkScope ?? 'legacy']);
this.inflight.get(scope)?.abort(new PrecheckSuperseded());
const structural = inspectStatement(input.source);
const targets = structural.some(item => item.code === 'lean_task_input_invalid')
? 0
: inspectScopedLeanDeclarations(input.source).filter(item => item.kind === 'theorem').length;
if (structural.length)
return { status: 'invalid', environment: input.environment, targets, sorries: 0, diagnostics: structural };
const key = crypto
.createHash('sha256')
.update(`${input.environment}\0${input.source}\0${input.libraryPack ? libraryPackDigest(input.libraryPack) : ''}`)
.digest('hex');
const cached = this.cache.get(key);
if (cached) {
this.cache.delete(key);
this.cache.set(key, cached);
return { ...cached, cached: true };
}
const busy = (): WebPrecheck => ({
status: 'busy',
environment: input.environment,
targets,
sorries: 0,
diagnostics: [],
});
const now = Date.now(),
times = (this.recent.get(owner) ?? []).filter(time => now - time < 60_000);
if (times.length >= this.limits.perMinute) {
this.recent.set(owner, times);
return busy();
}
// Reserve the owner rate allowance before waiting; distinct scopes share this limit.
times.push(now);
this.recent.set(owner, times);
const controller = new AbortController();
this.inflight.set(scope, controller);
const stop = () => controller.abort(signal.reason);
signal.addEventListener('abort', stop, { once: true });
try {
if (this.running >= this.limits.concurrency) {
if (this.waiting.length >= this.limits.queue) return busy();
await new Promise<void>((resolve, reject) => {
const turn = {
start: () => {
controller.signal.removeEventListener('abort', leave);
resolve();
},
createdAt: new Date().toISOString(),
};
const leave = () => {
this.waiting.splice(this.waiting.indexOf(turn), 1);
reject(controller.signal.reason);
};
this.waiting.push(turn);
controller.signal.addEventListener('abort', leave, { once: true });
});
} else {
this.running++;
}
try {
controller.signal.throwIfAborted();
let output: WebPrecheckOutput | undefined;
try {
output = await this.runner(input, controller.signal);
} catch {
if (controller.signal.aborted) throw controller.signal.reason;
}
controller.signal.throwIfAborted();
if (!output)
return { status: 'unavailable', environment: input.environment, targets, sorries: 0, diagnostics: [] };
const result = precheckResult(input.environment, output, targets);
// Only a finished compile describes the statement; timeouts and failures may pass on the next try.
if (['errors', 'ready', 'complete'].includes(result.status)) {
this.cache.set(key, result);
if (this.cache.size > this.limits.cache) this.cache.delete(this.cache.keys().next().value!);
}
return result;
} finally {
const next = this.waiting.shift();
if (next) next.start();
else this.running--;
}
} finally {
signal.removeEventListener('abort', stop);
if (this.inflight.get(scope) === controller) this.inflight.delete(scope);
}
}
prune() {
const now = Date.now();
for (const [owner, times] of this.recent) if (times.every(time => now - time >= 60_000)) this.recent.delete(owner);
}
close() {
for (const controller of this.inflight.values()) controller.abort(new PrecheckSuperseded());
}
}