Repository navigation
Expand file tree
/
Copy pathrecordRender.js
More file actions
1715 lines (1614 loc) · 64.9 KB
/
Copy pathrecordRender.js
File metadata and controls
1715 lines (1614 loc) · 64.9 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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// @ts-check
/* Commit records, parsed from a commit message and drawn as HTML. The
* caller (commitRecords.js) reads each commit's identity and message from
* git. The
* format is the `records` skill's (.agents/skills/records/SKILL.md): a
* subject, a `Why:` section, object blocks such as
* `AST modified (raw extensions):`, each followed by an optional `Example:`
* program and its forms as `Before (<form>):` and `After (<form>):` blocks,
* `Review:` and `Breaking:` sections, and the trailers.
*/
const REPO_URL = "https://github.com/rescript-lang/rescript";
/** @param {string} s */
export const esc = s =>
s
.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">")
.replace(/"/g, """);
// ---------------------------------------------------------------------------
// The forms a record writes an object in, and how each is drawn
/**
* How a form is drawn.
* @typedef {"math" | "tree" | "matrix" | "mapping" | "rescript" | "js" | "lambda" | "text" | "report"} Drawing
*/
/**
* Each form's drawing, by the name a `Before (<form>):` or `After (<form>):`
* block gives it: a compiler's printed tree or code, a diagnostic, or a
* hand-written typing rule, clause matrix or representation mapping, or
* reanalyze's report. A form
* of another name is drawn as text.
* @type {Record<string, Drawing>}
*/
export const FORMS = {
parse: "tree",
expanded: "tree",
typed: "tree",
lambda: "lambda",
js: "js",
rescript: "rescript",
diagnostic: "text",
text: "text",
rule: "math",
matrix: "matrix",
representation: "mapping",
reanalyze: "report",
};
/**
* An object block's heading: `<Kind> <added|modified|removed> (<object>)`,
* the kind one word, the object's parentheses optional.
*/
export const BLOCK =
/^([A-Z][A-Za-z]*) (added|modified|removed)(?: \(((?:[^()]|\([^()]*\))*)\))?$/;
/** A section an object block holds: its example or one version of a form. */
export const PART = /^(?:Example|(Before|After) \(([a-z]+)\))$/;
// ---------------------------------------------------------------------------
// Records
/**
* @typedef {{ name: string, text: string[], block: string[] }} Section
* @typedef {{
* sha: string, author: string, login?: string, date: string, message: string
* }} CommitInfo
* @typedef {CommitInfo & {
* subject: string, sections: Section[], coauthors: string[]
* }} CommitRecord
* @typedef {{ range?: string, records: CommitRecord[] }} Group
*/
/** The sections a message names besides object blocks and their parts. */
const NAMED = new Set(["Why", "Review", "Breaking"]);
/**
* A trailer line: `Key: value`, the key one word of letters, digits and
* hyphens other than a section's name.
* @param {string} l
*/
const isTrailer = l => {
const key = /^([A-Za-z][A-Za-z0-9-]*):\s+\S/.exec(l)?.[1];
return key !== undefined && !NAMED.has(key) && key !== "Example";
};
/**
* The line a message's trailers start at: the first of its last lines that
* are trailers or lines continuing one (starting with a space), the run
* starting at a trailer.
* @param {string[]} lines
*/
function trailerStart(lines) {
let start = lines.length;
for (let k = lines.length - 1; k > 0; k--) {
if (isTrailer(lines[k])) start = k;
else if (!/^\s+\S/.test(lines[k])) break;
}
return start;
}
/**
* A line with the tabs of its indentation expanded to stops 4 columns apart.
* @param {string} l
*/
const untab = l =>
l.replace(/^[ \t]+/, ws => {
let col = 0;
for (const c of ws) col = c === "\t" ? col + 4 - (col % 4) : col + 1;
return " ".repeat(col);
});
/** Whether a line is indented by 4 spaces or more. @param {string} l */
export const isIndented = l => /^ {4,}\S/.test(l);
/**
* A record's subject, sections and trailers. A section starts at a line
* `Name:`, where the name is an object block's heading, a version heading,
* `Why`, `Review` or `Breaking` outside a paragraph of prose, or `Example`
* alone on its line; it holds the text after its colon and the lines
* indented by 4 spaces under it. A blank line ends a section that holds
* only text. Unnamed sections hold the paragraphs and indented blocks
* between.
* @param {string} text
*/
function parseMessage(text) {
const lines = text.trimEnd().split("\n").map(untab);
const end = trailerStart(lines);
/** @type {Section[]} */
const sections = [];
/** @type {Section | undefined} */
let current;
const prose = () => {
/** @type {Section} */
const s = { name: "", text: [], block: [] };
sections.push(s);
return s;
};
for (const line of lines.slice(1, end)) {
const head = /^(\S(?:[^:]|\([^()]*\))*):(?:\s+(.*))?$/.exec(line);
const name = head?.[1] ?? "";
// `Why:`, `Review:` or `Breaking:` that prose wraps onto a line of its
// paragraph continues the paragraph.
const inParagraph =
current && !current.name && current.text.length && !current.block.length;
if (
head &&
(BLOCK.test(name) ||
(PART.test(name) && !(name === "Example" && head[2])) ||
(NAMED.has(name) && !inParagraph))
) {
current = { name, text: head[2] ? [head[2]] : [], block: [] };
sections.push(current);
} else if (isIndented(line)) {
current ??= prose();
current.block.push(line);
} else if (line.trim()) {
if (!current || current.block.length) current = prose();
current.text.push(line.trim());
} else if (current?.block.length) current.block.push("");
else if (current && (!current.name || current.text.length))
current = undefined;
}
return { subject: lines[0], sections, trailers: lines.slice(end) };
}
/**
* AI assistants by the email their `Co-Authored-By:` trailers give, and the
* short name drawn for them: the name in the trailer changes with the model
* ("Claude Opus 5.5"), the email does not.
*/
const ASSISTANTS = new Map([["noreply@anthropic.com", "Claude"]]);
/**
* A commit's record: its identity and its message, parsed; the co-authors
* are the names its `Co-Authored-By:` trailers give, an assistant's short.
* @param {CommitInfo} commit
* @returns {CommitRecord}
*/
export function parseRecord(commit) {
const { subject, sections, trailers } = parseMessage(commit.message);
const coauthors = trailers
.filter(l => /^Co-Authored-By:/i.test(l))
.map(l => {
const [, name, email = ""] =
/^Co-Authored-By:\s*(.*?)\s*(?:<([^>]*)>)?\s*$/i.exec(l) ?? [];
return ASSISTANTS.get(email.toLowerCase()) ?? name;
});
return { ...commit, subject, sections, coauthors: [...new Set(coauthors)] };
}
/**
* Whether a record says why its commit is made, as the format requires: a
* paragraph of prose or a `Why:` section with content. A subject with only
* trailers, object blocks or code has no description.
* @param {CommitRecord} r
*/
export const described = r =>
r.sections.some(
s =>
(s.name === "" && s.text.length > 0) ||
(s.name === "Why" && (s.text.length > 0 || s.block.some(l => l.trim()))),
);
/**
* Who made a commit, as `A Person + Claude`: its author, by the GitHub login
* when known, and its co-authors, each name drawn by `name` and the login
* as a link to the profile by `profile` (a link, not an `@` mention, which
* would notify the user).
* @param {CommitRecord} r
* @param {(name: string) => string} name
* @param {(login: string, url: string) => string} profile
*/
export const byline = (r, name, profile) =>
[
r.login && /^[A-Za-z0-9-]+$/.test(r.login)
? profile(r.login, `https://github.com/${r.login}`)
: name(r.author),
...r.coauthors.map(name),
].join(" + ");
// ---------------------------------------------------------------------------
// Code, highlighted by token
/**
* A language's tokens: a regular expression whose named groups are the
* token classes, and its keywords among the identifiers.
* @typedef {{ token: RegExp, keywords: Set<string> }} Lang
*/
/** @param {string} s */
const words = s => new Set(s.split(" "));
/** @type {{ [L in "rescript" | "js" | "lambda"]: Lang }} */
const LANG = {
rescript: {
token:
/(?<c>\/\/[^\n]*|\/\*[\s\S]*?\*\/)|(?<s>"(?:\\.|[^"\\\n])*"|`(?:\\.|[^`\\])*`|'(?:\\u\{[0-9a-fA-F]+\}|\\.|[^'\\\n])')|(?<a>@{1,2}[A-Za-z_][\w.]*|%{1,2}[A-Za-z_][\w.]*)|(?<p>#[A-Za-z_]\w*)|(?<n>\b\d[\d_]*(?:\.\d+)?(?:[eE][+-]?\d+)?n?\b|\b0[xob][0-9a-fA-F_]+\b)|(?<v>'[a-z]\w*)|(?<i>[A-Za-z_][\w']*)/g,
keywords: words(
"let rec and switch if else type module open include mutable async await for in to downto while external exception try catch when as private constraint assert dict list true false break continue of",
),
},
js: {
token:
/(?<c>\/\/[^\n]*|\/\*[\s\S]*?\*\/)|(?<s>"(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|(?<n>\b\d+(?:\.\d+)?(?:[eE][+-]?\d+)?n?\b|\b0x[0-9a-fA-F]+\b)|(?<i>[A-Za-z_$][\w$]*)/g,
keywords: words(
"let const var function return if else for while do new import export from as default this true false null undefined typeof instanceof class async await throw try catch finally of in switch case break continue void delete yield",
),
},
lambda: {
token:
/(?<s>"(?:\\.|[^"\\\n])*")|(?<p>#[A-Za-z_][\w.]*)|(?<i>[A-Za-z_][\w$.']*)(?<stamp>\/\d+)?|(?<n>-?\b\d+(?:\.\d+)?[nl]?\b)|(?<paren>[()])/g,
keywords: words(
"let letrec function if switch stringswitch staticcatch staticraise catch exit try with while for seq apply makeblock field setfield default case",
),
},
};
/**
* Code highlighted by token: comments, strings, attributes and extensions,
* polymorphic variants, numbers, keywords, capitalised names (modules,
* constructors), type variables; in Lambda, primitives (`#is_not_none`),
* identifier stamps (`x/1002`) and parentheses.
* @param {string} code
* @param {keyof typeof LANG} lang
*/
function highlight(code, lang) {
const { token, keywords } = LANG[lang];
let out = "";
let last = 0;
for (const m of code.matchAll(token)) {
out += esc(code.slice(last, m.index));
last = (m.index ?? 0) + m[0].length;
const g = m.groups ?? {};
const span = (/** @type {string} */ cls, /** @type {string} */ t) =>
t
.split("\n")
.map(part => `<span class="${cls}">${esc(part)}</span>`)
.join("\n");
if (g.i !== undefined) {
const id = g.i;
out += keywords.has(id)
? span("k", id)
: /^[A-Z]/.test(id)
? span("t", id)
: esc(id);
if (g.stamp) out += span("stamp", g.stamp);
} else {
const cls = ["c", "s", "a", "p", "n", "v", "paren"].find(
k => g[k] !== undefined,
);
out += cls ? span(cls, m[0]) : esc(m[0]);
}
}
return out + esc(code.slice(last));
}
/**
* The pairs of line numbers a longest common subsequence of `a` and `b`
* matches, in order, lines compared by `key`.
* @param {string[]} a
* @param {string[]} b
* @param {(line: string) => string} key
* @returns {[number, number][]}
*/
export function matchLines(a, b, key) {
const x = a.map(key);
const y = b.map(key);
/** @type {number[][]} */
const t = Array.from({ length: x.length + 1 }, () =>
new Array(y.length + 1).fill(0),
);
for (let i = x.length - 1; i >= 0; i--)
for (let j = y.length - 1; j >= 0; j--)
t[i][j] =
x[i] === y[j]
? t[i + 1][j + 1] + 1
: Math.max(t[i + 1][j], t[i][j + 1]);
/** @type {[number, number][]} */
const pairs = [];
for (let i = 0, j = 0; i < x.length && j < y.length; ) {
if (x[i] === y[j]) pairs.push([i++, j++]);
else if (t[i + 1][j] >= t[i][j + 1]) i++;
else j++;
}
return pairs;
}
/**
* The rows of a Before/After pair drawn side by side: a line common to both
* versions is one row; between two common lines, the lines only Before has
* and the lines only After has share rows, the shorter side padded with
* gaps (`null`). Lines compare with their indentation, so a line that moves
* to another depth is a change.
* @param {string[]} a
* @param {string[]} b
* @returns {{ a: number | null, b: number | null, same: boolean }[]}
*/
export function alignLines(a, b) {
/** @type {{ a: number | null, b: number | null, same: boolean }[]} */
const rows = [];
let i = 0;
let j = 0;
const ends = [...matchLines(a, b, l => l.trimEnd()), [a.length, b.length]];
for (const [x, y] of ends) {
for (let k = 0; k < Math.max(x - i, y - j); k++)
rows.push({
a: i + k < x ? i + k : null,
b: j + k < y ? j + k : null,
same: false,
});
if (x < a.length) rows.push({ a: x, b: y, same: true });
i = x + 1;
j = y + 1;
}
return rows;
}
/**
* The lines or parts of one version of a Before/After pair that the other
* lacks, and their shading.
* @typedef {{ marked?: Set<number>, mark?: "add" | "del" }} Marks
*/
/**
* One drawn line. A line too long for its column wraps, its continuation
* indented two columns past `indent`, the column its content starts at.
* @param {string} html
* @param {number} indent
* @param {string} [cls]
* @param {string} [style]
*/
const line = (html, indent, cls = "", style = "") =>
`<span class="ln${cls ? ` ${cls}` : ""}" style="${style}--i:${indent}">${html || " "}</span>`;
/** The column a line's content starts at. @param {string} l */
const indentOf = l => /^ */.exec(l)?.[0].length ?? 0;
/**
* Lines of code, each drawn by `draw`, as HTML, one string a line.
* @param {string[]} lines
* @param {(code: string) => string} draw
*/
const codeHtml = (lines, draw) => draw(lines.join("\n")).split("\n");
/** An elision line, `…` and any text, marking lines left out. @param {string} l */
export const elided = l => l.trimStart().startsWith("…");
/**
* Lines of code, each drawn by `draw`, the marked ones shaded and the
* elisions muted.
* @param {string[]} lines
* @param {(code: string) => string} draw
* @param {Marks} [marks]
*/
function codeLines(lines, draw, marks = {}) {
return `<pre class="code">${codeHtml(lines, draw)
.map((l, i) =>
line(
l,
indentOf(lines[i] ?? ""),
elided(lines[i] ?? "")
? "elide"
: marks.marked?.has(i)
? marks.mark
: "",
),
)
.join("")}</pre>`;
}
/** A note line of a drawing: `label: text`. */
export const NOTE = /^\s*[a-z][\w ]{0,20}:\s/;
/**
* The parts of a figure (a typing rule or a rewrite) that a Before/After
* pair compares: each part's text and its slot, the place it holds in the
* figure. Parts compare with the parts of the other version in their slot.
* @typedef {{ slot: string, text: string }} Atom
*/
/**
* The parts of `a` and of `b` outside a longest common subsequence of the
* parts in each slot: the parts a Before/After pair of figures changes.
* @param {Atom[]} a
* @param {Atom[]} b
* @returns {[Set<number>, Set<number>]}
*/
export function atomDiff(a, b) {
const del = new Set();
const add = new Set();
for (const slot of new Set([...a, ...b].map(x => x.slot))) {
const ia = a.flatMap((x, n) => (x.slot === slot ? [n] : []));
const ib = b.flatMap((x, n) => (x.slot === slot ? [n] : []));
const pairs = matchLines(
ia.map(n => a[n].text),
ib.map(n => b[n].text),
t => t.trim(),
);
const ka = new Set(pairs.map(p => p[0]));
const kb = new Set(pairs.map(p => p[1]));
for (const [k, n] of ia.entries()) if (!ka.has(k)) del.add(n);
for (const [k, n] of ib.entries()) if (!kb.has(k)) add.add(n);
}
return [del, add];
}
/**
* A group of code lines: plain code, or a rewrite, its terms in order
* (`a ⇝ b ⇝ c`) and its side conditions.
* @typedef {{ plain: string[] } | { terms: string[][], conds: string[] }} CodeGroup
*/
/**
* The groups of code separated by blank lines. In a group holding `⇝`, each
* `⇝` separates the code before it from the code after it (`lhs ⇝ rhs` on
* one line, or `⇝` alone on a line), and the `label: text` lines after the
* last term are side conditions.
* @param {string[]} lines
* @returns {CodeGroup[]}
*/
function codeGroups(lines) {
return groups(lines).map(ls => {
const last = ls.map(l => l.includes("⇝")).lastIndexOf(true);
if (last < 0) return { plain: ls };
const rest = ls.slice(last + 1);
const cond = rest.findIndex(l => NOTE.test(l));
const body = [
...ls.slice(0, last + 1),
...(cond < 0 ? rest : rest.slice(0, cond)),
];
/** @type {string[][]} */
const terms = [[]];
for (const l of body)
l.split("⇝").forEach((piece, i) => {
if (i > 0) terms.push([]);
const t = i === 0 ? piece.trimEnd() : piece.trim();
if (t.trim()) terms[terms.length - 1].push(t);
});
return {
terms: terms.map(dedent),
conds: cond < 0 ? [] : rest.slice(cond),
};
});
}
/**
* The parts of code a Before/After pair compares: each line of plain code,
* each line of a rewrite's term in the slot of the term's position, each
* side condition.
* @param {string[]} lines
* @returns {Atom[]}
*/
const codeAtoms = lines =>
codeGroups(lines).flatMap(g =>
"plain" in g
? g.plain.map(text => ({ slot: "plain", text }))
: [
...g.terms.flatMap((t, i) =>
t.map(text => ({ slot: `term${i}`, text })),
),
...g.conds.map(text => ({ slot: "cond", text })),
],
);
/**
* Code, or rewrites of code (`codeGroups`): each term drawn as code, `⇝`
* between, the side conditions drawn as mathematics. Marked parts
* (numbered as `codeAtoms` lists them) are shaded.
* @param {string[]} lines
* @param {keyof typeof LANG} lang
* @param {Marks} [marks]
*/
function code(lines, lang, marks = {}) {
const draw = (/** @type {string} */ c) => highlight(c, lang);
if (!lines.some(l => l.includes("⇝"))) return codeLines(lines, draw, marks);
let n = 0;
/** The marks of the next `count` parts, numbered from 0. @param {number} count */
const shade = count => {
const from = n;
n += count;
return {
marked: new Set(
Array.from({ length: count }, (_, k) => k).filter(k =>
marks.marked?.has(from + k),
),
),
mark: marks.mark,
};
};
return `<div class="rewrites">${codeGroups(lines)
.map(g => {
if ("plain" in g) return codeLines(g.plain, draw, shade(g.plain.length));
const terms = g.terms
.map(t => codeLines(t, draw, shade(t.length)))
.join('<span class="to">⇝</span>');
return (
`<div class="rewrite" style="--n:${g.terms.length - 1}">${terms}</div>` +
g.conds
.map(l =>
condition(l, shade(1).marked.size ? (marks.mark ?? "") : ""),
)
.join("")
);
})
.join("")}</div>`;
}
/**
* A side condition: `label: formula`, or a formula.
* @param {string} l
* @param {string} [mark]
*/
function condition(l, mark = "") {
const m = /^\s*([a-z][\w ]{0,20}):\s+(.*)$/.exec(l);
return `<div class="cond${mark ? ` ${mark}` : ""}">${m ? `<span class="label">${esc(m[1])}</span>` : ""}<span class="m">${math(m ? m[2] : l.trim())}</span></div>`;
}
// ---------------------------------------------------------------------------
// Inline text
/** Short shas of the cards on the page, for linking mentions. */
const pageShas = new Set();
/**
* Prose: `code` as highlighted ReScript; `#1234` and full pull request and
* issue URLs as `#1234` links; a 9-character short sha of a commit on the
* page as a link to its card.
* @param {string} s
*/
const inline = s =>
s
.split(/(`[^`]+`)/)
.map((part, i) =>
i % 2
? `<code>${highlight(part.slice(1, -1), "rescript")}</code>`
: esc(part)
.replace(
/https:\/\/github\.com\/rescript-lang\/rescript\/(pull|issues)\/(\d+)/g,
`<a href="${REPO_URL}/$1/$2">#$2</a>`,
)
.replace(
/(^|[\s(])#(\d{3,5})\b/g,
`$1<a href="${REPO_URL}/pull/$2">#$2</a>`,
)
.replace(/\b([0-9a-f]{9})\b/g, (m, sha) =>
pageShas.has(sha)
? `<a href="#c-${sha}"><code>${sha}</code></a>`
: m,
),
)
.join("");
// ---------------------------------------------------------------------------
// Mathematics: inference rules and formulas
/**
* A formula's tokens: `code` in backticks, a sub- or superscript (`_x`,
* `_{…}`, `^{…}`), a name, or any other character.
* @param {string} text
*/
export const mathTokens = text =>
text.matchAll(
/(?<code>`[^`]+`)|(?<script>_\{[^{}]*\}|\^\{[^{}]*\}|_[A-Za-z0-9Ͱ-Ͽ]+)|(?<name>[A-Za-zͰ-Ͽ][A-Za-z0-9Ͱ-Ͽ'′]*)|[\s\S]/g,
);
/**
* A formula as type theory sets it: one-letter names, with their primes,
* italic variables; `_x`, `_{…}` and `^{…}` sub- and superscripts (`e_1` is
* e with subscript 1); `code` in backticks highlighted ReScript.
* @param {string} text
* @returns {string}
*/
function math(text) {
return [...mathTokens(text)]
.map(m => {
const g = m.groups ?? {};
if (g.code)
return `<code class="m-code">${highlight(g.code.slice(1, -1), "rescript")}</code>`;
if (g.script) {
const tag = g.script.startsWith("^") ? "sup" : "sub";
return `<${tag}>${math(g.script.replace(/^[_^]\{?|\}$/g, ""))}</${tag}>`;
}
if (g.name && /^.[0-9'′]*$/.test(g.name))
return `<var>${esc(g.name)}</var>`;
return esc(m[0]);
})
.join("");
}
/** A line's parts: runs of three or more spaces separate side-by-side formulas. @param {string} line */
export const parts = line =>
line
.trim()
.split(/\s{3,}/)
.filter(Boolean);
/**
* The groups of a block's lines separated by blank lines.
* @param {string[]} block
*/
export function groups(block) {
/** @type {string[][]} */
const out = [[]];
for (const line of block) {
if (line.trim()) out[out.length - 1].push(line);
else if (out[out.length - 1].length) out.push([]);
}
return out.filter(g => g.length);
}
/**
* A group of mathematics: an inference rule (premises, the rule's name,
* the conclusion's lines) or rows of formulas.
* @typedef {{ premises: string[], name: string, conclusion: string[] } | { rows: string[][] }} MathGroup
*/
/**
* Mathematics: groups separated by blank lines; a group with a line of `─`
* is an inference rule (premises above, conclusion below, the rule's name in
* parentheses after the bar); any other group is a list of formulas.
* @param {string[]} block
* @returns {MathGroup[]}
*/
export const mathGroups = block =>
groups(block).map(g => {
const bar = g.findIndex(l => /^\s*─{3,}/.test(l));
if (bar < 0) return { rows: g.map(parts) };
return {
premises: g.slice(0, bar).flatMap(parts),
name: /\(([^()]+)\)\s*$/.exec(g[bar])?.[1] ?? "",
conclusion: g.slice(bar + 1).map(l => l.trim()),
};
});
/**
* The parts of mathematics a Before/After pair compares, in the order they
* are drawn: each premise, conclusion line and rule name, and each formula.
* @param {string[]} block
* @returns {Atom[]}
*/
export const mathAtoms = block =>
mathGroups(block).flatMap(g =>
"rows" in g
? g.rows.flat().map(text => ({ slot: "formula", text }))
: [
...g.premises.map(text => ({ slot: "premise", text })),
...g.conclusion.map(text => ({ slot: "conclusion", text })),
...(g.name ? [{ slot: "name", text: g.name }] : []),
],
);
/**
* Mathematics drawn (`mathGroups`): inference rules and rows of formulas,
* the marked parts (numbered as `mathAtoms` lists them) shaded.
* @param {string[]} block
* @param {Marks} [marks]
*/
function rules(block, marks = {}) {
let n = 0;
/** The next part's class attribute. */
const cls = (extra = "") => {
const c = [extra, marks.marked?.has(n++) ? (marks.mark ?? "") : ""]
.filter(Boolean)
.join(" ");
return c ? ` class="${c}"` : "";
};
const html = mathGroups(block).map(g => {
if ("rows" in g)
return `<div class="formulas">${g.rows
.map(
r =>
`<div class="row">${r.map(p => `<span${cls()}>${math(p)}</span>`).join("")}</div>`,
)
.join("")}</div>`;
const premises = g.premises
.map(p => `<span${cls()}>${math(p)}</span>`)
.join("");
const conclusion = g.conclusion
.map(l => `<div${cls()}>${math(l)}</div>`)
.join("");
return (
`<div class="infer"><div class="frac"><div class="premises">${premises}</div><div class="bar"></div><div class="conclusion">${conclusion}</div></div>` +
(g.name ? `<span${cls("rule-name")}>(${esc(g.name)})</span>` : "") +
`</div>`
);
});
return `<div class="rules">${html.join("")}</div>`;
}
// ---------------------------------------------------------------------------
// Trees, matrices, mappings
/**
* Whether a line of a tree is a node: a nonblank line other than a lone `[`
* or `]`, the list brackets of the compiler's tree printers. The elements
* of a list stand one level deeper than the node owning it.
* @param {string} l
*/
export const treeLine = l => l.trim() !== "" && !/^\s*[[\]]\s*$/.test(l);
/**
* One node of a tree: `label: Node …` shows its label muted; constructors
* (`Pexp_ternary`, `Some`) are coloured, strings and numbers literals,
* attributes (`@res.ternary`) marked.
* @param {string} t
*/
function treeNode(t) {
const lab = /^([a-z_][\w ]*):\s+(.*)$/.exec(t);
const drawn = (lab ? lab[2] : t)
.split(/("(?:\\.|[^"\\])*")/)
.map((part, i) =>
i % 2
? `<span class="s">${esc(part)}</span>`
: esc(part)
.replace(/(^|\s)(@[\w.]+)/g, '$1<span class="a">$2</span>')
.replace(/\b([A-Z][A-Za-z0-9_]*)\b/g, '<span class="t">$1</span>')
.replace(/(^|[\s(=])(\d+)\b/g, '$1<span class="n">$2</span>'),
)
.join("");
return (lab ? `<span class="label">${esc(lab[1])}:</span> ` : "") + drawn;
}
/**
* A tree written as indented lines, two spaces a level, drawn with
* connectors: for each node, its line's index, its HTML and the column it
* starts at. Depths count from the shallowest node, so a root drawn inside
* the printer's outer `[` stands at depth 0, drawn bare.
* @param {string[]} lines
* @returns {{ i: number, html: string, indent: number }[]}
*/
function treeRows(lines) {
const nodes = lines
.map((l, i) => ({ i, level: indentOf(l) >> 1, l }))
.filter(r => treeLine(r.l));
const top = Math.min(...nodes.map(r => r.level));
const rows = nodes.map(r => ({ ...r, depth: r.level - top }));
return rows.map((r, k) => {
// For each ancestor level, whether a later sibling still follows.
let prefix = "";
for (let d = 1; d <= r.depth; d++) {
let more = false;
for (let n = k + 1; n < rows.length && rows[n].depth >= d; n++)
if (rows[n].depth === d) {
more = true;
break;
}
// No-break spaces keep a node on the line of its connector.
prefix +=
d === r.depth
? more
? "├─\u00a0"
: "└─\u00a0"
: more
? "│\u00a0\u00a0"
: "\u00a0\u00a0\u00a0";
}
return {
i: r.i,
html: `<span class="branch">${prefix}</span>${treeNode(r.l.trim())}`,
indent: prefix.length,
};
});
}
/**
* A tree, drawn with connectors.
* @param {string[]} lines
*/
const tree = lines =>
`<pre class="code tree">${treeRows(lines)
.map(r => line(r.html, r.indent, elided(lines[r.i]) ? "elide" : ""))
.join("")}</pre>`;
/**
* The cells of a clause matrix's rows: columns three or more spaces apart.
* @param {string} l
*/
export const cellsOf = l => (NOTE.test(l) ? [] : parts(l));
/**
* A clause matrix of the match compiler: one row a line, columns three or
* more spaces apart, each cell a ReScript pattern; `label: text` lines are
* notes below it.
* @param {string[]} lines
*/
function matrix(lines) {
const rows = lines.filter(l => l.trim());
const cells = rows.filter(l => !NOTE.test(l));
const width = Math.max(1, ...cells.map(l => parts(l).length));
return (
`<div class="matrix" style="grid-template-columns:repeat(${width},max-content)">${cells
.map(l => {
const ps = parts(l);
return ps
.concat(Array(width - ps.length).fill(""))
.map(
p => `<code class="cell">${highlight(p, "rescript") || " "}</code>`,
)
.join("");
})
.join("")}</div>` +
rows
.filter(l => NOTE.test(l))
.map(l => condition(l))
.join("")
);
}
/**
* The width of each column of a clause matrix's rows.
* @param {string[]} lines
* @returns {number[]}
*/
export const columnWidths = lines =>
lines
.map(cellsOf)
.reduce(
(w, ps) =>
Array.from({ length: Math.max(w.length, ps.length) }, (_, c) =>
Math.max(w[c] ?? 0, ps[c]?.length ?? 0),
),
/** @type {number[]} */ ([]),
);
/**
* The lines of a clause matrix for aligned rows: each cell padded to its
* column's width in `widths`, the columns three spaces apart; a note drawn
* as a side condition.
* @param {string[]} lines
* @param {number[]} widths
*/
const matrixLines = (lines, widths) =>
lines.map(l =>
NOTE.test(l)
? condition(l)
: cellsOf(l)
.map((p, c) => highlight(p.padEnd(widths[c] ?? 0), "rescript"))
.join(" "),
);
/**
* A representation mapping's line split at its `↦`, or null for a note.
* @param {string} l
*/
export const mapsTo = l => {
const at = l.indexOf("↦");
return at < 0 ? null : [l.slice(0, at).trim(), l.slice(at + 1).trim()];
};
/**
* How ReScript values are represented in JavaScript: `ReScript ↦ JavaScript`
* lines, each side highlighted; `label: text` lines are conditions.
* @param {string[]} lines
*/
function mapping(lines) {
return `<div class="mapping">${lines
.map(l => {
if (!l.trim()) return "";
const m = mapsTo(l);
if (!m) return condition(l);
return `<div class="map"><code>${highlight(m[0], "rescript")}</code><span class="to">↦</span><code>${highlight(m[1], "js")}</code></div>`;
})
.join("")}</div>`;
}
/**
* The width of a representation mapping's ReScript side.
* @param {string[]} lines
*/
export const mappingWidth = lines =>
Math.max(0, ...lines.map(l => mapsTo(l)?.[0].length ?? 0));
/**
* The lines of a representation mapping for aligned rows: the ReScript side
* padded to `width`, so that the arrows align; a note drawn as a side
* condition.
* @param {string[]} lines
* @param {number} width
*/
const mappingLines = (lines, width) =>
lines.map(l => {
const m = mapsTo(l);
if (!l.trim()) return "";
if (!m) return condition(l);
return `${highlight(m[0].padEnd(width), "rescript")} <span class="to">↦</span> ${highlight(m[1], "js")}`;
});
// ---------------------------------------------------------------------------
// Reanalyze reports
/** A finding's location line: `File.res:3:5-11`. */
const LOCATION = /^\S+:\d+:\d+(?:-\d+(?::\d+)?)?$/;
/** An elision paragraph of a report: `…` or `...`, then any text. */
const REPORT_ELISION = /^\s*(?:…|\.\.\.)/;
/**
* One entry of a reanalyze report: a finding (its analysis, location and
* message lines), an elision marking findings left out, or any other
* paragraph, such as the closing count. `key` is the entry's text, its
* identity across versions.
* @typedef {{ key: string, analysis?: string, location?: string, elision?: boolean, message: string[] }} ReportEntry
*/
/**
* A reanalyze report as reanalyze prints it: paragraphs separated by blank
* lines, each finding an analysis line, a location line and its message
* lines. A paragraph starting with `…` or `...` is an elision.
* @param {string[]} lines
* @returns {ReportEntry[]}
*/
export const reportEntries = lines =>
groups(lines).map(g => {
const ls = dedent(g);
const key = ls.map(l => l.trimEnd()).join("\n");
if (REPORT_ELISION.test(ls[0])) return { key, elision: true, message: ls };
return ls.length >= 2 && LOCATION.test(ls[1].trim())
? {
key,
analysis: ls[0].trim(),
location: ls[1].trim(),
message: dedent(ls.slice(2)),
}
: { key, message: ls };
});
/**
* The analysis every finding of the reports names, when they all name the
* same one, or "".
* @param {string[][]} reports
*/
function sharedAnalysis(reports) {
const names = new Set(
reports.flatMap(r =>
reportEntries(r).flatMap(e => (e.analysis ? [e.analysis] : [])),
),
);
return names.size === 1 ? [...names][0] : "";
}
/**
* A finding's message: attributes such as `@throws(Not_found)` marked, and
* the locations it cites muted.
* @param {string} s
*/
const reportMessage = s =>
esc(s)
.replace(/@[\w.]+(?:\([^()]*\))?/g, '<span class="a">$&</span>')
.replace(
/\(([^\s()]+:\d+:\d+(?:-\d+)?)\)/g,
'(<span class="ref">$1</span>)',
);
/**
* How a report entry is drawn: its shading, its grid cell, its message