-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsync-go.mjs
More file actions
192 lines (178 loc) · 11.1 KB
/
sync-go.mjs
File metadata and controls
192 lines (178 loc) · 11.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
import { execFileSync } from "node:child_process";
import { createHash } from "node:crypto";
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { dirname, join, resolve } from "node:path";
import { fileURLToPath } from "node:url";
const ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "..");
const REPO = resolve(ROOT, "../..");
const REF = join(REPO, "references", "expr");
const write = (rel, content) => {
const file = join(ROOT, rel);
mkdirSync(dirname(file), { recursive: true });
writeFileSync(file, content.endsWith("\n") ? content : content + "\n");
};
const readRef = (rel) => readFileSync(join(REF, rel), "utf8");
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
const GO_TO_KIND = new Map([
["bool", "Kind.Bool"], ["int", "Kind.Int"], ["int8", "Kind.Int8"], ["int16", "Kind.Int16"],
["int32", "Kind.Int32"], ["rune", "Kind.Int32"], ["int64", "Kind.Int64"], ["uint", "Kind.Uint"],
["uint8", "Kind.Uint8"], ["byte", "Kind.Uint8"], ["uint16", "Kind.Uint16"], ["uint32", "Kind.Uint32"],
["uint64", "Kind.Uint64"], ["float32", "Kind.Float32"], ["float64", "Kind.Float64"],
["string", "Kind.String"], ["interface{}", "Kind.Interface"], ["interface {}", "Kind.Interface"],
["any", "Kind.Interface"], ["time.Time", "Kind.Struct"], ["time.Duration", "Kind.Int64"],
["time.Month", "Kind.Int"], ["time.Weekday", "Kind.Int"],
]);
function splitTopLevel(s) {
const out = [];
let depth = 0, cur = "";
for (let i = 0; i < s.length; i++) {
const ch = s[i];
if (ch === "(" || ch === "[" || ch === "{") depth++;
if (ch === ")" || ch === "]" || ch === "}") depth--;
if (ch === "," && depth === 0) { out.push(cur.trim()); cur = ""; continue; }
cur += ch;
}
if (cur.trim()) out.push(cur.trim());
return out;
}
function tsTypeExpr(goType) {
const t = goType.trim().replace(/\s+/g, " ");
if (t.startsWith("[]")) {
const elem = tsTypeExpr(t.slice(2));
return `sliceType(${elem}, ${JSON.stringify(t)})`;
}
const map = t.match(/^map\[(.+)](.+)$/);
if (map) return `mapType(${tsTypeExpr(map[1])}, ${tsTypeExpr(map[2])}, ${JSON.stringify(t)})`;
const kind = GO_TO_KIND.get(t);
if (!kind) return `new Type(Kind.Interface, ${JSON.stringify(t)})`;
return `new Type(${kind}, ${JSON.stringify(t.replace("interface{}", "interface {}"))})`;
}
function genFuncTypes() {
const src = readRef("vm/func_types[generated].go");
const entries = [];
for (const m of src.matchAll(/(\d+):\s*new\(func\(([^)]*)\)\s*([^),\n]+)\)/g)) {
const idx = Number(m[1]);
const ins = m[2].trim() ? splitTopLevel(m[2]).map(tsTypeExpr) : [];
const out = tsTypeExpr(m[3].trim());
entries[idx] = { ins, out };
}
const max = entries.length - 1;
const lines = [];
lines.push("// Code generated by scripts/sync-go.mjs from references/expr/vm/func_types[generated].go. DO NOT EDIT.");
lines.push("import { Kind } from './nature/kind.js';");
lines.push("import { Type } from './nature/type.js';");
lines.push("");
lines.push("export interface FuncTypeEntry { in: Type[]; out: Type[] }");
lines.push("const ft = (inTypes: Type[], outTypes: Type[]): FuncTypeEntry => ({ in: inTypes, out: outTypes });");
lines.push("const sliceType = (elem: Type, name: string): Type => { const t = new Type(Kind.Slice, name); t.elem = elem; return t; };");
lines.push("const mapType = (key: Type, elem: Type, name: string): Type => { const t = new Type(Kind.Map, name); t.key = key; t.elem = elem; return t; };");
lines.push("");
lines.push("export const FUNC_TYPES: FuncTypeEntry[] = [");
lines.push(" /* 0 */ ft([], []),");
for (let i = 1; i <= max; i++) {
const e = entries[i];
if (!e) lines.push(` /* ${i} */ ft([], []),`);
else lines.push(` /* ${i} */ ft([${e.ins.join(", ")}], [${e.out}]),`);
}
lines.push("];\n");
lines.push("export const FUNC_TYPES_ARITY: number[] = FUNC_TYPES.map((entry) => entry.in.length);");
write("src/checker/func_types.generated.ts", lines.join("\n"));
return { count: entries.filter(Boolean).length, sha: sha256(src) };
}
function genValuerMethods() {
const src = readRef("patcher/value/value.go");
const typeMethods = new Map([...src.matchAll(/type\s+(\w+Valuer)\s+interface\s+\{\s*\n\s*(As\w+)\(\)/g)].map((m) => [m[1], m[2]]));
const supported = src.match(/var supportedInterfaces = \[]reflect\.Type\{([\s\S]*?)\n}/)?.[1] ?? "";
const methods = [...supported.matchAll(/\(\*(\w+Valuer)\)/g)].map((m) => typeMethods.get(m[1])).filter(Boolean);
write("src/patcher/value/valuer_methods.generated.ts", `// Code generated by scripts/sync-go.mjs from references/expr/patcher/value/value.go. DO NOT EDIT.\nexport const VALUER_METHODS = ${JSON.stringify(methods, null, 2)} as const;\n`);
return { count: methods.length, sha: sha256(src) };
}
function goRun(source) {
const tmp = join(ROOT, "parity", "tmp_go_scan.go");
writeFileSync(tmp, source);
try { return execFileSync("go", ["run", tmp], { cwd: ROOT, encoding: "utf8" }); }
finally { try { writeFileSync(tmp, "// temporary scan file removed by sync-go\n"); } catch {} }
}
function genReflectMetadata() {
const scan = `package main
import (
"encoding/json"; "os"; "reflect"; "time"
)
type Embedded struct { ID int; hidden string }
type VisibleSample struct { Embedded; Name string; hidden int }
type MyInt int
type MyString string
type MyTime time.Time
func describe(t reflect.Type) map[string]any { return map[string]any{"name":t.Name(),"pkgPath":t.PkgPath(),"kind":t.Kind().String(),"string":t.String(),"comparable":t.Comparable()} }
func main(){
out := map[string]any{}
vf:=reflect.VisibleFields(reflect.TypeOf(VisibleSample{})); fields:=[]any{}
for _, f := range vf { fields=append(fields,map[string]any{"name":f.Name,"type":f.Type.String(),"index":f.Index,"anonymous":f.Anonymous,"pkgPath":f.PkgPath,"exported":f.IsExported()}) }
out["visibleFields"] = map[string]any{"sample":"VisibleSample","fields":fields}
out["stdTypes"] = []any{describe(reflect.TypeOf(time.Time{})), describe(reflect.TypeOf(time.Duration(0))), describe(reflect.TypeOf([]any{})), describe(reflect.TypeOf(map[string]any{})), describe(reflect.TypeOf(func(any) bool { return true }))}
out["namedTypes"] = []any{describe(reflect.TypeOf(MyInt(0))), describe(reflect.TypeOf(MyString(""))), describe(reflect.TypeOf(MyTime{}))}
json.NewEncoder(os.Stdout).Encode(out)
}`;
const data = JSON.parse(goRun(scan));
write("parity/metadata/visible_fields.generated.json", JSON.stringify(data.visibleFields, null, 2));
write("parity/metadata/named_types.generated.json", JSON.stringify(data.namedTypes, null, 2));
const ts = `// Code generated by scripts/sync-go.mjs from Go reflect scan. DO NOT EDIT.\nimport { Kind } from './kind.js';\nimport { Type, anyType } from './type.js';\n\nexport interface StdTypeDescriptor { name: string; pkgPath: string; kind: string; string: string; comparable: boolean }\nexport const STD_TYPE_DESCRIPTORS: StdTypeDescriptor[] = ${JSON.stringify(data.stdTypes, null, 2)};\n\nexport function StdType(name: string): Type {\n const d = STD_TYPE_DESCRIPTORS.find((item) => item.string === name || item.name === name);\n if (!d) return anyType;\n const kind = d.kind === 'struct' ? Kind.Struct : d.kind === 'int64' ? Kind.Int64 : d.kind === 'slice' ? Kind.Slice : d.kind === 'map' ? Kind.Map : d.kind === 'func' ? Kind.Func : Kind.Interface;\n return new Type(kind, d.string);\n}\n`;
write("src/checker/nature/std_types.generated.ts", ts);
return { visible: data.visibleFields.fields.length, std: data.stdTypes.length, named: data.namedTypes.length };
}
function genBuiltins() {
const src = readRef("builtin/builtin.go");
const nameMatches = [...src.matchAll(/Name:\s+"([^"]+)"/g)];
const builtins = nameMatches.map((m, index) => {
const start = m.index ?? 0;
const end = nameMatches[index + 1]?.index ?? src.indexOf("\n}\n", start);
const block = src.slice(start, end);
const name = m[1];
return { index, name, predicate: /Predicate:\s+true/.test(block), fast: /Fast:\s+\w+/.test(block) };
});
write("parity/metadata/builtins.generated.json", JSON.stringify({ source: "references/expr/builtin/builtin.go", count: builtins.length, builtins }, null, 2));
return { count: builtins.length, sha: sha256(src) };
}
function genTimeFixtures() {
const scan = `package main
import("encoding/json";"os";"time")
type Row struct{ Layout string \`json:"layout"\`; Input string \`json:"input"\`; Formatted string \`json:"formatted"\`; UnixNano int64 \`json:"unixNano"\`; Error string \`json:"error,omitempty"\` }
func main(){ layouts:=[]string{"2006-01-02","2006-01-02 15:04:05","Mon Jan 2 15:04:05 MST 2006",time.RFC3339,time.RFC3339Nano,"02 Jan 06 15:04 MST"}; inputs:=[]string{"2024-03-05","2024-03-05 14:30:15","Tue Mar 5 14:30:15 UTC 2024","2024-03-05T14:30:15Z","2024-03-05T14:30:15.123456789Z","05 Mar 24 14:30 UTC"}; rows:=[]Row{}; for i,l:= range layouts { t,err:=time.Parse(l,inputs[i]); r:=Row{Layout:l,Input:inputs[i]}; if err!=nil { r.Error=err.Error() } else { r.Formatted=t.Format(l); r.UnixNano=t.UnixNano() }; rows=append(rows,r)}; json.NewEncoder(os.Stdout).Encode(rows)}`;
const rows = JSON.parse(goRun(scan));
write("parity/fixtures/time_layout.generated.json", JSON.stringify(rows, null, 2));
return { count: rows.length };
}
function genReports(summary) {
const lines = [
"# GENERATED_DIVERGENCES.md",
"",
"Generated by `npm run sync:go`. Do not edit manually unless generator behavior changes.",
"",
"| Area | Source | Output | Count | Classification |",
"|---|---|---|---:|---|",
`| FUNC_TYPES | references/expr/vm/func_types[generated].go | src/checker/func_types.generated.ts | ${summary.funcTypes.count} | FULLY_AUTOMATED |`,
`| FUNC_TYPES_ARITY | generated from FUNC_TYPES | src/checker/func_types.generated.ts | ${summary.funcTypes.count + 1} | FULLY_AUTOMATED |`,
`| VALUER_METHODS | references/expr/patcher/value/value.go | src/patcher/value/valuer_methods.generated.ts | ${summary.valuers.count} | FULLY_AUTOMATED |`,
`| Visible fields | Go reflect.VisibleFields scan | parity/metadata/visible_fields.generated.json | ${summary.reflect.visible} | MOSTLY_AUTOMATED |`,
`| Standard type descriptors | Go reflect scan | src/checker/nature/std_types.generated.ts | ${summary.reflect.std} | MOSTLY_AUTOMATED |`,
`| Named type metadata | Go reflect scan | parity/metadata/named_types.generated.json | ${summary.reflect.named} | MOSTLY_AUTOMATED |`,
`| Builtin registry snapshot | references/expr/builtin/builtin.go | parity/metadata/builtins.generated.json | ${summary.builtins.count} | FULLY_AUTOMATED drift snapshot |`,
`| Time layout fixture matrix | Go time.Parse/time.Format | parity/fixtures/time_layout.generated.json | ${summary.time.count} | FULLY_AUTOMATED fixture |`,
"",
"Manual-only areas remain where Go runtime/checker behavior must be hand-ported into TypeScript adapters.",
];
write("GENERATED_DIVERGENCES.md", lines.join("\n"));
}
function run() {
if (!existsSync(REF)) throw new Error(`missing references/expr at ${REF}`);
const summary = {
funcTypes: genFuncTypes(),
valuers: genValuerMethods(),
reflect: genReflectMetadata(),
builtins: genBuiltins(),
time: genTimeFixtures(),
};
genReports(summary);
console.log(JSON.stringify(summary, null, 2));
}
run();