Repository navigation
Expand file tree
/
Copy pathformalizationReport.ts
More file actions
277 lines (272 loc) · 12.5 KB
/
Copy pathformalizationReport.ts
File metadata and controls
277 lines (272 loc) · 12.5 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
274
275
276
277
import { formalizationDigest, type FormalizationEvidence } from '../../src/math/formalization';
import {
collapsed,
count,
identifierChar,
lineEnds,
offsetSpans,
type SourceOffsets,
} from '../../src/math/informalizationAlignment';
import { inspectLeanDeclarationRegions, inspectScopedLeanDeclarations } from '../../src/math/leanSource';
import { recordedLeanTaskEnvironment } from '../../src/math/leanTaskEnvironment';
import { maskLeanComments } from '../../src/math/leanSyntax';
import {
webFormalizationAspects,
webFormalizationRelationRank,
type WebExplanationSpan,
type WebFormalizationCorrespondence,
type WebFormalizationReport,
} from './shared';
/** Spans (lines from 1, UTF-16 columns) of `text[start, end)` in a whole file. */
export const fileSpans = (text: string, place: SourceOffsets): WebExplanationSpan[] =>
offsetSpans(text, place.start, place.end).map(span => ({ ...span, line: span.line + 1 }));
/**
* Where a Lean file states the named declarations (every one when `names` is absent): a theorem's header up to its `:=`,
* a definition's or instance's whole text. Offsets with CRLF read as LF.
*/
export function declarationRegions(source: string, names?: ReadonlySet<string>): SourceOffsets[] {
const masked = maskLeanComments(lineEnds(source)),
regions = inspectLeanDeclarationRegions(masked);
return inspectScopedLeanDeclarations(masked).flatMap((item, index) => {
const region = regions[index]!;
if (names && !names.has(item.qualifiedName)) return [];
const header =
masked.slice(region.bodyOffset - 2, region.bodyOffset) === ':=' ? region.bodyOffset - 2 : region.bodyOffset;
return [{ start: item.startOffset, end: item.kind === 'theorem' ? header : region.endOffset }];
});
}
/** Qualified names of the declarations a Lean file states. */
export const declarationNames = (source: string) =>
new Set(inspectScopedLeanDeclarations(maskLeanComments(lineEnds(source))).map(item => item.qualifiedName));
type Review = { reviewer: string; review: NonNullable<FormalizationEvidence['review']> };
const reviewsOf = (evidence: FormalizationEvidence): Review[] =>
evidence.workflow
? evidence.workflow.reviews.map(item => ({ reviewer: item.reviewerId, review: item.review }))
: evidence.review
? [{ reviewer: 'reviewer', review: evidence.review }]
: [];
const position = (value: number | null) => value ?? Number.MAX_SAFE_INTEGER;
/** A statement fragment's trailing proof hole (`:= by sorry`), which a proof of that statement replaces. */
const PROOF_HOLE = /\s*:=\s*(?:by\s+)?sorry\s*$/u;
/** Whether `source[start, end)` starts or ends inside a name, as `x` does in `exp` or `x₁`. */
function cutsName(source: string, start: number, end: number) {
const name = (char: string | undefined) => char !== undefined && identifierChar.test(char);
return (
(name([...source.slice(start, start + 2)][0]) && name([...source.slice(Math.max(0, start - 2), start)].at(-1))) ||
(name([...source.slice(Math.max(start, end - 2), end)].at(-1)) && name([...source.slice(end, end + 2)][0]))
);
}
/**
* Every place inside `regions` where `value` is written, matched as the host's findWithin matches (whitespace runs
* collapsed) but never inside a name, copies not overlapping, at most 64: a definition or domain is often written more
* than once.
*/
function writtenWithin(source: string, value: string, regions: readonly SourceOffsets[]): SourceOffsets[] {
const { text, offsets } = collapsed(source),
needle = collapsed(value).text,
found: SourceOffsets[] = [];
if (!needle) return found;
for (let at = text.indexOf(needle); at >= 0 && found.length < 64; at = text.indexOf(needle, at + 1)) {
const start = offsets[at]!,
end = offsets[at + needle.length - 1]! + 1;
if (cutsName(source, start, end) || !regions.some(region => start >= region.start && end <= region.end)) continue;
found.push({ start, end });
at += needle.length - 1;
}
return found;
}
/**
* Where an original fragment written more than once is quoted: the copy inside a longer fragment that is around no other
* copy and whose Lean overlaps its own, else the first. In "spanned by a countably infinite set … is finite or countably
* infinite", "countably infinite" matched with `Set.Countable T ∧ Set.Infinite T` is the second.
*/
function placeRepeats(original: string, items: readonly WebFormalizationCorrespondence[]) {
const first = items.map(item => item.originalStart);
const overlap = (a: WebExplanationSpan, b: WebExplanationSpan) =>
a.line === b.line && a.start < b.end && b.start < a.end;
for (const item of items) {
if (item.originalStart === null || original.indexOf(item.original, item.originalStart + 1) < 0) continue;
const copies: number[] = [],
length = item.original.length;
for (let at = item.originalStart; at >= 0 && copies.length < 16; at = original.indexOf(item.original, at + 1))
copies.push(at);
const agreed = copies.find(copy =>
items.some((other, index) => {
const start = first[index];
if (other === item || start === null || !other.lean.some(span => item.lean.some(own => overlap(span, own))))
return false;
const inside = (at: number) => start <= at && at + length <= start + other.original.length;
return inside(copy) && copies.filter(inside).length === 1;
}),
);
if (agreed !== undefined) {
item.originalStart = agreed;
item.originalEnd = agreed + length;
}
}
}
/**
* The structured reviews' fragment correspondences, one per distinct (aspect, original, Lean) triple with the weakest
* relation any reviewer gave it, and every place its Lean fragment is written inside `regions` of `source` (comments
* skipped), and where its original fragment is quoted (see placeRepeats). A fragment that ends in the statement's proof
* hole is found without it, since a proof's header stops at `:=`.
*/
export function formalizationCorrespondences(
evidence: FormalizationEvidence,
source: string,
regions: readonly SourceOffsets[],
): WebFormalizationCorrespondence[] {
const text = lineEnds(source),
masked = maskLeanComments(text),
original = evidence.request.statement;
const merged = new Map<string, WebFormalizationCorrespondence>();
for (const { review } of reviewsOf(evidence)) {
if (!('correspondences' in review)) continue;
for (const item of review.correspondences) {
const key = JSON.stringify([item.aspect, item.originalFragment, item.candidateFragment]),
found = merged.get(key);
const explanation = item.explanation.trim();
if (found) {
found.reviewers++;
if (webFormalizationRelationRank[item.relation] > webFormalizationRelationRank[found.relation])
found.relation = item.relation;
if (explanation && !found.explanations.includes(explanation)) found.explanations.push(explanation);
continue;
}
const at = original.indexOf(item.originalFragment),
header = item.candidateFragment.replace(PROOF_HOLE, '');
const written = writtenWithin(masked, item.candidateFragment, regions);
const places =
written.length || !header || header === item.candidateFragment
? written
: writtenWithin(masked, header, regions);
merged.set(key, {
aspect: item.aspect,
relation: item.relation,
original: item.originalFragment,
originalStart: at < 0 ? null : at,
originalEnd: at < 0 ? null : at + item.originalFragment.length,
leanText: item.candidateFragment,
lean: places.flatMap(place => fileSpans(text, place)),
reviewers: 1,
explanations: explanation ? [explanation] : [],
});
}
}
placeRepeats(original, [...merged.values()]);
const order = (aspect: string) => webFormalizationAspects.indexOf(aspect as (typeof webFormalizationAspects)[number]);
return [...merged.values()].sort(
(a, b) => order(a.aspect) - order(b.aspect) || position(a.originalStart) - position(b.originalStart),
);
}
/** The comparison page preserves whether a statement was independently reviewed or only compiled. */
export function formalizationReport(evidence: FormalizationEvidence): WebFormalizationReport {
const statement = lineEnds(evidence.candidate.source);
// The report names the Lean and Mathlib the evidence was checked in, not today's pins.
const environment = recordedLeanTaskEnvironment(evidence.request.environment, evidence.request.environmentDigest);
if (!environment) throw new Error('formalization_request_environment_unknown');
const masked = maskLeanComments(statement),
regions = inspectLeanDeclarationRegions(masked);
const declarations = inspectScopedLeanDeclarations(masked),
original = evidence.request.statement;
const targets = evidence.targets.map(target => {
const index = declarations.findIndex(item => item.qualifiedName === target.name);
if (index < 0) return { name: target.name, lines: { start: 1, end: count(statement, statement.length) + 1 } };
const region = regions[index]!,
end = statement.slice(0, region.endOffset).trimEnd().length;
return {
name: target.name,
lines: { start: count(statement, region.startOffset) + 1, end: count(statement, Math.max(0, end - 1)) + 1 },
};
});
const plan = evidence.workflow?.plan.output,
quotes = (ids: readonly string[]) =>
ids.flatMap(id => {
const span = plan?.spans.find(item => item.id === id);
return span ? [span.text] : [];
});
const { translation } = evidence;
return {
schema: 'theorem-os.web-formalization-report.v1',
problemId: evidence.request.problemId,
original,
statement,
environment: evidence.request.environment,
toolchain: environment.toolchain,
mathlibRevision: environment.mathlibRevision ?? null,
targets,
correspondences: formalizationCorrespondences(evidence, statement, [{ start: 0, end: statement.length }]),
...(evidence.schema === 'theorem-os.formalization-evidence.v4' ? { semanticReview: 'not-performed' as const } : {}),
backtranslation: translation
? {
mathematics: translation.mathematics,
assumptions: translation.assumptions,
definitions: translation.definitions,
targets: translation.targets.map(item => ({ name: item.name, mathematics: item.mathematics })),
}
: null,
coverage: evidence.candidate.coverage.map(item => {
const at = original.indexOf(item.originalText);
return {
original: item.originalText,
originalStart: at < 0 ? null : at,
targets: item.targetNames,
explanation: item.explanation,
};
}),
...(plan
? {
plan: {
taskKind: plan.taskKind,
conclusions: plan.conclusions.map(item => ({
mathematics: item.mathematics,
targets: item.targetNames,
quotes: quotes(item.spanIds),
})),
assumptions: plan.assumptions.map(item => ({
mathematics: item.mathematics,
quotes: quotes(item.spanIds),
})),
definitions: plan.definitions.map(item => ({
mathematics: item.mathematics,
names: item.leanNames,
quotes: quotes(item.spanIds),
})),
unresolved: plan.unresolved.map(item => ({ description: item.description, quotes: quotes(item.spanIds) })),
},
}
: {}),
reviews: reviewsOf(evidence).map(({ reviewer, review }) =>
'correspondences' in review
? {
reviewer,
verdict: review.verdict,
summary: review.summary,
checks: Object.entries(review.checks).map(([name, value]) => ({ name, value })),
issues: [],
...('fidelity' in review && review.fidelity
? {
fidelity: review.fidelity.targets.map(item => ({
target: item.targetName,
original: item.originalFragment,
sourceClaim: item.sourceClaim,
candidateClaim: item.candidateClaim,
})),
}
: {}),
}
: {
reviewer,
verdict: review.verdict,
summary: review.summary,
checks: Object.entries(review.checks).map(([name, value]) => ({ name, value: String(value) })),
issues: 'issues' in review ? review.issues : [],
},
),
model: evidence.request.model,
effort: evidence.request.effort,
rounds: evidence.round,
evidenceSha256: formalizationDigest(evidence),
approvedAt: evidence.approvedAt,
};
}