Repository navigation
Expand file tree
/
Copy pathencoder.ts
More file actions
408 lines (358 loc) · 13.9 KB
/
Copy pathencoder.ts
File metadata and controls
408 lines (358 loc) · 13.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
import type {
FileReference,
LiteralLikeNode,
Node,
NodeArray,
SourceFile,
TemplateLiteralLikeNode,
} from "../../ast/index.ts";
import { SyntaxKind } from "../../ast/index.ts";
import {
getNodeCommonData,
getNodeDataType,
} from "./encoder.generated.ts";
import { MsgpackWriter } from "./msgpack.ts";
import {
childProperties,
HEADER_OFFSET_EXTENDED_DATA,
HEADER_OFFSET_METADATA,
HEADER_OFFSET_NODES,
HEADER_OFFSET_STRING_TABLE,
HEADER_OFFSET_STRING_TABLE_OFFSETS,
HEADER_OFFSET_STRUCTURED_DATA,
HEADER_SIZE,
KIND_NODE_LIST,
NODE_DATA_TYPE_CHILDREN,
NODE_DATA_TYPE_EXTENDED,
NODE_DATA_TYPE_STRING,
NODE_LEN,
PROTOCOL_VERSION,
} from "./protocol.ts";
import { encodeWtf8 } from "./wtf8.ts";
const NODE_FIELDS = NODE_LEN / 4;
const NODE_FIELD_NEXT = 3;
const NO_STRUCTURED_DATA = 0xFFFFFFFF;
// String table that accumulates strings into a flat byte pool.
class StringTable {
private parts: Uint8Array[];
private byteLen: number;
private offsets: number[];
constructor() {
this.parts = [];
this.byteLen = 0;
this.offsets = [];
}
add(text: string): number {
const index = this.offsets.length;
const encoded = encodeWtf8(text);
const offset = this.byteLen;
this.parts.push(encoded);
this.byteLen += encoded.length;
this.offsets.push(offset, offset + encoded.length);
return index;
}
encode(): Uint8Array {
const offsetBytes = new Uint8Array(this.offsets.length * 4);
const view = new DataView(offsetBytes.buffer);
for (let i = 0; i < this.offsets.length; i++) {
view.setUint32(i * 4, this.offsets[i], true);
}
const result = new Uint8Array(offsetBytes.length + this.byteLen);
result.set(offsetBytes, 0);
let offset = offsetBytes.length;
for (const part of this.parts) {
result.set(part, offset);
offset += part.length;
}
return result;
}
stringByteLength(): number {
return this.byteLen;
}
offsetsCount(): number {
return this.offsets.length;
}
}
function getChildrenPropertyMask(node: Node): number {
const kind = node.kind;
const props = childProperties[kind];
if (!props) {
return 0;
}
const n = node as unknown as Record<string, unknown>;
let mask = 0;
for (let i = 0; i < props.length; i++) {
const prop = props[i];
if (prop !== undefined && isChildPresent(n[prop])) {
mask |= 1 << i;
}
}
return mask;
}
// A child is "present" if it's non-null/non-undefined.
// This matches the Go encoder's behavior where non-nil NodeLists (even empty)
// are treated as present, and only nil NodeLists are absent.
function isChildPresent(v: unknown): boolean {
if (v === undefined || v === null) return false;
return true;
}
function recordNodeStrings(node: Node, strs: StringTable): number {
return strs.add((node as LiteralLikeNode).text ?? "");
}
function encodeFileReferences(refs: readonly FileReference[] | undefined, writer: MsgpackWriter): number {
if (!refs || refs.length === 0) return NO_STRUCTURED_DATA;
const offset = writer.finish().length;
writer.writeArrayHeader(refs.length);
for (const ref of refs) {
writer.writeArrayHeader(5);
writer.writeUint(ref.pos);
writer.writeUint(ref.end);
writer.writeString(ref.fileName);
writer.writeUint(ref.resolutionMode ?? 0);
writer.writeBool(ref.preserve ?? false);
}
return offset;
}
function recordExtendedData(node: Node, strs: StringTable, extendedData: number[], structuredWriter: MsgpackWriter): number {
const offset = extendedData.length * 4;
if (node.kind === SyntaxKind.SourceFile) {
const sf = node as SourceFile;
const textIndex = strs.add(sf.text);
const fileNameIndex = strs.add(sf.fileName);
const pathIndex = strs.add(sf.path);
const referencedFilesOffset = encodeFileReferences(sf.referencedFiles, structuredWriter);
const typeRefDirectivesOffset = encodeFileReferences(sf.typeReferenceDirectives, structuredWriter);
const libRefDirectivesOffset = encodeFileReferences(sf.libReferenceDirectives, structuredWriter);
// Content-mapper metadata is program-owned and supplied only by the Go encoder.
extendedData.push(textIndex, fileNameIndex, pathIndex, sf.languageVariant, sf.scriptKind, referencedFilesOffset, typeRefDirectivesOffset, libRefDirectivesOffset, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, 0, textIndex, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA, NO_STRUCTURED_DATA);
}
else if (
node.kind === SyntaxKind.TemplateHead ||
node.kind === SyntaxKind.TemplateMiddle ||
node.kind === SyntaxKind.TemplateTail
) {
const tmpl = node as TemplateLiteralLikeNode;
const text: string = tmpl.text ?? "";
const rawText: string = tmpl.rawText ?? "";
const templateFlags: number = tmpl.templateFlags ?? 0;
const textIndex = strs.add(text);
const rawTextIndex = strs.add(rawText);
extendedData.push(textIndex, rawTextIndex, templateFlags);
}
else {
// StringLiteral, NumericLiteral, BigIntLiteral, RegularExpressionLiteral,
// NoSubstitutionTemplateLiteral — format: [textIndex, tokenFlags]
const n = node as any;
const text: string = n.text ?? "";
const tokenFlags: number = n.tokenFlags ?? 0;
const textIndex = strs.add(text);
extendedData.push(textIndex, tokenFlags);
}
return offset;
}
function getNodeData(node: Node, strs: StringTable, extendedData: number[], structuredWriter: MsgpackWriter): number {
const t = getNodeDataType(node.kind);
const common = getNodeCommonData(node);
switch (t) {
case NODE_DATA_TYPE_CHILDREN:
return t | common | getChildrenPropertyMask(node);
case NODE_DATA_TYPE_STRING:
return t | common | recordNodeStrings(node, strs);
case NODE_DATA_TYPE_EXTENDED:
return t | common | recordExtendedData(node, strs, extendedData, structuredWriter);
default:
throw new Error("unreachable");
}
}
function getChildPropertiesForNode(node: Node): readonly (string | undefined)[] | undefined {
return childProperties[node.kind];
}
// Returns whether a value is a NodeArray (array-like with pos and end).
function isNodeArray(value: any): value is NodeArray<Node> {
return Array.isArray(value) && typeof (value as any).pos === "number" && typeof (value as any).end === "number";
}
/**
* Encode a SourceFile AST node into the binary format.
*/
export function encodeSourceFile(sourceFile: SourceFile): Uint8Array {
return encodeNode(sourceFile);
}
/**
* Encode an arbitrary AST node into the binary format.
* When encoding a non-SourceFile node, the header hash and parse options fields will be zero.
*/
export function encodeNode(node: Node): Uint8Array {
const strs = new StringTable();
const extendedDataValues: number[] = [];
const structuredWriter = new MsgpackWriter();
// We'll build an array of uint32 values for the nodes section, 7 per node
const nodeValues: number[] = [];
// Nil node (index 0)
nodeValues.push(0, 0, 0, 0, 0, 0, 0);
let nodeCount = 0;
let parentIndex = 0;
let prevIndex = 0;
function visitNode(node: Node): void {
nodeCount++;
const currentIndex = nodeCount;
if (prevIndex !== 0) {
// Set next pointer on previous sibling
nodeValues[prevIndex * NODE_FIELDS + NODE_FIELD_NEXT] = currentIndex;
}
const data = getNodeData(node, strs, extendedDataValues, structuredWriter);
nodeValues.push(
node.kind,
node.pos >= 0 ? node.pos : 0,
node.end >= 0 ? node.end : 0,
0, // next (filled in later)
parentIndex,
data,
node.flags,
);
const saveParentIndex = parentIndex;
const savePrevIndex = prevIndex;
parentIndex = currentIndex;
prevIndex = 0;
visitChildren(node);
prevIndex = currentIndex;
parentIndex = saveParentIndex;
}
function visitNodeList(list: NodeArray<Node>): void {
if (!list) {
return;
}
nodeCount++;
const currentIndex = nodeCount;
if (prevIndex !== 0) {
nodeValues[prevIndex * NODE_FIELDS + NODE_FIELD_NEXT] = currentIndex;
}
nodeValues.push(
KIND_NODE_LIST,
list.pos >= 0 ? list.pos : 0,
list.end >= 0 ? list.end : 0,
0, // next
parentIndex,
list.length, // data for NodeList is its length
list.hasTrailingComma ? 1 : 0, // NodeLists have no AST flags; this slot is reused for hasTrailingComma
);
const saveParentIndex = parentIndex;
parentIndex = currentIndex;
prevIndex = 0;
for (const child of list) {
visitNode(child);
}
prevIndex = currentIndex;
parentIndex = saveParentIndex;
}
function visitChildren(node: Node): void {
const props = getChildPropertiesForNode(node);
const n = node as any;
if (props) {
for (const propName of props) {
if (propName === undefined) continue;
const child = n[propName];
if (child === undefined || child === null) continue;
if (isNodeArray(child)) {
visitNodeList(child);
}
else {
visitNode(child);
}
}
}
}
// Encode root node
nodeCount++;
parentIndex++;
const rootData = getNodeData(node, strs, extendedDataValues, structuredWriter);
nodeValues.push(
node.kind,
node.pos >= 0 ? node.pos : 0,
node.end >= 0 ? node.end : 0,
0,
0,
rootData,
node.flags,
);
const saveParent = parentIndex;
prevIndex = 0;
parentIndex = 1; // root is at index 1
visitChildren(node);
parentIndex = saveParent;
// Encode extended data section
const extendedDataBytes = new Uint8Array(extendedDataValues.length * 4);
const extView = new DataView(extendedDataBytes.buffer);
for (let i = 0; i < extendedDataValues.length; i++) {
extView.setUint32(i * 4, extendedDataValues[i], true);
}
// Encode structured data section
const structuredDataBytes = structuredWriter.finish();
// Encode string table
const strsBytes = strs.encode();
// Encode nodes section
const nodesBytes = new Uint8Array(nodeValues.length * 4);
const nodesView = new DataView(nodesBytes.buffer);
for (let i = 0; i < nodeValues.length; i++) {
nodesView.setUint32(i * 4, nodeValues[i] >>> 0, true);
}
// Calculate section offsets
const offsetStringTableOffsets = HEADER_SIZE;
const offsetStringTableData = HEADER_SIZE + strs.offsetsCount() * 4;
const offsetExtendedData = offsetStringTableData + strs.stringByteLength();
const offsetStructuredData = offsetExtendedData + extendedDataBytes.length;
const offsetNodes = offsetStructuredData + structuredDataBytes.length;
// Build header
const header = new Uint8Array(HEADER_SIZE);
const headerView = new DataView(header.buffer);
const metadata = PROTOCOL_VERSION << 24;
headerView.setUint32(HEADER_OFFSET_METADATA, metadata, true);
// bytes 4-19: hash (zero for non-SourceFile, we don't have access to xxh3 here)
// byte 20-23: parse options (zero for non-SourceFile)
headerView.setUint32(HEADER_OFFSET_STRING_TABLE_OFFSETS, offsetStringTableOffsets, true);
headerView.setUint32(HEADER_OFFSET_STRING_TABLE, offsetStringTableData, true);
headerView.setUint32(HEADER_OFFSET_EXTENDED_DATA, offsetExtendedData, true);
headerView.setUint32(HEADER_OFFSET_STRUCTURED_DATA, offsetStructuredData, true);
headerView.setUint32(HEADER_OFFSET_NODES, offsetNodes, true);
// Concatenate all sections
const result = new Uint8Array(header.length + strsBytes.length + extendedDataBytes.length + structuredDataBytes.length + nodesBytes.length);
result.set(header, 0);
result.set(strsBytes, HEADER_SIZE);
result.set(extendedDataBytes, offsetExtendedData);
result.set(structuredDataBytes, offsetStructuredData);
result.set(nodesBytes, offsetNodes);
return result;
}
interface NodeBuffer extends Uint8Array {
toString(encoding?: "base64"): string;
}
const nodeBuffer = (globalThis as {
Buffer?: {
from(buffer: ArrayBufferLike, byteOffset: number, length: number): NodeBuffer;
from(data: string, encoding: "base64"): NodeBuffer;
};
}).Buffer;
/**
* Encode a Uint8Array to a base64 string.
*/
export const uint8ArrayToBase64: (data: Uint8Array) => string = "toBase64" in Uint8Array.prototype
? data => (data as Uint8Array & { toBase64(): string; }).toBase64()
: nodeBuffer
? data => nodeBuffer.from(data.buffer, data.byteOffset, data.byteLength).toString("base64")
: data => {
let binary = "";
for (let i = 0; i < data.length; i += 0x8000) {
binary += String.fromCharCode(...data.subarray(i, i + 0x8000));
}
return btoa(binary);
};
const base64ToUint8Array: (data: string) => Uint8Array = "fromBase64" in Uint8Array
? (Uint8Array as unknown as { fromBase64(data: string): Uint8Array; }).fromBase64
: nodeBuffer
? data => {
const buffer = nodeBuffer.from(data, "base64");
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
: data => Uint8Array.from(atob(data), character => character.charCodeAt(0));
export function sourceFileResponseToUint8Array(response: { readonly data: string; } | null | undefined): Uint8Array | undefined {
return response ? base64ToUint8Array(response.data) : undefined;
}