-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathliterals.ts
More file actions
353 lines (312 loc) · 11.3 KB
/
literals.ts
File metadata and controls
353 lines (312 loc) · 11.3 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
import {
Expression,
ArrayNode,
ObjectNode,
MapNode,
SetNode,
StringNode,
} from "../../ast/types.js";
import { parseMapTypeString, parseSetTypeString } from "../infrastructure/type-system.js";
import type {
IStringGenerator,
IStringMapGenerator,
IMapGenerator,
ISetGenerator,
IStringSetGenerator,
IArrayGenerator,
} from "../infrastructure/generator-context.js";
export interface LiteralGeneratorContext {
nextTemp(): string;
emit(instruction: string): void;
generateExpression(expr: Expression, params: string[]): string;
setVariableType(name: string, type: string): void;
getVariableType(name: string): string | undefined;
setUsesPromises(value: boolean): void;
getThisPointer(): string | null;
getCurrentDeclaredMapType(): string | undefined;
getCurrentDeclaredSetType(): string | undefined;
classGenGenerateNewExpression(className: string, args: Expression[], params: string[]): string;
ensureDouble(value: string): string;
readonly stringGen: IStringGenerator;
readonly stringMapGen: IStringMapGenerator;
readonly arrayGen: IArrayGenerator;
readonly mapGen: IMapGenerator;
readonly setGen: ISetGenerator;
readonly stringSetGen: IStringSetGenerator;
readonly regexGen: {
generateRegexCompile(pattern: string, flags: string): string;
generateRegexCompileRuntime(patternPtr: string, cflags: number): string;
};
readonly objectGen: {
generateObjectLiteral(expr: Expression, params: string[]): string;
};
}
/**
* LiteralExpressionGenerator
*
* Generates LLVM IR for literal expressions:
* - Numbers (integer and floating-point)
* - Booleans (true/false)
* - Strings (delegates to StringGenerator)
* - Regex (delegates to RegexGenerator)
* - Arrays (delegates to ArrayGenerator)
* - Objects (delegates to ObjectGenerator)
* - Maps (delegates to MapGenerator)
* - Sets (delegates to SetGenerator)
* - New expressions (delegates to ClassGenerator)
* - This keyword
*/
export class LiteralExpressionGenerator {
constructor(private ctx: LiteralGeneratorContext) {}
/**
* Generate number literal
* Converts integers to double via sitofp for consistency with JavaScript semantics
*/
generateNumber(value: number): string {
const isInteger = value % 1 === 0;
if (isInteger && value >= -9007199254740991 && value <= 9007199254740991) {
const temp = this.ctx.nextTemp();
const intStr = value.toFixed(0);
this.ctx.emit(`${temp} = add i64 ${intStr}, 0`);
this.ctx.setVariableType(temp, "i64");
return temp;
} else {
const s = String(value);
if (
!s.includes(".") &&
!s.includes("e") &&
!s.includes("E") &&
!s.includes("inf") &&
!s.includes("NaN")
) {
return s + ".0";
}
return s;
}
}
/**
* Generate boolean literal (true/false)
* Converts to double for compatibility with numeric system
*/
generateBoolean(value: boolean): string {
const boolValue = value ? 1 : 0;
const temp = this.ctx.nextTemp();
this.ctx.emit(`${temp} = add i64 ${boolValue}, 0`);
this.ctx.setVariableType(temp, "i64");
return temp;
}
/**
* Generate string literal (delegates to StringGenerator)
*/
generateString(value: string): string {
return this.ctx.stringGen.doCreateStringConstant(value);
}
/**
* Generate regex literal (delegates to RegexGenerator)
*/
generateRegex(pattern: string, flags: string): string {
return this.ctx.regexGen.generateRegexCompile(pattern, flags);
}
/**
* Generate array literal (delegates to ArrayGenerator)
* ArrayGenerator uses context pattern - no sync needed! 🎯
*/
generateArray(expr: ArrayNode, params: string[]): string {
return this.ctx.arrayGen.generateArrayLiteral(expr, params);
}
/**
* Generate object literal (delegates to ObjectGenerator)
*/
generateObject(expr: ObjectNode, params: string[]): string {
return this.ctx.objectGen.generateObjectLiteral(expr, params);
}
/**
* Generate Map literal (delegates to MapGenerator or StringMapGenerator)
*/
generateMap(expr: MapNode, params: string[]): string {
if (expr.keyType === "string") {
return this.ctx.stringMapGen.generateEmptyStringMap();
}
const declaredType = this.ctx.getCurrentDeclaredMapType();
if (declaredType) {
const mapParsed = parseMapTypeString(declaredType);
if (mapParsed && mapParsed.keyType === "string") {
return this.ctx.stringMapGen.generateEmptyStringMap();
}
}
return this.ctx.mapGen.generateMapLiteral(expr, params);
}
/**
* Generate Set literal (delegates to SetGenerator or StringSetGenerator)
*/
generateSet(expr: SetNode, params: string[]): string {
if (expr.valueType === "string") {
return this.ctx.stringSetGen.generateEmptyStringSet();
}
const declaredType = this.ctx.getCurrentDeclaredSetType();
if (declaredType) {
const setParsed = parseSetTypeString(declaredType);
if (setParsed && setParsed.valueType === "string") {
return this.ctx.stringSetGen.generateEmptyStringSet();
}
}
return this.ctx.setGen.generateSetLiteral(expr, params);
}
/**
* Generate new expression (delegates to ClassGenerator or built-in types)
*/
generateNew(
className: string,
args: Expression[],
params: string[],
typeArgs?: string[],
): string {
if (className === "Promise") {
return this.generateNewPromise(args, params);
}
if (className === "RegExp") {
return this.generateNewRegExp(args, params);
}
if (className === "Set") {
if (!typeArgs || typeArgs.length === 0) {
throw new Error(
"new Set() requires an explicit type argument, e.g. new Set<string>() or new Set<number>()",
);
}
if (typeArgs[0] === "string") {
return this.ctx.stringSetGen.generateEmptyStringSet();
}
return this.ctx.setGen.generateSetLiteral({ type: "set", values: [] }, params);
}
if (className === "Uint8Array") {
return this.generateNewUint8Array(args, params);
}
if (className === "Date") {
return this.generateNewDate(args, params);
}
if (className === "URL") {
return this.generateNewUrl(args, params);
}
if (className === "URLSearchParams") {
return this.generateNewUrlSearchParams(args, params);
}
return this.ctx.classGenGenerateNewExpression(className, args, params);
}
/**
* Generate new Promise(executor) expression
* The executor is a function (resolve, reject) => { ... }
*/
generateNewPromise(_args: Expression[], _params: string[]): string {
this.ctx.setUsesPromises(true);
const promiseResult = this.ctx.nextTemp();
this.ctx.emit(`${promiseResult} = call %Promise* @__Promise_new()`);
this.ctx.setVariableType(promiseResult, "%Promise*");
return promiseResult;
}
generateNewRegExp(args: Expression[], params: string[]): string {
if (args.length < 1) {
throw new Error("new RegExp() requires at least 1 argument");
}
const patternArg = args[0] as StringNode;
const flagsArg = args.length > 1 ? (args[1] as StringNode) : null;
let flags = "";
if (flagsArg && flagsArg.type === "string" && flagsArg.value !== undefined) {
flags = flagsArg.value;
}
if (patternArg.type === "string" && patternArg.value !== undefined) {
return this.ctx.regexGen.generateRegexCompile(patternArg.value, flags);
}
const REG_EXTENDED = 1;
const REG_ICASE = 2;
const REG_NEWLINE = process.platform === "darwin" ? 8 : 4;
let cflags = REG_EXTENDED;
if (flags.indexOf("i") !== -1) cflags = cflags | REG_ICASE;
if (flags.indexOf("m") !== -1) cflags = cflags | REG_NEWLINE;
const patternPtr = this.ctx.generateExpression(args[0], params);
return this.ctx.regexGen.generateRegexCompileRuntime(patternPtr, cflags);
}
private generateNewUint8Array(args: Expression[], params: string[]): string {
if (args.length < 1) {
throw new Error("new Uint8Array() requires a size argument");
}
const sizeValue = this.ctx.generateExpression(args[0], params);
const sizeDouble = this.ctx.ensureDouble(sizeValue);
const sizeI32 = this.ctx.nextTemp();
this.ctx.emit(`${sizeI32} = fptosi double ${sizeDouble} to i32`);
const sizeI64 = this.ctx.nextTemp();
this.ctx.emit(`${sizeI64} = sext i32 ${sizeI32} to i64`);
const structSize = this.ctx.nextTemp();
this.ctx.emit(`${structSize} = add i64 0, 12`);
const structRaw = this.ctx.nextTemp();
this.ctx.emit(`${structRaw} = call i8* @GC_malloc(i64 ${structSize})`);
const structPtr = this.ctx.nextTemp();
this.ctx.emit(`${structPtr} = bitcast i8* ${structRaw} to %Uint8Array*`);
const dataPtr = this.ctx.nextTemp();
this.ctx.emit(`${dataPtr} = call i8* @GC_malloc_atomic(i64 ${sizeI64})`);
this.ctx.emit(
`call void @llvm.memset.p0i8.i64(i8* ${dataPtr}, i8 0, i64 ${sizeI64}, i1 false)`,
);
const dataFieldPtr = this.ctx.nextTemp();
this.ctx.emit(
`${dataFieldPtr} = getelementptr inbounds %Uint8Array, %Uint8Array* ${structPtr}, i32 0, i32 0`,
);
this.ctx.emit(`store i8* ${dataPtr}, i8** ${dataFieldPtr}`);
const lenFieldPtr = this.ctx.nextTemp();
this.ctx.emit(
`${lenFieldPtr} = getelementptr inbounds %Uint8Array, %Uint8Array* ${structPtr}, i32 0, i32 1`,
);
this.ctx.emit(`store i32 ${sizeI32}, i32* ${lenFieldPtr}`);
const capFieldPtr = this.ctx.nextTemp();
this.ctx.emit(
`${capFieldPtr} = getelementptr inbounds %Uint8Array, %Uint8Array* ${structPtr}, i32 0, i32 2`,
);
this.ctx.emit(`store i32 ${sizeI32}, i32* ${capFieldPtr}`);
this.ctx.setVariableType(structPtr, "%Uint8Array*");
return structPtr;
}
private generateNewUrl(args: Expression[], params: string[]): string {
if (args.length < 1) {
throw new Error("new URL() requires at least 1 argument");
}
const hrefPtr = this.ctx.generateExpression(args[0], params);
this.ctx.setVariableType(hrefPtr, "i8*");
return hrefPtr;
}
private generateNewUrlSearchParams(args: Expression[], params: string[]): string {
if (args.length === 0) {
return this.ctx.stringGen.doCreateStringConstant("");
}
const queryPtr = this.ctx.generateExpression(args[0], params);
this.ctx.setVariableType(queryPtr, "i8*");
return queryPtr;
}
private generateNewDate(args: Expression[], params: string[]): string {
const structRaw = this.ctx.nextTemp();
this.ctx.emit(`${structRaw} = call i8* @GC_malloc(i64 8)`);
const datePtr = this.ctx.nextTemp();
this.ctx.emit(`${datePtr} = bitcast i8* ${structRaw} to %Date*`);
let msValue: string;
if (args.length === 0) {
msValue = this.ctx.nextTemp();
this.ctx.emit(`${msValue} = call double @cs_time_ms()`);
} else {
msValue = this.ctx.ensureDouble(this.ctx.generateExpression(args[0], params));
}
const fieldPtr = this.ctx.nextTemp();
this.ctx.emit(`${fieldPtr} = getelementptr inbounds %Date, %Date* ${datePtr}, i32 0, i32 0`);
this.ctx.emit(`store double ${msValue}, double* ${fieldPtr}`);
this.ctx.setVariableType(datePtr, "%Date*");
return datePtr;
}
/**
* Generate 'this' keyword
* Returns the current this pointer from class context
*/
generateThis(): string {
const thisPtr = this.ctx.getThisPointer();
if (!thisPtr) {
throw new Error("this keyword used outside of class method or constructor");
}
return thisPtr;
}
}