-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathcheck_examples.mjs
More file actions
1810 lines (1695 loc) · 87.1 KB
/
Copy pathcheck_examples.mjs
File metadata and controls
1810 lines (1695 loc) · 87.1 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
#!/usr/bin/env node
// Gate: every documentation code sample marked `check_build` compiles.
//
// node scripts/check_examples.mjs # the gate
// node scripts/check_examples.mjs --only "^Reference/Core"
// node scripts/check_examples.mjs --census # classify every tb fence
// node scripts/check_examples.mjs --propose # compile unmarked ones too
// node scripts/check_examples.mjs --propose --apply # ...and mark the ones that pass
// node scripts/check_examples.mjs --report survey.json # group a saved survey
//
// Exit: 0 clean, 1 a sample does not compile, 2 the harness failed.
//
// ------------------------------------------------------------------ why
//
// A ```tb fence is something check_code_regions.mjs protects the CONTENTS of
// and nothing ever evaluates. Two samples that do not compile shipped that way:
// WinNativeCommonCtls/ListView's flagship example passes an icon key in a slot
// the same package's prose says raises 35613, and Core/Event's first sample was
// a Sub with no name. Every gate was green over both.
//
// This is the tool that asks the compiler. It is NEVER part of build.bat,
// check.bat, test.bat or either CI workflow, for three reasons that are not
// going to change: an IDE cold start is 8-11 s where a whole site build is ~4 s;
// `npm install` has to remain sufficient to build the docs, and a twinBASIC
// install is not on that path; and CI has no Windows box, no private desktop
// and no CDP-reachable WebView2. It is `examples.bat`, run by a person, the same
// deal sweep_a11y.mjs already makes.
//
// ------------------------------------------------------------- opt-in, and why
//
// 1,124 `tb` fences under docs/, and a quarter of them are not programs: a
// statement run with an elision in it, a syntax skeleton, an `If` with no `End
// If`. A gate demanding that every fence compile would need hundreds of
// opt-outs on day one, and a list of hundreds of exceptions is a list nobody
// maintains. So a sample says it is complete by carrying `check_build` in its
// fence info string, and everything else is left alone -- which makes the
// marker the thing to get right, not the harness.
//
// ------------------------------------------------------- how a batch is built
//
// IDE cost is flat in project size -- what is paid for is startup, not
// compilation -- so samples are packed many to a project. Measured on this
// corpus: 1,082 auto-wrapped fences over 16 projects, four concurrent lanes,
// 36.6 s wall including packing. One project per sample would be over three
// hours.
//
// Three collision rules fall out of putting unrelated samples in one
// compilation unit, and each is a real hazard rather than a precaution:
//
// * one generated `Module tbx_<hash>` per fence, hashed from its id;
// * everything generated is Private -- eleven pages declare a `MyString`;
// * a generated module must not share a name with the project, or
// [RunAfterBuild]'s call becomes ambiguous and the IDE reports it at
// EXECUTION time, so the build is green and nothing runs.
//
// `Sub Main` is not one of them, though it was once listed as one. The template
// brings a Main, and a sample may bring its own beside it: two `Public Sub
// Main`s in different modules compile (measured, BETA 983), which is how the
// WinServicesLib `Module Startup` samples build as written.
//
// And one that does not: a sample can take the compiler down. twinBASIC runs it
// in-process with user code, and a two-line syntax skeleton in Attributes.md
// crashes it outright (BUGS-TO-REPORT.md). In a batch that costs every other
// sample its result, so a crash is isolated, paid for only on failure: the
// sample tbbuild names as the one the compiler died parsing is built on its own
// and the rest without it, a crash that names none bisects, O(log n) builds, and
// one that needs several samples at once is reported with all of them.
import { spawn } from "node:child_process";
import {
cpSync, existsSync, mkdirSync, promises as fs, readdirSync, readFileSync, rmSync,
writeFileSync,
} from "node:fs";
import { tmpdir } from "node:os";
import path from "node:path";
import { fileURLToPath } from "node:url";
import {
BODY_SLOTS, CONCAT_KEY, HIDDEN_MARKER, MARKER, RUN_MARKER, SLOTS, classify,
collectFences, concatFences, moduleName, parseInfo, partOf, resourcePath, wrapFence,
} from "./lib/tb-fences.mjs";
import { buildNumber, compilerExe, findIde, runCompiler } from "./lib/tb-install.mjs";
import { finishTidy, startTidy } from "./lib/tb-registry.mjs";
const REPO = path.dirname(path.dirname(fileURLToPath(import.meta.url)));
const DOCS = path.join(REPO, "docs");
const TEMPLATES = path.join(REPO, "test", "example-projects");
// ---------------------------------------------------------------- arguments
const argv = process.argv.slice(2);
const flag = (n) => argv.includes("--" + n);
const opt = (n, d) => { const i = argv.indexOf("--" + n); return i < 0 ? d : argv[i + 1]; };
const MODE_CENSUS = flag("census");
const MODE_PROPOSE = flag("propose");
const MODE_REPORT = opt("report", null);
const APPLY = flag("apply");
const VERBOSE = flag("verbose");
const AS_JSON = flag("json");
const only = opt("only", null) ? new RegExp(opt("only", null)) : null;
const jobs = Math.max(1, Number(opt("jobs", 4)));
const basePort = Number(opt("port", 9480));
const batchSize = Math.max(1, Number(opt("batch", 120)));
if (flag("help")) {
console.log(`usage: node scripts/check_examples.mjs [options]
--only <regex> restrict to pages whose path matches
--census classify every tb fence and print the table; no compiler
--propose treat every classifiable fence as marked, and say which pass
--apply with --propose, add \`${MARKER}\` to the fences that passed
--report <file> group the findings of a saved \`--propose --json\` survey by
diagnostic, section, undeclared symbol and page; no compiler
--jobs <n> concurrent IDE lanes (default 4)
--port <n> base DevTools port (default 9480)
--batch <n> samples per generated project (default 120)
--ide <path> twinBASIC.exe (default: $TB_IDE, else the newest on the Desktop)
--keep leave the generated projects on disk and say where
--verbose also print warnings, not only errors
--json one JSON object instead of a report`);
process.exit(0);
}
// A page's template, when its fence does not name one. Inferred from the path
// because the package a sample needs is what the page is ABOUT -- stating
// project= on all 263 Reference/Built-In fences would be markup that only ever
// repeats the directory name above it.
function defaultProject(rel) {
// The two browser packages come first, because each brings a stage set whose
// `WebView` is its own control type. Both tutorials tell the reader to drop a
// control on a form and name it `WebView` -- one a CefBrowser, one a WebView2
// -- so the pages cannot share a project, and the split is by path because
// the control a page means is what the page is about.
if (/^(Tutorials|Reference\/Built-In)\/CEF\//.test(rel)) return "cef";
if (/^(Tutorials|Reference\/Built-In)\/WebView2\//.test(rel)) return "webview2";
if (/^Reference\/Built-In\//.test(rel)) return "packages";
// A tutorial about a package needs that package. Most are a folder named
// after one; Testing-with-Assert is a single file, so it is named here.
if (/^Tutorials\/CustomControls\//.test(rel)) return "packages";
if (/^Tutorials\/Testing-with-Assert\.md$/.test(rel)) return "packages";
// `console` stays the default, and it is the stricter environment on purpose:
// a Core or VBA sample should compile in a project that references only what
// every project references, which is what a reader will have.
return "console";
}
/**
* Which template a template is a delta of.
*
* A template used to be a whole exported tree, and five of them meant five
* copies of a stage set that is mostly the same list -- which is the
* duplication WIP.ExamplesBuild.md predicted would bite once a third appeared.
* A template named here holds only the files that DIFFER from its base:
* `vb-private` is a Settings with one reference rewritten, `cef` and
* `webview2` are one stage file each.
*
* The relation lives in the tool rather than in the tree on purpose. The
* alternative was a marker file in the template directory, and a template
* directory is an exported twinBASIC project that the compiler's `import` verb
* has to accept -- so a stray file there is a thing to test rather than a thing
* to declare.
*/
const TEMPLATE_BASE = {
"vb-private": "console",
"cc-private": "packages",
"wnc-private": "packages",
"cef-private": "cef",
implicit: "console",
cef: "packages",
webview2: "packages",
};
/** A template and everything it inherits from, base first. */
function templateChain(name) {
const chain = [];
for (let n = name, guard = 0; n; n = TEMPLATE_BASE[n]) {
if (guard++ > 8) throw new Error(`template inheritance cycle at ${name}`);
chain.unshift(n);
}
return chain;
}
/** Does this template resolve to a project with a Settings anywhere in its chain? */
function templateResolves(name) {
if (!existsSync(path.join(TEMPLATES, name))) return false;
return templateChain(name).some((n) => existsSync(path.join(TEMPLATES, n, "Settings")));
}
// What `inherits=` does to a slot that was inferred for a Module container. A
// sample naming a base is class code-behind whatever the classifier thought,
// and `Me` may well not appear in the excerpt that proves it.
const PROMOTE_TO_CLASS = { module: "class", sub: "method" };
// A report line. Under --json it goes to stderr, so the payload is the only
// thing on stdout and a caller can pipe it straight into a parser -- which the
// first --json run could not, because the probe line and the batch progress
// were sitting in front of it.
const say = (...a) => (AS_JSON ? console.error(...a) : console.log(...a));
// ------------------------------------------------------------------ selection
const findings = [];
const addFinding = (fence, message, detail, extra = {}) =>
findings.push({
id: fence.id, rel: fence.rel, line: fence.line, message, detail,
// The slot and template are carried rather than described, so `--report`
// groups on fields instead of parsing them back out of the message.
slot: fence.slot, project: fence.project, ...extra,
});
/**
* Join every `concat_group` into one fence before anything else looks at them.
*
* Done here rather than in the batcher because the members are unclassifiable
* apart -- each half of a split `Class` is an unclosed block -- so the join has
* to happen before `classify`, not after. Members keep their identity through
* `concatParts`, which is what turns a diagnostic back into a page line.
*/
function joinConcatGroups(fences) {
const groups = new Map();
const out = [];
for (const fence of fences) {
const name = fence.keys.get(CONCAT_KEY);
if (!name) { out.push(fence); continue; }
// A group is its page's own, the way hidden context is. Keyed by name
// alone, two pages that picked the same name would be stitched into one
// unit -- a class opened on one page and closed on another -- and nothing
// would say so, because the join happens before anything is classified.
const key = `${fence.rel}\u0000${name}`;
if (!groups.has(key)) { groups.set(key, []); out.push({ concatPlaceholder: key }); }
groups.get(key).push(fence);
}
return out.flatMap((f) => {
if (!f.concatPlaceholder) return [f];
const parts = groups.get(f.concatPlaceholder)
.sort((a, b) => a.rel.localeCompare(b.rel) || a.line - b.line);
return [concatFences(parts)];
});
}
function select(fences) {
const chosen = [];
for (const fence of joinConcatGroups(fences)) {
if (only && !only.test(fence.rel)) continue;
// A mistyped marker is a finding in every mode, including --census. It is
// the one thing here that fails silently otherwise: an unrecognised token
// in an info string renders identically to no token at all, so a sample
// marked `check_bild` would never be compiled and nothing would say so.
if (fence.bad.length) {
addFinding(fence, `unrecognised fence markup: ${fence.bad.join(" ")}`,
`known flags: ${MARKER}, ${RUN_MARKER}, ${HIDDEN_MARKER}; keys: slot=${SLOTS.join("|")}, ` +
`inherits=, project=, projname=, id=, expect-error=, resource=, inert=, ${CONCAT_KEY}=`);
continue;
}
// A resource fence is a FILE the project needs, not a sample: it is never
// compiled, never counted, and travels with the samples that read it. The
// path is checked here because a bad one would otherwise be written
// somewhere outside the staged project.
if (fence.isResource) {
const rel = resourcePath(fence.keys.get("resource"));
if (!rel) {
addFinding(fence, `resource= is not a path inside the project: ${fence.keys.get("resource")}`,
"it must be project-relative, with no drive letter and no `..` segment");
continue;
}
fence.resourceRel = rel;
fence.project = fence.keys.get("project") ?? defaultProject(fence.rel);
chosen.push(fence);
continue;
}
// `inert=<reason>` and `check_build` are contradictory claims about the same
// fence, and the wrong one would win silently.
if (fence.keys.has("inert") && fence.flags.has(MARKER)) {
addFinding(fence, `inert=${fence.keys.get("inert")} and \`${MARKER}\` contradict each other`,
"a fence is either not a program, or one this compiles -- not both");
continue;
}
const marked = fence.flags.has(MARKER);
if (!marked && !MODE_PROPOSE && !MODE_CENSUS) continue;
const inferred = classify(fence.content);
const stated = fence.keys.get("slot");
let slot = stated ?? inferred.slot;
// `inherits=` names what the sample is code-behind OF, so it settles the
// container on its own: saying both it and slot=class would be the same
// fact written twice, and the pair could then disagree.
fence.base = fence.keys.get("inherits") ?? null;
if (fence.base && slot) slot = PROMOTE_TO_CLASS[slot] ?? slot;
fence.inferred = inferred;
fence.slot = slot;
fence.slotStated = Boolean(stated);
fence.project = fence.keys.get("project") ?? defaultProject(fence.rel);
fence.marked = marked;
// `inert=<reason>` is a decision already taken: this fence is not a program
// and nobody is coming back to it. It is classified like any other -- the
// census still says what shape it is -- and then goes no further: never
// compiled, never proposed, so a survey stops re-reporting the settled
// hundred on every pass. It is still counted, under its reason, because a
// census that cannot tell "settled" from "not looked at yet" cannot say
// what the backlog is.
fence.inert = fence.keys.get("inert") ?? null;
if (MODE_CENSUS) { chosen.push(fence); continue; }
if (fence.inert) continue;
if (!slot) {
// Marked but unclassifiable is a finding; unmarked and unclassifiable is
// just a fragment, which is the normal state of most of the corpus.
if (marked) {
addFinding(fence, `marked \`${MARKER}\` but its shape could not be inferred: ${inferred.reason}`,
`state one explicitly: slot=${SLOTS.join(" | slot=")}`);
}
continue;
}
if (!templateResolves(fence.project)) {
addFinding(fence, `no such template project: ${fence.project}`,
`templates live in test/example-projects/: ${readdirSync(TEMPLATES).join(", ")}`);
continue;
}
chosen.push(fence);
}
return chosen;
}
/**
* A `projname` group has to be whole, and has to agree about its template.
*
* Marking three of a group's four samples is the failure this exists to name.
* The three are compiled without the one that defines what they use, and the
* errors that come back describe a missing symbol rather than a missing
* marker -- which sends the reader to the sample that is fine.
*/
function checkGroups(all, selected) {
const members = new Map();
for (const f of all) {
const name = f.keys.get("projname");
if (!name) continue;
if (!members.has(name)) members.set(name, []);
members.get(name).push(f);
}
const chosen = new Set(selected.map((f) => f.id));
const where = (f) => `docs/${f.rel}:${f.line}`;
for (const [name, list] of members) {
const inRun = list.filter((f) => chosen.has(f.id));
if (!inRun.length) continue;
const missing = list.filter((f) => !chosen.has(f.id));
// A member `--only` left out is the caller's own doing, so it is advisory --
// but never silent. The group is one program: the half in the run compiles
// without the half that declares what it uses, and the errors name a missing
// symbol rather than a narrowed run. WinServicesLib's four-page group was
// read as a real failure that way, `--only` having taken the page that
// declares MyService while the ones instantiating
// `ServiceCreator(Of MyService)` stayed.
const cut = only ? missing.filter((f) => !only.test(f.rel)) : [];
const unmarked = missing.filter((f) => !cut.includes(f));
if (unmarked.length) {
addFinding(inRun[0], `projname=${name} is incomplete: ${inRun.length} of ${list.length} samples are in this run`,
"unmarked or excluded: " + unmarked.map(where).join(", "));
}
if (cut.length) {
addFinding(inRun[0],
`projname=${name} is cut by --only: ${inRun.length} of ${list.length} samples are in this run`,
"left out: " + cut.map(where).join(", ") +
" -- a group is compiled as one project, so these results are not a full run's",
{ advisory: true });
}
const templates = new Set(inRun.map((f) => f.project));
if (templates.size > 1) {
addFinding(inRun[0], `projname=${name} asks for more than one template: ${[...templates].join(", ")}`,
"one group is one project, so it is one template");
}
}
}
// ------------------------------------------------------------------- batching
//
// A batch is a project. Two samples may not land in one when they would declare
// the same name at project scope -- `Class MyClass` appears on four pages -- so
// the packer keeps the names each open batch has already taken and puts a
// colliding sample in the next batch that has room for it.
function makeBatches(fences) {
// A `hidden` fence is not a unit of its own: it is the PAGE's context, and
// it joins every project that holds a sample from that page. So a page can
// carry the declarations its samples assume -- the class its prose describes
// but never lists, an API Declare -- instead of those living in a template
// stage set shared with six hundred unrelated pages.
//
// Keyed by page AND template, because the same page can send samples to two
// templates and a hidden block compiled into the wrong one would fail for a
// reason that has nothing to do with the page.
//
// A `resource` fence travels the same way and for the same reason -- it is a
// file the page's samples read at compile time, not a unit of its own.
const hiddenByPage = new Map();
const visible = [];
for (const f of fences) {
if (!f.flags.has(HIDDEN_MARKER) && !f.isResource) { visible.push(f); continue; }
const key = `${f.project}\u0000${f.rel}`;
if (!hiddenByPage.has(key)) hiddenByPage.set(key, []);
hiddenByPage.get(key).push(f);
}
const hiddenFor = (project, rel) => hiddenByPage.get(`${project}\u0000${rel}`) ?? [];
const byProject = new Map();
for (const f of visible) {
if (!byProject.has(f.project)) byProject.set(f.project, []);
byProject.get(f.project).push(f);
}
// Samples sharing a `projname` are placed as ONE unit, because they are one
// program: the Assert tutorial defines PadLeft in one fence and tests it in
// the next three, and any of those alone is not a sample anybody wrote.
//
// Nothing groups by accident. An ungrouped sample is its own unit, so a
// sample can never quietly come to depend on a neighbour that a later edit
// moves to another project -- which is exactly how the survey and the gate
// came to disagree about the same tutorial, one run finding PadLeft in the
// batch and the other not.
const unit = (f) => (f.keys.get("projname") ? `@${f.keys.get("projname")}` : `#${f.id}`);
// Fill the lanes rather than the batches. Filling each batch to --batch
// before opening another one put 120, 55, 4 and 3 samples on four lanes, and
// a lane's cost is ~8 s of IDE startup plus a compile that is nearly free --
// so the run takes as long as its biggest batch whatever the others do.
// ...but not below a floor, or a three-sample run starts three IDEs to save
// nothing: the wall time of one batch is IDE startup either way, and the
// extra instances only compete for the box.
const target = Math.min(batchSize, Math.max(16, Math.ceil(fences.length / jobs)));
const batches = [];
for (const [project, list] of byProject) {
// Units, in first-appearance order, so the layout is a function of the
// selection and nothing else.
const units = new Map();
for (const fence of list) {
const key = unit(fence);
if (!units.has(key)) units.set(key, []);
units.get(key).push(fence);
}
const open = [];
for (const [key, members] of units) {
// Only the slots that put declarations at container scope export
// anything. A `sub` or `method` sample's declarations are inside a
// Private Sub and cannot collide with anything.
const nameOf = (f) =>
(BODY_SLOTS.has(f.slot) ? [] : (f.inferred?.names ?? [])).map((n) => n.toLowerCase());
const pages = new Set(members.map((f) => f.rel));
const names = members.flatMap(nameOf);
// What the unit's pages' hidden context would ADD to a batch. It is kept
// apart from the unit's own names because it is charged per PAGE, not per
// unit: a page's hidden block is copied into a batch once, so two samples
// from one page do not collide over it. Folding the two together made
// every page with hidden context split into one batch per sample -- each
// costing a whole IDE start -- because the second sample "clashed" with
// the context the first had just brought.
const hiddenNamesFor = (rel) => hiddenFor(project, rel).flatMap(nameOf);
// A GROUP GETS ITS OWN PROJECT, and nothing else joins it. Togetherness
// alone would leave a group's result depending on whichever unrelated
// samples happened to share the batch -- so the guarantee is the one the
// author can actually reason about: what compiles is what they grouped,
// plus the template. It costs one project per group, and groups are
// written by hand, so there are never many.
if (key.startsWith("@")) {
const own = new Set(names);
for (const rel of pages) for (const n of hiddenNamesFor(rel)) own.add(n);
batches.push({
project, fences: [...members], names: own, pages, group: key.slice(1),
});
continue;
}
let placed = false;
for (const batch of open) {
if (batch.fences.length >= target) continue;
if (names.some((n) => batch.names.has(n))) continue;
// Only the pages this batch does not already carry bring new context.
const newPages = [...pages].filter((rel) => !batch.pages.has(rel));
const incoming = newPages.flatMap(hiddenNamesFor);
if (incoming.some((n) => batch.names.has(n))) continue;
batch.fences.push(...members);
for (const n of names) batch.names.add(n);
for (const n of incoming) batch.names.add(n);
for (const rel of newPages) batch.pages.add(rel);
placed = true;
break;
}
if (placed) continue;
const own = new Set(names);
for (const rel of pages) for (const n of hiddenNamesFor(rel)) own.add(n);
const batch = { project, fences: [...members], names: own, pages };
open.push(batch);
batches.push(batch);
}
}
// Every batch now takes the hidden context of every page it draws from. Done
// last so the placement above decides layout and this only adds to it.
for (const batch of batches) {
for (const rel of batch.pages ?? []) batch.fences.push(...hiddenFor(batch.project, rel));
}
return batches;
}
// ------------------------------------------------------------------ generation
let stageCounter = 0;
/** Stage a batch into its own tree, pack it, and return the .twinproj path. */
function stageBatch(batch, work) {
const index = stageCounter++;
const dir = path.join(work, `b${index}`);
rmSync(dir, { recursive: true, force: true });
// Base first, then each delta over it: a file the delta carries replaces the
// base's copy of the same name, and everything else is inherited.
for (const name of templateChain(batch.project)) {
cpSync(path.join(TEMPLATES, name), dir, { recursive: true });
}
const settingsPath = path.join(dir, "Settings");
const settings = JSON.parse(readFileSync(settingsPath, "utf8"));
const name = `DocSamples${index}`;
settings["project.name"] = name;
// Keyed per batch: two projects sharing an id confuse the IDE's recents list.
settings["project.id"] =
`{7B247500-0000-4000-9000-7B2475${String(index).padStart(6, "0")}}`;
// An explicit file, never the ${SourcePath} template. That template opens a
// native Save dialog on build, and on tbbuild's private desktop the dialog is
// invisible and unreachable -- so the build never happens while the WebView2
// renderer stays responsive and every health check says the IDE is fine.
settings["project.buildPath"] = path.join(dir, `${name}.exe`).split("/").join("\\");
writeFileSync(settingsPath, JSON.stringify(settings, null, "\t") + "\n", "utf8");
const map = new Map();
for (const fence of batch.fences) {
// A resource fence is written where the project expects to find it, not
// compiled. `import` packs a Resources/ tree into the .twinproj and the
// compile-time attributes read it from there -- measured against
// [PopulateFrom], which populates an Enum's members while compiling.
if (fence.isResource) {
const dest = path.join(dir, ...fence.resourceRel.split("/"));
mkdirSync(path.dirname(dest), { recursive: true });
writeFileSync(dest, fence.content.replace(/\r\n?/g, "\n"), "utf8");
continue;
}
const mod = moduleName(fence.id);
const { text, offset } = wrapFence(fence, fence.slot, mod, fence.base);
// CRLF, as the IDE writes .twin files.
writeFileSync(path.join(dir, "Sources", `${mod}.twin`),
text.replace(/\r\n?/g, "\n").replace(/\n/g, "\r\n"), "utf8");
map.set(`${mod}.twin`, { fence, offset });
}
const proj = path.join(work, `b${index}.twinproj`);
// Pure Windows paths: the compiler prefixes \\?\, which does not accept
// forward slashes, and a mixed path fails with "input twinproj file does not
// exist" rather than with anything about separators.
const pack = runCompiler(COMPILER,
["import", proj.split("/").join("\\"), dir.split("/").join("\\"), "--overwrite"]);
// import's exit code does not say whether it worked -- 0 on the failures it
// reports, 999 on a tree holding an embedded package, which a resource= fence
// staged under Packages/ would make -- so runCompiler reads the output.
if (!pack.done) throw new Error(`packing failed${pack.why}:\n${pack.tail}`);
return { proj, dir, map };
}
// ------------------------------------------------------------------- building
const IDE = findIde(opt("ide", undefined));
const COMPILER = IDE ? compilerExe(IDE) : null;
// The registry tidy for the whole run (lib/tb-registry.mjs): taken in main()
// before the first lane starts, finished once the last one has ended -- and
// by the top-level catch, if main() dies in between.
let tidy = null;
/**
* The samples of a staged batch that tbbuild's crash report says the compiler
* died parsing, as fence ids.
*
* tbbuild names them on its `last parsing:` line by the file's base name, which
* for a sample is its generated module's: `last parsing: tbx_df66b6fa33.twin`
* for a batch of nine holding the crash fixture. A file that is no sample of
* the batch -- the template's own source -- names nothing, and neither does a
* report without the line.
*/
function crashedIn(report, map) {
const ids = new Set();
const line = /^last parsing: (.+)$/m.exec(report)?.[1] ?? "";
for (const file of line.split(",")) {
const entry = map.get(file.trim().split(/[\\/]/).pop());
if (entry) ids.add(entry.fence.id);
}
return ids;
}
/** Build one staged batch; returns per-fence errors, or a crash marker. */
async function buildStaged(staged, port) {
const args = [path.join(REPO, "scripts", "tbbuild.mjs"), staged.proj,
"--port", String(port), "--json"];
if (IDE) args.push("--ide", IDE);
if (flag("show")) args.push("--show");
if (flag("hide")) args.push("--hide");
const child = spawn(process.execPath, args, { stdio: ["ignore", "pipe", "pipe"] });
let out = "", err = "";
child.stdout.on("data", (d) => { out += d; });
child.stderr.on("data", (d) => { err += d; });
const code = await new Promise((r) => child.on("exit", r));
if (code === 4) return { crashed: true, detail: err.trim(), named: crashedIn(err, staged.map) };
if (code !== 0 && code !== 1) {
throw new Error(`tbbuild exited ${code} on ${staged.proj}\n${err.trim() || out.trim()}`);
}
let result;
try { result = JSON.parse(out); }
catch { throw new Error(`tbbuild produced no JSON on ${staged.proj}\n${err.trim()}`); }
const perFence = new Map();
// A row in a shape this does not parse. Nothing in it names a file, so no
// amount of splitting the batch would find its cause; it is reported as
// itself.
const unreadable = [];
// An ERROR against a file that is not one of this batch's generated samples:
// the template's own source, or -- the case that cost this comment -- a
// source inside a referenced PACKAGE. `runBatch` isolates one of those to the
// sample that caused it, because it usually has one.
const unattributed = [];
for (const row of result.diagnostics ?? []) {
const m = /^\{(\w+)\}\s+(\S+)\s+\[(\d+),(\d+)\]:\s*(.*)$/.exec(row);
if (!m) { unreadable.push(row); continue; }
const [, severity, file, lineRaw, , message] = m;
if (severity !== "ERROR" && !VERBOSE) continue;
const base = file.split("/").pop();
const entry = staged.map.get(base);
if (!entry) {
if (severity === "ERROR") unattributed.push(row);
continue;
}
const genLine = Number(lineRaw);
// `genLine - offset` is the 1-based line within the fence's own body. For a
// joined unit that body spans several fences, so the part decides both the
// page line and which fence the finding belongs to.
const bodyLine = genLine - entry.offset;
const part = entry.fence.concatParts ? partOf(entry.fence.concatParts, bodyLine) : null;
const owner = part ? part.fence : entry.fence;
const pageLine = part ? part.pageLine : entry.fence.line + bodyLine;
if (!perFence.has(entry.fence.id)) perFence.set(entry.fence.id, []);
perFence.get(entry.fence.id).push({ severity, pageLine, message, rel: owner.rel });
}
return { perFence, unreadable, unattributed };
}
/**
* A batch's units, and the page context that travels with them.
*
* Isolation cuts a batch by unit, never through one. The unit is what
* `makeBatches` made it: a `projname` group is one program, and a page's
* `hidden` context travels with every sample from that page. Cutting the fence
* array instead would take a group's definitions away from its tests and then
* report the tests -- an isolation run that manufactures the failure it claims
* to have found. The hidden fences sit at the END of `batch.fences`, so a plain
* slice loses them for one part outright.
*/
function unitsOf(batch) {
// Hidden fences and resource files are page context: they follow the samples
// rather than being split between them.
const travels = (f) => f.flags.has(HIDDEN_MARKER) || f.isResource;
const units = new Map();
for (const f of batch.fences) {
if (travels(f)) continue;
const key = f.keys.get("projname") ? `@${f.keys.get("projname")}` : `#${f.id}`;
if (!units.has(key)) units.set(key, []);
units.get(key).push(f);
}
return { list: [...units.values()], hidden: batch.fences.filter(travels) };
}
/** A batch of some of another's units, with the page context those units need. */
function batchOf(batch, units, hidden) {
const fences = units.flat();
const pages = new Set(fences.map((f) => f.rel));
return { ...batch, fences: [...fences, ...hidden.filter((h) => pages.has(h.rel))], pages };
}
/**
* Halve a batch WITHOUT cutting through anything that has to stay together.
*
* Returns null when there is one unit left, which is the leaf: the smallest
* thing that can be blamed.
*/
function splitBatch(batch) {
const { list, hidden } = unitsOf(batch);
if (list.length < 2) return null;
const half = Math.ceil(list.length / 2);
return [list.slice(0, half), list.slice(half)].map((part) => batchOf(batch, part, hidden));
}
/**
* Take the units holding these samples out of a batch: [those units, the rest].
*
* Null when that divides nothing -- no sample of the batch named, or every unit
* named -- which is what keeps a recursion on either part smaller than the
* batch it came from. Hidden context is not a unit, so naming it takes nothing
* out; the samples it travels with are left for halving to find.
*/
function takeOut(batch, ids) {
const { list, hidden } = unitsOf(batch);
const named = list.filter((u) => u.some((f) => ids.has(f.id)));
if (!named.length || named.length === list.length) return null;
return [batchOf(batch, named, hidden),
batchOf(batch, list.filter((u) => !named.includes(u)), hidden)];
}
/** The visible samples of a leaf batch, and how to describe it in a finding. */
function leafOf(batch) {
const visible = batch.fences.filter((f) => !f.flags.has(HIDDEN_MARKER) && !f.isResource);
const rest = visible.length > 1
? ` -- one of the ${visible.length} samples in group \`${batch.group ?? "?"}\`, ` +
"which is compiled as one program and cannot be split further"
: "";
return { rep: visible[0] ?? batch.fences[0], ids: visible.map((f) => f.id), rest };
}
// The stage index is in every diagnostic's path, so two builds of one template
// produce rows that differ by a number. Compared without this, a template's own
// fault is never recognised as its own and every batch bisects to the bottom.
const sameRow = (row) => row.replace(/[/\\]DocSamples\d+[/\\]/, "/");
/**
* Does this template emit that diagnostic with NO samples in it?
*
* One build per template, memoised and shared across lanes, asked before any
* splitting. Without it the two cases are indistinguishable at the leaf: a
* sample that provoked a diagnostic inside a package source, and a template that
* emits it unprompted. Guessing the first would bisect every batch to a single
* sample -- hundreds of IDE starts -- and then blame an arbitrary one.
*/
const templateOwnRows = new Map();
function ownRowsOf(project, lane) {
if (!templateOwnRows.has(project)) {
templateOwnRows.set(project, (async () => {
const result = await lane.build({ project, fences: [] });
const rows = result.crashed
? [`the ${project} template crashes the compiler with no samples in it`]
: [...(result.unattributed ?? []), ...(result.unreadable ?? [])];
if (rows.length) {
lane.note(` note: template \`${project}\` does not build clean on its own; ` +
`${rows.length} row(s) are its own, not any sample's`);
}
return new Set(rows.map(sameRow));
})());
}
return templateOwnRows.get(project);
}
/**
* A lane: where a batch is built, and where what isolating it finds goes.
*
* This one stages each batch into the lane's own workspace and builds it on the
* lane's port. The probes hand `runBatch` a fake, whose builds crash on sets of
* samples a probe chooses -- which is how isolation is tested without an IDE,
* and without a crash that needs two real samples to happen.
*/
function laneOf(port, work) {
return {
async build(batch) {
const staged = stageBatch(batch, work);
const result = await buildStaged(staged, port);
if (!flag("keep")) rmSync(staged.dir, { recursive: true, force: true });
return result;
},
finding: addFinding,
note: say,
};
}
// A function, not a shared object: spreading one would hand every caller the
// same arrays, and a recursion that pushes into them is a bug waiting.
const blank = () => ({
perFence: new Map(), templateFaults: [], crashed: [], blamed: [], blamedRows: new Map(),
});
/** Several parts' results, as one batch's. */
function merge(subs) {
const merged = blank();
for (const sub of subs) {
for (const [k, v] of sub.perFence ?? []) merged.perFence.set(k, v);
for (const [k, v] of sub.blamedRows ?? []) merged.blamedRows.set(k, v);
merged.templateFaults.push(...(sub.templateFaults ?? []));
merged.crashed.push(...(sub.crashed ?? []));
merged.blamed.push(...(sub.blamed ?? []));
}
return merged;
}
/** Build both halves of a batch; null when it is one unit, which cannot be halved. */
async function split(batch, lane, why) {
const parts = splitBatch(batch);
if (!parts) return null;
lane.note(` ${why} in ${batch.fences.length} sample(s) [${batch.project}]: splitting to find it`);
const subs = [];
for (const part of parts) subs.push(await runBatch(part, lane));
return merge(subs);
}
/**
* Find what took the compiler down in a batch, and build everything else.
*
* Start where tbbuild says the compiler died: the sample it was parsing is
* built on its own and the rest without it, two builds where halving pays two
* for every level. With no sample of the batch named, halve. Either way a
* crash can need several samples at once, and then no part crashes by itself
* -- the named sample and the rest both build, or both halves do. That used to
* end with every sample of the batch counted as compiling; `together` finds the
* samples the crash needs instead.
*
* The result is marked `fromCrash`, because a part that crashed may come back
* with nothing in `crashed` -- its crash needed several samples too -- and
* whether a part crashed is what decides the next step.
*/
async function isolateCrash(batch, named, lane) {
const where = `a compiler crash in ${batch.fences.length} sample(s) [${batch.project}]`;
let parts = takeOut(batch, named);
if (parts) lane.note(` ${where}: building the sample it died parsing on its own`);
else if ((parts = splitBatch(batch))) lane.note(` ${where}: splitting to find it`);
else {
const { rep, ids, rest } = leafOf(batch);
lane.finding(rep, "crashes the twinBASIC compiler" + rest,
"the compiler dies parsing this sample; record it in BUGS-TO-REPORT.md");
// Named back to the caller, because a crashed sample produced no
// diagnostics and would otherwise be counted as one that compiled -- the
// same false-clean shape tbbuild's own crash check exists to close.
return { ...blank(), crashed: ids, fromCrash: true };
}
const subs = [];
for (const part of parts) subs.push(await runBatch(part, lane));
if (subs.some((s) => s.fromCrash)) return { ...merge(subs), fromCrash: true };
lane.note(" neither part crashes on its own: looking for the samples it needs together");
return { ...merge([...subs, await together(batch, ...parts, lane)]), fromCrash: true };
}
/**
* The samples a crash needs when it needs several: `a` and `b` each built
* clean, and together they crash.
*
* `partners` finds the smallest part of a pool that still crashes with what is
* held fixed. Whichever half of the pool crashes with it holds what the crash
* needs; when neither does, each half holds some of it, and each is searched
* with the other held. That assumes a crash follows from what a build holds --
* more samples never prevent one -- and the last build checks it: a set that
* does not crash as found is reported whole instead.
*
* Every member built clean in `a` or `b`, so each has its own result. They are
* blamed rather than passed, because together they take the compiler down.
*/
async function together(batch, a, b, lane) {
const { hidden } = unitsOf(batch);
const crashes = async (units) => !!(await lane.build(batchOf(batch, units, hidden))).crashed;
const partners = async (fixed, pool) => {
if (pool.length === 1) return pool;
const half = Math.ceil(pool.length / 2);
const [x, y] = [pool.slice(0, half), pool.slice(half)];
if (await crashes([...fixed, ...x])) return partners(fixed, x);
if (await crashes([...fixed, ...y])) return partners(fixed, y);
const inX = await partners([...fixed, ...y], x);
return [...inX, ...await partners([...fixed, ...inX], y)];
};
const inA = unitsOf(a).list, inB = unitsOf(b).list;
const needB = await partners(inA, inB);
const needA = await partners(needB, inA);
const found = await crashes([...needA, ...needB]);
const members = (found ? [...needA, ...needB] : [...inA, ...inB]).flat()
.filter((f) => !f.flags.has(HIDDEN_MARKER) && !f.isResource);
const [rep, ...others] = members;
lane.finding(rep, `crashes the twinBASIC compiler when built with ${others.length} other ` +
`sample(s), though none of the ${members.length} does on its own`,
`the others: ${others.map((f) => `${f.rel}:${f.line}`).join(", ")}` +
(found ? "" : "; no smaller set that crashes was found") + " -- record it in BUGS-TO-REPORT.md");
return { ...blank(), blamed: members.map((f) => f.id) };
}
/**
* Build a batch, isolating a crash or an unattributable diagnostic.
*
* A crash goes to `isolateCrash`; an unattributable diagnostic is attributed by
* halving until one unit is left. A crash is a compiler bug as well as a
* finding, and BUGS-TO-REPORT.md is where one goes. An unattributable
* diagnostic is the subtler of the two: the sample that caused it may have no
* diagnostic of its own at all -- a generic instantiated with a type the
* project does not have reports inside the PACKAGE's source, against the
* generic's own type parameter -- so before this the sample was counted as
* compiling while the run failed with a row naming no page.
*/
async function runBatch(batch, lane) {
const result = await lane.build(batch);
if (result.crashed) return isolateCrash(batch, result.named, lane);
const unreadable = result.unreadable ?? [];
const rows = [...new Set((result.unattributed ?? []).map(sameRow))];
if (!rows.length) {
return { perFence: result.perFence, templateFaults: unreadable, crashed: [], blamed: [] };
}
const own = await ownRowsOf(batch.project, lane);
const mine = rows.filter((r) => !own.has(r));
if (!mine.length) {
// Every row is the template's own. Reported as a template fault, which is
// what it is, and no sample is blamed for it.
return { perFence: result.perFence, templateFaults: [...rows, ...unreadable], crashed: [], blamed: [] };
}
const deeper = await split(batch, lane, "a diagnostic outside every sample");
if (deeper) return { ...deeper, templateFaults: [...deeper.templateFaults, ...unreadable] };
// Blamed, not passed: the whole point is that such a sample can produce no
// diagnostic of its own, so counting it as compiling is the false clean. The
// rows go back to `main` rather than straight into a finding, so a sample with
// errors of its own as well reads as one finding instead of two.
const { rep, ids, rest } = leafOf(batch);
return {
perFence: result.perFence, templateFaults: unreadable, crashed: [], blamed: ids,
blamedRows: new Map([[rep.id, { rows: mine, rest }]]),
};
}
/** Run every batch across `jobs` lanes, each with its own port and workspace. */
async function runAll(batches, work) {
const queue = [...batches];
const results = [];
const lanes = Array.from({ length: Math.min(jobs, queue.length) }, async (_, i) => {
// A lane owns its port AND its workspace. Two IDEs pointed at one source
// tree both wedge and neither ever returns -- distinct ports are not
// enough, which cost two runs to learn.
const laneWork = path.join(work, `lane${i}`);
mkdirSync(laneWork, { recursive: true });
const lane = laneOf(basePort + i, laneWork);
while (queue.length) {
const batch = queue.shift();
process.stderr.write(` building ${batch.fences.length} sample(s) [${batch.project}] on lane ${i}\n`);
results.push(await runBatch(batch, lane));
}
});
await Promise.all(lanes);
return results;
}
// --------------------------------------------------------------------- census
/**
* The bucket a page counts towards in a census or a survey report.
*
* A package is the unit the work is actually organised by, and it sits one level
* deeper than `Reference/` -- `Reference/Default/VB`, `Reference/Built-In/CEF`.
* Bucketing by the first two segments instead would put all thirteen packages in
* one row called `Reference/Built-In` and hide exactly what the report is for.
* A page directly under a section is its own bucket, because `Attributes.md`
* carrying twelve is a fact about that page rather than about `Reference/`.
*/
function sectionOf(rel) {
const parts = rel.split(/[\\/]/);
if (parts[0] === "Reference" && (parts[1] === "Default" || parts[1] === "Built-In")) {
return parts.slice(0, 3).join("/");
}
if (parts[0] === "Reference") return parts.slice(0, 2).join("/");
return parts.slice(0, 2).join("/");
}
/** `n key` lines, biggest first. */
function tallyLines(map, limit = Infinity) {
return [...map].sort((a, b) => b[1] - a[1] || String(a[0]).localeCompare(String(b[0])))
.slice(0, limit)
.map(([k, n]) => ` ${String(n).padStart(4)} ${k}`);
}
function census(fences) {
const tally = new Map();
const reasons = new Map();
for (const f of fences) {
const key = f.slot ?? "fragment";
tally.set(key, (tally.get(key) ?? 0) + 1);
if (!f.slot) {
const why = (f.inferred.reason ?? "?").split(" ").slice(0, 2).join(" ");
reasons.set(why, (reasons.get(why) ?? 0) + 1);
}
}
const total = fences.length;
const marked = fences.filter((f) => f.marked).length;
say(`${total} tb fence(s) in ${new Set(fences.map((f) => f.rel)).size} page(s), ` +
`${marked} marked \`${MARKER}\`\n`);
say(" slot count share");
for (const slot of [...SLOTS, "fragment"]) {
const n = tally.get(slot) ?? 0;
say(` ${slot.padEnd(9)} ${String(n).padStart(5)} ${(n / total * 100).toFixed(1)}%`);
}
if (reasons.size) {
say("\n why a fragment is a fragment:");