@yannosay/sinth 1.8.1 → 1.8.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1524 +1,1524 @@
1
- import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
2
- import { Lexer } from "./lexer.ts";
3
- import { compileExprToJS, compileIfToJS } from "./expr.ts";
4
- import { tagNameToPascal } from "../utils.ts";
5
-
6
-
7
-
8
- export class Parser {
9
- private pos = 0;
10
- private loopVar: string | null = null;
11
- private _varDecls: VarDeclaration[] = [];
12
-
13
- constructor(private tokens: Token[], private file: string) {}
14
-
15
-
16
- parse(): SinthFile {
17
- let isPage = false;
18
- const imports: ImportNode[] = [];
19
- const meta: MetaEntry[] = [];
20
- const defs: CompDef[] = [];
21
- const functions: FunctionDef[] = [];
22
- const uses: CompUse[] = [];
23
- const styles: StyleBlock[] = [];
24
- const scripts: ScriptBlock[] = [];
25
- const customEls: CustomElDecl[] = [];
26
- const varDecls: VarDeclaration[] = [];
27
- this._varDecls = varDecls;
28
-
29
- if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
30
-
31
- while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
32
-
33
- while (this.isMetaStart()) {
34
- const entry = this.parseMeta();
35
- meta.push(entry);
36
- if (entry.key === "title") isPage = true;
37
- }
38
-
39
-
40
- while (this.check(TT.IDENT) && this.peek().value === "var") {
41
- const vd = this.parseVarDeclaration();
42
- if (vd) { varDecls.push(vd); }
43
- }
44
-
45
-
46
- while (!this.check(TT.EOF)) {
47
- if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
48
- else if (this.check(TT.KW_FUNCTION)) { functions.push(this.parseFunctionDef()); } // ← new
49
- else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
50
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
51
- else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
52
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
53
- const vd = this.parseVarDeclaration();
54
- if (vd) varDecls.push(vd);
55
- }
56
- else if (this.check(TT.KW_IF)) {
57
- const ifNode = this.parseIfBlock();
58
- uses.push(...this.flattenIfToUses(ifNode, scripts));
59
- }
60
- else if (this.check(TT.KW_FOR)) {
61
- const forNode = this.parseForLoop();
62
- uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
63
- }
64
- else if (this.check(TT.LPAREN)) {
65
- const loc = this.peek().loc;
66
- this.consume(TT.LPAREN);
67
- const expr = this.parseExpression();
68
- if (!expr) throw new SinthError("Expected expression after '('", loc);
69
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", loc);
70
- this.consume(TT.RPAREN);
71
- uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc }], loc });
72
- }
73
- else if (this.check(TT.IDENT)) {
74
- const savedPos = this.pos;
75
- const identName = this.peek().value;
76
- const nextType = this.tokens[this.pos + 1]?.type;
77
-
78
- // detect accidental top-level expressions (guess == target" instead of "if guess == target")
79
- const isComparison = [TT.OP_EQEQ, TT.OP_NEQ, TT.OP_LT, TT.OP_GT, TT.OP_LTEQ, TT.OP_GTEQ].includes(nextType);
80
- const isLogicAndOr = nextType === TT.IDENT && (this.tokens[this.pos + 1]?.value === "and" || this.tokens[this.pos + 1]?.value === "or");
81
-
82
- if (isComparison || isLogicAndOr) {
83
- throw new SinthError(
84
- `Unexpected expression '${identName} ...' at top level. Did you mean to wrap this in an 'if' block?`,
85
- this.peek().loc,
86
- );
87
- }
88
-
89
- // top-level assignment: ident = expr
90
- if (nextType === TT.EQUALS ||
91
- (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) ||
92
- (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
93
- this.consume(TT.IDENT); // consume name
94
- let op: AssignOp = "=";
95
- if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
96
- else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
97
- this.consume(TT.EQUALS);
98
- const expr = this.parseExpression();
99
- if (expr) {
100
- const js = `${identName} ${op} ${compileExprToJS(expr)};
101
- sinthRender();`;
102
- scripts.push({ raw: js, attrs: {}, loc: this.peek().loc });
103
- }
104
- continue;
105
- }
106
-
107
- if (nextType === TT.LPAREN && identName[0] === identName[0].toLowerCase()) {
108
- this.consume(TT.IDENT);
109
- this.consume(TT.LPAREN);
110
- const args: Expression[] = [];
111
- if (!this.check(TT.RPAREN)) {
112
- args.push(this.parseExpression()!);
113
- while (this.check(TT.COMMA)) {
114
- this.consume(TT.COMMA);
115
- args.push(this.parseExpression()!);
116
- }
117
- }
118
- this.consume(TT.RPAREN);
119
- const expr: Expression = { kind: "call", callee: { kind: "variable", name: identName }, args };
120
- uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc: this.peek().loc }], loc: this.peek().loc });
121
- } else {
122
- this.pos = savedPos;
123
- uses.push(this.parseCompUse());
124
- }
125
- }
126
- else throw new SinthError(
127
- `Unexpected token '${this.peek().value}' (${TT[this.peek().type]}) at top level`,
128
- this.peek().loc,
129
- );
130
- }
131
-
132
- this._visited.clear();
133
- return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls };
134
- }
135
-
136
- private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
137
- const bodyHasComp = ifNode.body.some(c => c.kind === "use");
138
- const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
139
- if (!bodyHasComp && !elseHasComp) {
140
- scripts.push({ raw: compileIfToJS(ifNode), attrs: {}, loc: ifNode.loc });
141
- return [];
142
- }
143
- const syntheticUse: CompUse = {
144
- kind: "use",
145
- name: "__IF_ROOT__",
146
- attrs: [],
147
- children: [ifNode],
148
- loc: ifNode.loc,
149
- };
150
- return [syntheticUse];
151
- }
152
-
153
- // imports
154
-
155
- private parseImport(): ImportNode {
156
- const loc = this.consume(TT.KW_IMPORT).loc;
157
- if (this.check(TT.KW_CSS)) {
158
- this.consume(TT.KW_CSS);
159
- return { kind: "css", path: this.consume(TT.STRING).value, loc };
160
- }
161
- if (this.check(TT.STRING)) {
162
- return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
163
- }
164
- if (this.check(TT.IDENT)) {
165
- const name = this.consume(TT.IDENT).value;
166
- let alias: string | undefined;
167
- if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
168
- return { kind: "js", name, alias, loc };
169
- }
170
- throw new SinthError(`Expected import path, library name, or 'css'`, loc);
171
- }
172
-
173
- // metadata
174
-
175
- private isMetaStart(): boolean {
176
- if (!this.check(TT.IDENT)) return false;
177
- return this.tokens[this.pos + 1]?.type === TT.EQUALS;
178
- }
179
-
180
- private parseMeta(): MetaEntry {
181
- const loc = this.peek().loc;
182
- const key = this.consume(TT.IDENT).value;
183
- this.consume(TT.EQUALS);
184
- return { key, value: this.parseLiteral(), loc };
185
- }
186
-
187
- // var declarations
188
-
189
- private parseVarDeclaration(): VarDeclaration | null {
190
- const loc = this.peek().loc;
191
- this.consume(TT.IDENT);
192
-
193
- const typeTok = this.consume(TT.IDENT);
194
- let typeStr = typeTok.value;
195
- if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
196
- this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
197
- typeStr = "str[]";
198
- }
199
- if (!["int", "str", "bool", "str[]", "obj", "ui"].includes(typeStr)) {
200
- throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj, component`, typeTok.loc);
201
- }
202
-
203
- const nameTok = this.consume(TT.IDENT);
204
- let val: Literal | null = null;
205
-
206
- if (this.check(TT.EQUALS)) {
207
- this.consume(TT.EQUALS);
208
- if (this.check(TT.LBRACKET)) {
209
- val = this.parseArrayLiteral();
210
- } else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
211
- const savedPos = this.pos;
212
- const expr = this.parseExpression();
213
- if (expr && (expr.kind !== "literal" || (expr.kind === "literal" && expr.value?.kind === "str" && expr.value.value.startsWith("__VAR__")))) {
214
- val = { kind: "str", value: `__EXPR__${JSON.stringify(expr)}` };
215
- } else {
216
- this.pos = savedPos;
217
- val = this.parseLiteral();
218
- }
219
- } else if (this.check(TT.NUMBER)) {
220
- val = this.parseLiteral();
221
- } else {
222
- val = this.parseLiteral();
223
- }
224
- }
225
-
226
- return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
227
- }
228
-
229
- private parseArrayLiteral(): Literal {
230
- this.consume(TT.LBRACKET);
231
- const items: any[] = [];
232
- while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
233
- if (this.check(TT.LBRACE)) {
234
- items.push(this.parseObjectLiteral());
235
- } else if (this.check(TT.STRING)) {
236
- items.push(this.consume(TT.STRING).value);
237
- } else if (this.check(TT.NUMBER)) {
238
- items.push(parseFloat(this.consume(TT.NUMBER).value));
239
- } else if (this.check(TT.BOOL_TRUE)) {
240
- this.consume(TT.BOOL_TRUE);
241
- items.push(true);
242
- } else if (this.check(TT.BOOL_FALSE)) {
243
- this.consume(TT.BOOL_FALSE);
244
- items.push(false);
245
- } else if (this.check(TT.NULL_LIT)) {
246
- this.consume(TT.NULL_LIT);
247
- items.push(null);
248
- }
249
- if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
250
- }
251
- this.consume(TT.RBRACKET);
252
- return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
253
- }
254
-
255
- private parseObjectLiteral(): Record<string, any> {
256
- this.consume(TT.LBRACE);
257
- const obj: Record<string, any> = {};
258
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
259
- const key = this.consume(TT.IDENT).value;
260
- this.consume(TT.COLON);
261
- if (this.check(TT.STRING)) {
262
- obj[key] = this.consume(TT.STRING).value;
263
- } else if (this.check(TT.NUMBER)) {
264
- obj[key] = parseFloat(this.consume(TT.NUMBER).value);
265
- } else if (this.check(TT.BOOL_TRUE)) {
266
- this.consume(TT.BOOL_TRUE);
267
- obj[key] = true;
268
- } else if (this.check(TT.BOOL_FALSE)) {
269
- this.consume(TT.BOOL_FALSE);
270
- obj[key] = false;
271
- } else if (this.check(TT.NULL_LIT)) {
272
- this.consume(TT.NULL_LIT);
273
- obj[key] = null;
274
- } else if (this.check(TT.IDENT)) {
275
- obj[key] = `__VAR__${this.consume(TT.IDENT).value}`;
276
- } else {
277
- throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
278
- }
279
- if (this.check(TT.COMMA)) this.consume(TT.COMMA);
280
- }
281
- this.consume(TT.RBRACE);
282
- return obj;
283
- }
284
-
285
- private _visited: Set<number> = new Set();
286
- parseExpression(skipBinary: boolean = false): Expression | null {
287
- if (this._visited.has(this.pos)) throw new SinthError("Circular expression reference", this.peek().loc);
288
- this._visited.add(this.pos);
289
- const tok = this.peek();
290
-
291
-
292
- // unary 'not'
293
- if ((tok.type === TT.IDENT && tok.value === "not") || tok.type === TT.OP_NOT) {
294
- if (tok.type === TT.IDENT) this.consume(TT.IDENT); else this.consume(TT.OP_NOT);
295
- const operand = this.parseExpression();
296
- if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
297
- const unaryExpr: Expression = { kind: "unary", op: "not", operand };
298
- return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(unaryExpr)));
299
- }
300
-
301
- if (this.check(TT.LPAREN)) {
302
- this.consume(TT.LPAREN);
303
- const inner = this.parseExpression();
304
- if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
305
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
306
- this.consume(TT.RPAREN);
307
- const result = this.parseCallExpr(this.parsePostfix(inner));
308
- return skipBinary ? result : this.parseBinaryRHS(result);
309
- }
310
-
311
- if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
312
- this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT) || this.check(TT.LBRACE) || this.check(TT.LBRACKET)) {
313
- const lit = this.parseLiteral();
314
- const base: Expression = { kind: "literal", value: lit };
315
- return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(base)));
316
- }
317
-
318
- // remove as function
319
- if ((tok.type as any) === TT.KW_REMOVE) {
320
- const name = this.consume(TT.KW_REMOVE).value;
321
- return this.parseBinaryRHS(this.parseCallExpr({ kind: "variable", name }));
322
- }
323
-
324
- // var or assignment
325
- if (tok.type === TT.IDENT) {
326
- let memo = false;
327
- let rawName = this.consume(TT.IDENT).value;
328
- if (rawName.startsWith("$")) {
329
- memo = true;
330
- rawName = rawName.substring(1);
331
- }
332
- const name = rawName;
333
- let varExpr: Expression;
334
-
335
- // dot notation -> e.g. user.age
336
- if (this.check(TT.DOT)) {
337
- this.consume(TT.DOT);
338
- const propName = this.consume(TT.IDENT).value;
339
- const fullName = `${name}.${propName}`;
340
- varExpr = { kind: "variable", name: fullName };
341
- } else {
342
- varExpr = { kind: "variable", name };
343
- }
344
-
345
- // apply bracket postfixes (e.g. data[key], data["x"])
346
- const indexedExpr = this.parsePostfix(varExpr);
347
-
348
- // if indexing was applied, we don't allow assignment, just binary RHS (after possible call)
349
- if (indexedExpr !== varExpr) {
350
- return this.parseBinaryRHS(this.parseCallExpr(indexedExpr));
351
- }
352
-
353
- // no indexing – check for assignment operators
354
- const nextType = this.tokens[this.pos]?.type;
355
- if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
356
- this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
357
- const rhs = this.parseExpression();
358
- if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
359
- return { kind: "assign", target: varExpr.name!, op: "+=", right: rhs };
360
- }
361
- if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
362
- this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
363
- const rhs = this.parseExpression();
364
- if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
365
- return { kind: "assign", target: varExpr.name!, op: "-=", right: rhs };
366
- }
367
- if (nextType === TT.EQUALS) {
368
- this.consume(TT.EQUALS);
369
- const rhs = this.parseExpression();
370
- if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
371
- return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
372
- }
373
-
374
- return this.parseBinaryRHS(this.parseCallExpr(varExpr));
375
- }
376
-
377
- return null;
378
- }
379
-
380
-
381
-
382
- private parsePrimary(): Expression {
383
- const tok = this.peek();
384
- if (tok.type === TT.NUMBER || tok.type === TT.STRING || tok.type === TT.BOOL_TRUE || tok.type === TT.BOOL_FALSE || tok.type === TT.NULL_LIT) {
385
- const lit = this.parseLiteral();
386
- return { kind: "literal", value: lit };
387
- }
388
- if (tok.type === TT.IDENT) {
389
- let memo = false;
390
- let rawName = this.consume(TT.IDENT).value;
391
- if (rawName.startsWith("$")) {
392
- memo = true;
393
- rawName = rawName.substring(1);
394
- }
395
- const name = rawName;
396
- let expr: Expression;
397
- if (this.check(TT.DOT)) {
398
- this.consume(TT.DOT);
399
- expr = { kind: "variable", name: name + "." + this.consume(TT.IDENT).value };
400
- } else {
401
- expr = { kind: "variable", name };
402
- }
403
- if (memo) expr.memo = true;
404
- return expr;
405
- }
406
- if (tok.type === TT.LPAREN) {
407
- this.consume(TT.LPAREN);
408
- const inner = this.parseExpression();
409
- this.consume(TT.RPAREN);
410
- return inner!;
411
- }
412
- if (tok.type === TT.LBRACE) {
413
- const obj = this.parseObjectLiteral();
414
- return { kind: "literal", value: { kind: "str", value: JSON.stringify(obj) } };
415
- }
416
- throw new SinthError(`Expected expression`, this.peek().loc);
417
- }
418
-
419
- private parseComparison(left: Expression): Expression {
420
- const savedPos = this.pos;
421
- const t = this.peek().type;
422
- let op: BinaryOp | null = null;
423
- if (t === TT.OP_EQEQ) op = "==";
424
- else if (t === TT.OP_NEQ) op = "!=";
425
- else if (t === TT.OP_LT) op = "<";
426
- else if (t === TT.OP_GT) op = ">";
427
- else if (t === TT.OP_LTEQ) op = "<=";
428
- else if (t === TT.OP_GTEQ) op = ">=";
429
- if (!op) return left;
430
- this.pos++;
431
- const rightPrimary = this.parsePrimary();
432
- const rightWithPostfix = this.parsePostfix(rightPrimary);
433
- const rightWithCall = this.parseCallExpr(rightWithPostfix);
434
- const right = this.parseArithmetic(rightWithCall);
435
- if (!right) {
436
- this.pos = savedPos;
437
- return left;
438
- }
439
- if (this.pos === savedPos) return { kind: "binary", left, op, right };
440
- return { kind: "binary", left, op, right };
441
- }
442
-
443
- private parseLogical(left: Expression): Expression {
444
- const savedPos = this.pos;
445
- const t = this.peek().type;
446
- let op: BinaryOp | null = null;
447
- if (t === TT.IDENT && this.peek().value === "and") op = "and";
448
- else if (t === TT.IDENT && this.peek().value === "or") op = "or";
449
- if (!op) return left;
450
- this.pos++;
451
- const right = this.parseExpression();
452
- if (!right) {
453
- this.pos = savedPos;
454
- return left;
455
- }
456
- return this.parseLogical({ kind: "binary", left, op, right });
457
- }
458
-
459
- private parseArithmetic(left: Expression): Expression {
460
- while (true) {
461
- const t = this.peek().type;
462
- let op: BinaryOp | null = null;
463
- if (t === TT.OP_PLUS) op = "+";
464
- else if (t === TT.OP_MINUS) op = "-";
465
- else if (t === TT.OP_STAR) op = "*";
466
- else if (t === TT.OP_SLASH) op = "/";
467
- else if (t === TT.OP_MOD) op = "%";
468
- if (!op) break;
469
- this.pos++;
470
- const rightPrimary = this.parsePrimary();
471
- const rightWithPostfix = this.parsePostfix(rightPrimary);
472
- const rightWithCall = this.parseCallExpr(rightWithPostfix);
473
- const right = rightWithCall;
474
- if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
475
- left = { kind: "binary", left, op, right };
476
- }
477
- return left;
478
- }
479
-
480
- private parseBinaryRHS(left: Expression): Expression {
481
- left = this.parseArithmetic(left);
482
- left = this.parseComparison(left);
483
- left = this.parseLogical(left);
484
- return left;
485
- }
486
-
487
- private parsePostfix(base: Expression): Expression {
488
- let expr = base;
489
- while (this.check(TT.LBRACKET)) {
490
- this.consume(TT.LBRACKET);
491
- const key = this.parseExpression();
492
- if (!key) throw new SinthError("Expected expression inside [...]", this.peek().loc);
493
- this.consume(TT.RBRACKET);
494
- expr = { kind: "index", object: expr, key };
495
- }
496
- return expr;
497
- }
498
-
499
- private parseCallExpr(expr: Expression): Expression {
500
- while (this.check(TT.LPAREN)) {
501
- this.consume(TT.LPAREN);
502
- const args: Expression[] = [];
503
- if (!this.check(TT.RPAREN)) {
504
- args.push(this.parseExpression()!);
505
- while (this.check(TT.COMMA)) {
506
- this.consume(TT.COMMA);
507
- args.push(this.parseExpression()!);
508
- }
509
- }
510
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')' after arguments", this.peek().loc);
511
- this.consume(TT.RPAREN);
512
- expr = { kind: "call", callee: expr, args };
513
- }
514
- return expr;
515
- }
516
-
517
-
518
- // component definitions
519
-
520
- private parseFunctionDef(): FunctionDef {
521
- const loc = this.consume(TT.KW_FUNCTION).loc;
522
- const name = this.consume(TT.IDENT).value;
523
- if (name[0] === name[0].toUpperCase() && name[0] !== name[0].toLowerCase()) {
524
- throw new SinthError(`Function '${name}' must start with lowercase. Use 'component' for uppercase names.`, loc);
525
- }
526
- const params = this.parseParamDecls();
527
- let returnType: VarType | undefined;
528
- if (this.check(TT.OP_ARROW)) {
529
- this.consume(TT.OP_ARROW);
530
- const typeTok = this.consume(TT.IDENT);
531
- if (!["int","str","bool","str[]","obj","ui"].includes(typeTok.value)) {
532
- throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj, ui`, typeTok.loc);
533
- }
534
- returnType = typeTok.value as VarType;
535
- }
536
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after function signature", this.peek().loc);
537
- this.consume(TT.LBRACE);
538
- const body = this.parseUnifiedBody();
539
- this.consume(TT.RBRACE);
540
- return { name, params, returnType, body, loc };
541
- }
542
-
543
- private parseCompDef(): CompDef {
544
- const loc = this.consume(TT.KW_COMPONENT).loc;
545
- const name = this.consume(TT.IDENT).value;
546
- const params = this.parseParamDecls();
547
- const rawTok = this.consume(TT.RAW_BLOCK);
548
- const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
549
- return { name, params, body, styles, scripts, loc };
550
- }
551
-
552
- private parseCustomEl(): CustomElDecl {
553
- const loc = this.peek().loc;
554
- if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
555
- else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
556
- const sinthName = this.consume(TT.IDENT).value;
557
- let exportTag: string | undefined;
558
- if (this.check(TT.LPAREN)) {
559
- this.consume(TT.LPAREN);
560
- while (!this.check(TT.RPAREN)) {
561
- const attrName = this.consume(TT.IDENT).value;
562
- if (attrName === "export") {
563
- this.consume(TT.COLON);
564
- if (!this.check(TT.OP_LT)) throw new SinthError("Expected '<tag/>' after 'export:'", this.peek().loc);
565
- this.consume(TT.OP_LT);
566
- exportTag = this.consume(TT.IDENT).value;
567
- if (!this.check(TT.OP_SLASH)) throw new SinthError("Expected '/>' in tag literal", this.peek().loc);
568
- this.consume(TT.OP_SLASH);
569
- this.consume(TT.OP_GT);
570
- }
571
- if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
572
- }
573
- this.consume(TT.RPAREN);
574
- }
575
- if (this.check(TT.RAW_BLOCK)) {
576
- const rawTok = this.consume(TT.RAW_BLOCK);
577
- const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
578
- const sub = new Parser(tokens, rawTok.loc.file);
579
- sub._varDecls = this._varDecls;
580
- const parsed = sub.parseBodyContents();
581
- return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body: parsed.body, styles: parsed.styles, scripts: parsed.scripts, varDecls: this._varDecls, loc };
582
- }
583
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after custom element declaration", this.peek().loc);
584
- this.consume(TT.LBRACE);
585
- const body: Child[] = [];
586
- const styles: StyleBlock[] = [];
587
- const scripts: ScriptBlock[] = [];
588
- const varDecls: VarDeclaration[] = [];
589
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
590
- if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
591
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
592
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
593
- const vd = this.parseVarDeclaration();
594
- if (vd) varDecls.push(vd);
595
- }
596
- else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
597
- else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
598
- else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
599
- else if (this.check(TT.STRING)) {
600
- body.push({ kind: "text", value: this.consume(TT.STRING).value, loc: this.peek().loc });
601
- }
602
- else throw new SinthError(`Unexpected token in custom element body`, this.peek().loc);
603
- }
604
- this.consume(TT.RBRACE);
605
- return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body, styles, scripts, varDecls, loc };
606
- }
607
-
608
- private parseReturnStmt(): ReturnStmt {
609
- const loc = this.consume(TT.KW_RETURN).loc;
610
- let expression: Expression | undefined;
611
- if (!this.check(TT.RBRACE) && !this.check(TT.EOF) && !this.check(TT.KW_IF) && !this.check(TT.KW_FOR) && !this.check(TT.KW_RETURN)) {
612
- expression = this.parseExpression() ?? undefined;
613
- }
614
- return { kind: "return", expression, loc };
615
- }
616
-
617
- private parseParamDecls(): ParamDecl[] {
618
- const params: ParamDecl[] = [];
619
- if (!this.check(TT.LPAREN)) return params;
620
- this.consume(TT.LPAREN);
621
- while (!this.check(TT.RPAREN)) {
622
- const ploc = this.peek().loc;
623
- let pname: string;
624
- let paramType: VarType | undefined;
625
- if (this.check(TT.IDENT) && ["int","str","bool","str[]","obj"].includes(this.peek().value) &&
626
- this.tokens[this.pos + 1]?.type === TT.IDENT) {
627
- paramType = this.consume(TT.IDENT).value as VarType;
628
- pname = this.consume(TT.IDENT).value;
629
- } else {
630
- const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
631
- pname = nameTok.value;
632
- }
633
- let defaultVal: Literal | undefined;
634
- if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
635
- params.push({ name: pname, paramType, defaultVal, loc: ploc });
636
- if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
637
- }
638
- this.consume(TT.RPAREN);
639
- return params;
640
- }
641
-
642
- private parseCompBody(
643
- raw: string,
644
- loc: Loc,
645
- ): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
646
- const tokens = new Lexer(raw, loc.file).tokenize();
647
- const sub = new Parser(tokens, loc.file);
648
- sub._varDecls = this._varDecls;
649
- return sub.parseBodyContents();
650
- }
651
-
652
- private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
653
- const body: Child[] = [], styles: StyleBlock[] = [], scripts: ScriptBlock[] = [];
654
- while (!this.check(TT.EOF)) {
655
- if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
656
- else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
657
- else if (this.check(TT.STRING)) {
658
- const loc = this.peek().loc;
659
- body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
660
- }
661
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
662
- const vd = this.parseVarDeclaration();
663
- if (vd) this._varDecls.push(vd);
664
- continue;
665
- }
666
- else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
667
- else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
668
- else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
669
- else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
670
- else throw new SinthError(
671
- `Unexpected token '${this.peek().value}' in component body`,
672
- this.peek().loc,
673
- );
674
- }
675
- return { body, styles, scripts };
676
- }
677
-
678
- // if / else blocks
679
-
680
- private parseIfBlock(): IfBlock {
681
- const loc = this.consume(TT.KW_IF).loc;
682
- const condition = this.parseExpression();
683
- if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
684
-
685
- let persist = false;
686
- if (this.check(TT.IDENT) && this.peek().value === "persist") {
687
- this.consume(TT.IDENT);
688
- persist = true;
689
- }
690
- this.consume(TT.LBRACE);
691
- const body = this.parseUnifiedBody();
692
- this.consume(TT.RBRACE);
693
-
694
- const elseBody = this.parseElseChain();
695
-
696
- return { kind: "if", condition, body, elseBody, persist, loc };
697
- }
698
-
699
- private parseElseChain(): Child[] | undefined {
700
- if (!this.check(TT.KW_ELSE)) return undefined;
701
-
702
- const elseTok = this.consume(TT.KW_ELSE);
703
-
704
- if (this.check(TT.LBRACE)) {
705
- this.consume(TT.LBRACE);
706
- const body = this.parseUnifiedBody();
707
- this.consume(TT.RBRACE);
708
- return body;
709
- }
710
-
711
- if (this.check(TT.KW_IF) || elseTok.value === "elif") {
712
- const ifBlock = this.parseIfContinue(elseTok);
713
- return [ifBlock];
714
- }
715
-
716
- throw new SinthError("Expected '{', 'if', or 'elif' after 'else'", this.peek().loc);
717
- }
718
-
719
- private parseIfContinue(elseTok: Token): IfBlock {
720
- let condition: Expression;
721
-
722
- if (elseTok.value === "elif") {
723
- condition = this.parseExpression()!;
724
- if (!condition) throw new SinthError("Expected condition after 'elif'", this.peek().loc);
725
- } else {
726
- this.consume(TT.KW_IF);
727
- condition = this.parseExpression()!;
728
- if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
729
- }
730
-
731
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after condition", this.peek().loc);
732
- this.consume(TT.LBRACE);
733
- const body = this.parseUnifiedBody();
734
- this.consume(TT.RBRACE);
735
-
736
- const elseBody = this.parseElseChain();
737
-
738
- return { kind: "if", condition, body, elseBody, loc: elseTok.loc };
739
- }
740
-
741
- private parseRawIfStatement(): string {
742
- this.consume(TT.KW_IF);
743
- const cond = this.parseExpression();
744
- if (!cond) throw new SinthError("Expected condition after 'if'", this.peek().loc);
745
- const condJS = compileExprToJS(cond);
746
- this.consume(TT.LBRACE);
747
- let depth = 1;
748
- const bodyTokens: Token[] = [];
749
- while (depth > 0 && !this.check(TT.EOF)) {
750
- const t = this.peek();
751
- if (t.type === TT.LBRACE) depth++;
752
- else if (t.type === TT.RBRACE) {
753
- depth--;
754
- if (depth === 0) break;
755
- }
756
- bodyTokens.push(this.consume(t.type));
757
- }
758
- this.consume(TT.RBRACE);
759
- const rawBody = bodyTokens.map(t => {
760
- if (t.type === TT.STRING) return '"' + t.value + '"';
761
- return t.value;
762
- }).join(' ');
763
- let result = `if (${condJS}) { ${rawBody} }`;
764
- if (this.check(TT.KW_ELSE)) {
765
- this.consume(TT.KW_ELSE);
766
- if (this.check(TT.KW_IF)) {
767
- const elseIfJS = this.parseRawIfStatement();
768
- result += ` else ${elseIfJS}`;
769
- } else {
770
- this.consume(TT.LBRACE);
771
- depth = 1;
772
- const elseTokens: Token[] = [];
773
- while (depth > 0 && !this.check(TT.EOF)) {
774
- const t = this.peek();
775
- if (t.type === TT.LBRACE) depth++;
776
- else if (t.type === TT.RBRACE) {
777
- depth--;
778
- if (depth === 0) break;
779
- }
780
- elseTokens.push(this.consume(t.type));
781
- }
782
- this.consume(TT.RBRACE);
783
- const elseBody = elseTokens.map(t => {
784
- if (t.type === TT.STRING) return '"' + t.value + '"';
785
- return t.value;
786
- }).join(' ');
787
- result += ` else { ${elseBody} }`;
788
- }
789
- }
790
- return result;
791
- }
792
-
793
- private parseUnifiedBody(): Child[] {
794
- const children: Child[] = [];
795
-
796
- while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
797
- if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
798
- if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
799
- if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
800
- if (this.check(TT.LPAREN)) {
801
- const loc = this.peek().loc;
802
- const expr = this.parseExpression();
803
- if (expr) {
804
- children.push({ kind: "expr", expression: expr, loc });
805
- }
806
- continue;
807
- }
808
- if (this.check(TT.IDENT)) {
809
- const savedPos = this.pos;
810
- const name = this.peek().value;
811
- const nextType = this.tokens[this.pos + 1]?.type;
812
- if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
813
- this.consume(TT.IDENT);
814
- let op: AssignOp = "=";
815
- if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
816
- else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
817
- this.consume(TT.EQUALS);
818
- const rhs = this.parseExpression();
819
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
820
- children.push({ kind: "assign_stmt", expression: { kind: "assign", target: name, op, right: rhs }, loc: this.peek().loc });
821
- continue;
822
- }
823
- this.pos = savedPos;
824
- }
825
- if (this.check(TT.STRING)) {
826
- const loc = this.peek().loc;
827
- let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
828
- while (this.check(TT.OP_PLUS)) {
829
- this.consume(TT.OP_PLUS);
830
- let rhs: Expression | null = null;
831
- if (this.check(TT.STRING)) {
832
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
833
- } else if (this.check(TT.IDENT)) {
834
- const rhsName = this.consume(TT.IDENT).value;
835
- rhs = { kind: "variable", name: rhsName };
836
- } else {
837
- rhs = this.parseExpression(true);
838
- }
839
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
840
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
841
- }
842
- children.push({ kind: "expr", expression: leftExpr, loc });
843
- continue;
844
- }
845
-
846
- if (this.check(TT.KW_REMOVE)) {
847
- const loc = this.consume(TT.KW_REMOVE).loc;
848
- if (this.check(TT.STRING)) {
849
- const target = this.consume(TT.STRING).value;
850
- children.push({ kind: "remove", target, loc });
851
- } else {
852
- throw new SinthError(
853
- `Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
854
- this.peek().loc,
855
- );
856
- }
857
- continue;
858
- }
859
- if (this.check(TT.IDENT) && this.peek().value === "var") {
860
- const vd = this.parseVarDeclaration();
861
- if (vd) this._varDecls.push(vd);
862
- continue;
863
- }
864
-
865
- if (this.check(TT.IDENT)) {
866
- const loc = this.peek().loc;
867
- const name = this.peek().value;
868
- const nextType = this.tokens[this.pos + 1]?.type;
869
- const nextNextType = this.tokens[this.pos + 2]?.type;
870
-
871
- if (nextType === TT.DOT && (nextNextType === TT.EQUALS ||
872
- (nextNextType === TT.OP_PLUS && this.tokens[this.pos + 3]?.type === TT.EQUALS) ||
873
- (nextNextType === TT.OP_MINUS && this.tokens[this.pos + 3]?.type === TT.EQUALS))) {
874
- let fullName = this.consume(TT.IDENT).value;
875
- this.consume(TT.DOT);
876
- fullName = fullName + "." + this.consume(TT.IDENT).value;
877
-
878
- let op: AssignOp = "=";
879
- const afterDotType = this.tokens[this.pos]?.type;
880
- if (afterDotType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
881
- this.consume(TT.OP_PLUS); op = "+=";
882
- } else if (afterDotType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
883
- this.consume(TT.OP_MINUS); op = "-=";
884
- }
885
- this.consume(TT.EQUALS);
886
- const rhs = this.parseExpression();
887
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
888
- const assignExpr: Expression = { kind: "assign", target: fullName, op, right: rhs };
889
- children.push({ kind: "assign_stmt", expression: assignExpr, loc });
890
- continue;
891
- }
892
-
893
- // assignment: ident = expr | ident += expr | ident -= expr
894
- const isSimpleAssign = nextType === TT.EQUALS;
895
- const isPlusAssign = nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
896
- const isMinusAssign = nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
897
-
898
- if (isSimpleAssign || isPlusAssign || isMinusAssign) {
899
- this.consume(TT.IDENT); // consume name
900
- let op: AssignOp = "=";
901
- if (isPlusAssign) { this.consume(TT.OP_PLUS); op = "+="; }
902
- else if (isMinusAssign) { this.consume(TT.OP_MINUS); op = "-="; }
903
- this.consume(TT.EQUALS);
904
- const rhs = this.parseExpression();
905
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
906
- const assignExpr: Expression = { kind: "assign", target: name, op, right: rhs };
907
- children.push({ kind: "assign_stmt", expression: assignExpr, loc });
908
- continue;
909
- }
910
-
911
- if (nextType === TT.LPAREN) {
912
- const identName = this.peek().value;
913
- const isMemo = identName.startsWith("$");
914
- const realName = isMemo ? identName.substring(1) : identName;
915
- if (realName[0] === realName[0].toUpperCase() && realName[0] !== realName[0].toLowerCase()) {
916
- children.push(this.parseCompUse());
917
- } else {
918
- this.consume(TT.IDENT);
919
- this.consume(TT.LPAREN);
920
- const args: Expression[] = [];
921
- if (!this.check(TT.RPAREN)) {
922
- args.push(this.parseExpression()!);
923
- while (this.check(TT.COMMA)) {
924
- this.consume(TT.COMMA);
925
- args.push(this.parseExpression()!);
926
- }
927
- }
928
- this.consume(TT.RPAREN);
929
- const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
930
- children.push({ kind: "expr", expression: callExpr, loc });
931
- }
932
- continue;
933
- }
934
- if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
935
- children.push(this.parseCompUse());
936
- continue;
937
- }
938
-
939
- // var expression
940
- // check dot notation variable reference (user.age without assignment)
941
- if (nextType === TT.DOT) {
942
- let fullName = this.consume(TT.IDENT).value;
943
- this.consume(TT.DOT);
944
- fullName = fullName + "." + this.consume(TT.IDENT).value;
945
- if (this.check(TT.LPAREN)) {
946
- this.consume(TT.LPAREN);
947
- const args: Expression[] = [];
948
- if (!this.check(TT.RPAREN)) {
949
- args.push(this.parseExpression()!);
950
- while (this.check(TT.COMMA)) {
951
- this.consume(TT.COMMA);
952
- args.push(this.parseExpression()!);
953
- }
954
- }
955
- this.consume(TT.RPAREN);
956
- children.push({ kind: "expr", expression: { kind: "call", callee: { kind: "variable", name: fullName }, args }, loc });
957
- } else {
958
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
959
- }
960
- continue;
961
- }
962
-
963
- // bracket notation: ident[...]
964
- if (nextType === TT.LBRACKET) {
965
- this.consume(TT.IDENT);
966
- const varExpr: Expression = { kind: "variable", name };
967
- const indexedExpr = this.parsePostfix(varExpr);
968
- children.push({ kind: "expr", expression: indexedExpr, loc });
969
- continue;
970
- }
971
-
972
-
973
- // simple variable reference
974
- this.consume(TT.IDENT);
975
- children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
976
- continue;
977
- }
978
-
979
- // reject implicit concatenation only after expression children
980
- if (children.length > 0) {
981
- const lastChild = children[children.length - 1];
982
- if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
983
- const nextTT = this.tokens[this.pos]?.type;
984
- if (
985
- nextTT === TT.STRING || nextTT === TT.NUMBER ||
986
- nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
987
- (nextTT === TT.IDENT &&
988
- this.tokens[this.pos]?.value !== "var" &&
989
- this.tokens[this.pos]?.value !== "if" &&
990
- this.tokens[this.pos]?.value !== "for" &&
991
- this.tokens[this.pos]?.value !== "else" &&
992
- this.tokens[this.pos]?.value !== "and" &&
993
- this.tokens[this.pos]?.value !== "or" &&
994
- this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
995
- ) {
996
- throw new SinthError(
997
- `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
998
- this.peek().loc,
999
- );
1000
- }
1001
- }
1002
- }
1003
- }
1004
-
1005
- return children;
1006
- }
1007
-
1008
-
1009
- private parseForLoop(): ForLoop {
1010
- const loc = this.consume(TT.KW_FOR).loc;
1011
- const firstVar = this.consume(TT.IDENT).value;
1012
- let keyVar: string | undefined;
1013
- let itemVar: string;
1014
- let indexVar: string | undefined;
1015
- if (this.check(TT.COMMA)) {
1016
- this.consume(TT.COMMA);
1017
- const secondVar = this.consume(TT.IDENT).value;
1018
- if (this.check(TT.COMMA)) {
1019
- this.consume(TT.COMMA);
1020
- keyVar = firstVar;
1021
- itemVar = secondVar;
1022
- indexVar = this.consume(TT.IDENT).value;
1023
- } else {
1024
- itemVar = firstVar;
1025
- indexVar = secondVar;
1026
- }
1027
- } else {
1028
- itemVar = firstVar;
1029
- }
1030
- if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1031
- this.consume(TT.KW_IN);
1032
- let arrayVar = this.consume(TT.IDENT).value;
1033
- while (this.check(TT.DOT)) {
1034
- this.consume(TT.DOT);
1035
- const propName = this.consume(TT.IDENT).value;
1036
- if (this.check(TT.LPAREN)) {
1037
- this.consume(TT.LPAREN);
1038
- const args: string[] = [];
1039
- if (!this.check(TT.RPAREN)) {
1040
- if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1041
- else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1042
- while (this.check(TT.COMMA)) {
1043
- this.consume(TT.COMMA);
1044
- if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1045
- else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1046
- }
1047
- }
1048
- this.consume(TT.RPAREN);
1049
- arrayVar = arrayVar + "." + propName + "(" + args.map(a => JSON.stringify(a)).join(",") + ")";
1050
- } else {
1051
- arrayVar = arrayVar + "." + propName;
1052
- }
1053
- }
1054
-
1055
- if (keyVar === undefined && indexVar !== undefined) {
1056
- const srcDecl = this._varDecls.find(d => d.name === arrayVar);
1057
- if (srcDecl && srcDecl.varType === "obj") {
1058
- const val = srcDecl.value;
1059
- const isArray = val && val.kind === "str" && val.value.startsWith("__ARR__");
1060
- if (!isArray) {
1061
- keyVar = itemVar;
1062
- itemVar = indexVar;
1063
- indexVar = undefined;
1064
- }
1065
- }
1066
- }
1067
-
1068
- if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
1069
- this.consume(TT.LBRACE);
1070
- this.loopVar = itemVar;
1071
- const body = this.parseChildList();
1072
- this.loopVar = null;
1073
- this.consume(TT.RBRACE);
1074
-
1075
- return { kind: "for", keyVar, itemVar, indexVar, arrayVar, body, loc };
1076
- }
1077
-
1078
-
1079
-
1080
- private parseCompUse(): CompUse {
1081
- const loc = this.peek().loc;
1082
- const name = this.consume(TT.IDENT).value;
1083
- const attrs: Attr[] = [];
1084
-
1085
- if (this.check(TT.LPAREN)) {
1086
- this.consume(TT.LPAREN);
1087
- while (!this.check(TT.RPAREN)) {
1088
- const aloc = this.peek().loc;
1089
- const aname = this.consume(TT.IDENT).value;
1090
- let value: Literal | null = null;
1091
- if (this.check(TT.COLON)) {
1092
- this.consume(TT.COLON);
1093
- if (this.isEventAttr(aname)) {
1094
- if (this.check(TT.STRING)) {
1095
- value = this.parseLiteral();
1096
- } else {
1097
- const savedPos = this.pos;
1098
- const expr = this.parseExpression();
1099
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI) || this.check(TT.KW_IF))) {
1100
- const actions: (Expression | { kind: "if"; js: string })[] = [{ kind: "expr", expr } as any];
1101
- while (this.check(TT.OP_SEMI)) {
1102
- this.consume(TT.OP_SEMI);
1103
- if (this.check(TT.KW_IF)) {
1104
- const jsIf = this.parseRawIfStatement();
1105
- actions.push({ kind: "if", js: jsIf });
1106
- } else {
1107
- const next = this.parseExpression();
1108
- if (next) actions.push({ kind: "expr", expr: next } as any);
1109
- else break;
1110
- }
1111
- }
1112
- const hasIf = actions.some(a => a.kind === "if");
1113
- if (actions.length === 1 && !hasIf) {
1114
- const single = (actions[0] as any).expr as Expression;
1115
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(single) };
1116
- } else {
1117
- const partsJS: string[] = [];
1118
- for (const a of actions) {
1119
- if (a.kind === "if") {
1120
- partsJS.push((a as any).js as string);
1121
- } else {
1122
- partsJS.push(compileExprToJS((a as any).expr as Expression) + ";");
1123
- }
1124
- }
1125
- value = { kind: "str", value: "__ACTION_JS__" + partsJS.join(" ") };
1126
- }
1127
- } else {
1128
- this.pos = savedPos;
1129
- value = this.parseLiteral();
1130
- }
1131
- }
1132
- } else {
1133
- if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
1134
- this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
1135
- this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
1136
- value = this.parseLiteral();
1137
- } else if (this.check(TT.IDENT) || this.check(TT.LPAREN) || this.check(TT.NUMBER)) {
1138
- const savedPos = this.pos;
1139
- const expr = this.parseExpression();
1140
- if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
1141
- value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
1142
- } else {
1143
- this.pos = savedPos;
1144
- if (this.check(TT.IDENT)) {
1145
- value = { kind: "str", value: this.consume(TT.IDENT).value };
1146
- } else {
1147
- value = this.parseLiteral();
1148
- }
1149
- }
1150
- } else {
1151
- value = this.parseLiteral();
1152
- }
1153
- }
1154
- }
1155
- attrs.push({ name: aname, value, loc: aloc });
1156
- if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
1157
- }
1158
- this.consume(TT.RPAREN);
1159
- }
1160
-
1161
- const children: Child[] = [];
1162
- if (this.check(TT.RAW_BLOCK)) {
1163
- const rawTok = this.consume(TT.RAW_BLOCK);
1164
- const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
1165
- const sub = new Parser(tokens, rawTok.loc.file);
1166
- sub._varDecls = this._varDecls;
1167
- children.push(...sub.parseChildList());
1168
- } else if (this.check(TT.LBRACE)) {
1169
- this.consume(TT.LBRACE);
1170
- children.push(...this.parseChildList());
1171
- this.consume(TT.RBRACE);
1172
- }
1173
-
1174
- return { kind: "use", name, attrs, children, loc };
1175
- }
1176
-
1177
- private isEventAttr(name: string): boolean {
1178
- return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
1179
- }
1180
-
1181
- private parseChildList(): Child[] {
1182
- const children: Child[] = [];
1183
- let _iter = 0;
1184
- while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1185
- if (++_iter > 1000) throw new SinthError("Infinite loop in children", this.peek().loc);
1186
-
1187
- if (this.check(TT.LPAREN)) {
1188
- const loc = this.peek().loc;
1189
- this.consume(TT.LPAREN);
1190
- let expr = this.parseExpression(true);
1191
- if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
1192
- if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
1193
- this.consume(TT.RPAREN);
1194
- while (this.check(TT.OP_PLUS)) {
1195
- this.consume(TT.OP_PLUS);
1196
- let rhs: Expression | null = null;
1197
- if (this.check(TT.STRING)) {
1198
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1199
- } else if (this.check(TT.IDENT)) {
1200
- const rhsName = this.consume(TT.IDENT).value;
1201
- rhs = { kind: "variable", name: rhsName };
1202
- } else {
1203
- rhs = this.parseExpression(true);
1204
- }
1205
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1206
- expr = { kind: "binary", left: expr, op: "+", right: rhs };
1207
- }
1208
- children.push({ kind: "expr", expression: expr, loc });
1209
- continue;
1210
- }
1211
- if (this.check(TT.STRING)) {
1212
- const loc = this.peek().loc;
1213
- let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1214
- while (this.check(TT.OP_PLUS)) {
1215
- this.consume(TT.OP_PLUS);
1216
- let rhs: Expression | null = null;
1217
- if (this.check(TT.STRING)) {
1218
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1219
- } else if (this.check(TT.IDENT)) {
1220
- const rhsName = this.consume(TT.IDENT).value;
1221
- if (this.check(TT.LPAREN)) {
1222
- this.consume(TT.LPAREN);
1223
- const args: Expression[] = [];
1224
- if (!this.check(TT.RPAREN)) {
1225
- args.push(this.parseExpression()!);
1226
- while (this.check(TT.COMMA)) {
1227
- this.consume(TT.COMMA);
1228
- args.push(this.parseExpression()!);
1229
- }
1230
- }
1231
- this.consume(TT.RPAREN);
1232
- rhs = { kind: "call", callee: { kind: "variable", name: rhsName }, args };
1233
- } else if (this.check(TT.DOT)) {
1234
- this.consume(TT.DOT);
1235
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1236
- } else {
1237
- rhs = { kind: "variable", name: rhsName };
1238
- }
1239
- } else {
1240
- rhs = this.parseExpression(true);
1241
- }
1242
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1243
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1244
- }
1245
- children.push({ kind: "expr", expression: leftExpr, loc });
1246
- }
1247
- else if (this.check(TT.IDENT) && this.peek().value === "var") {
1248
- const vd = this.parseVarDeclaration();
1249
- if (vd) this._varDecls.push(vd);
1250
- continue;
1251
- }
1252
- else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
1253
- else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
1254
- else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
1255
- else if (this.check(TT.IDENT)) {
1256
- const loc = this.peek().loc;
1257
- const rawName = this.peek().value;
1258
- const nextType = this.tokens[this.pos + 1]?.type;
1259
-
1260
- if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
1261
- this.consume(TT.IDENT);
1262
- let op: AssignOp = "=";
1263
- if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
1264
- else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
1265
- this.consume(TT.EQUALS);
1266
- const rhs = this.parseExpression();
1267
- if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
1268
- children.push({ kind: "assign_stmt", expression: { kind: "assign", target: rawName, op, right: rhs }, loc });
1269
- continue;
1270
- }
1271
-
1272
- if (nextType === TT.DOT) {
1273
- let rawFirst = this.consume(TT.IDENT).value;
1274
- const isMemo = rawFirst.startsWith("$");
1275
- const firstPart = isMemo ? rawFirst.slice(1) : rawFirst;
1276
- this.consume(TT.DOT);
1277
- const fullName = firstPart + "." + this.consume(TT.IDENT).value;
1278
- const afterDotType = this.tokens[this.pos]?.type;
1279
-
1280
- if (afterDotType === TT.OP_PLUS) {
1281
- let leftExpr: Expression = { kind: "variable", name: fullName };
1282
- while (this.check(TT.OP_PLUS)) {
1283
- this.consume(TT.OP_PLUS);
1284
- let rhs: Expression | null = null;
1285
- if (this.check(TT.STRING)) {
1286
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1287
- } else if (this.check(TT.IDENT)) {
1288
- const rhsName = this.consume(TT.IDENT).value;
1289
- if (this.check(TT.DOT)) {
1290
- this.consume(TT.DOT);
1291
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1292
- } else {
1293
- rhs = { kind: "variable", name: rhsName };
1294
- }
1295
- } else {
1296
- rhs = this.parseExpression(true);
1297
- }
1298
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1299
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1300
- }
1301
- children.push({ kind: "expr", expression: leftExpr, loc });
1302
- } else if (this.loopVar && fullName.split('.')[0] === this.loopVar) {
1303
- children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1304
- } else if (afterDotType === TT.LPAREN) {
1305
- this.consume(TT.LPAREN);
1306
- const args: Expression[] = [];
1307
- if (!this.check(TT.RPAREN)) {
1308
- args.push(this.parseExpression()!);
1309
- while (this.check(TT.COMMA)) {
1310
- this.consume(TT.COMMA);
1311
- args.push(this.parseExpression()!);
1312
- }
1313
- }
1314
- this.consume(TT.RPAREN);
1315
- const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: fullName }, args, memo: isMemo || undefined };
1316
- children.push({ kind: "expr", expression: callExpr, loc });
1317
- } else if (afterDotType === TT.LBRACE || afterDotType === TT.RAW_BLOCK) {
1318
- throw new SinthError(`Unexpected dot notation before component usage`, loc);
1319
- } else {
1320
- const varExpr: Expression = { kind: "variable", name: fullName };
1321
- if (isMemo) varExpr.memo = true;
1322
- children.push({ kind: "expr", expression: varExpr, loc });
1323
- }
1324
- continue;
1325
- } else if (nextType === TT.OP_PLUS) {
1326
- const name = this.consume(TT.IDENT).value;
1327
- let leftExpr: Expression = { kind: "variable", name };
1328
- while (this.check(TT.OP_PLUS)) {
1329
- this.consume(TT.OP_PLUS);
1330
- let rhs: Expression | null = null;
1331
- if (this.check(TT.STRING)) {
1332
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1333
- } else if (this.check(TT.IDENT)) {
1334
- const rhsName = this.consume(TT.IDENT).value;
1335
- if (this.check(TT.DOT)) {
1336
- this.consume(TT.DOT);
1337
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1338
- } else {
1339
- rhs = { kind: "variable", name: rhsName };
1340
- }
1341
- } else {
1342
- rhs = this.parseExpression(true);
1343
- }
1344
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1345
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1346
- }
1347
- children.push({ kind: "expr", expression: leftExpr, loc });
1348
- } else if (this.loopVar && rawName === this.loopVar) {
1349
- this.consume(TT.IDENT);
1350
- children.push({ kind: "expr", expression: { kind: "variable", name: rawName }, loc });
1351
- } else if (nextType === TT.LBRACKET) {
1352
- const name = this.consume(TT.IDENT).value;
1353
- const varExpr: Expression = { kind: "variable", name };
1354
- let indexedExpr = this.parsePostfix(varExpr);
1355
- if (this.check(TT.OP_PLUS)) {
1356
- let leftExpr: Expression = indexedExpr;
1357
- while (this.check(TT.OP_PLUS)) {
1358
- this.consume(TT.OP_PLUS);
1359
- let rhs: Expression | null = null;
1360
- if (this.check(TT.STRING)) {
1361
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1362
- } else if (this.check(TT.IDENT)) {
1363
- const rhsName = this.consume(TT.IDENT).value;
1364
- if (this.check(TT.DOT)) {
1365
- this.consume(TT.DOT);
1366
- rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1367
- } else {
1368
- rhs = { kind: "variable", name: rhsName };
1369
- }
1370
- } else {
1371
- rhs = this.parseExpression(true);
1372
- }
1373
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1374
- leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1375
- }
1376
- children.push({ kind: "expr", expression: leftExpr, loc });
1377
- } else {
1378
- children.push({ kind: "expr", expression: indexedExpr, loc });
1379
- }
1380
- } else if (nextType === TT.LPAREN) {
1381
- const identName = this.peek().value;
1382
- const isMemo = identName.startsWith("$");
1383
- const realName = isMemo ? identName.substring(1) : identName;
1384
- if (realName[0] === realName[0].toUpperCase() && realName[0] !== realName[0].toLowerCase()) {
1385
- children.push(this.parseCompUse());
1386
- continue;
1387
- } else {
1388
- this.consume(TT.IDENT);
1389
- this.consume(TT.LPAREN);
1390
- const args: Expression[] = [];
1391
- if (!this.check(TT.RPAREN)) {
1392
- args.push(this.parseExpression()!);
1393
- while (this.check(TT.COMMA)) {
1394
- this.consume(TT.COMMA);
1395
- args.push(this.parseExpression()!);
1396
- }
1397
- }
1398
- this.consume(TT.RPAREN);
1399
- let finalExpr: Expression = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
1400
- while (this.check(TT.OP_PLUS)) {
1401
- this.consume(TT.OP_PLUS);
1402
- let rhs: Expression | null = null;
1403
- if (this.check(TT.STRING)) {
1404
- rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1405
- } else if (this.check(TT.IDENT)) {
1406
- rhs = this.parseExpression();
1407
- } else {
1408
- rhs = this.parseExpression(true);
1409
- }
1410
- if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1411
- finalExpr = { kind: "binary", left: finalExpr, op: "+", right: rhs };
1412
- }
1413
- children.push({ kind: "expr", expression: finalExpr, loc });
1414
- continue;
1415
- }
1416
- } else if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1417
- children.push(this.parseCompUse());
1418
- continue;
1419
- } else {
1420
- const name = this.consume(TT.IDENT).value;
1421
- children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1422
- }
1423
- }
1424
- // reject implicit concatenation only after expression children
1425
- if (children.length > 0) {
1426
- const lastChild = children[children.length - 1];
1427
- if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1428
- const nextTT = this.tokens[this.pos]?.type;
1429
- if (
1430
- nextTT === TT.STRING || nextTT === TT.NUMBER ||
1431
- nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1432
- (nextTT === TT.IDENT &&
1433
- this.tokens[this.pos]?.value !== "var" &&
1434
- this.tokens[this.pos]?.value !== "if" &&
1435
- this.tokens[this.pos]?.value !== "for" &&
1436
- this.tokens[this.pos]?.value !== "else" &&
1437
- this.tokens[this.pos]?.value !== "and" &&
1438
- this.tokens[this.pos]?.value !== "or" &&
1439
- this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
1440
- ) {
1441
- throw new SinthError(
1442
- `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1443
- this.peek().loc,
1444
- );
1445
- }
1446
- }
1447
- }
1448
- if (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
1449
- throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1450
- }
1451
- }
1452
- return children;
1453
- }
1454
-
1455
- // style & script blocks
1456
-
1457
- private parseStyleBlock(): StyleBlock {
1458
- const loc = this.consume(TT.KW_STYLE).loc;
1459
- let global = false, lang: "css" | "scss" = "css", target: string | undefined;
1460
- const extraAttrs: Record<string, string> = {};
1461
-
1462
- while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1463
- if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
1464
- else if (this.check(TT.KW_LANG)) {
1465
- this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
1466
- const lv = this.consume(TT.STRING).value;
1467
- if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
1468
- lang = lv as "css" | "scss";
1469
- }
1470
- else if (this.check(TT.IDENT)) {
1471
- if (this.tokens[this.pos + 1]?.type !== TT.EQUALS) {
1472
- target = this.consume(TT.IDENT).value;
1473
- } else {
1474
- const k = this.consume(TT.IDENT).value;
1475
- this.consume(TT.EQUALS);
1476
- extraAttrs[k] = this.consume(TT.STRING).value;
1477
- }
1478
- }
1479
- else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
1480
- }
1481
-
1482
- return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, target, extraAttrs, loc };
1483
- }
1484
-
1485
- private parseScriptBlock(): ScriptBlock {
1486
- const loc = this.consume(TT.KW_SCRIPT).loc;
1487
- const attrs: Record<string, string> = {};
1488
- while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1489
- const key = this.consume(TT.IDENT).value;
1490
- if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
1491
- else { attrs[key] = "true"; }
1492
- }
1493
- return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
1494
- }
1495
-
1496
- private parseLiteral(): Literal {
1497
- const tok = this.peek();
1498
- if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
1499
- if (this.check(TT.LBRACE)) {
1500
- const obj = this.parseObjectLiteral();
1501
- return { kind: "str", value: JSON.stringify(obj) };
1502
- }
1503
- if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
1504
- if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
1505
- if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
1506
- if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
1507
- if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
1508
- throw new SinthError(`Expected literal value, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
1509
- }
1510
-
1511
- private peek(): Token { return this.tokens[this.pos]; }
1512
- private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
1513
- private consume(t: TT): Token {
1514
- const tok = this.tokens[this.pos];
1515
- if (tok.type !== t) {
1516
- throw new SinthError(
1517
- `Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
1518
- tok.loc,
1519
- );
1520
- }
1521
- this.pos++;
1522
- return tok;
1523
- }
1
+ import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
2
+ import { Lexer } from "./lexer.ts";
3
+ import { compileExprToJS, compileIfToJS } from "./expr.ts";
4
+ import { tagNameToPascal } from "../utils.ts";
5
+
6
+
7
+
8
+ export class Parser {
9
+ private pos = 0;
10
+ private loopVar: string | null = null;
11
+ private _varDecls: VarDeclaration[] = [];
12
+
13
+ constructor(private tokens: Token[], private file: string) {}
14
+
15
+
16
+ parse(): SinthFile {
17
+ let isPage = false;
18
+ const imports: ImportNode[] = [];
19
+ const meta: MetaEntry[] = [];
20
+ const defs: CompDef[] = [];
21
+ const functions: FunctionDef[] = [];
22
+ const uses: CompUse[] = [];
23
+ const styles: StyleBlock[] = [];
24
+ const scripts: ScriptBlock[] = [];
25
+ const customEls: CustomElDecl[] = [];
26
+ const varDecls: VarDeclaration[] = [];
27
+ this._varDecls = varDecls;
28
+
29
+ if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
30
+
31
+ while (this.check(TT.KW_IMPORT)) imports.push(this.parseImport());
32
+
33
+ while (this.isMetaStart()) {
34
+ const entry = this.parseMeta();
35
+ meta.push(entry);
36
+ if (entry.key === "title") isPage = true;
37
+ }
38
+
39
+
40
+ while (this.check(TT.IDENT) && this.peek().value === "var") {
41
+ const vd = this.parseVarDeclaration();
42
+ if (vd) { varDecls.push(vd); }
43
+ }
44
+
45
+
46
+ while (!this.check(TT.EOF)) {
47
+ if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
48
+ else if (this.check(TT.KW_FUNCTION)) { functions.push(this.parseFunctionDef()); } // ← new
49
+ else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
50
+ else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
51
+ else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
52
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
53
+ const vd = this.parseVarDeclaration();
54
+ if (vd) varDecls.push(vd);
55
+ }
56
+ else if (this.check(TT.KW_IF)) {
57
+ const ifNode = this.parseIfBlock();
58
+ uses.push(...this.flattenIfToUses(ifNode, scripts));
59
+ }
60
+ else if (this.check(TT.KW_FOR)) {
61
+ const forNode = this.parseForLoop();
62
+ uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [forNode], loc: forNode.loc });
63
+ }
64
+ else if (this.check(TT.LPAREN)) {
65
+ const loc = this.peek().loc;
66
+ this.consume(TT.LPAREN);
67
+ const expr = this.parseExpression();
68
+ if (!expr) throw new SinthError("Expected expression after '('", loc);
69
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", loc);
70
+ this.consume(TT.RPAREN);
71
+ uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc }], loc });
72
+ }
73
+ else if (this.check(TT.IDENT)) {
74
+ const savedPos = this.pos;
75
+ const identName = this.peek().value;
76
+ const nextType = this.tokens[this.pos + 1]?.type;
77
+
78
+ // detect accidental top-level expressions (guess == target" instead of "if guess == target")
79
+ const isComparison = [TT.OP_EQEQ, TT.OP_NEQ, TT.OP_LT, TT.OP_GT, TT.OP_LTEQ, TT.OP_GTEQ].includes(nextType);
80
+ const isLogicAndOr = nextType === TT.IDENT && (this.tokens[this.pos + 1]?.value === "and" || this.tokens[this.pos + 1]?.value === "or");
81
+
82
+ if (isComparison || isLogicAndOr) {
83
+ throw new SinthError(
84
+ `Unexpected expression '${identName} ...' at top level. Did you mean to wrap this in an 'if' block?`,
85
+ this.peek().loc,
86
+ );
87
+ }
88
+
89
+ // top-level assignment: ident = expr
90
+ if (nextType === TT.EQUALS ||
91
+ (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) ||
92
+ (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
93
+ this.consume(TT.IDENT); // consume name
94
+ let op: AssignOp = "=";
95
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
96
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
97
+ this.consume(TT.EQUALS);
98
+ const expr = this.parseExpression();
99
+ if (expr) {
100
+ const js = `${identName} ${op} ${compileExprToJS(expr)};
101
+ sinthRender();`;
102
+ scripts.push({ raw: js, attrs: {}, loc: this.peek().loc });
103
+ }
104
+ continue;
105
+ }
106
+
107
+ if (nextType === TT.LPAREN && identName[0] === identName[0].toLowerCase()) {
108
+ this.consume(TT.IDENT);
109
+ this.consume(TT.LPAREN);
110
+ const args: Expression[] = [];
111
+ if (!this.check(TT.RPAREN)) {
112
+ args.push(this.parseExpression()!);
113
+ while (this.check(TT.COMMA)) {
114
+ this.consume(TT.COMMA);
115
+ args.push(this.parseExpression()!);
116
+ }
117
+ }
118
+ this.consume(TT.RPAREN);
119
+ const expr: Expression = { kind: "call", callee: { kind: "variable", name: identName }, args };
120
+ uses.push({ kind: "use", name: "__IF_ROOT__", attrs: [], children: [{ kind: "expr", expression: expr, loc: this.peek().loc }], loc: this.peek().loc });
121
+ } else {
122
+ this.pos = savedPos;
123
+ uses.push(this.parseCompUse());
124
+ }
125
+ }
126
+ else throw new SinthError(
127
+ `Unexpected token '${this.peek().value}' (${TT[this.peek().type]}) at top level`,
128
+ this.peek().loc,
129
+ );
130
+ }
131
+
132
+ this._visited.clear();
133
+ return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls };
134
+ }
135
+
136
+ private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
137
+ const bodyHasComp = ifNode.body.some(c => c.kind === "use");
138
+ const elseHasComp = (ifNode.elseBody ?? []).some(c => c.kind === "use");
139
+ if (!bodyHasComp && !elseHasComp) {
140
+ scripts.push({ raw: compileIfToJS(ifNode), attrs: {}, loc: ifNode.loc });
141
+ return [];
142
+ }
143
+ const syntheticUse: CompUse = {
144
+ kind: "use",
145
+ name: "__IF_ROOT__",
146
+ attrs: [],
147
+ children: [ifNode],
148
+ loc: ifNode.loc,
149
+ };
150
+ return [syntheticUse];
151
+ }
152
+
153
+ // imports
154
+
155
+ private parseImport(): ImportNode {
156
+ const loc = this.consume(TT.KW_IMPORT).loc;
157
+ if (this.check(TT.KW_CSS)) {
158
+ this.consume(TT.KW_CSS);
159
+ return { kind: "css", path: this.consume(TT.STRING).value, loc };
160
+ }
161
+ if (this.check(TT.STRING)) {
162
+ return { kind: "sinth", path: this.consume(TT.STRING).value, loc };
163
+ }
164
+ if (this.check(TT.IDENT)) {
165
+ const name = this.consume(TT.IDENT).value;
166
+ let alias: string | undefined;
167
+ if (this.check(TT.KW_AS)) { this.consume(TT.KW_AS); alias = this.consume(TT.IDENT).value; }
168
+ return { kind: "js", name, alias, loc };
169
+ }
170
+ throw new SinthError(`Expected import path, library name, or 'css'`, loc);
171
+ }
172
+
173
+ // metadata
174
+
175
+ private isMetaStart(): boolean {
176
+ if (!this.check(TT.IDENT)) return false;
177
+ return this.tokens[this.pos + 1]?.type === TT.EQUALS;
178
+ }
179
+
180
+ private parseMeta(): MetaEntry {
181
+ const loc = this.peek().loc;
182
+ const key = this.consume(TT.IDENT).value;
183
+ this.consume(TT.EQUALS);
184
+ return { key, value: this.parseLiteral(), loc };
185
+ }
186
+
187
+ // var declarations
188
+
189
+ private parseVarDeclaration(): VarDeclaration | null {
190
+ const loc = this.peek().loc;
191
+ this.consume(TT.IDENT);
192
+
193
+ const typeTok = this.consume(TT.IDENT);
194
+ let typeStr = typeTok.value;
195
+ if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
196
+ this.consume(TT.LBRACKET); this.consume(TT.RBRACKET);
197
+ typeStr = "str[]";
198
+ }
199
+ if (!["int", "str", "bool", "str[]", "obj", "ui"].includes(typeStr)) {
200
+ throw new SinthError(`Unknown type '${typeStr}'. Expected: int, str, bool, str[], obj, component`, typeTok.loc);
201
+ }
202
+
203
+ const nameTok = this.consume(TT.IDENT);
204
+ let val: Literal | null = null;
205
+
206
+ if (this.check(TT.EQUALS)) {
207
+ this.consume(TT.EQUALS);
208
+ if (this.check(TT.LBRACKET)) {
209
+ val = this.parseArrayLiteral();
210
+ } else if (this.check(TT.IDENT) || this.check(TT.LPAREN)) {
211
+ const savedPos = this.pos;
212
+ const expr = this.parseExpression();
213
+ if (expr && (expr.kind !== "literal" || (expr.kind === "literal" && expr.value?.kind === "str" && expr.value.value.startsWith("__VAR__")))) {
214
+ val = { kind: "str", value: `__EXPR__${JSON.stringify(expr)}` };
215
+ } else {
216
+ this.pos = savedPos;
217
+ val = this.parseLiteral();
218
+ }
219
+ } else if (this.check(TT.NUMBER)) {
220
+ val = this.parseLiteral();
221
+ } else {
222
+ val = this.parseLiteral();
223
+ }
224
+ }
225
+
226
+ return { kind: "var", name: nameTok.value, varType: typeStr as VarType, value: val, loc };
227
+ }
228
+
229
+ private parseArrayLiteral(): Literal {
230
+ this.consume(TT.LBRACKET);
231
+ const items: any[] = [];
232
+ while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
233
+ if (this.check(TT.LBRACE)) {
234
+ items.push(this.parseObjectLiteral());
235
+ } else if (this.check(TT.STRING)) {
236
+ items.push(this.consume(TT.STRING).value);
237
+ } else if (this.check(TT.NUMBER)) {
238
+ items.push(parseFloat(this.consume(TT.NUMBER).value));
239
+ } else if (this.check(TT.BOOL_TRUE)) {
240
+ this.consume(TT.BOOL_TRUE);
241
+ items.push(true);
242
+ } else if (this.check(TT.BOOL_FALSE)) {
243
+ this.consume(TT.BOOL_FALSE);
244
+ items.push(false);
245
+ } else if (this.check(TT.NULL_LIT)) {
246
+ this.consume(TT.NULL_LIT);
247
+ items.push(null);
248
+ }
249
+ if (this.check(TT.COMMA)) this.consume(TT.COMMA); else break;
250
+ }
251
+ this.consume(TT.RBRACKET);
252
+ return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
253
+ }
254
+
255
+ private parseObjectLiteral(): Record<string, any> {
256
+ this.consume(TT.LBRACE);
257
+ const obj: Record<string, any> = {};
258
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
259
+ const key = this.consume(TT.IDENT).value;
260
+ this.consume(TT.COLON);
261
+ if (this.check(TT.STRING)) {
262
+ obj[key] = this.consume(TT.STRING).value;
263
+ } else if (this.check(TT.NUMBER)) {
264
+ obj[key] = parseFloat(this.consume(TT.NUMBER).value);
265
+ } else if (this.check(TT.BOOL_TRUE)) {
266
+ this.consume(TT.BOOL_TRUE);
267
+ obj[key] = true;
268
+ } else if (this.check(TT.BOOL_FALSE)) {
269
+ this.consume(TT.BOOL_FALSE);
270
+ obj[key] = false;
271
+ } else if (this.check(TT.NULL_LIT)) {
272
+ this.consume(TT.NULL_LIT);
273
+ obj[key] = null;
274
+ } else if (this.check(TT.IDENT)) {
275
+ obj[key] = `__VAR__${this.consume(TT.IDENT).value}`;
276
+ } else {
277
+ throw new SinthError(`Expected literal value for key '${key}'`, this.peek().loc);
278
+ }
279
+ if (this.check(TT.COMMA)) this.consume(TT.COMMA);
280
+ }
281
+ this.consume(TT.RBRACE);
282
+ return obj;
283
+ }
284
+
285
+ private _visited: Set<number> = new Set();
286
+ parseExpression(skipBinary: boolean = false): Expression | null {
287
+ if (this._visited.has(this.pos)) throw new SinthError("Circular expression reference", this.peek().loc);
288
+ this._visited.add(this.pos);
289
+ const tok = this.peek();
290
+
291
+
292
+ // unary 'not'
293
+ if ((tok.type === TT.IDENT && tok.value === "not") || tok.type === TT.OP_NOT) {
294
+ if (tok.type === TT.IDENT) this.consume(TT.IDENT); else this.consume(TT.OP_NOT);
295
+ const operand = this.parseExpression();
296
+ if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
297
+ const unaryExpr: Expression = { kind: "unary", op: "not", operand };
298
+ return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(unaryExpr)));
299
+ }
300
+
301
+ if (this.check(TT.LPAREN)) {
302
+ this.consume(TT.LPAREN);
303
+ const inner = this.parseExpression();
304
+ if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
305
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
306
+ this.consume(TT.RPAREN);
307
+ const result = this.parseCallExpr(this.parsePostfix(inner));
308
+ return skipBinary ? result : this.parseBinaryRHS(result);
309
+ }
310
+
311
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) ||
312
+ this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT) || this.check(TT.LBRACE) || this.check(TT.LBRACKET)) {
313
+ const lit = this.parseLiteral();
314
+ const base: Expression = { kind: "literal", value: lit };
315
+ return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(base)));
316
+ }
317
+
318
+ // remove as function
319
+ if ((tok.type as any) === TT.KW_REMOVE) {
320
+ const name = this.consume(TT.KW_REMOVE).value;
321
+ return this.parseBinaryRHS(this.parseCallExpr({ kind: "variable", name }));
322
+ }
323
+
324
+ // var or assignment
325
+ if (tok.type === TT.IDENT) {
326
+ let memo = false;
327
+ let rawName = this.consume(TT.IDENT).value;
328
+ if (rawName.startsWith("$")) {
329
+ memo = true;
330
+ rawName = rawName.substring(1);
331
+ }
332
+ const name = rawName;
333
+ let varExpr: Expression;
334
+
335
+ // dot notation -> e.g. user.age
336
+ if (this.check(TT.DOT)) {
337
+ this.consume(TT.DOT);
338
+ const propName = this.consume(TT.IDENT).value;
339
+ const fullName = `${name}.${propName}`;
340
+ varExpr = { kind: "variable", name: fullName };
341
+ } else {
342
+ varExpr = { kind: "variable", name };
343
+ }
344
+
345
+ // apply bracket postfixes (e.g. data[key], data["x"])
346
+ const indexedExpr = this.parsePostfix(varExpr);
347
+
348
+ // if indexing was applied, we don't allow assignment, just binary RHS (after possible call)
349
+ if (indexedExpr !== varExpr) {
350
+ return this.parseBinaryRHS(this.parseCallExpr(indexedExpr));
351
+ }
352
+
353
+ // no indexing – check for assignment operators
354
+ const nextType = this.tokens[this.pos]?.type;
355
+ if (nextType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
356
+ this.consume(TT.OP_PLUS); this.consume(TT.EQUALS);
357
+ const rhs = this.parseExpression();
358
+ if (!rhs) throw new SinthError("Expected expression after +=", this.peek().loc);
359
+ return { kind: "assign", target: varExpr.name!, op: "+=", right: rhs };
360
+ }
361
+ if (nextType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
362
+ this.consume(TT.OP_MINUS); this.consume(TT.EQUALS);
363
+ const rhs = this.parseExpression();
364
+ if (!rhs) throw new SinthError("Expected expression after -=", this.peek().loc);
365
+ return { kind: "assign", target: varExpr.name!, op: "-=", right: rhs };
366
+ }
367
+ if (nextType === TT.EQUALS) {
368
+ this.consume(TT.EQUALS);
369
+ const rhs = this.parseExpression();
370
+ if (!rhs) throw new SinthError("Expected expression after =", this.peek().loc);
371
+ return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
372
+ }
373
+
374
+ return this.parseBinaryRHS(this.parseCallExpr(varExpr));
375
+ }
376
+
377
+ return null;
378
+ }
379
+
380
+
381
+
382
+ private parsePrimary(): Expression {
383
+ const tok = this.peek();
384
+ if (tok.type === TT.NUMBER || tok.type === TT.STRING || tok.type === TT.BOOL_TRUE || tok.type === TT.BOOL_FALSE || tok.type === TT.NULL_LIT) {
385
+ const lit = this.parseLiteral();
386
+ return { kind: "literal", value: lit };
387
+ }
388
+ if (tok.type === TT.IDENT) {
389
+ let memo = false;
390
+ let rawName = this.consume(TT.IDENT).value;
391
+ if (rawName.startsWith("$")) {
392
+ memo = true;
393
+ rawName = rawName.substring(1);
394
+ }
395
+ const name = rawName;
396
+ let expr: Expression;
397
+ if (this.check(TT.DOT)) {
398
+ this.consume(TT.DOT);
399
+ expr = { kind: "variable", name: name + "." + this.consume(TT.IDENT).value };
400
+ } else {
401
+ expr = { kind: "variable", name };
402
+ }
403
+ if (memo) expr.memo = true;
404
+ return expr;
405
+ }
406
+ if (tok.type === TT.LPAREN) {
407
+ this.consume(TT.LPAREN);
408
+ const inner = this.parseExpression();
409
+ this.consume(TT.RPAREN);
410
+ return inner!;
411
+ }
412
+ if (tok.type === TT.LBRACE) {
413
+ const obj = this.parseObjectLiteral();
414
+ return { kind: "literal", value: { kind: "str", value: JSON.stringify(obj) } };
415
+ }
416
+ throw new SinthError(`Expected expression`, this.peek().loc);
417
+ }
418
+
419
+ private parseComparison(left: Expression): Expression {
420
+ const savedPos = this.pos;
421
+ const t = this.peek().type;
422
+ let op: BinaryOp | null = null;
423
+ if (t === TT.OP_EQEQ) op = "==";
424
+ else if (t === TT.OP_NEQ) op = "!=";
425
+ else if (t === TT.OP_LT) op = "<";
426
+ else if (t === TT.OP_GT) op = ">";
427
+ else if (t === TT.OP_LTEQ) op = "<=";
428
+ else if (t === TT.OP_GTEQ) op = ">=";
429
+ if (!op) return left;
430
+ this.pos++;
431
+ const rightPrimary = this.parsePrimary();
432
+ const rightWithPostfix = this.parsePostfix(rightPrimary);
433
+ const rightWithCall = this.parseCallExpr(rightWithPostfix);
434
+ const right = this.parseArithmetic(rightWithCall);
435
+ if (!right) {
436
+ this.pos = savedPos;
437
+ return left;
438
+ }
439
+ if (this.pos === savedPos) return { kind: "binary", left, op, right };
440
+ return { kind: "binary", left, op, right };
441
+ }
442
+
443
+ private parseLogical(left: Expression): Expression {
444
+ const savedPos = this.pos;
445
+ const t = this.peek().type;
446
+ let op: BinaryOp | null = null;
447
+ if (t === TT.IDENT && this.peek().value === "and") op = "and";
448
+ else if (t === TT.IDENT && this.peek().value === "or") op = "or";
449
+ if (!op) return left;
450
+ this.pos++;
451
+ const right = this.parseExpression();
452
+ if (!right) {
453
+ this.pos = savedPos;
454
+ return left;
455
+ }
456
+ return this.parseLogical({ kind: "binary", left, op, right });
457
+ }
458
+
459
+ private parseArithmetic(left: Expression): Expression {
460
+ while (true) {
461
+ const t = this.peek().type;
462
+ let op: BinaryOp | null = null;
463
+ if (t === TT.OP_PLUS) op = "+";
464
+ else if (t === TT.OP_MINUS) op = "-";
465
+ else if (t === TT.OP_STAR) op = "*";
466
+ else if (t === TT.OP_SLASH) op = "/";
467
+ else if (t === TT.OP_MOD) op = "%";
468
+ if (!op) break;
469
+ this.pos++;
470
+ const rightPrimary = this.parsePrimary();
471
+ const rightWithPostfix = this.parsePostfix(rightPrimary);
472
+ const rightWithCall = this.parseCallExpr(rightWithPostfix);
473
+ const right = rightWithCall;
474
+ if (!right) throw new SinthError(`Expected expression after '${op}'`, this.peek().loc);
475
+ left = { kind: "binary", left, op, right };
476
+ }
477
+ return left;
478
+ }
479
+
480
+ private parseBinaryRHS(left: Expression): Expression {
481
+ left = this.parseArithmetic(left);
482
+ left = this.parseComparison(left);
483
+ left = this.parseLogical(left);
484
+ return left;
485
+ }
486
+
487
+ private parsePostfix(base: Expression): Expression {
488
+ let expr = base;
489
+ while (this.check(TT.LBRACKET)) {
490
+ this.consume(TT.LBRACKET);
491
+ const key = this.parseExpression();
492
+ if (!key) throw new SinthError("Expected expression inside [...]", this.peek().loc);
493
+ this.consume(TT.RBRACKET);
494
+ expr = { kind: "index", object: expr, key };
495
+ }
496
+ return expr;
497
+ }
498
+
499
+ private parseCallExpr(expr: Expression): Expression {
500
+ while (this.check(TT.LPAREN)) {
501
+ this.consume(TT.LPAREN);
502
+ const args: Expression[] = [];
503
+ if (!this.check(TT.RPAREN)) {
504
+ args.push(this.parseExpression()!);
505
+ while (this.check(TT.COMMA)) {
506
+ this.consume(TT.COMMA);
507
+ args.push(this.parseExpression()!);
508
+ }
509
+ }
510
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')' after arguments", this.peek().loc);
511
+ this.consume(TT.RPAREN);
512
+ expr = { kind: "call", callee: expr, args };
513
+ }
514
+ return expr;
515
+ }
516
+
517
+
518
+ // component definitions
519
+
520
+ private parseFunctionDef(): FunctionDef {
521
+ const loc = this.consume(TT.KW_FUNCTION).loc;
522
+ const name = this.consume(TT.IDENT).value;
523
+ if (name[0] === name[0].toUpperCase() && name[0] !== name[0].toLowerCase()) {
524
+ throw new SinthError(`Function '${name}' must start with lowercase. Use 'component' for uppercase names.`, loc);
525
+ }
526
+ const params = this.parseParamDecls();
527
+ let returnType: VarType | undefined;
528
+ if (this.check(TT.OP_ARROW)) {
529
+ this.consume(TT.OP_ARROW);
530
+ const typeTok = this.consume(TT.IDENT);
531
+ if (!["int","str","bool","str[]","obj","ui"].includes(typeTok.value)) {
532
+ throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj, ui`, typeTok.loc);
533
+ }
534
+ returnType = typeTok.value as VarType;
535
+ }
536
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after function signature", this.peek().loc);
537
+ this.consume(TT.LBRACE);
538
+ const body = this.parseUnifiedBody();
539
+ this.consume(TT.RBRACE);
540
+ return { name, params, returnType, body, loc };
541
+ }
542
+
543
+ private parseCompDef(): CompDef {
544
+ const loc = this.consume(TT.KW_COMPONENT).loc;
545
+ const name = this.consume(TT.IDENT).value;
546
+ const params = this.parseParamDecls();
547
+ const rawTok = this.consume(TT.RAW_BLOCK);
548
+ const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
549
+ return { name, params, body, styles, scripts, loc };
550
+ }
551
+
552
+ private parseCustomEl(): CustomElDecl {
553
+ const loc = this.peek().loc;
554
+ if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
555
+ else if (this.check(TT.KW_CUSTOM)) this.consume(TT.KW_CUSTOM);
556
+ const sinthName = this.consume(TT.IDENT).value;
557
+ let exportTag: string | undefined;
558
+ if (this.check(TT.LPAREN)) {
559
+ this.consume(TT.LPAREN);
560
+ while (!this.check(TT.RPAREN)) {
561
+ const attrName = this.consume(TT.IDENT).value;
562
+ if (attrName === "export") {
563
+ this.consume(TT.COLON);
564
+ if (!this.check(TT.OP_LT)) throw new SinthError("Expected '<tag/>' after 'export:'", this.peek().loc);
565
+ this.consume(TT.OP_LT);
566
+ exportTag = this.consume(TT.IDENT).value;
567
+ if (!this.check(TT.OP_SLASH)) throw new SinthError("Expected '/>' in tag literal", this.peek().loc);
568
+ this.consume(TT.OP_SLASH);
569
+ this.consume(TT.OP_GT);
570
+ }
571
+ if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
572
+ }
573
+ this.consume(TT.RPAREN);
574
+ }
575
+ if (this.check(TT.RAW_BLOCK)) {
576
+ const rawTok = this.consume(TT.RAW_BLOCK);
577
+ const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
578
+ const sub = new Parser(tokens, rawTok.loc.file);
579
+ sub._varDecls = this._varDecls;
580
+ const parsed = sub.parseBodyContents();
581
+ return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body: parsed.body, styles: parsed.styles, scripts: parsed.scripts, varDecls: this._varDecls, loc };
582
+ }
583
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after custom element declaration", this.peek().loc);
584
+ this.consume(TT.LBRACE);
585
+ const body: Child[] = [];
586
+ const styles: StyleBlock[] = [];
587
+ const scripts: ScriptBlock[] = [];
588
+ const varDecls: VarDeclaration[] = [];
589
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
590
+ if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
591
+ else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
592
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
593
+ const vd = this.parseVarDeclaration();
594
+ if (vd) varDecls.push(vd);
595
+ }
596
+ else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
597
+ else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
598
+ else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
599
+ else if (this.check(TT.STRING)) {
600
+ body.push({ kind: "text", value: this.consume(TT.STRING).value, loc: this.peek().loc });
601
+ }
602
+ else throw new SinthError(`Unexpected token in custom element body`, this.peek().loc);
603
+ }
604
+ this.consume(TT.RBRACE);
605
+ return { sinthName, tagName: sinthName.toLowerCase(), exportTag, params: [], body, styles, scripts, varDecls, loc };
606
+ }
607
+
608
+ private parseReturnStmt(): ReturnStmt {
609
+ const loc = this.consume(TT.KW_RETURN).loc;
610
+ let expression: Expression | undefined;
611
+ if (!this.check(TT.RBRACE) && !this.check(TT.EOF) && !this.check(TT.KW_IF) && !this.check(TT.KW_FOR) && !this.check(TT.KW_RETURN)) {
612
+ expression = this.parseExpression() ?? undefined;
613
+ }
614
+ return { kind: "return", expression, loc };
615
+ }
616
+
617
+ private parseParamDecls(): ParamDecl[] {
618
+ const params: ParamDecl[] = [];
619
+ if (!this.check(TT.LPAREN)) return params;
620
+ this.consume(TT.LPAREN);
621
+ while (!this.check(TT.RPAREN)) {
622
+ const ploc = this.peek().loc;
623
+ let pname: string;
624
+ let paramType: VarType | undefined;
625
+ if (this.check(TT.IDENT) && ["int","str","bool","str[]","obj"].includes(this.peek().value) &&
626
+ this.tokens[this.pos + 1]?.type === TT.IDENT) {
627
+ paramType = this.consume(TT.IDENT).value as VarType;
628
+ pname = this.consume(TT.IDENT).value;
629
+ } else {
630
+ const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
631
+ pname = nameTok.value;
632
+ }
633
+ let defaultVal: Literal | undefined;
634
+ if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
635
+ params.push({ name: pname, paramType, defaultVal, loc: ploc });
636
+ if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
637
+ }
638
+ this.consume(TT.RPAREN);
639
+ return params;
640
+ }
641
+
642
+ private parseCompBody(
643
+ raw: string,
644
+ loc: Loc,
645
+ ): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
646
+ const tokens = new Lexer(raw, loc.file).tokenize();
647
+ const sub = new Parser(tokens, loc.file);
648
+ sub._varDecls = this._varDecls;
649
+ return sub.parseBodyContents();
650
+ }
651
+
652
+ private parseBodyContents(): { body: Child[]; styles: StyleBlock[]; scripts: ScriptBlock[] } {
653
+ const body: Child[] = [], styles: StyleBlock[] = [], scripts: ScriptBlock[] = [];
654
+ while (!this.check(TT.EOF)) {
655
+ if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
656
+ else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
657
+ else if (this.check(TT.STRING)) {
658
+ const loc = this.peek().loc;
659
+ body.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
660
+ }
661
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
662
+ const vd = this.parseVarDeclaration();
663
+ if (vd) this._varDecls.push(vd);
664
+ continue;
665
+ }
666
+ else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
667
+ else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
668
+ else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
669
+ else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
670
+ else throw new SinthError(
671
+ `Unexpected token '${this.peek().value}' in component body`,
672
+ this.peek().loc,
673
+ );
674
+ }
675
+ return { body, styles, scripts };
676
+ }
677
+
678
+ // if / else blocks
679
+
680
+ private parseIfBlock(): IfBlock {
681
+ const loc = this.consume(TT.KW_IF).loc;
682
+ const condition = this.parseExpression();
683
+ if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
684
+
685
+ let persist = false;
686
+ if (this.check(TT.IDENT) && this.peek().value === "persist") {
687
+ this.consume(TT.IDENT);
688
+ persist = true;
689
+ }
690
+ this.consume(TT.LBRACE);
691
+ const body = this.parseUnifiedBody();
692
+ this.consume(TT.RBRACE);
693
+
694
+ const elseBody = this.parseElseChain();
695
+
696
+ return { kind: "if", condition, body, elseBody, persist, loc };
697
+ }
698
+
699
+ private parseElseChain(): Child[] | undefined {
700
+ if (!this.check(TT.KW_ELSE)) return undefined;
701
+
702
+ const elseTok = this.consume(TT.KW_ELSE);
703
+
704
+ if (this.check(TT.LBRACE)) {
705
+ this.consume(TT.LBRACE);
706
+ const body = this.parseUnifiedBody();
707
+ this.consume(TT.RBRACE);
708
+ return body;
709
+ }
710
+
711
+ if (this.check(TT.KW_IF) || elseTok.value === "elif") {
712
+ const ifBlock = this.parseIfContinue(elseTok);
713
+ return [ifBlock];
714
+ }
715
+
716
+ throw new SinthError("Expected '{', 'if', or 'elif' after 'else'", this.peek().loc);
717
+ }
718
+
719
+ private parseIfContinue(elseTok: Token): IfBlock {
720
+ let condition: Expression;
721
+
722
+ if (elseTok.value === "elif") {
723
+ condition = this.parseExpression()!;
724
+ if (!condition) throw new SinthError("Expected condition after 'elif'", this.peek().loc);
725
+ } else {
726
+ this.consume(TT.KW_IF);
727
+ condition = this.parseExpression()!;
728
+ if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
729
+ }
730
+
731
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after condition", this.peek().loc);
732
+ this.consume(TT.LBRACE);
733
+ const body = this.parseUnifiedBody();
734
+ this.consume(TT.RBRACE);
735
+
736
+ const elseBody = this.parseElseChain();
737
+
738
+ return { kind: "if", condition, body, elseBody, loc: elseTok.loc };
739
+ }
740
+
741
+ private parseRawIfStatement(): string {
742
+ this.consume(TT.KW_IF);
743
+ const cond = this.parseExpression();
744
+ if (!cond) throw new SinthError("Expected condition after 'if'", this.peek().loc);
745
+ const condJS = compileExprToJS(cond);
746
+ this.consume(TT.LBRACE);
747
+ let depth = 1;
748
+ const bodyTokens: Token[] = [];
749
+ while (depth > 0 && !this.check(TT.EOF)) {
750
+ const t = this.peek();
751
+ if (t.type === TT.LBRACE) depth++;
752
+ else if (t.type === TT.RBRACE) {
753
+ depth--;
754
+ if (depth === 0) break;
755
+ }
756
+ bodyTokens.push(this.consume(t.type));
757
+ }
758
+ this.consume(TT.RBRACE);
759
+ const rawBody = bodyTokens.map(t => {
760
+ if (t.type === TT.STRING) return '"' + t.value + '"';
761
+ return t.value;
762
+ }).join(' ');
763
+ let result = `if (${condJS}) { ${rawBody} }`;
764
+ if (this.check(TT.KW_ELSE)) {
765
+ this.consume(TT.KW_ELSE);
766
+ if (this.check(TT.KW_IF)) {
767
+ const elseIfJS = this.parseRawIfStatement();
768
+ result += ` else ${elseIfJS}`;
769
+ } else {
770
+ this.consume(TT.LBRACE);
771
+ depth = 1;
772
+ const elseTokens: Token[] = [];
773
+ while (depth > 0 && !this.check(TT.EOF)) {
774
+ const t = this.peek();
775
+ if (t.type === TT.LBRACE) depth++;
776
+ else if (t.type === TT.RBRACE) {
777
+ depth--;
778
+ if (depth === 0) break;
779
+ }
780
+ elseTokens.push(this.consume(t.type));
781
+ }
782
+ this.consume(TT.RBRACE);
783
+ const elseBody = elseTokens.map(t => {
784
+ if (t.type === TT.STRING) return '"' + t.value + '"';
785
+ return t.value;
786
+ }).join(' ');
787
+ result += ` else { ${elseBody} }`;
788
+ }
789
+ }
790
+ return result;
791
+ }
792
+
793
+ private parseUnifiedBody(): Child[] {
794
+ const children: Child[] = [];
795
+
796
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
797
+ if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
798
+ if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
799
+ if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
800
+ if (this.check(TT.LPAREN)) {
801
+ const loc = this.peek().loc;
802
+ const expr = this.parseExpression();
803
+ if (expr) {
804
+ children.push({ kind: "expr", expression: expr, loc });
805
+ }
806
+ continue;
807
+ }
808
+ if (this.check(TT.IDENT)) {
809
+ const savedPos = this.pos;
810
+ const name = this.peek().value;
811
+ const nextType = this.tokens[this.pos + 1]?.type;
812
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
813
+ this.consume(TT.IDENT);
814
+ let op: AssignOp = "=";
815
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
816
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
817
+ this.consume(TT.EQUALS);
818
+ const rhs = this.parseExpression();
819
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
820
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: name, op, right: rhs }, loc: this.peek().loc });
821
+ continue;
822
+ }
823
+ this.pos = savedPos;
824
+ }
825
+ if (this.check(TT.STRING)) {
826
+ const loc = this.peek().loc;
827
+ let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
828
+ while (this.check(TT.OP_PLUS)) {
829
+ this.consume(TT.OP_PLUS);
830
+ let rhs: Expression | null = null;
831
+ if (this.check(TT.STRING)) {
832
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
833
+ } else if (this.check(TT.IDENT)) {
834
+ const rhsName = this.consume(TT.IDENT).value;
835
+ rhs = { kind: "variable", name: rhsName };
836
+ } else {
837
+ rhs = this.parseExpression(true);
838
+ }
839
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
840
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
841
+ }
842
+ children.push({ kind: "expr", expression: leftExpr, loc });
843
+ continue;
844
+ }
845
+
846
+ if (this.check(TT.KW_REMOVE)) {
847
+ const loc = this.consume(TT.KW_REMOVE).loc;
848
+ if (this.check(TT.STRING)) {
849
+ const target = this.consume(TT.STRING).value;
850
+ children.push({ kind: "remove", target, loc });
851
+ } else {
852
+ throw new SinthError(
853
+ `Expected a string after 'remove', got '${this.peek().value}'. Use remove "id".`,
854
+ this.peek().loc,
855
+ );
856
+ }
857
+ continue;
858
+ }
859
+ if (this.check(TT.IDENT) && this.peek().value === "var") {
860
+ const vd = this.parseVarDeclaration();
861
+ if (vd) this._varDecls.push(vd);
862
+ continue;
863
+ }
864
+
865
+ if (this.check(TT.IDENT)) {
866
+ const loc = this.peek().loc;
867
+ const name = this.peek().value;
868
+ const nextType = this.tokens[this.pos + 1]?.type;
869
+ const nextNextType = this.tokens[this.pos + 2]?.type;
870
+
871
+ if (nextType === TT.DOT && (nextNextType === TT.EQUALS ||
872
+ (nextNextType === TT.OP_PLUS && this.tokens[this.pos + 3]?.type === TT.EQUALS) ||
873
+ (nextNextType === TT.OP_MINUS && this.tokens[this.pos + 3]?.type === TT.EQUALS))) {
874
+ let fullName = this.consume(TT.IDENT).value;
875
+ this.consume(TT.DOT);
876
+ fullName = fullName + "." + this.consume(TT.IDENT).value;
877
+
878
+ let op: AssignOp = "=";
879
+ const afterDotType = this.tokens[this.pos]?.type;
880
+ if (afterDotType === TT.OP_PLUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
881
+ this.consume(TT.OP_PLUS); op = "+=";
882
+ } else if (afterDotType === TT.OP_MINUS && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
883
+ this.consume(TT.OP_MINUS); op = "-=";
884
+ }
885
+ this.consume(TT.EQUALS);
886
+ const rhs = this.parseExpression();
887
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
888
+ const assignExpr: Expression = { kind: "assign", target: fullName, op, right: rhs };
889
+ children.push({ kind: "assign_stmt", expression: assignExpr, loc });
890
+ continue;
891
+ }
892
+
893
+ // assignment: ident = expr | ident += expr | ident -= expr
894
+ const isSimpleAssign = nextType === TT.EQUALS;
895
+ const isPlusAssign = nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
896
+ const isMinusAssign = nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS;
897
+
898
+ if (isSimpleAssign || isPlusAssign || isMinusAssign) {
899
+ this.consume(TT.IDENT); // consume name
900
+ let op: AssignOp = "=";
901
+ if (isPlusAssign) { this.consume(TT.OP_PLUS); op = "+="; }
902
+ else if (isMinusAssign) { this.consume(TT.OP_MINUS); op = "-="; }
903
+ this.consume(TT.EQUALS);
904
+ const rhs = this.parseExpression();
905
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
906
+ const assignExpr: Expression = { kind: "assign", target: name, op, right: rhs };
907
+ children.push({ kind: "assign_stmt", expression: assignExpr, loc });
908
+ continue;
909
+ }
910
+
911
+ if (nextType === TT.LPAREN) {
912
+ const identName = this.peek().value;
913
+ const isMemo = identName.startsWith("$");
914
+ const realName = isMemo ? identName.substring(1) : identName;
915
+ if (realName[0] === realName[0].toUpperCase() && realName[0] !== realName[0].toLowerCase()) {
916
+ children.push(this.parseCompUse());
917
+ } else {
918
+ this.consume(TT.IDENT);
919
+ this.consume(TT.LPAREN);
920
+ const args: Expression[] = [];
921
+ if (!this.check(TT.RPAREN)) {
922
+ args.push(this.parseExpression()!);
923
+ while (this.check(TT.COMMA)) {
924
+ this.consume(TT.COMMA);
925
+ args.push(this.parseExpression()!);
926
+ }
927
+ }
928
+ this.consume(TT.RPAREN);
929
+ const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
930
+ children.push({ kind: "expr", expression: callExpr, loc });
931
+ }
932
+ continue;
933
+ }
934
+ if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
935
+ children.push(this.parseCompUse());
936
+ continue;
937
+ }
938
+
939
+ // var expression
940
+ // check dot notation variable reference (user.age without assignment)
941
+ if (nextType === TT.DOT) {
942
+ let fullName = this.consume(TT.IDENT).value;
943
+ this.consume(TT.DOT);
944
+ fullName = fullName + "." + this.consume(TT.IDENT).value;
945
+ if (this.check(TT.LPAREN)) {
946
+ this.consume(TT.LPAREN);
947
+ const args: Expression[] = [];
948
+ if (!this.check(TT.RPAREN)) {
949
+ args.push(this.parseExpression()!);
950
+ while (this.check(TT.COMMA)) {
951
+ this.consume(TT.COMMA);
952
+ args.push(this.parseExpression()!);
953
+ }
954
+ }
955
+ this.consume(TT.RPAREN);
956
+ children.push({ kind: "expr", expression: { kind: "call", callee: { kind: "variable", name: fullName }, args }, loc });
957
+ } else {
958
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
959
+ }
960
+ continue;
961
+ }
962
+
963
+ // bracket notation: ident[...]
964
+ if (nextType === TT.LBRACKET) {
965
+ this.consume(TT.IDENT);
966
+ const varExpr: Expression = { kind: "variable", name };
967
+ const indexedExpr = this.parsePostfix(varExpr);
968
+ children.push({ kind: "expr", expression: indexedExpr, loc });
969
+ continue;
970
+ }
971
+
972
+
973
+ // simple variable reference
974
+ this.consume(TT.IDENT);
975
+ children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
976
+ continue;
977
+ }
978
+
979
+ // reject implicit concatenation only after expression children
980
+ if (children.length > 0) {
981
+ const lastChild = children[children.length - 1];
982
+ if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
983
+ const nextTT = this.tokens[this.pos]?.type;
984
+ if (
985
+ nextTT === TT.STRING || nextTT === TT.NUMBER ||
986
+ nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
987
+ (nextTT === TT.IDENT &&
988
+ this.tokens[this.pos]?.value !== "var" &&
989
+ this.tokens[this.pos]?.value !== "if" &&
990
+ this.tokens[this.pos]?.value !== "for" &&
991
+ this.tokens[this.pos]?.value !== "else" &&
992
+ this.tokens[this.pos]?.value !== "and" &&
993
+ this.tokens[this.pos]?.value !== "or" &&
994
+ this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
995
+ ) {
996
+ throw new SinthError(
997
+ `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
998
+ this.peek().loc,
999
+ );
1000
+ }
1001
+ }
1002
+ }
1003
+ }
1004
+
1005
+ return children;
1006
+ }
1007
+
1008
+
1009
+ private parseForLoop(): ForLoop {
1010
+ const loc = this.consume(TT.KW_FOR).loc;
1011
+ const firstVar = this.consume(TT.IDENT).value;
1012
+ let keyVar: string | undefined;
1013
+ let itemVar: string;
1014
+ let indexVar: string | undefined;
1015
+ if (this.check(TT.COMMA)) {
1016
+ this.consume(TT.COMMA);
1017
+ const secondVar = this.consume(TT.IDENT).value;
1018
+ if (this.check(TT.COMMA)) {
1019
+ this.consume(TT.COMMA);
1020
+ keyVar = firstVar;
1021
+ itemVar = secondVar;
1022
+ indexVar = this.consume(TT.IDENT).value;
1023
+ } else {
1024
+ itemVar = firstVar;
1025
+ indexVar = secondVar;
1026
+ }
1027
+ } else {
1028
+ itemVar = firstVar;
1029
+ }
1030
+ if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
1031
+ this.consume(TT.KW_IN);
1032
+ let arrayVar = this.consume(TT.IDENT).value;
1033
+ while (this.check(TT.DOT)) {
1034
+ this.consume(TT.DOT);
1035
+ const propName = this.consume(TT.IDENT).value;
1036
+ if (this.check(TT.LPAREN)) {
1037
+ this.consume(TT.LPAREN);
1038
+ const args: string[] = [];
1039
+ if (!this.check(TT.RPAREN)) {
1040
+ if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1041
+ else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1042
+ while (this.check(TT.COMMA)) {
1043
+ this.consume(TT.COMMA);
1044
+ if (this.check(TT.STRING)) args.push(this.consume(TT.STRING).value);
1045
+ else if (this.check(TT.NUMBER)) args.push(this.consume(TT.NUMBER).value);
1046
+ }
1047
+ }
1048
+ this.consume(TT.RPAREN);
1049
+ arrayVar = arrayVar + "." + propName + "(" + args.map(a => JSON.stringify(a)).join(",") + ")";
1050
+ } else {
1051
+ arrayVar = arrayVar + "." + propName;
1052
+ }
1053
+ }
1054
+
1055
+ if (keyVar === undefined && indexVar !== undefined) {
1056
+ const srcDecl = this._varDecls.find(d => d.name === arrayVar);
1057
+ if (srcDecl && srcDecl.varType === "obj") {
1058
+ const val = srcDecl.value;
1059
+ const isArray = val && val.kind === "str" && val.value.startsWith("__ARR__");
1060
+ if (!isArray) {
1061
+ keyVar = itemVar;
1062
+ itemVar = indexVar;
1063
+ indexVar = undefined;
1064
+ }
1065
+ }
1066
+ }
1067
+
1068
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after for..in expression", this.peek().loc);
1069
+ this.consume(TT.LBRACE);
1070
+ this.loopVar = itemVar;
1071
+ const body = this.parseChildList();
1072
+ this.loopVar = null;
1073
+ this.consume(TT.RBRACE);
1074
+
1075
+ return { kind: "for", keyVar, itemVar, indexVar, arrayVar, body, loc };
1076
+ }
1077
+
1078
+
1079
+
1080
+ private parseCompUse(): CompUse {
1081
+ const loc = this.peek().loc;
1082
+ const name = this.consume(TT.IDENT).value;
1083
+ const attrs: Attr[] = [];
1084
+
1085
+ if (this.check(TT.LPAREN)) {
1086
+ this.consume(TT.LPAREN);
1087
+ while (!this.check(TT.RPAREN)) {
1088
+ const aloc = this.peek().loc;
1089
+ const aname = this.consume(TT.IDENT).value;
1090
+ let value: Literal | null = null;
1091
+ if (this.check(TT.COLON)) {
1092
+ this.consume(TT.COLON);
1093
+ if (this.isEventAttr(aname)) {
1094
+ if (this.check(TT.STRING)) {
1095
+ value = this.parseLiteral();
1096
+ } else {
1097
+ const savedPos = this.pos;
1098
+ const expr = this.parseExpression();
1099
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN) || this.check(TT.OP_SEMI) || this.check(TT.KW_IF))) {
1100
+ const actions: (Expression | { kind: "if"; js: string })[] = [{ kind: "expr", expr } as any];
1101
+ while (this.check(TT.OP_SEMI)) {
1102
+ this.consume(TT.OP_SEMI);
1103
+ if (this.check(TT.KW_IF)) {
1104
+ const jsIf = this.parseRawIfStatement();
1105
+ actions.push({ kind: "if", js: jsIf });
1106
+ } else {
1107
+ const next = this.parseExpression();
1108
+ if (next) actions.push({ kind: "expr", expr: next } as any);
1109
+ else break;
1110
+ }
1111
+ }
1112
+ const hasIf = actions.some(a => a.kind === "if");
1113
+ if (actions.length === 1 && !hasIf) {
1114
+ const single = (actions[0] as any).expr as Expression;
1115
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(single) };
1116
+ } else {
1117
+ const partsJS: string[] = [];
1118
+ for (const a of actions) {
1119
+ if (a.kind === "if") {
1120
+ partsJS.push((a as any).js as string);
1121
+ } else {
1122
+ partsJS.push(compileExprToJS((a as any).expr as Expression) + ";");
1123
+ }
1124
+ }
1125
+ value = { kind: "str", value: "__ACTION_JS__" + partsJS.join(" ") };
1126
+ }
1127
+ } else {
1128
+ this.pos = savedPos;
1129
+ value = this.parseLiteral();
1130
+ }
1131
+ }
1132
+ } else {
1133
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) ||
1134
+ this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) ||
1135
+ this.check(TT.NULL_LIT) || this.check(TT.LBRACKET) || this.check(TT.LBRACE)) {
1136
+ value = this.parseLiteral();
1137
+ } else if (this.check(TT.IDENT) || this.check(TT.LPAREN) || this.check(TT.NUMBER)) {
1138
+ const savedPos = this.pos;
1139
+ const expr = this.parseExpression();
1140
+ if (expr && (this.check(TT.COMMA) || this.check(TT.RPAREN))) {
1141
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
1142
+ } else {
1143
+ this.pos = savedPos;
1144
+ if (this.check(TT.IDENT)) {
1145
+ value = { kind: "str", value: this.consume(TT.IDENT).value };
1146
+ } else {
1147
+ value = this.parseLiteral();
1148
+ }
1149
+ }
1150
+ } else {
1151
+ value = this.parseLiteral();
1152
+ }
1153
+ }
1154
+ }
1155
+ attrs.push({ name: aname, value, loc: aloc });
1156
+ if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
1157
+ }
1158
+ this.consume(TT.RPAREN);
1159
+ }
1160
+
1161
+ const children: Child[] = [];
1162
+ if (this.check(TT.RAW_BLOCK)) {
1163
+ const rawTok = this.consume(TT.RAW_BLOCK);
1164
+ const tokens = new Lexer(rawTok.value, rawTok.loc.file).tokenize();
1165
+ const sub = new Parser(tokens, rawTok.loc.file);
1166
+ sub._varDecls = this._varDecls;
1167
+ children.push(...sub.parseChildList());
1168
+ } else if (this.check(TT.LBRACE)) {
1169
+ this.consume(TT.LBRACE);
1170
+ children.push(...this.parseChildList());
1171
+ this.consume(TT.RBRACE);
1172
+ }
1173
+
1174
+ return { kind: "use", name, attrs, children, loc };
1175
+ }
1176
+
1177
+ private isEventAttr(name: string): boolean {
1178
+ return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
1179
+ }
1180
+
1181
+ private parseChildList(): Child[] {
1182
+ const children: Child[] = [];
1183
+ let _iter = 0;
1184
+ while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
1185
+ if (++_iter > 1000) throw new SinthError("Infinite loop in children", this.peek().loc);
1186
+
1187
+ if (this.check(TT.LPAREN)) {
1188
+ const loc = this.peek().loc;
1189
+ this.consume(TT.LPAREN);
1190
+ let expr = this.parseExpression(true);
1191
+ if (!expr) throw new SinthError("Expected expression after '('", this.peek().loc);
1192
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')'", this.peek().loc);
1193
+ this.consume(TT.RPAREN);
1194
+ while (this.check(TT.OP_PLUS)) {
1195
+ this.consume(TT.OP_PLUS);
1196
+ let rhs: Expression | null = null;
1197
+ if (this.check(TT.STRING)) {
1198
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1199
+ } else if (this.check(TT.IDENT)) {
1200
+ const rhsName = this.consume(TT.IDENT).value;
1201
+ rhs = { kind: "variable", name: rhsName };
1202
+ } else {
1203
+ rhs = this.parseExpression(true);
1204
+ }
1205
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1206
+ expr = { kind: "binary", left: expr, op: "+", right: rhs };
1207
+ }
1208
+ children.push({ kind: "expr", expression: expr, loc });
1209
+ continue;
1210
+ }
1211
+ if (this.check(TT.STRING)) {
1212
+ const loc = this.peek().loc;
1213
+ let leftExpr: Expression = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1214
+ while (this.check(TT.OP_PLUS)) {
1215
+ this.consume(TT.OP_PLUS);
1216
+ let rhs: Expression | null = null;
1217
+ if (this.check(TT.STRING)) {
1218
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1219
+ } else if (this.check(TT.IDENT)) {
1220
+ const rhsName = this.consume(TT.IDENT).value;
1221
+ if (this.check(TT.LPAREN)) {
1222
+ this.consume(TT.LPAREN);
1223
+ const args: Expression[] = [];
1224
+ if (!this.check(TT.RPAREN)) {
1225
+ args.push(this.parseExpression()!);
1226
+ while (this.check(TT.COMMA)) {
1227
+ this.consume(TT.COMMA);
1228
+ args.push(this.parseExpression()!);
1229
+ }
1230
+ }
1231
+ this.consume(TT.RPAREN);
1232
+ rhs = { kind: "call", callee: { kind: "variable", name: rhsName }, args };
1233
+ } else if (this.check(TT.DOT)) {
1234
+ this.consume(TT.DOT);
1235
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1236
+ } else {
1237
+ rhs = { kind: "variable", name: rhsName };
1238
+ }
1239
+ } else {
1240
+ rhs = this.parseExpression(true);
1241
+ }
1242
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1243
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1244
+ }
1245
+ children.push({ kind: "expr", expression: leftExpr, loc });
1246
+ }
1247
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
1248
+ const vd = this.parseVarDeclaration();
1249
+ if (vd) this._varDecls.push(vd);
1250
+ continue;
1251
+ }
1252
+ else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
1253
+ else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
1254
+ else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
1255
+ else if (this.check(TT.IDENT)) {
1256
+ const loc = this.peek().loc;
1257
+ const rawName = this.peek().value;
1258
+ const nextType = this.tokens[this.pos + 1]?.type;
1259
+
1260
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
1261
+ this.consume(TT.IDENT);
1262
+ let op: AssignOp = "=";
1263
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
1264
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
1265
+ this.consume(TT.EQUALS);
1266
+ const rhs = this.parseExpression();
1267
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
1268
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: rawName, op, right: rhs }, loc });
1269
+ continue;
1270
+ }
1271
+
1272
+ if (nextType === TT.DOT) {
1273
+ let rawFirst = this.consume(TT.IDENT).value;
1274
+ const isMemo = rawFirst.startsWith("$");
1275
+ const firstPart = isMemo ? rawFirst.slice(1) : rawFirst;
1276
+ this.consume(TT.DOT);
1277
+ const fullName = firstPart + "." + this.consume(TT.IDENT).value;
1278
+ const afterDotType = this.tokens[this.pos]?.type;
1279
+
1280
+ if (afterDotType === TT.OP_PLUS) {
1281
+ let leftExpr: Expression = { kind: "variable", name: fullName };
1282
+ while (this.check(TT.OP_PLUS)) {
1283
+ this.consume(TT.OP_PLUS);
1284
+ let rhs: Expression | null = null;
1285
+ if (this.check(TT.STRING)) {
1286
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1287
+ } else if (this.check(TT.IDENT)) {
1288
+ const rhsName = this.consume(TT.IDENT).value;
1289
+ if (this.check(TT.DOT)) {
1290
+ this.consume(TT.DOT);
1291
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1292
+ } else {
1293
+ rhs = { kind: "variable", name: rhsName };
1294
+ }
1295
+ } else {
1296
+ rhs = this.parseExpression(true);
1297
+ }
1298
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1299
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1300
+ }
1301
+ children.push({ kind: "expr", expression: leftExpr, loc });
1302
+ } else if (this.loopVar && fullName.split('.')[0] === this.loopVar) {
1303
+ children.push({ kind: "expr", expression: { kind: "variable", name: fullName }, loc });
1304
+ } else if (afterDotType === TT.LPAREN) {
1305
+ this.consume(TT.LPAREN);
1306
+ const args: Expression[] = [];
1307
+ if (!this.check(TT.RPAREN)) {
1308
+ args.push(this.parseExpression()!);
1309
+ while (this.check(TT.COMMA)) {
1310
+ this.consume(TT.COMMA);
1311
+ args.push(this.parseExpression()!);
1312
+ }
1313
+ }
1314
+ this.consume(TT.RPAREN);
1315
+ const callExpr: Expression = { kind: "call", callee: { kind: "variable", name: fullName }, args, memo: isMemo || undefined };
1316
+ children.push({ kind: "expr", expression: callExpr, loc });
1317
+ } else if (afterDotType === TT.LBRACE || afterDotType === TT.RAW_BLOCK) {
1318
+ throw new SinthError(`Unexpected dot notation before component usage`, loc);
1319
+ } else {
1320
+ const varExpr: Expression = { kind: "variable", name: fullName };
1321
+ if (isMemo) varExpr.memo = true;
1322
+ children.push({ kind: "expr", expression: varExpr, loc });
1323
+ }
1324
+ continue;
1325
+ } else if (nextType === TT.OP_PLUS) {
1326
+ const name = this.consume(TT.IDENT).value;
1327
+ let leftExpr: Expression = { kind: "variable", name };
1328
+ while (this.check(TT.OP_PLUS)) {
1329
+ this.consume(TT.OP_PLUS);
1330
+ let rhs: Expression | null = null;
1331
+ if (this.check(TT.STRING)) {
1332
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1333
+ } else if (this.check(TT.IDENT)) {
1334
+ const rhsName = this.consume(TT.IDENT).value;
1335
+ if (this.check(TT.DOT)) {
1336
+ this.consume(TT.DOT);
1337
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1338
+ } else {
1339
+ rhs = { kind: "variable", name: rhsName };
1340
+ }
1341
+ } else {
1342
+ rhs = this.parseExpression(true);
1343
+ }
1344
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1345
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1346
+ }
1347
+ children.push({ kind: "expr", expression: leftExpr, loc });
1348
+ } else if (this.loopVar && rawName === this.loopVar) {
1349
+ this.consume(TT.IDENT);
1350
+ children.push({ kind: "expr", expression: { kind: "variable", name: rawName }, loc });
1351
+ } else if (nextType === TT.LBRACKET) {
1352
+ const name = this.consume(TT.IDENT).value;
1353
+ const varExpr: Expression = { kind: "variable", name };
1354
+ let indexedExpr = this.parsePostfix(varExpr);
1355
+ if (this.check(TT.OP_PLUS)) {
1356
+ let leftExpr: Expression = indexedExpr;
1357
+ while (this.check(TT.OP_PLUS)) {
1358
+ this.consume(TT.OP_PLUS);
1359
+ let rhs: Expression | null = null;
1360
+ if (this.check(TT.STRING)) {
1361
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1362
+ } else if (this.check(TT.IDENT)) {
1363
+ const rhsName = this.consume(TT.IDENT).value;
1364
+ if (this.check(TT.DOT)) {
1365
+ this.consume(TT.DOT);
1366
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
1367
+ } else {
1368
+ rhs = { kind: "variable", name: rhsName };
1369
+ }
1370
+ } else {
1371
+ rhs = this.parseExpression(true);
1372
+ }
1373
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1374
+ leftExpr = { kind: "binary", left: leftExpr, op: "+", right: rhs };
1375
+ }
1376
+ children.push({ kind: "expr", expression: leftExpr, loc });
1377
+ } else {
1378
+ children.push({ kind: "expr", expression: indexedExpr, loc });
1379
+ }
1380
+ } else if (nextType === TT.LPAREN) {
1381
+ const identName = this.peek().value;
1382
+ const isMemo = identName.startsWith("$");
1383
+ const realName = isMemo ? identName.substring(1) : identName;
1384
+ if (realName[0] === realName[0].toUpperCase() && realName[0] !== realName[0].toLowerCase()) {
1385
+ children.push(this.parseCompUse());
1386
+ continue;
1387
+ } else {
1388
+ this.consume(TT.IDENT);
1389
+ this.consume(TT.LPAREN);
1390
+ const args: Expression[] = [];
1391
+ if (!this.check(TT.RPAREN)) {
1392
+ args.push(this.parseExpression()!);
1393
+ while (this.check(TT.COMMA)) {
1394
+ this.consume(TT.COMMA);
1395
+ args.push(this.parseExpression()!);
1396
+ }
1397
+ }
1398
+ this.consume(TT.RPAREN);
1399
+ let finalExpr: Expression = { kind: "call", callee: { kind: "variable", name: realName }, args, memo: isMemo || undefined };
1400
+ while (this.check(TT.OP_PLUS)) {
1401
+ this.consume(TT.OP_PLUS);
1402
+ let rhs: Expression | null = null;
1403
+ if (this.check(TT.STRING)) {
1404
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
1405
+ } else if (this.check(TT.IDENT)) {
1406
+ rhs = this.parseExpression();
1407
+ } else {
1408
+ rhs = this.parseExpression(true);
1409
+ }
1410
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
1411
+ finalExpr = { kind: "binary", left: finalExpr, op: "+", right: rhs };
1412
+ }
1413
+ children.push({ kind: "expr", expression: finalExpr, loc });
1414
+ continue;
1415
+ }
1416
+ } else if (nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1417
+ children.push(this.parseCompUse());
1418
+ continue;
1419
+ } else {
1420
+ const name = this.consume(TT.IDENT).value;
1421
+ children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1422
+ }
1423
+ }
1424
+ // reject implicit concatenation only after expression children
1425
+ if (children.length > 0) {
1426
+ const lastChild = children[children.length - 1];
1427
+ if (lastChild.kind === "text" || lastChild.kind === "expr" || lastChild.kind === "assign_stmt") {
1428
+ const nextTT = this.tokens[this.pos]?.type;
1429
+ if (
1430
+ nextTT === TT.STRING || nextTT === TT.NUMBER ||
1431
+ nextTT === TT.BOOL_TRUE || nextTT === TT.BOOL_FALSE || nextTT === TT.NULL_LIT ||
1432
+ (nextTT === TT.IDENT &&
1433
+ this.tokens[this.pos]?.value !== "var" &&
1434
+ this.tokens[this.pos]?.value !== "if" &&
1435
+ this.tokens[this.pos]?.value !== "for" &&
1436
+ this.tokens[this.pos]?.value !== "else" &&
1437
+ this.tokens[this.pos]?.value !== "and" &&
1438
+ this.tokens[this.pos]?.value !== "or" &&
1439
+ this.tokens[this.pos]?.value[0] !== this.tokens[this.pos]?.value[0]?.toUpperCase())
1440
+ ) {
1441
+ throw new SinthError(
1442
+ `Unexpected ${TT[nextTT]}. Use '+' to concatenate values.`,
1443
+ this.peek().loc,
1444
+ );
1445
+ }
1446
+ }
1447
+ }
1448
+ if (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
1449
+ throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
1450
+ }
1451
+ }
1452
+ return children;
1453
+ }
1454
+
1455
+ // style & script blocks
1456
+
1457
+ private parseStyleBlock(): StyleBlock {
1458
+ const loc = this.consume(TT.KW_STYLE).loc;
1459
+ let global = false, lang: "css" | "scss" = "css", target: string | undefined;
1460
+ const extraAttrs: Record<string, string> = {};
1461
+
1462
+ while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1463
+ if (this.check(TT.KW_GLOBAL)) { global = true; this.consume(TT.KW_GLOBAL); }
1464
+ else if (this.check(TT.KW_LANG)) {
1465
+ this.consume(TT.KW_LANG); this.consume(TT.EQUALS);
1466
+ const lv = this.consume(TT.STRING).value;
1467
+ if (lv !== "css" && lv !== "scss") throw new SinthError(`Unsupported style lang '${lv}'`, loc);
1468
+ lang = lv as "css" | "scss";
1469
+ }
1470
+ else if (this.check(TT.IDENT)) {
1471
+ if (this.tokens[this.pos + 1]?.type !== TT.EQUALS) {
1472
+ target = this.consume(TT.IDENT).value;
1473
+ } else {
1474
+ const k = this.consume(TT.IDENT).value;
1475
+ this.consume(TT.EQUALS);
1476
+ extraAttrs[k] = this.consume(TT.STRING).value;
1477
+ }
1478
+ }
1479
+ else throw new SinthError(`Unexpected token '${this.peek().value}' in style modifiers`, this.peek().loc);
1480
+ }
1481
+
1482
+ return { global, lang, raw: this.consume(TT.RAW_BLOCK).value, target, extraAttrs, loc };
1483
+ }
1484
+
1485
+ private parseScriptBlock(): ScriptBlock {
1486
+ const loc = this.consume(TT.KW_SCRIPT).loc;
1487
+ const attrs: Record<string, string> = {};
1488
+ while (!this.check(TT.RAW_BLOCK) && !this.check(TT.EOF)) {
1489
+ const key = this.consume(TT.IDENT).value;
1490
+ if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); attrs[key] = this.consume(TT.STRING).value; }
1491
+ else { attrs[key] = "true"; }
1492
+ }
1493
+ return { raw: this.consume(TT.RAW_BLOCK).value, attrs, loc };
1494
+ }
1495
+
1496
+ private parseLiteral(): Literal {
1497
+ const tok = this.peek();
1498
+ if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
1499
+ if (this.check(TT.LBRACE)) {
1500
+ const obj = this.parseObjectLiteral();
1501
+ return { kind: "str", value: JSON.stringify(obj) };
1502
+ }
1503
+ if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
1504
+ if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
1505
+ if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
1506
+ if (this.check(TT.BOOL_FALSE)){ this.consume(TT.BOOL_FALSE);return { kind: "bool", value: false }; }
1507
+ if (this.check(TT.NULL_LIT)) { this.consume(TT.NULL_LIT); return { kind: "null" }; }
1508
+ throw new SinthError(`Expected literal value, got '${tok.value}' (${TT[tok.type]})`, tok.loc);
1509
+ }
1510
+
1511
+ private peek(): Token { return this.tokens[this.pos]; }
1512
+ private check(t: TT): boolean { return this.tokens[this.pos]?.type === t; }
1513
+ private consume(t: TT): Token {
1514
+ const tok = this.tokens[this.pos];
1515
+ if (tok.type !== t) {
1516
+ throw new SinthError(
1517
+ `Expected ${TT[t]}, got '${tok.value}' (${TT[tok.type]})`,
1518
+ tok.loc,
1519
+ );
1520
+ }
1521
+ this.pos++;
1522
+ return tok;
1523
+ }
1524
1524
  }