-
Notifications
You must be signed in to change notification settings - Fork 13.8k
Expand file tree
/
Copy pathHerebyfile.mjs
More file actions
2873 lines (2521 loc) · 103 KB
/
Copy pathHerebyfile.mjs
File metadata and controls
2873 lines (2521 loc) · 103 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
import AdmZip from "adm-zip";
import chokidar from "chokidar";
import { task } from "hereby";
import assert from "node:assert";
import crypto from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import url from "node:url";
import {
parseArgs,
styleText,
} from "node:util";
import * as tar from "tar";
import {
x,
xSync,
} from "tinyexec";
if (process.platform === "win32") {
process.chdir(fs.realpathSync.native(process.cwd()));
}
const __filename = url.fileURLToPath(new URL(import.meta.url));
const __dirname = path.dirname(__filename);
const isCI = !!process.env.CI || !!process.env.TF_BUILD;
/**
* @typedef {{
* captureOutput?: boolean;
* cwd?: string;
* env?: NodeJS.ProcessEnv;
* signal?: AbortSignal;
* }} RunOptions
*/
/**
* @param {string} arg
*/
function formatCommandArg(arg) {
return arg && /^[\w@%+=:,./-]+$/.test(arg) ? arg : JSON.stringify(arg);
}
/**
* @param {string} command
* @param {readonly string[]} [args]
* @param {RunOptions} [options]
*/
function run(command, args = [], options = {}) {
console.log("$ " + [command, ...args].map(formatCommandArg).join(" "));
return x(command, args, {
throwOnError: true,
...(options.signal ? { signal: options.signal } : {}),
nodeOptions: {
cwd: options.cwd,
env: options.env ? { ...process.env, ...options.env } : undefined,
stdio: options.captureOutput ? "pipe" : "inherit",
},
});
}
/**
* @param {string} command
* @param {readonly string[]} [args]
* @param {Omit<RunOptions, "captureOutput">} [options]
*/
function runOutput(command, args, options) {
return run(command, args, { ...options, captureOutput: true });
}
/**
* @param {string} name
* @param {boolean} defaultValue
* @returns {boolean}
*/
function parseEnvBoolean(name, defaultValue = false) {
name = "TSGO_HEREBY_" + name.toUpperCase();
const value = process.env[name];
if (!value) {
return defaultValue;
}
switch (value.toUpperCase()) {
case "1":
case "TRUE":
case "YES":
case "ON":
return true;
case "0":
case "FALSE":
case "NO":
case "OFF":
return false;
}
throw new Error(`Invalid value for ${name}: ${value}`);
}
const { values: rawOptions } = parseArgs({
args: process.argv.slice(2),
options: {
tests: { type: "string", short: "t" },
fix: { type: "boolean" },
debug: { type: "boolean" },
dirty: { type: "boolean" },
release: { type: "boolean" },
setPrerelease: { type: "string" },
forRelease: { type: "boolean" },
race: { type: "boolean", default: parseEnvBoolean("RACE") },
noembed: { type: "boolean", default: parseEnvBoolean("NOEMBED") },
concurrentTestPrograms: { type: "boolean", default: parseEnvBoolean("CONCURRENT_TEST_PROGRAMS") },
coverage: { type: "boolean", default: parseEnvBoolean("COVERAGE") },
},
strict: false,
allowPositionals: true,
allowNegative: true,
});
// We can't use parseArgs' strict mode as it errors on hereby's --tasks flag.
/**
* @typedef {{ [K in keyof typeof rawOptions as {} extends Record<K, 1> ? never : K]: typeof rawOptions[K] }} Options
*/
const options = /** @type {Options} */ (rawOptions);
// Native release branches can edit these constants to publish a fixed stable version.
// Main publishes prerelease builds of the TypeScript package.
const nativePreviewReleaseProfile = /** @type {"native-preview" | "typescript"} */ ("typescript");
const nativePreviewReleaseVersion = /** @type {string | undefined} */ (undefined);
const produceNativePreviewVsix = /** @type {boolean} */ (false);
const produceTypeScriptNightlyVsix = /** @type {boolean} */ (true);
const usePublishedPlatformPackagesForVsix = /** @type {boolean} */ (false);
const produceAnyVsix = produceNativePreviewVsix || produceTypeScriptNightlyVsix;
const publishAsTypescript = nativePreviewReleaseProfile === "typescript";
if (options.forRelease && !options.setPrerelease && (!nativePreviewReleaseVersion || produceAnyVsix)) {
throw new Error("forRelease requires setPrerelease unless nativePreviewReleaseVersion is hardcoded and VSIX production is disabled");
}
if (usePublishedPlatformPackagesForVsix && !publishAsTypescript) {
throw new Error("usePublishedPlatformPackagesForVsix requires nativePreviewReleaseProfile to be 'typescript'");
}
const defaultGoBuildTags = [
...(options.noembed ? ["noembed"] : []),
];
/**
* @param {...string} extra
* @returns {string[]}
*/
function goBuildTags(...extra) {
const tags = new Set(defaultGoBuildTags.concat(extra));
return tags.size ? [`-tags=${[...tags].join(",")}`] : [];
}
const goBuildFlags = [
...(options.race ? ["-race"] : []),
// https://github.com/go-delve/delve/blob/62cd2d423c6a85991e49d6a70cc5cb3e97d6ceef/Documentation/usage/dlv_exec.md?plain=1#L12
...(options.debug ? ["-gcflags=all=-N -l"] : []),
];
const goBuildEnv = {
...(options.race ? {} : { CGO_ENABLED: "0" }),
};
/**
* @template T
* @param {() => T} fn
* @returns {() => T}
*/
function memoize(fn) {
/** @type {T} */
let value;
return () => {
if (fn !== undefined) {
value = fn();
fn = /** @type {any} */ (undefined);
}
return value;
};
}
/**
* @param {string} pattern
* @param {string[]} [exclude]
*/
async function globFiles(pattern, exclude) {
const files = [];
const absolute = path.isAbsolute(pattern);
for await (const entry of fs.promises.glob(pattern, { exclude, withFileTypes: true })) {
if (entry.isFile()) {
const file = path.join(entry.parentPath, entry.name);
files.push(absolute ? file : path.relative(process.cwd(), file));
}
}
return files;
}
/**
* @param {(() => Promise<void>)[]} tasks
* @param {number} concurrency
*/
async function runWithConcurrencyLimit(tasks, concurrency) {
const queue = tasks.values();
/** @type {unknown[]} */
const errors = [];
const workers = Array.from({ length: Math.min(concurrency, tasks.length) }, async () => {
for (const task of queue) {
try {
await task();
}
catch (error) {
errors.push(error);
}
}
});
await Promise.all(workers);
if (errors.length === 1) {
throw errors[0];
}
if (errors.length > 1) {
throw new AggregateError(errors, `${errors.length} concurrent tasks failed`);
}
}
const tools = new Map([
["gotest.tools/gotestsum", "latest"],
]);
const hasGotestsum = memoize(() => {
try {
return xSync("gotestsum", ["--version"], {
nodeOptions: { stdio: "ignore" },
}).exitCode === 0;
}
catch {
return false;
}
});
const builtLocal = "./built/local";
const libsDir = "./tsc/internal/bundled/libs";
const libsRegexp = /(?:^|[\\/])internal[\\/]bundled[\\/]libs[\\/]/;
/**
* @param {string} out
*/
async function generateLibs(out) {
await fs.promises.mkdir(out, { recursive: true });
const libs = await fs.promises.readdir(libsDir);
await Promise.all(libs.map(async lib => {
fs.promises.copyFile(path.join(libsDir, lib), path.join(out, lib));
}));
}
export const lib = task({
name: "lib",
description: "Copies the libs to built/local.",
run: () => generateLibs(builtLocal),
});
/**
* Gets the release build flags for stripping debug info.
* @param {string} [versionOverride] Optional version to embed in the binary.
* @returns {string[]}
*/
function getReleaseBuildFlags(versionOverride) {
let ldflags = "-ldflags=-s -w";
if (versionOverride) {
ldflags += ` -X github.com/microsoft/TypeScript/tsc/internal/core.version=${versionOverride}`;
}
return ["-trimpath", ldflags];
}
/**
* @param {object} [opts]
* @param {string} [opts.out]
* @param {AbortSignal} [opts.abortSignal]
* @param {Record<string, string | undefined>} [opts.env]
* @param {string[]} [opts.extraFlags]
*/
function buildTsc(opts) {
opts ||= {};
const out = opts.out ?? path.resolve("./built/local/tsc" + (process.platform === "win32" ? ".exe" : ""));
const env = { ...goBuildEnv, ...opts.env };
return run("go", ["build", ...goBuildFlags, ...(opts.extraFlags ?? []), ...goBuildTags("noembed"), "-o", out, "./cmd/tsc"], {
signal: opts.abortSignal,
env,
cwd: "./tsc",
});
}
export const tscBuild = task({
name: "tsc:build",
description: "Builds the tsc binary.",
run: async () => {
await buildTsc({ extraFlags: options.release ? getReleaseBuildFlags() : [] });
},
});
export const tsgo = task({
name: "tsgo",
dependencies: [lib, tscBuild],
});
export const local = task({
name: "local",
dependencies: [tsgo],
});
export const build = task({
name: "build",
dependencies: [local],
});
export const buildWatch = task({
name: "build:watch",
description: "Builds the tsc binary and watches for changes.",
run: async () => {
await watchDebounced("build:watch", async (paths, abortSignal) => {
let libsChanged = false;
let goChanged = false;
if (paths) {
for (const p of paths) {
if (libsRegexp.test(p)) {
libsChanged = true;
}
else if (p.endsWith(".go")) {
goChanged = true;
}
if (libsChanged && goChanged) {
break;
}
}
}
else {
libsChanged = true;
goChanged = true;
}
if (libsChanged) {
console.log("Generating libs...");
await generateLibs(builtLocal);
}
if (goChanged) {
console.log("Building tsgo...");
await buildTsc({ abortSignal });
}
}, {
paths: ["tsc/cmd", "tsc/internal"],
ignored: path => /[\\/]testdata[\\/]/.test(path),
});
},
});
export const cleanBuilt = task({
name: "clean:built",
hiddenFromTaskList: true,
run: () => rimraf("built"),
});
export const generate = task({
name: "generate",
description: "Runs go generate on the project.",
run: async () => {
await run("go", ["generate", "-v", "./..."], { cwd: "./tsc" });
},
});
export const generateExtension = task({
name: "generate:extension",
description: "Generates files in the extension",
run: async () => {
await run("npm", ["run", "-w", "native-preview", "generateLocBundle"]);
},
});
// ── Enum generation from Go source ──────────────────────────────
/**
* @typedef {{
* name: string;
* goPrefix: string;
* goFile: string;
* outDir: string;
* stringEnum?: boolean;
* excludeMembers?: readonly string[];
* valueReplacements?: Record<string, string>;
* }} EnumDef
*/
/** @type {EnumDef[]} */
const enumDefs = [
{ name: "SymbolFlags", goPrefix: "SymbolFlags", goFile: "tsc/internal/ast/symbolflags.go", outDir: "packages/typescript/src/enums" },
{ name: "CheckFlags", goPrefix: "CheckFlags", goFile: "tsc/internal/ast/checkflags.go", outDir: "packages/typescript/src/enums" },
{ name: "TypeFlags", goPrefix: "TypeFlags", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "ObjectFlags", goPrefix: "ObjectFlags", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "SignatureFlags", goPrefix: "SignatureFlags", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "SignatureKind", goPrefix: "SignatureKind", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "ElementFlags", goPrefix: "ElementFlags", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "TypePredicateKind", goPrefix: "TypePredicateKind", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "TypeFormatFlags", goPrefix: "TypeFormatFlags", goFile: "tsc/internal/checker/types.go", outDir: "packages/typescript/src/enums" },
{ name: "DiagnosticCategory", goPrefix: "Category", goFile: "tsc/internal/diagnostics/diagnostics.go", outDir: "packages/typescript/src/enums" },
{ name: "SyntaxKind", goPrefix: "Kind", goFile: "tsc/internal/ast/kind_generated.go", outDir: "packages/typescript/src/enums" },
{ name: "NodeFlags", goPrefix: "NodeFlags", goFile: "tsc/internal/ast/nodeflags.go", outDir: "packages/typescript/src/enums" },
{ name: "OuterExpressionKinds", goPrefix: "OEK", goFile: "tsc/internal/ast/utilities.go", outDir: "packages/typescript/src/enums" },
{ name: "ModifierFlags", goPrefix: "ModifierFlags", goFile: "tsc/internal/ast/modifierflags.go", outDir: "packages/typescript/src/enums" },
{ name: "ModuleKind", goPrefix: "ModuleKind", goFile: "tsc/internal/core/compileroptions.go", outDir: "packages/typescript/src/enums" },
{ name: "ModuleResolutionKind", goPrefix: "ModuleResolutionKind", goFile: "tsc/internal/core/compileroptions.go", outDir: "packages/typescript/src/enums" },
{ name: "ModuleDetectionKind", goPrefix: "ModuleDetectionKind", goFile: "tsc/internal/core/compileroptions.go", outDir: "packages/typescript/src/enums" },
{ name: "NewLineKind", goPrefix: "NewLineKind", goFile: "tsc/internal/core/compileroptions.go", outDir: "packages/typescript/src/enums" },
{ name: "JsxEmit", goPrefix: "JsxEmit", goFile: "tsc/internal/core/compileroptions.go", outDir: "packages/typescript/src/enums" },
{ name: "ScriptKind", goPrefix: "ScriptKind", goFile: "tsc/internal/core/scriptkind.go", outDir: "packages/typescript/src/enums" },
{ name: "TokenFlags", goPrefix: "TokenFlags", goFile: "tsc/internal/ast/tokenflags.go", outDir: "packages/typescript/src/enums" },
{ name: "DiagnosticDirectivePolicy", goPrefix: "MappedDiagnosticDirectivePolicy", goFile: "tsc/internal/ast/ast.go", outDir: "packages/typescript/src/enums" },
{ name: "SpanMapKind", goPrefix: "Kind", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/src/enums" },
{ name: "SpanMapFidelity", goPrefix: "Fidelity", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/src/enums" },
{ name: "SpanMapFeature", goPrefix: "Feature", goFile: "tsc/internal/spanmap/spanmap.go", outDir: "packages/typescript/src/enums" },
{ name: "NodeBuilderFlags", goPrefix: "Flags", goFile: "tsc/internal/nodebuilder/types.go", outDir: "packages/typescript/src/enums" },
{ name: "CompletionItemKind", goPrefix: "CompletionItemKind", goFile: "tsc/internal/lsp/lsproto/lsp_generated.go", outDir: "packages/typescript/src/enums" },
{ name: "EmitOnly", goPrefix: "Emit", goFile: "tsc/internal/compiler/emitter.go", outDir: "packages/typescript/src/enums", excludeMembers: ["OnlyBuilderSignature"] },
// String enum: Go stores internal names with a "\xFE" sentinel prefix, but the escaped
// form sent over the wire uses "__" (see EscapeSymbolName), so map the sentinel accordingly.
{ name: "InternalSymbolName", goPrefix: "InternalSymbolName", goFile: "tsc/internal/ast/symbol.go", outDir: "packages/typescript/src/enums", stringEnum: true, valueReplacements: { InternalSymbolNamePrefix: "__" } },
];
/**
* @param {string} block
* @param {EnumDef} def
* @returns {EnumMember[]}
*/
function parseGoConstBlock(block, def) {
const prefix = def.goPrefix;
const members = [];
let iotaCounter = 0;
let iotaExpression;
const lines = block.split("\n");
let i = 0;
while (i < lines.length) {
const rawLine = lines[i];
const line = rawLine.replace(/\/\/.*$/, "").trim();
if (!line) {
i++;
continue;
}
// Match: PrefixName Type = value or PrefixName = value
const fullMatch = line.match(new RegExp(`^(${prefix}\\w+)\\s+(?:\\S+\\s*)?=\\s*(.+)$`));
// Match bare iota continuation: just PrefixName
const bareMatch = !fullMatch && iotaExpression !== undefined
? line.match(new RegExp(`^(${prefix}\\w+)$`))
: null;
if (!fullMatch && !bareMatch) {
i++;
continue;
}
const goName = fullMatch ? fullMatch[1] : /** @type {RegExpMatchArray} */ (bareMatch)[1];
let goValue = fullMatch ? fullMatch[2].trim() : "";
const memberName = goName.slice(prefix.length);
// Accumulate continuation lines ending with |
i++;
while (i < lines.length && goValue.endsWith("|")) {
const nextRaw = lines[i];
const nextLine = nextRaw.replace(/\/\/.*$/, "").trim();
if (!nextLine) {
i++;
continue;
}
goValue += " " + nextLine;
i++;
}
let tsValue;
if (def.stringEnum) {
tsValue = parseGoStringValue(goValue, def.valueReplacements ?? {});
}
else {
let numericValue = goValue;
if (goValue.includes("iota")) {
iotaExpression = goValue;
numericValue = goValue.replace(/\biota\b/g, String(iotaCounter));
}
else if (iotaExpression !== undefined && goValue === "") {
numericValue = iotaExpression.replace(/\biota\b/g, String(iotaCounter));
}
tsValue = translateGoNumericExpression(numericValue, prefix);
}
members.push({ name: memberName, value: tsValue });
iotaCounter++;
}
return members;
}
const goBinaryPrecedence = new Map([
["||", 1],
["&&", 2],
["==", 3],
["!=", 3],
["<", 3],
["<=", 3],
[">", 3],
[">=", 3],
["+", 4],
["-", 4],
["|", 4],
["^", 4],
["*", 5],
["/", 5],
["%", 5],
["<<", 5],
[">>", 5],
["&", 5],
["&^", 5],
]);
const tsBinaryPrecedence = new Map([
["||", 4],
["&&", 5],
["|", 6],
["^", 7],
["&", 8],
["==", 9],
["!=", 9],
["<", 10],
["<=", 10],
[">", 10],
[">=", 10],
["<<", 11],
[">>", 11],
["+", 12],
["-", 12],
["*", 13],
["/", 13],
["%", 13],
]);
/**
* @typedef {{ kind: "token"; text: string }
* | { kind: "unary"; operator: string; operand: GoExpression }
* | { kind: "binary"; operator: string; left: GoExpression; right: GoExpression }
* | { kind: "parenthesized"; expression: GoExpression }} GoExpression
*/
/**
* Parse with Go's precedence and print with TypeScript's precedence, adding parentheses where
* copying the expression verbatim would change its meaning.
* @param {string} expression
* @param {string} prefix
*/
function translateGoNumericExpression(expression, prefix) {
const tokens = expression.match(/<<|>>|&\^|\|\||&&|==|!=|<=|>=|[()+\-*/%&|^<>]|(?:0[xX][\dA-Fa-f_]+|0[bB][01_]+|0[oO][0-7_]+|\d[\d_]*)|[A-Za-z_]\w*/g) ?? [];
const withoutWhitespace = expression.replace(/\s/g, "");
if (tokens.join("") !== withoutWhitespace) {
throw new Error(`Cannot parse numeric enum value: ${expression}`);
}
let tokenIndex = 0;
/** @returns {GoExpression} */
function parseUnary() {
const token = tokens[tokenIndex];
if (token === "+" || token === "-" || token === "^") {
tokenIndex++;
return { kind: "unary", operator: token === "^" ? "~" : token, operand: parseUnary() };
}
if (token === "(") {
tokenIndex++;
const inner = parseBinary(1);
if (tokens[tokenIndex] !== ")") {
throw new Error(`Unmatched parenthesis in numeric enum value: ${expression}`);
}
tokenIndex++;
return { kind: "parenthesized", expression: inner };
}
if (token === undefined || goBinaryPrecedence.has(token) || token === ")") {
throw new Error(`Expected operand in numeric enum value: ${expression}`);
}
tokenIndex++;
return { kind: "token", text: token.replace(new RegExp(`^${prefix}`), "") };
}
/**
* @param {number} minimumPrecedence
* @returns {GoExpression}
*/
function parseBinary(minimumPrecedence) {
let left = parseUnary();
while (true) {
const operator = tokens[tokenIndex];
const precedence = goBinaryPrecedence.get(operator);
if (precedence === undefined || precedence < minimumPrecedence) break;
tokenIndex++;
const right = parseBinary(precedence + 1);
left = { kind: "binary", operator, left, right };
}
return left;
}
const parsed = parseBinary(1);
if (tokenIndex !== tokens.length) {
throw new Error(`Unexpected token '${tokens[tokenIndex]}' in numeric enum value: ${expression}`);
}
/**
* @param {GoExpression} node
* @param {number} minimumPrecedence
* @returns {string}
*/
function print(node, minimumPrecedence) {
if (node.kind === "token") return node.text;
if (node.kind === "parenthesized") return `(${print(node.expression, 0)})`;
if (node.kind === "unary") {
const text = `${node.operator}${print(node.operand, 14)}`;
return 14 < minimumPrecedence ? `(${text})` : text;
}
const operator = node.operator === "&^" ? "&" : node.operator;
const precedence = tsBinaryPrecedence.get(operator);
assert(precedence !== undefined);
const right = node.operator === "&^"
? `~${print(node.right, 14)}`
: print(node.right, precedence + 1);
const text = `${print(node.left, precedence)} ${operator} ${right}`;
return precedence < minimumPrecedence ? `(${text})` : text;
}
return print(parsed, 0);
}
/**
* Resolve a Go string-constant expression (e.g. `Prefix + "call"` or `"export="`)
* into a quoted, JS-escaped TypeScript string literal. `replacements` maps bare
* Go identifiers (such as a sentinel-prefix constant) to their literal value.
* @param {string} goValue
* @param {Record<string, string>} replacements
* @returns {string}
*/
function parseGoStringValue(goValue, replacements) {
let result = "";
for (const part of goValue.split("+").map(p => p.trim())) {
if (Object.prototype.hasOwnProperty.call(replacements, part)) {
result += replacements[part];
continue;
}
const stringMatch = part.match(/^"((?:[^"\\]|\\.)*)"$/);
if (stringMatch === null) {
throw new Error(`Cannot parse string enum value: ${goValue}`);
}
// Interpret Go escape sequences via JSON, then re-stringify below.
result += JSON.parse(`"${stringMatch[1]}"`);
}
return JSON.stringify(result);
}
/**
* @typedef {{
* name: string;
* value: string;
* }} EnumMember
*/
/**
* @param {EnumDef} def
* @returns {EnumMember[]}
*/
function parseGoEnum(def) {
const source = fs.readFileSync(def.goFile, "utf-8");
const constBlockRegex = /const\s*\(([\s\S]*?)\n\)/g;
for (const match of source.matchAll(constBlockRegex)) {
const members = parseGoConstBlock(match[1], def).filter(member => !def.excludeMembers?.includes(member.name));
if (members.length > 0) return topoSortMembers(members);
}
throw new Error(`No members found for enum ${def.name} in ${def.goFile}`);
}
/**
* Topologically sort enum members so composite members appear after
* all members they reference (Go allows forward references, TS does not).
* @param {EnumMember[]} members
* @returns {EnumMember[]}
*/
function topoSortMembers(members) {
const nameSet = new Set(members.map(m => m.name));
/** @type {Map<string, Set<string>>} */
const deps = new Map();
for (const m of members) {
/** @type {Set<string>} */
const refs = new Set();
// Find all identifier references in the value that are other member names
for (const [ref] of m.value.matchAll(/\b([A-Za-z_]\w*)\b/g)) {
if (ref !== m.name && nameSet.has(ref)) refs.add(ref);
}
deps.set(m.name, refs);
}
const sorted = /** @type {EnumMember[]} */ ([]);
const visited = new Set();
const visiting = new Set();
/** @param {string} name */
function visit(name) {
if (visited.has(name)) return;
if (visiting.has(name)) return; // cycle — keep original order
visiting.add(name);
for (const dep of deps.get(name) ?? []) {
visit(dep);
}
visiting.delete(name);
visited.add(name);
sorted.push(/** @type {EnumMember} */ (members.find(m => m.name === name)));
}
for (const m of members) {
visit(m.name);
}
return sorted;
}
/**
* @param {EnumDef} def
* @param {EnumMember[]} members
* @returns {string}
*/
function renderEnumTS(def, members) {
const header = `// Code generated by Herebyfile.mjs generate:enums from ${def.goFile}. DO NOT EDIT.\n\n`;
const lines = members.map(m => ` ${m.name} = ${m.value},`);
return `${header}export enum ${def.name} {\n${lines.join("\n")}\n}\n`;
}
const enumValuesGeneratedGoPath = "tsc/internal/api/enum_values_generated.go";
/**
* @typedef {{
* def: EnumDef
* code: string,
* fileNames: string[]
* members: EnumMember[]
* }} GeneratedEnum
*/
/**
* Ask the Go compiler what it actually thinks each numeric member's value is, so that
* generated TS values can be checked against Go's own arithmetic rather than trusting that
* copying operator-by-operator text from Go into JS preserves precedence/semantics.
*
* Writes tsc/internal/api/enum_values_generated.go, a standalone program that imports every
* package referenced by enumDefs and references each member by its original Go identifier
* (not by re-deriving it from the parsed TS text), so Go itself — not this script — computes
* the ground-truth value, then prints them as JSON. `internal/api` is used as the host package
* because it already imports (nearly) every package enums are sourced from.
*
* @param {GeneratedEnum[]} generatedEnums
* @returns {Promise<Record<string, Record<string, number>>>} enum def name -> (memberName -> Go value)
*/
async function computeGoGroundTruth(generatedEnums) {
/** @type {Map<string, {importPath: string, pkgName: string}>} */
const packagesByDir = new Map();
/**
* @param {EnumDef} def
* @returns {string}
*/
function getPackageName(def) {
const dir = path.dirname(def.goFile);
const importPath = `github.com/microsoft/TypeScript/tsc/${dir.replace(/^tsc[\\/]/, "")}`.replace(/\\/g, "/");
let info = packagesByDir.get(dir);
if (info === undefined) {
info = { importPath, pkgName: path.basename(dir) };
packagesByDir.set(dir, info);
}
return info.pkgName;
}
/** @type {string[]} */
const entries = [];
for (const { def, members } of generatedEnums) {
if (def.stringEnum) continue;
const pkgName = getPackageName(def);
/** @type {string[]} */
const memberEntries = members.map(m => {
return `\t\t\t${JSON.stringify(m.name)}: toInt32(${pkgName}.${def.goPrefix}${m.name}),`;
});
entries.push(
`\t\t${JSON.stringify(def.name)}: {\n${memberEntries.join("\n")}\n\t\t},`,
);
}
const importLines = [...packagesByDir.values()]
.sort((a, b) => a.importPath.localeCompare(b.importPath))
.map(({ pkgName, importPath }) => `\t${pkgName} "${importPath}"`);
const goSource = `//go:build ignore
// Code generated by Herebyfile.mjs generate:enums. DO NOT EDIT.
// Running this program prints the real Go-evaluated value of every generated enum member as
// JSON, so generate:enums can validate that the TypeScript it emits agrees with Go's own
// arithmetic (catching, e.g., operator-precedence mistakes introduced by copying Go expression
// text into TypeScript verbatim).
package main
import (
\t"encoding/json"
\t"os"
${importLines.join("\n")}
)
func main() {
\tvalues := map[string]map[string]int32{
${entries.join("\n")}
\t}
\tif err := json.NewEncoder(os.Stdout).Encode(values); err != nil {
\t\tpanic(err)
\t}
}
// A generic function call (unlike a constant conversion) forces Go to evaluate the conversion at
// runtime, truncating uint32-backed flags with a leading bitwise-not the same way JS's 32-bit
// bitwise operators would, instead of rejecting "constant overflows int32" at compile time.
func toInt32[T ~int8 | ~int16 | ~int32 | ~int | ~uint8 | ~uint16 | ~uint32](v T) int32 {
\treturn int32(v)
}
`;
fs.writeFileSync(enumValuesGeneratedGoPath, goSource);
await run("dprint", ["fmt", enumValuesGeneratedGoPath]);
const { stdout } = await runOutput("go", ["run", enumValuesGeneratedGoPath]);
/** @type {Record<string, Record<string, number>>} */
const parsed = JSON.parse(stdout);
return parsed;
}
/**
* Evaluate the generated IIFE in a sandbox and return each member's actual runtime value, so
* validation checks what TS really computes rather than re-deriving it from the source text.
* @param {string} enumSource
* @param {string} enumName
* @returns {Promise<Record<string, number | string>>}
*/
async function evaluateEnumMembers(enumSource, enumName) {
const enumModule = await import(`data:text/javascript;charset=utf-8,${encodeURIComponent(enumSource)}`);
/** @type {Record<string, number | string>} */
const enumObj = enumModule[enumName];
return enumObj;
}
async function runGenerateEnums() {
const ts = /** @type {typeof import("typescript")} */ (await import("typescript"));
/**
* @param {string} enumSource
* @param {string} enumName
* @returns {string}
*/
function transpile(enumSource, enumName) {
return ts.transpileModule(enumSource, {
compilerOptions: {
module: ts.ModuleKind.ESNext,
target: ts.ScriptTarget.ESNext,
},
}).outputText;
}
/**
* @param {string} enumSource
* @param {string} enumName
* @returns {string}
*/
function convertEnumToTs(enumSource, enumName) {
return enumSource.replace(
`export var ${enumName};`,
`export var ${enumName}: any;`,
);
}
console.log("Generating enums from Go source...");
/** @type {Array<GeneratedEnum>} */
const generatedEnums = [];
for (const def of enumDefs) {
const members = parseGoEnum(def);
const camelName = def.name.charAt(0).toLowerCase() + def.name.slice(1);
fs.mkdirSync(def.outDir, { recursive: true });
// Generate .enum.ts (TypeScript enum — used for types)
const enumTS = renderEnumTS(def, members);
const enumPath = path.join(def.outDir, `${camelName}.enum.ts`);
fs.writeFileSync(enumPath, enumTS);
// Generate .ts (IIFE — used at runtime)
const enumJsCode = transpile(enumTS, def.name);
const iifeSource = convertEnumToTs(enumJsCode, def.name);
const iifePath = path.join(def.outDir, `${camelName}.ts`);
fs.writeFileSync(iifePath, iifeSource);
generatedEnums.push({
code: enumJsCode,
def,
members,
fileNames: [enumPath, iifePath],
});
console.log(` ${def.name}: ${members.length} members → ${camelName}.enum.ts, ${camelName}.ts`);
}
console.log("Getting values from go");
const goValuesByEnum = await computeGoGroundTruth(generatedEnums);
/** @type {string[]} */
const mismatches = [];
for (const { def, members, code } of generatedEnums) {
if (def.stringEnum) continue;
const goValues = goValuesByEnum[def.name];
assert(goValues, `Enum ${def.name} was not outputted from GO`);
const tsValues = await evaluateEnumMembers(code, def.name);
for (const m of members) {
const goValue = goValues[m.name];
const tsValue = tsValues[m.name];
if (tsValue !== goValue) {
mismatches.push(
`${def.name}.${m.name}: Go says ${goValue}, but generated TS (\`${m.value}\`) evaluates to ${tsValue}`,
);
}
}
}
if (mismatches.length > 0) {
throw new Error(
`Generated enum values disagree with Go (likely an operator precedence or transcription bug in generate:enums):\n` +
mismatches.map(m => ` - ${m}`).join("\n"),
);
}
console.log("All generated values match Go.");
await run("dprint", ["fmt", ...generatedEnums.flatMap(e => e.fileNames)]);
console.log("Done.");
}
export const generateEnums = task({
name: "generate:enums",
description: "Generates TypeScript enum files from Go source.",
run: runGenerateEnums,
});
export const generateAST = task({
name: "generate:ast",
description: "Generates AST and encoder files from ast.json.",
run: () => run("node", ["./tools/scripts/tsc/generate.ts"]),
});
export const generateAPI = task({
name: "generate:api",
description: "Generates API files from internal/api/proto.go and internal/api/session.go.",
run: async () => {
await run("go", ["-C", "./tools", "run", "./gen-proto", "../tsc/internal/api/proto.go", "../packages/typescript/src/api/proto.generated.ts"]);
await run("npx", ["dprint", "fmt", "packages/typescript/src/api/proto.generated.ts"]);
},
});
// ── Vendored npm dependencies ───────────────────────────────────
const vendorJsonrpcDir = "packages/typescript/vendor/vscode-jsonrpc";
const vendorJsonrpcSrc = "node_modules/vscode-jsonrpc";
// Files copied verbatim from the installed vscode-jsonrpc package into the
// vendored copy. Only the runtime files needed by the `#vscode-jsonrpc/node`
// import (lib + typings + package.json) plus license/readme are vendored.
const vendorJsonrpcFiles = ["package.json", "README.md", "License.txt", "lib", "typings"];
async function runGenerateVendor() {
const src = path.join(__dirname, vendorJsonrpcSrc);
const dest = path.join(__dirname, vendorJsonrpcDir);
if (!fs.existsSync(src)) {
throw new Error(`${vendorJsonrpcSrc} is not installed; run \`npm ci\` first.`);
}
await rimraf(dest);
await fs.promises.mkdir(dest, { recursive: true });
for (const file of vendorJsonrpcFiles) {
await cpRecursive(path.join(src, file), path.join(dest, file));
}
}