@yannosay/sinth 0.0.19 → 0.2.0
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.
- package/package.json +1 -1
- package/src/sinth.ts +609 -50
package/package.json
CHANGED
package/src/sinth.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
// Sinth Compiler v0.0
|
|
2
|
+
// Sinth Compiler v0.1.0 — enum fix, raw-block detection, import resolution, CSS conversion, slot escaping, custom-elements, HTML5 map
|
|
3
3
|
|
|
4
4
|
import * as fs from "fs";
|
|
5
5
|
import * as path from "path";
|
|
@@ -11,18 +11,22 @@ import * as http from "http";
|
|
|
11
11
|
|
|
12
12
|
interface Loc { file: string; line: number; col: number }
|
|
13
13
|
|
|
14
|
-
// === v0.0
|
|
14
|
+
// === v0.1.0: Must be plain `enum TT`, NOT `const enum TT` — const enum breaks TT[t] string indexing ===
|
|
15
15
|
enum TT {
|
|
16
|
-
LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
|
|
16
|
+
LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT, LBRACKET, RBRACKET,
|
|
17
17
|
STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_LIT,
|
|
18
18
|
RAW_BLOCK,
|
|
19
19
|
IDENT,
|
|
20
20
|
KW_IMPORT, KW_AS, KW_CSS,
|
|
21
21
|
KW_COMPONENT, KW_STYLE, KW_SCRIPT,
|
|
22
22
|
KW_GLOBAL, KW_PAGE, KW_LANG,
|
|
23
|
-
// === v0.0.15: KW_CUSTOM_EL and KW_CUSTOM ensured present ===
|
|
24
23
|
KW_CUSTOM_EL,
|
|
25
24
|
KW_CUSTOM,
|
|
25
|
+
// v0.2.0: Control flow keywords
|
|
26
|
+
KW_IF, KW_ELSE, KW_FOR, KW_IN,
|
|
27
|
+
// v0.1.0: Logic operators
|
|
28
|
+
OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH,
|
|
29
|
+
OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
|
|
26
30
|
EOF,
|
|
27
31
|
}
|
|
28
32
|
|
|
@@ -37,7 +41,10 @@ type Literal = LitStr | LitNum | LitBool | LitNull;
|
|
|
37
41
|
interface Attr { name: string; value: Literal | null; loc: Loc }
|
|
38
42
|
interface TextNode { kind: "text"; value: string; loc: Loc }
|
|
39
43
|
interface CompUse { kind: "use"; name: string; attrs: Attr[]; children: Child[]; loc: Loc }
|
|
40
|
-
|
|
44
|
+
interface ExprNode { kind: "expr"; expression: Expression; loc: Loc }
|
|
45
|
+
interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
|
|
46
|
+
interface ForLoop { kind: "for"; itemVar: string; arrayVar: string; body: Child[]; loc: Loc }
|
|
47
|
+
type Child = TextNode | CompUse | ExprNode | IfBlock | ForLoop;
|
|
41
48
|
|
|
42
49
|
interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
|
|
43
50
|
interface StyleBlock { global: boolean; lang: "css" | "scss"; raw: string; extraAttrs: Record<string, string>; loc: Loc }
|
|
@@ -54,6 +61,34 @@ type ImportNode =
|
|
|
54
61
|
|
|
55
62
|
interface MetaEntry { key: string; value: Literal; loc: Loc }
|
|
56
63
|
|
|
64
|
+
// === v0.1.0: Logic types ===
|
|
65
|
+
type VarType = "int" | "str" | "bool" | "str[]";
|
|
66
|
+
|
|
67
|
+
interface VarDeclaration {
|
|
68
|
+
kind: "var";
|
|
69
|
+
name: string;
|
|
70
|
+
varType: VarType;
|
|
71
|
+
value: Literal;
|
|
72
|
+
loc: Loc;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
// === v0.1.0: Expression AST ===
|
|
76
|
+
type UnaryOp = "not" | "-";
|
|
77
|
+
type BinaryOp = "+" | "-" | "*" | "/" | "==" | "!=" | "<" | ">" | "<=" | ">=" | "and" | "or";
|
|
78
|
+
type AssignOp = "=" | "+=" | "-=";
|
|
79
|
+
type PostfixOp = "++" | "--";
|
|
80
|
+
|
|
81
|
+
interface Expression {
|
|
82
|
+
kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix";
|
|
83
|
+
value?: Literal;
|
|
84
|
+
name?: string;
|
|
85
|
+
op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
|
|
86
|
+
operand?: Expression;
|
|
87
|
+
left?: Expression;
|
|
88
|
+
right?: Expression;
|
|
89
|
+
target?: string;
|
|
90
|
+
}
|
|
91
|
+
|
|
57
92
|
interface SinthFile {
|
|
58
93
|
filePath: string;
|
|
59
94
|
isPage: boolean;
|
|
@@ -64,6 +99,7 @@ interface SinthFile {
|
|
|
64
99
|
styles: StyleBlock[];
|
|
65
100
|
scripts: ScriptBlock[];
|
|
66
101
|
customEls: CustomElDecl[];
|
|
102
|
+
varDecls: VarDeclaration[];
|
|
67
103
|
}
|
|
68
104
|
|
|
69
105
|
interface CompileCtx {
|
|
@@ -102,7 +138,7 @@ class SinthError extends Error {
|
|
|
102
138
|
return s;
|
|
103
139
|
}
|
|
104
140
|
|
|
105
|
-
// === v0.0
|
|
141
|
+
// === v0.1.0: Attach source line to produce error preview ===
|
|
106
142
|
withSource(lines: string[]): SinthError {
|
|
107
143
|
if (!this.loc || this.sourceLine !== undefined) return this;
|
|
108
144
|
const line = lines[this.loc.line - 1] ?? "";
|
|
@@ -173,9 +209,13 @@ const KEYWORDS: Record<string, TT> = {
|
|
|
173
209
|
"true": TT.BOOL_TRUE,
|
|
174
210
|
"false": TT.BOOL_FALSE,
|
|
175
211
|
"null": TT.NULL_LIT,
|
|
176
|
-
// === v0.0
|
|
212
|
+
// === v0.1.0: custom-element and custom lexed as hyphenated identifier ===
|
|
177
213
|
"custom-element": TT.KW_CUSTOM_EL,
|
|
178
214
|
"custom": TT.KW_CUSTOM,
|
|
215
|
+
"if": TT.KW_IF,
|
|
216
|
+
"else": TT.KW_ELSE,
|
|
217
|
+
"for": TT.KW_FOR,
|
|
218
|
+
"in": TT.KW_IN,
|
|
179
219
|
};
|
|
180
220
|
|
|
181
221
|
export class Lexer {
|
|
@@ -201,7 +241,21 @@ export class Lexer {
|
|
|
201
241
|
if (ch === ",") { tokens.push(this.single(TT.COMMA, loc)); continue; }
|
|
202
242
|
if (ch === ".") { tokens.push(this.single(TT.DOT, loc)); continue; }
|
|
203
243
|
if (ch === ":") { tokens.push(this.single(TT.COLON, loc)); continue; }
|
|
244
|
+
if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
|
|
245
|
+
if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
|
|
246
|
+
if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
|
|
204
247
|
if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
|
|
248
|
+
if (ch === "[") { tokens.push(this.single(TT.LBRACKET, loc)); continue; }
|
|
249
|
+
if (ch === "]") { tokens.push(this.single(TT.RBRACKET, loc)); continue; }
|
|
250
|
+
|
|
251
|
+
// v0.1.0: Logic operators
|
|
252
|
+
if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
|
|
253
|
+
if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) { tokens.push(this.single(TT.OP_MINUS, loc)); continue; }
|
|
254
|
+
if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
|
|
255
|
+
if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
|
|
256
|
+
if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
|
|
257
|
+
if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
|
|
258
|
+
if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
|
|
205
259
|
|
|
206
260
|
if (ch === "{") {
|
|
207
261
|
if (this.rawBlockPending) {
|
|
@@ -221,7 +275,7 @@ export class Lexer {
|
|
|
221
275
|
|
|
222
276
|
if (this.isIdentStart(ch)) {
|
|
223
277
|
const tok = this.readIdent(loc);
|
|
224
|
-
// === v0.0
|
|
278
|
+
// === v0.1.0: Also set rawBlockPending for component, custom-element, custom ===
|
|
225
279
|
if (
|
|
226
280
|
tok.type === TT.KW_STYLE ||
|
|
227
281
|
tok.type === TT.KW_SCRIPT ||
|
|
@@ -386,7 +440,7 @@ export class Lexer {
|
|
|
386
440
|
|
|
387
441
|
private readIdent(loc: Loc): Token {
|
|
388
442
|
let s = "";
|
|
389
|
-
// === v0.0
|
|
443
|
+
// === v0.1.0: isIdentCont includes '-' so "custom-element" is read as one token ===
|
|
390
444
|
while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
|
|
391
445
|
s += this.src[this.pos]; this.adv();
|
|
392
446
|
}
|
|
@@ -407,7 +461,7 @@ export class Lexer {
|
|
|
407
461
|
private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
|
|
408
462
|
private isDigit(c: string) { return c >= "0" && c <= "9"; }
|
|
409
463
|
private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
|
|
410
|
-
// === v0.0
|
|
464
|
+
// === v0.1.0: '-' allowed in identifiers so "custom-element" is a single token ===
|
|
411
465
|
private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
|
|
412
466
|
}
|
|
413
467
|
|
|
@@ -417,6 +471,7 @@ export class Lexer {
|
|
|
417
471
|
|
|
418
472
|
export class Parser {
|
|
419
473
|
private pos = 0;
|
|
474
|
+
private loopVar: string | null = null;
|
|
420
475
|
|
|
421
476
|
constructor(private tokens: Token[], private file: string) {}
|
|
422
477
|
|
|
@@ -430,6 +485,7 @@ export class Parser {
|
|
|
430
485
|
const styles: StyleBlock[] = [];
|
|
431
486
|
const scripts: ScriptBlock[] = [];
|
|
432
487
|
const customEls: CustomElDecl[] = [];
|
|
488
|
+
const varDecls: VarDeclaration[] = [];
|
|
433
489
|
|
|
434
490
|
// 1. Optional page keyword
|
|
435
491
|
if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
|
|
@@ -439,22 +495,56 @@ export class Parser {
|
|
|
439
495
|
|
|
440
496
|
// 3. Metadata — key = value pairs (lexer has already stripped comments/whitespace)
|
|
441
497
|
while (this.isMetaStart()) {
|
|
498
|
+
const keyName = this.tokens[this.pos].value;
|
|
499
|
+
if (varDecls.some(v => v.name === keyName)) {
|
|
500
|
+
break;
|
|
501
|
+
}
|
|
442
502
|
const entry = this.parseMeta();
|
|
443
503
|
meta.push(entry);
|
|
444
504
|
if (entry.key === "title") isPage = true;
|
|
445
505
|
}
|
|
446
506
|
|
|
447
507
|
// 4. Body: component definitions, usages, style, script, custom-element
|
|
508
|
+
// 4a. Variable declarations (v0.1.0 logic)
|
|
509
|
+
while (this.check(TT.IDENT) && this.peek().value === "var") {
|
|
510
|
+
const vd = this.parseVarDeclaration();
|
|
511
|
+
if (vd) varDecls.push(vd);
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
// 4b. Body: component definitions, usages, style, script, custom-element
|
|
448
515
|
while (!this.check(TT.EOF)) {
|
|
449
516
|
if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
|
|
450
517
|
else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
|
|
451
518
|
else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
|
|
452
519
|
else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
|
|
453
|
-
else if (this.check(TT.IDENT))
|
|
520
|
+
else if (this.check(TT.IDENT)) {
|
|
521
|
+
// Check if it's a variable assignment (ident = expression)
|
|
522
|
+
const savedPos = this.pos;
|
|
523
|
+
const identName = this.consume(TT.IDENT).value;
|
|
524
|
+
if (this.check(TT.EQUALS)) {
|
|
525
|
+
// It's an assignment: variableName = value
|
|
526
|
+
this.consume(TT.EQUALS);
|
|
527
|
+
const expr = this.parseExpression();
|
|
528
|
+
if (expr) {
|
|
529
|
+
// Wrap as inline script assignment
|
|
530
|
+
const jsExpr = compileExprToJS(expr);
|
|
531
|
+
const scriptBlock: ScriptBlock = {
|
|
532
|
+
raw: `${identName} = ${jsExpr};\nsinthRender();`,
|
|
533
|
+
attrs: {},
|
|
534
|
+
loc: this.peek().loc,
|
|
535
|
+
};
|
|
536
|
+
scripts.push(scriptBlock);
|
|
537
|
+
continue;
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
// Not an assignment, revert and parse as component usage
|
|
541
|
+
this.pos = savedPos;
|
|
542
|
+
uses.push(this.parseCompUse());
|
|
543
|
+
}
|
|
454
544
|
else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
|
|
455
545
|
}
|
|
456
546
|
|
|
457
|
-
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls };
|
|
547
|
+
return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
|
|
458
548
|
}
|
|
459
549
|
|
|
460
550
|
// ── Imports ──────────────────────────────────────────────
|
|
@@ -490,27 +580,211 @@ export class Parser {
|
|
|
490
580
|
return this.tokens[this.pos + 1]?.type === TT.EQUALS;
|
|
491
581
|
}
|
|
492
582
|
|
|
493
|
-
|
|
583
|
+
private parseMeta(): MetaEntry {
|
|
494
584
|
const loc = this.peek().loc;
|
|
495
585
|
const key = this.consume(TT.IDENT).value;
|
|
496
586
|
this.consume(TT.EQUALS);
|
|
497
587
|
return { key, value: this.parseLiteral(), loc };
|
|
498
588
|
}
|
|
499
589
|
|
|
590
|
+
// === v0.1.0: Parse variable declaration ===
|
|
591
|
+
private parseVarDeclaration(): VarDeclaration | null {
|
|
592
|
+
const loc = this.peek().loc;
|
|
593
|
+
this.consume(TT.IDENT); // 'var'
|
|
594
|
+
|
|
595
|
+
const typeTok = this.consume(TT.IDENT);
|
|
596
|
+
let typeStr = typeTok.value;
|
|
597
|
+
if (this.check(TT.LBRACKET) && this.tokens[this.pos + 1]?.type === TT.RBRACKET) {
|
|
598
|
+
this.consume(TT.LBRACKET);
|
|
599
|
+
this.consume(TT.RBRACKET);
|
|
600
|
+
typeStr = "str[]";
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
|
|
604
|
+
throw new SinthError(`Unknown type '${typeStr}'. Expected int, str, bool, or str[]`, typeTok.loc);
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
const nameTok = this.consume(TT.IDENT);
|
|
608
|
+
let val: Literal | null = null;
|
|
609
|
+
|
|
610
|
+
if (this.check(TT.EQUALS)) {
|
|
611
|
+
this.consume(TT.EQUALS);
|
|
612
|
+
if (this.check(TT.LBRACKET)) {
|
|
613
|
+
val = this.parseArrayLiteral();
|
|
614
|
+
} else if (this.check(TT.IDENT)) {
|
|
615
|
+
const refName = this.consume(TT.IDENT).value;
|
|
616
|
+
val = { kind: "str", value: `__VAR__${refName}` };
|
|
617
|
+
} else {
|
|
618
|
+
val = this.parseLiteral();
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
|
|
622
|
+
return {
|
|
623
|
+
kind: "var",
|
|
624
|
+
name: nameTok.value,
|
|
625
|
+
varType: typeStr as VarType,
|
|
626
|
+
value: val,
|
|
627
|
+
loc,
|
|
628
|
+
};
|
|
629
|
+
}
|
|
630
|
+
|
|
631
|
+
private parseArrayLiteral(): Literal {
|
|
632
|
+
const loc = this.consume(TT.LBRACKET).loc;
|
|
633
|
+
const items: string[] = [];
|
|
634
|
+
|
|
635
|
+
while (!this.check(TT.RBRACKET) && !this.check(TT.EOF)) {
|
|
636
|
+
if (this.check(TT.STRING)) {
|
|
637
|
+
items.push(this.consume(TT.STRING).value);
|
|
638
|
+
} else if (this.check(TT.NUMBER)) {
|
|
639
|
+
items.push(this.consume(TT.NUMBER).value);
|
|
640
|
+
} else if (this.check(TT.BOOL_TRUE)) {
|
|
641
|
+
this.consume(TT.BOOL_TRUE);
|
|
642
|
+
items.push("true");
|
|
643
|
+
} else if (this.check(TT.BOOL_FALSE)) {
|
|
644
|
+
this.consume(TT.BOOL_FALSE);
|
|
645
|
+
items.push("false");
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
if (this.check(TT.COMMA)) {
|
|
649
|
+
this.consume(TT.COMMA);
|
|
650
|
+
} else {
|
|
651
|
+
break;
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
this.consume(TT.RBRACKET);
|
|
656
|
+
return { kind: "str", value: `__ARR__${JSON.stringify(items)}` };
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
|
|
660
|
+
// ── Expression parsing (v0.1.0) ────────────────────────
|
|
661
|
+
private parseExpression(): Expression | null {
|
|
662
|
+
const tok = this.peek();
|
|
663
|
+
|
|
664
|
+
// Unary 'not'
|
|
665
|
+
if (tok.type === TT.IDENT && tok.value === "not") {
|
|
666
|
+
this.consume(TT.IDENT); // consume 'not'
|
|
667
|
+
const operand = this.parseExpression();
|
|
668
|
+
if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
|
|
669
|
+
return { kind: "unary", op: "not", operand };
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
// Literal
|
|
673
|
+
if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
|
|
674
|
+
const lit = this.parseLiteral();
|
|
675
|
+
if (lit) return { kind: "literal", value: lit };
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// Variable — check for assignment operators after it
|
|
679
|
+
if (tok.type === TT.IDENT) {
|
|
680
|
+
const name = this.consume(TT.IDENT).value;
|
|
681
|
+
|
|
682
|
+
|
|
683
|
+
// Check for == (comparison)
|
|
684
|
+
if (this.check(TT.OP_EQEQ)) {
|
|
685
|
+
this.consume(TT.OP_EQEQ);
|
|
686
|
+
const right = this.parseExpression();
|
|
687
|
+
if (!right) throw new SinthError("Expected expression after ==", this.peek().loc);
|
|
688
|
+
return { kind: "binary", left: { kind: "variable", name }, op: "==", right };
|
|
689
|
+
}
|
|
690
|
+
|
|
691
|
+
// Check for !=
|
|
692
|
+
if (this.check(TT.OP_NEQ)) {
|
|
693
|
+
this.consume(TT.OP_NEQ);
|
|
694
|
+
const right = this.parseExpression();
|
|
695
|
+
if (!right) throw new SinthError("Expected expression after !=", this.peek().loc);
|
|
696
|
+
return { kind: "binary", left: { kind: "variable", name }, op: "!=", right };
|
|
697
|
+
}
|
|
698
|
+
|
|
699
|
+
// Check for <
|
|
700
|
+
if (this.check(TT.OP_LT)) {
|
|
701
|
+
this.consume(TT.OP_LT);
|
|
702
|
+
const right = this.parseExpression();
|
|
703
|
+
if (!right) throw new SinthError("Expected expression after <", this.peek().loc);
|
|
704
|
+
return { kind: "binary", left: { kind: "variable", name }, op: "<", right };
|
|
705
|
+
}
|
|
706
|
+
// Check for >
|
|
707
|
+
if (this.check(TT.OP_GT)) {
|
|
708
|
+
this.consume(TT.OP_GT);
|
|
709
|
+
const right = this.parseExpression();
|
|
710
|
+
if (!right) throw new SinthError("Expected expression after >", this.peek().loc);
|
|
711
|
+
return { kind: "binary", left: { kind: "variable", name }, op: ">", right };
|
|
712
|
+
}
|
|
713
|
+
|
|
714
|
+
// Check for >=
|
|
715
|
+
if (this.check(TT.OP_GTEQ)) {
|
|
716
|
+
this.consume(TT.OP_GTEQ);
|
|
717
|
+
const right = this.parseExpression();
|
|
718
|
+
if (!right) throw new SinthError("Expected expression after >= ", this.peek().loc);
|
|
719
|
+
return { kind: "binary", left: { kind: "variable", name }, op: ">=", right };
|
|
720
|
+
}
|
|
721
|
+
// Check for <=
|
|
722
|
+
if (this.check(TT.OP_LTEQ)) {
|
|
723
|
+
this.consume(TT.OP_LTEQ);
|
|
724
|
+
const right = this.parseExpression();
|
|
725
|
+
if (!right) throw new SinthError("Expected expression after <=", this.peek().loc);
|
|
726
|
+
return { kind: "binary", left: { kind: "variable", name }, op: "<=", right };
|
|
727
|
+
}
|
|
728
|
+
|
|
729
|
+
// Check for +=, -=, =
|
|
730
|
+
if (this.check(TT.OP_PLUS) || this.check(TT.OP_MINUS) || this.check(TT.EQUALS)) {
|
|
731
|
+
const opTok = this.peek();
|
|
732
|
+
|
|
733
|
+
// += (only if next-next token is =)
|
|
734
|
+
const nextTok = this.tokens[this.pos + 1];
|
|
735
|
+
if (opTok.type === TT.OP_PLUS && nextTok && nextTok.type === TT.EQUALS) {
|
|
736
|
+
const right = this.parseExpression();
|
|
737
|
+
if (!right) throw new SinthError("Expected expression after +=", this.peek().loc);
|
|
738
|
+
return { kind: "assign", target: name, op: "+=", right };
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
// -=
|
|
742
|
+
if (opTok.type === TT.OP_MINUS && nextTok && nextTok.type === TT.EQUALS) {
|
|
743
|
+
this.consume(TT.OP_MINUS);
|
|
744
|
+
this.consume(TT.EQUALS);
|
|
745
|
+
const right = this.parseExpression();
|
|
746
|
+
if (!right) throw new SinthError("Expected expression after -=", this.peek().loc);
|
|
747
|
+
return { kind: "assign", target: name, op: "-=", right };
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
// =
|
|
751
|
+
if (opTok.type === TT.EQUALS) {
|
|
752
|
+
this.consume(TT.EQUALS);
|
|
753
|
+
const right = this.parseExpression();
|
|
754
|
+
if (!right) throw new SinthError("Expected expression after =", this.peek().loc);
|
|
755
|
+
return { kind: "assign", target: name, op: "=", right };
|
|
756
|
+
}
|
|
757
|
+
|
|
758
|
+
// Plain + or - (binary operator)
|
|
759
|
+
if (opTok.type === TT.OP_PLUS || opTok.type === TT.OP_MINUS) {
|
|
760
|
+
const op = this.consume(opTok.type).value as "+" | "-";
|
|
761
|
+
const right = this.parseExpression();
|
|
762
|
+
if (!right) throw new SinthError("Expected expression after " + op, this.peek().loc);
|
|
763
|
+
return { kind: "binary", left: { kind: "variable", name }, op, right };
|
|
764
|
+
}
|
|
765
|
+
}
|
|
766
|
+
|
|
767
|
+
// Just a variable reference
|
|
768
|
+
return { kind: "variable", name };
|
|
769
|
+
}
|
|
770
|
+
|
|
771
|
+
return null;
|
|
772
|
+
}
|
|
773
|
+
|
|
500
774
|
// ── Component definitions ─────────────────────────────────
|
|
501
775
|
|
|
502
776
|
private parseCompDef(): CompDef {
|
|
503
777
|
const loc = this.consume(TT.KW_COMPONENT).loc;
|
|
504
778
|
const name = this.consume(TT.IDENT).value;
|
|
505
779
|
const params = this.parseParamDecls();
|
|
506
|
-
// === v0.0
|
|
780
|
+
// === v0.1.0: rawBlockPending was set by the lexer when KW_COMPONENT was read;
|
|
507
781
|
// the next token is therefore RAW_BLOCK, not LBRACE ===
|
|
508
782
|
const rawTok = this.consume(TT.RAW_BLOCK);
|
|
509
783
|
const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
|
|
510
784
|
return { name, params, body, styles, scripts, loc };
|
|
511
785
|
}
|
|
512
786
|
|
|
513
|
-
// === v0.0
|
|
787
|
+
// === v0.1.0: Parse custom-element / custom declarations ===
|
|
514
788
|
private parseCustomEl(): CustomElDecl {
|
|
515
789
|
const loc = this.peek().loc;
|
|
516
790
|
if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
|
|
@@ -571,7 +845,27 @@ export class Parser {
|
|
|
571
845
|
const aloc = this.peek().loc;
|
|
572
846
|
const aname = this.consume(TT.IDENT).value;
|
|
573
847
|
let value: Literal | null = null;
|
|
574
|
-
if (this.check(TT.COLON)) {
|
|
848
|
+
if (this.check(TT.COLON)) {
|
|
849
|
+
this.consume(TT.COLON);
|
|
850
|
+
// For event attributes, try parsing the rest as an expression
|
|
851
|
+
if (this.isEventAttribute(aname)) {
|
|
852
|
+
const startTokens = this.pos;
|
|
853
|
+
let expr = this.parseExpression();
|
|
854
|
+
if (expr && !this.check(TT.COMMA) && !this.check(TT.RPAREN) && !this.check(TT.EOF)) {
|
|
855
|
+
// If there are more tokens, it's probably not a simple expression
|
|
856
|
+
this.pos = startTokens;
|
|
857
|
+
expr = null;
|
|
858
|
+
}
|
|
859
|
+
if (expr) {
|
|
860
|
+
value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
|
|
861
|
+
} else {
|
|
862
|
+
this.pos = startTokens;
|
|
863
|
+
value = this.parseLiteral();
|
|
864
|
+
}
|
|
865
|
+
} else {
|
|
866
|
+
value = this.parseLiteral();
|
|
867
|
+
}
|
|
868
|
+
}
|
|
575
869
|
attrs.push({ name: aname, value, loc: aloc });
|
|
576
870
|
if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
|
|
577
871
|
}
|
|
@@ -592,14 +886,115 @@ export class Parser {
|
|
|
592
886
|
return { kind: "use", name, attrs, children, loc };
|
|
593
887
|
}
|
|
594
888
|
|
|
889
|
+
private parseIfBlock(): IfBlock {
|
|
890
|
+
const loc = this.consume(TT.KW_IF).loc;
|
|
891
|
+
const condition = this.parseExpression();
|
|
892
|
+
if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
|
|
893
|
+
|
|
894
|
+
let body: Child[];
|
|
895
|
+
if (this.check(TT.LBRACE)) {
|
|
896
|
+
this.consume(TT.LBRACE);
|
|
897
|
+
body = this.parseChildList();
|
|
898
|
+
this.consume(TT.RBRACE);
|
|
899
|
+
} else {
|
|
900
|
+
body = [];
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
let elseBody: Child[] | undefined;
|
|
904
|
+
if (this.check(TT.KW_ELSE)) {
|
|
905
|
+
this.consume(TT.KW_ELSE);
|
|
906
|
+
if (this.check(TT.LBRACE)) {
|
|
907
|
+
this.consume(TT.LBRACE);
|
|
908
|
+
elseBody = this.parseChildList();
|
|
909
|
+
this.consume(TT.RBRACE);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
|
|
913
|
+
return { kind: "if", condition, body, elseBody, loc };
|
|
914
|
+
}
|
|
915
|
+
|
|
916
|
+
private parseForLoop(): ForLoop {
|
|
917
|
+
const loc = this.consume(TT.KW_FOR).loc;
|
|
918
|
+
const itemVar = this.consume(TT.IDENT).value;
|
|
919
|
+
if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
|
|
920
|
+
this.consume(TT.KW_IN);
|
|
921
|
+
const arrayVar = this.consume(TT.IDENT).value;
|
|
922
|
+
|
|
923
|
+
let body: Child[];
|
|
924
|
+
if (this.check(TT.LBRACE)) {
|
|
925
|
+
this.consume(TT.LBRACE);
|
|
926
|
+
this.loopVar = itemVar;
|
|
927
|
+
body = this.parseChildList();
|
|
928
|
+
this.loopVar = null;
|
|
929
|
+
this.consume(TT.RBRACE);
|
|
930
|
+
} else {
|
|
931
|
+
body = [];
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
return { kind: "for", itemVar, arrayVar, body, loc };
|
|
935
|
+
}
|
|
936
|
+
|
|
937
|
+
private isEventAttribute(name: string): boolean {
|
|
938
|
+
return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
|
|
939
|
+
}
|
|
940
|
+
|
|
595
941
|
private parseChildList(): Child[] {
|
|
596
942
|
const children: Child[] = [];
|
|
597
943
|
while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
|
|
598
944
|
if (this.check(TT.STRING)) {
|
|
599
945
|
const loc = this.peek().loc;
|
|
600
|
-
|
|
946
|
+
const strVal = this.consume(TT.STRING).value;
|
|
947
|
+
if (this.check(TT.OP_PLUS)) {
|
|
948
|
+
this.consume(TT.OP_PLUS);
|
|
949
|
+
const rightExpr = this.parseExpression();
|
|
950
|
+
if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
|
|
951
|
+
children.push({ kind: "expr", expression: {
|
|
952
|
+
kind: "binary",
|
|
953
|
+
left: { kind: "literal", value: { kind: "str", value: strVal } },
|
|
954
|
+
op: "+",
|
|
955
|
+
right: rightExpr,
|
|
956
|
+
}, loc });
|
|
957
|
+
} else {
|
|
958
|
+
children.push({ kind: "text", value: strVal, loc });
|
|
959
|
+
}
|
|
960
|
+
} else if (this.check(TT.KW_IF)) {
|
|
961
|
+
children.push(this.parseIfBlock());
|
|
962
|
+
} else if (this.check(TT.KW_FOR)) {
|
|
963
|
+
children.push(this.parseForLoop());
|
|
601
964
|
} else if (this.check(TT.IDENT)) {
|
|
602
|
-
|
|
965
|
+
// Check if next token is + (variable + something)
|
|
966
|
+
if (this.tokens[this.pos + 1]?.type === TT.OP_PLUS) {
|
|
967
|
+
const loc = this.peek().loc;
|
|
968
|
+
const varName = this.consume(TT.IDENT).value;
|
|
969
|
+
this.consume(TT.OP_PLUS); // consume +
|
|
970
|
+
// Check if what follows is a string
|
|
971
|
+
if (this.check(TT.STRING)) {
|
|
972
|
+
const rightStr = this.consume(TT.STRING).value;
|
|
973
|
+
children.push({ kind: "expr", expression: {
|
|
974
|
+
kind: "binary",
|
|
975
|
+
left: { kind: "variable", name: varName },
|
|
976
|
+
op: "+",
|
|
977
|
+
right: { kind: "literal", value: { kind: "str", value: rightStr } },
|
|
978
|
+
}, loc });
|
|
979
|
+
} else {
|
|
980
|
+
// variable + expression
|
|
981
|
+
const rightExpr = this.parseExpression();
|
|
982
|
+
if (rightExpr) {
|
|
983
|
+
children.push({ kind: "expr", expression: {
|
|
984
|
+
kind: "binary",
|
|
985
|
+
left: { kind: "variable", name: varName },
|
|
986
|
+
op: "+",
|
|
987
|
+
right: rightExpr,
|
|
988
|
+
}, loc });
|
|
989
|
+
}
|
|
990
|
+
}
|
|
991
|
+
} else if (this.loopVar && this.peek().value === this.loopVar) {
|
|
992
|
+
const loc = this.peek().loc;
|
|
993
|
+
const name = this.consume(TT.IDENT).value;
|
|
994
|
+
children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
|
|
995
|
+
} else {
|
|
996
|
+
children.push(this.parseCompUse());
|
|
997
|
+
}
|
|
603
998
|
} else {
|
|
604
999
|
throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
|
|
605
1000
|
}
|
|
@@ -652,6 +1047,7 @@ export class Parser {
|
|
|
652
1047
|
|
|
653
1048
|
private parseLiteral(): Literal {
|
|
654
1049
|
const tok = this.peek();
|
|
1050
|
+
if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
|
|
655
1051
|
if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
|
|
656
1052
|
if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
|
|
657
1053
|
if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
|
|
@@ -690,7 +1086,7 @@ interface ResolvedImports {
|
|
|
690
1086
|
// Module-level import stack for circular detection
|
|
691
1087
|
const IMPORT_STACK: string[] = [];
|
|
692
1088
|
|
|
693
|
-
// === v0.0
|
|
1089
|
+
// === v0.1.0: parseFile catches errors and attaches source line preview ===
|
|
694
1090
|
function parseFile(filePath: string): SinthFile {
|
|
695
1091
|
if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
|
|
696
1092
|
const src = fs.readFileSync(filePath, "utf-8");
|
|
@@ -744,7 +1140,7 @@ function resolveImports(
|
|
|
744
1140
|
const src = resolveLibrary(imp.name, cfg);
|
|
745
1141
|
jsLinks.push({ src, attrs: {} });
|
|
746
1142
|
|
|
747
|
-
// === v0.0
|
|
1143
|
+
// === v0.1.0: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
|
|
748
1144
|
for (const libDir of cfg.libraryPaths) {
|
|
749
1145
|
const companion = path.join(libDir, imp.name + ".sinth");
|
|
750
1146
|
if (fs.existsSync(companion) && !visited.has(companion)) {
|
|
@@ -802,7 +1198,7 @@ function resolveLibrary(name: string, cfg: ResolverConfig): string {
|
|
|
802
1198
|
return `/libraries/${base}`;
|
|
803
1199
|
}
|
|
804
1200
|
|
|
805
|
-
// === v0.0
|
|
1201
|
+
// === v0.1.0: resolveSinthPath — first try relative to importing file, then library paths ===
|
|
806
1202
|
function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
|
|
807
1203
|
// Explicit relative path
|
|
808
1204
|
if (p.startsWith("./") || p.startsWith("../")) {
|
|
@@ -813,7 +1209,7 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
|
|
|
813
1209
|
throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
|
|
814
1210
|
}
|
|
815
1211
|
|
|
816
|
-
// === v0.0
|
|
1212
|
+
// === v0.1.0: Non-relative paths (e.g. "components/Card.sinth"): try relative to importing
|
|
817
1213
|
// file's directory FIRST, then fall back to library paths ===
|
|
818
1214
|
const relToFile = path.resolve(path.dirname(fromFile), p);
|
|
819
1215
|
if (fs.existsSync(relToFile)) return relToFile;
|
|
@@ -839,7 +1235,7 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
|
|
|
839
1235
|
|
|
840
1236
|
interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
|
|
841
1237
|
|
|
842
|
-
// === v0.0
|
|
1238
|
+
// === v0.1.0: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
|
|
843
1239
|
const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
844
1240
|
// ── Structural ──────────────────────────────────────────
|
|
845
1241
|
Main: { tag: "main" },
|
|
@@ -857,12 +1253,12 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
857
1253
|
Flex: { tag: "div", defaultClass: "flex" },
|
|
858
1254
|
Stack: { tag: "div", defaultClass: "stack" },
|
|
859
1255
|
Row: { tag: "div", defaultClass: "row" },
|
|
860
|
-
// === v0.0
|
|
1256
|
+
// === v0.1.0: Column = grid helper div; Col = HTML void table col ===
|
|
861
1257
|
Column: { tag: "div", defaultClass: "col" },
|
|
862
1258
|
// ── Typography ────────────────────────────────────────────
|
|
863
1259
|
Heading: { tag: "h1" }, // resolved dynamically by level attr
|
|
864
1260
|
Paragraph: { tag: "p" },
|
|
865
|
-
// === v0.0
|
|
1261
|
+
// === v0.1.0: SubHeading convenience component ===
|
|
866
1262
|
SubHeading: { tag: "p", defaultClass: "subheading" },
|
|
867
1263
|
Lead: { tag: "p", defaultClass: "lead" },
|
|
868
1264
|
Small: { tag: "small" },
|
|
@@ -929,7 +1325,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
929
1325
|
Wbr: { tag: "wbr", voidEl: true },
|
|
930
1326
|
Source: { tag: "source", voidEl: true },
|
|
931
1327
|
Embed: { tag: "embed", voidEl: true },
|
|
932
|
-
// === v0.0
|
|
1328
|
+
// === v0.1.0: Col = HTML void table column (NOT the grid div) ===
|
|
933
1329
|
Col: { tag: "col", voidEl: true },
|
|
934
1330
|
Area: { tag: "area", voidEl: true },
|
|
935
1331
|
// ── Lists ─────────────────────────────────────────────────
|
|
@@ -949,9 +1345,9 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
|
|
|
949
1345
|
Template: { tag: "template" },
|
|
950
1346
|
Slot: { tag: "slot" },
|
|
951
1347
|
NoScript: { tag: "noscript" },
|
|
952
|
-
// === v0.0
|
|
1348
|
+
// === v0.1.0: CardGrid convenience layout wrapper ===
|
|
953
1349
|
CardGrid: { tag: "div", defaultClass: "card-grid" },
|
|
954
|
-
// === v0.0
|
|
1350
|
+
// === v0.1.0: RawHTML marker — handled specially in renderCompUse ===
|
|
955
1351
|
RawHTML: { tag: "__RAW__" },
|
|
956
1352
|
};
|
|
957
1353
|
|
|
@@ -970,7 +1366,7 @@ function eventAttrName(name: string): string | null {
|
|
|
970
1366
|
// SECTION 7: STYLE PROCESSOR
|
|
971
1367
|
// ═══════════════════════════════════════════════════════════
|
|
972
1368
|
|
|
973
|
-
// === v0.0
|
|
1369
|
+
// === v0.1.0: Completely rewritten convertCSSProps — bulletproof line-by-line approach ===
|
|
974
1370
|
// Rules:
|
|
975
1371
|
// - Match lines of the form: [whitespace] camelCaseProp : "value" [;]
|
|
976
1372
|
// - Convert property name camelCase → kebab-case
|
|
@@ -1024,7 +1420,7 @@ function convertCSSProps(css: string): string {
|
|
|
1024
1420
|
}).join("\n");
|
|
1025
1421
|
}
|
|
1026
1422
|
|
|
1027
|
-
// === v0.0
|
|
1423
|
+
// === v0.1.0: processStyleBlock — correct order: interpolate {param} → camelCase convert → SCSS → scope ===
|
|
1028
1424
|
function processStyleBlock(
|
|
1029
1425
|
block: StyleBlock,
|
|
1030
1426
|
hash: string,
|
|
@@ -1193,14 +1589,30 @@ function resolveBuiltinTag(
|
|
|
1193
1589
|
function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
|
|
1194
1590
|
const { name, value } = attr;
|
|
1195
1591
|
|
|
1196
|
-
if (value === null) return name;
|
|
1197
|
-
if (value.kind === "null") return "";
|
|
1198
|
-
if (value.kind === "bool") return value.value ? name : "";
|
|
1592
|
+
if (value === null) return name;
|
|
1593
|
+
if (value.kind === "null") return "";
|
|
1594
|
+
if (value.kind === "bool") return value.value ? name : "";
|
|
1199
1595
|
if (value.kind === "num") return `${name}="${value.value}"`;
|
|
1200
1596
|
|
|
1201
|
-
// String value — interpolate {param}, then emit
|
|
1202
1597
|
let raw = value.value;
|
|
1203
|
-
|
|
1598
|
+
|
|
1599
|
+
// Check for inline expression
|
|
1600
|
+
if (raw.startsWith("__EXPR__")) {
|
|
1601
|
+
const exprJson = raw.substring("__EXPR__".length);
|
|
1602
|
+
try {
|
|
1603
|
+
const expr: Expression = JSON.parse(exprJson);
|
|
1604
|
+
const jsExpr = compileExprToJS(expr);
|
|
1605
|
+
const ev = eventAttrName(name);
|
|
1606
|
+
if (ev) {
|
|
1607
|
+
return `${ev}="(function(){ ${jsExpr}; })()"`;
|
|
1608
|
+
}
|
|
1609
|
+
return `${name}="${escAttr(jsExpr)}"`;
|
|
1610
|
+
} catch {
|
|
1611
|
+
// Fall through to normal handling
|
|
1612
|
+
}
|
|
1613
|
+
}
|
|
1614
|
+
|
|
1615
|
+
raw = interpolateAttr(raw, paramMap);
|
|
1204
1616
|
|
|
1205
1617
|
const ev = eventAttrName(name);
|
|
1206
1618
|
if (ev) {
|
|
@@ -1210,7 +1622,7 @@ function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
|
|
|
1210
1622
|
return `${name}="${escAttr(raw)}"`;
|
|
1211
1623
|
}
|
|
1212
1624
|
|
|
1213
|
-
// === v0.0
|
|
1625
|
+
// === v0.1.0: renderText — "$slot" protected from double-escaping via placeholder approach ===
|
|
1214
1626
|
function renderText(text: string, params: Map<string, string>): string {
|
|
1215
1627
|
// Map of placeholder → raw HTML for slot-like params
|
|
1216
1628
|
const rawSlots = new Map<string, string>();
|
|
@@ -1248,7 +1660,7 @@ function renderText(text: string, params: Map<string, string>): string {
|
|
|
1248
1660
|
// Step 5: Restore \$ → $
|
|
1249
1661
|
s = s.replace(/\x00DOLLAR\x00/g, "$");
|
|
1250
1662
|
|
|
1251
|
-
// === v0.0
|
|
1663
|
+
// === v0.1.0: Warn about {identifier} patterns remaining after substitution ===
|
|
1252
1664
|
const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
|
|
1253
1665
|
let m: RegExpExecArray | null;
|
|
1254
1666
|
while ((m = braceRe.exec(s)) !== null) {
|
|
@@ -1275,6 +1687,32 @@ function renderChild(
|
|
|
1275
1687
|
): string {
|
|
1276
1688
|
if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
|
|
1277
1689
|
if (child.kind === "text") return renderText(child.value, params);
|
|
1690
|
+
if (child.kind === "expr") {
|
|
1691
|
+
const jsExpr = compileExprToJS(child.expression);
|
|
1692
|
+
return `<span class="sinth-expr" data-expr="${escAttr(jsExpr)}"></span>`;
|
|
1693
|
+
}
|
|
1694
|
+
if (child.kind === "if") {
|
|
1695
|
+
const condJS = compileExprToJS(child.condition);
|
|
1696
|
+
const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
1697
|
+
const elseHTML = child.elseBody ? child.elseBody.map(c => renderChild(c, ctx, params, depth + 1)).join("") : "";
|
|
1698
|
+
return `<template data-sinth-if="${escAttr(condJS)}">${bodyHTML}</template>` +
|
|
1699
|
+
(elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "");
|
|
1700
|
+
}
|
|
1701
|
+
if (child.kind === "for") {
|
|
1702
|
+
let bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
|
|
1703
|
+
// Replace component tags for the loop variable with expression spans
|
|
1704
|
+
const itemVar = child.itemVar;
|
|
1705
|
+
bodyHTML = bodyHTML.replace(
|
|
1706
|
+
new RegExp(`<${itemVar}[^>]*>(.*?)</${itemVar}>`, 'g'),
|
|
1707
|
+
(_, content) => {
|
|
1708
|
+
if (!content || content.trim() === '') {
|
|
1709
|
+
return `<span class="sinth-expr" data-expr="${itemVar}"></span>`;
|
|
1710
|
+
}
|
|
1711
|
+
return `<span class="sinth-expr" data-expr="${itemVar}">${content}</span>`;
|
|
1712
|
+
}
|
|
1713
|
+
);
|
|
1714
|
+
return `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(itemVar)}">${bodyHTML}</template>`;
|
|
1715
|
+
}
|
|
1278
1716
|
return renderCompUse(child, ctx, params, depth);
|
|
1279
1717
|
}
|
|
1280
1718
|
|
|
@@ -1284,7 +1722,7 @@ function renderCompUse(
|
|
|
1284
1722
|
params: Map<string, string>,
|
|
1285
1723
|
depth: number,
|
|
1286
1724
|
): string {
|
|
1287
|
-
// === v0.0
|
|
1725
|
+
// === v0.1.0: RawHTML — output content attribute verbatim, no wrapping tag, no scoping ===
|
|
1288
1726
|
if (use.name === "RawHTML") {
|
|
1289
1727
|
const ca = use.attrs.find(a => a.name === "content");
|
|
1290
1728
|
if (!ca || !ca.value) return "";
|
|
@@ -1329,7 +1767,7 @@ function renderCompUse(
|
|
|
1329
1767
|
const classes = [defaultClass, userClass].filter(Boolean).join(" ");
|
|
1330
1768
|
if (classes) attrParts.push(`class="${escAttr(classes)}"`);
|
|
1331
1769
|
|
|
1332
|
-
// === v0.0
|
|
1770
|
+
// === v0.1.0: Default type="button" for <button> elements ===
|
|
1333
1771
|
if (tag === "button" && !use.attrs.some(a => a.name === "type")) {
|
|
1334
1772
|
attrParts.push(`type="button"`);
|
|
1335
1773
|
}
|
|
@@ -1391,7 +1829,7 @@ function expandUserComp(
|
|
|
1391
1829
|
const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
|
|
1392
1830
|
local.set("slot", slotHTML);
|
|
1393
1831
|
|
|
1394
|
-
// === v0.0
|
|
1832
|
+
// === v0.1.0: Process component style blocks with instance params and push to extraCSS ===
|
|
1395
1833
|
for (const block of def.styles) {
|
|
1396
1834
|
ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
|
|
1397
1835
|
}
|
|
@@ -1399,6 +1837,38 @@ function expandUserComp(
|
|
|
1399
1837
|
return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
|
|
1400
1838
|
}
|
|
1401
1839
|
|
|
1840
|
+
// === v0.1.0: Expression to JS helper ===
|
|
1841
|
+
function compileExprToJS(expr: Expression): string {
|
|
1842
|
+
switch (expr.kind) {
|
|
1843
|
+
case "literal":
|
|
1844
|
+
if (!expr.value) return "null";
|
|
1845
|
+
if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
|
|
1846
|
+
if (expr.value.kind === "num") return String((expr.value as LitNum).value);
|
|
1847
|
+
if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
|
|
1848
|
+
return "null";
|
|
1849
|
+
case "variable":
|
|
1850
|
+
return expr.name || "undefined";
|
|
1851
|
+
case "binary": {
|
|
1852
|
+
const left = compileExprToJS(expr.left!);
|
|
1853
|
+
const right = compileExprToJS(expr.right!);
|
|
1854
|
+
const op = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op;
|
|
1855
|
+
return `(${left} ${op} ${right})`;
|
|
1856
|
+
}
|
|
1857
|
+
case "unary": {
|
|
1858
|
+
const op = expr.op === "not" ? "!" : expr.op;
|
|
1859
|
+
return `${op}(${compileExprToJS(expr.operand!)})`;
|
|
1860
|
+
}
|
|
1861
|
+
case "assign": {
|
|
1862
|
+
const val = expr.right ? compileExprToJS(expr.right) : "null";
|
|
1863
|
+
return `${expr.target} ${expr.op} ${val}`;
|
|
1864
|
+
}
|
|
1865
|
+
case "postfix":
|
|
1866
|
+
return `${expr.target}${expr.op}`;
|
|
1867
|
+
default:
|
|
1868
|
+
return "";
|
|
1869
|
+
}
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1402
1872
|
// ═══════════════════════════════════════════════════════════
|
|
1403
1873
|
// SECTION 9: SCRIPT COLLECTOR
|
|
1404
1874
|
// ═══════════════════════════════════════════════════════════
|
|
@@ -1492,7 +1962,7 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
|
|
|
1492
1962
|
return { title, fav, lang, charset, viewport, metaTags, metaProps };
|
|
1493
1963
|
}
|
|
1494
1964
|
|
|
1495
|
-
// === v0.0
|
|
1965
|
+
// === v0.1.0: .jpg and .jpeg return "image/jpeg" ===
|
|
1496
1966
|
function faviconType(p: string): string {
|
|
1497
1967
|
const ext = path.extname(p).toLowerCase();
|
|
1498
1968
|
switch (ext) {
|
|
@@ -1555,7 +2025,7 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
|
1555
2025
|
const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
|
|
1556
2026
|
const hash = fnv1a(absPath);
|
|
1557
2027
|
|
|
1558
|
-
// === v0.0
|
|
2028
|
+
// === v0.1.0: extraCSS collected during rendering (per-instance component styles) ===
|
|
1559
2029
|
const ctx: CompileCtx = {
|
|
1560
2030
|
allDefs, customEls, cssLinks, jsLinks,
|
|
1561
2031
|
scopeHash: hash, pageFile: absPath, extraCSS: [],
|
|
@@ -1619,8 +2089,97 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
|
|
|
1619
2089
|
head,
|
|
1620
2090
|
`<body data-s="${hash}">`,
|
|
1621
2091
|
bodyHTML,
|
|
1622
|
-
|
|
1623
|
-
|
|
2092
|
+
`<script>
|
|
2093
|
+
// v0.2.0: Sinth variable declarations
|
|
2094
|
+
${file.varDecls.map(v => {
|
|
2095
|
+
if (!v.value) return `let ${v.name};`; // uninitialized
|
|
2096
|
+
const val = litToString(v.value);
|
|
2097
|
+
|
|
2098
|
+
// Variable reference: __VAR__count → count
|
|
2099
|
+
if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
|
|
2100
|
+
const refName = val.slice(7);
|
|
2101
|
+
return `let ${v.name} = ${refName};`;
|
|
2102
|
+
}
|
|
2103
|
+
|
|
2104
|
+
// Array literal: __ARR__["a","b"]
|
|
2105
|
+
if (val.startsWith("__ARR__")) {
|
|
2106
|
+
return `let ${v.name} = ${val.slice(7)};`;
|
|
2107
|
+
}
|
|
2108
|
+
|
|
2109
|
+
if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
|
|
2110
|
+
return `let ${v.name} = ${val};`;
|
|
2111
|
+
}).join("\n")}
|
|
2112
|
+
|
|
2113
|
+
// v0.2.0: Store original page HTML for full re-render
|
|
2114
|
+
const _sinthBodyHTML = document.body.innerHTML;
|
|
2115
|
+
|
|
2116
|
+
function sinthRender() {
|
|
2117
|
+
// Save current scroll position
|
|
2118
|
+
const scrollX = window.scrollX;
|
|
2119
|
+
const scrollY = window.scrollY;
|
|
2120
|
+
|
|
2121
|
+
// Re-render the entire body from the original HTML
|
|
2122
|
+
document.body.innerHTML = _sinthBodyHTML;
|
|
2123
|
+
|
|
2124
|
+
// Re-process all templates recursively
|
|
2125
|
+
function processTemplates(root) {
|
|
2126
|
+
root.querySelectorAll('template[data-sinth-if]').forEach(t => {
|
|
2127
|
+
const cond = new Function('return ' + t.dataset.sinthIf)();
|
|
2128
|
+
if (cond) {
|
|
2129
|
+
const frag = document.createRange().createContextualFragment(t.innerHTML);
|
|
2130
|
+
t.replaceWith(frag);
|
|
2131
|
+
processTemplates(root); // Re-process in case templates were nested
|
|
2132
|
+
} else {
|
|
2133
|
+
const elseT = t.nextElementSibling;
|
|
2134
|
+
if (elseT && elseT.matches && elseT.matches('template[data-sinth-else]')) {
|
|
2135
|
+
const frag = document.createRange().createContextualFragment(elseT.innerHTML);
|
|
2136
|
+
elseT.replaceWith(frag);
|
|
2137
|
+
processTemplates(root);
|
|
2138
|
+
}
|
|
2139
|
+
t.remove();
|
|
2140
|
+
}
|
|
2141
|
+
});
|
|
2142
|
+
root.querySelectorAll('template[data-sinth-for]').forEach(t => {
|
|
2143
|
+
const arr = eval(t.dataset.sinthFor);
|
|
2144
|
+
if (arr && Array.isArray(arr)) {
|
|
2145
|
+
const itemName = t.dataset.sinthItem;
|
|
2146
|
+
const frag = document.createDocumentFragment();
|
|
2147
|
+
arr.forEach(item => {
|
|
2148
|
+
// Fill the expression spans with the actual loop value BEFORE adding to DOM
|
|
2149
|
+
let itemHTML = t.innerHTML;
|
|
2150
|
+
const regex = new RegExp('<span class="sinth-expr" data-expr="' + itemName + '"></span>', 'g');
|
|
2151
|
+
itemHTML = itemHTML.replace(regex, '<span class="sinth-expr" data-expr="' + itemName + '">' + item + '</span>');
|
|
2152
|
+
frag.append(document.createRange().createContextualFragment(itemHTML));
|
|
2153
|
+
});
|
|
2154
|
+
t.replaceWith(frag);
|
|
2155
|
+
processTemplates(root);
|
|
2156
|
+
}
|
|
2157
|
+
});
|
|
2158
|
+
}
|
|
2159
|
+
processTemplates(document.body);
|
|
2160
|
+
|
|
2161
|
+
// Update all expression spans
|
|
2162
|
+
document.querySelectorAll('.sinth-expr').forEach(el => {
|
|
2163
|
+
try { el.textContent = eval(el.dataset.expr); } catch(e) {}
|
|
2164
|
+
});
|
|
2165
|
+
|
|
2166
|
+
// Update onclick handlers
|
|
2167
|
+
document.querySelectorAll('[onclick]').forEach(el => {
|
|
2168
|
+
const oc = el.getAttribute('onclick');
|
|
2169
|
+
if (oc && oc.startsWith('(function(){') && !oc.includes('sinthRender()')) {
|
|
2170
|
+
const inner = oc.slice(12, -4);
|
|
2171
|
+
el.setAttribute('onclick', '(function(){' + inner + ';sinthRender();})()');
|
|
2172
|
+
}
|
|
2173
|
+
});
|
|
2174
|
+
|
|
2175
|
+
// Restore scroll
|
|
2176
|
+
window.scrollTo(scrollX, scrollY);
|
|
2177
|
+
}
|
|
2178
|
+
|
|
2179
|
+
// Initial render
|
|
2180
|
+
sinthRender();
|
|
2181
|
+
</script>`,
|
|
2182
|
+
scriptTags.join("\n"), "</body>",
|
|
1624
2183
|
"</html>",
|
|
1625
2184
|
].join("\n");
|
|
1626
2185
|
|
|
@@ -1635,7 +2194,7 @@ function minifyHTML(html: string): string {
|
|
|
1635
2194
|
// SECTION 12: FILE DISCOVERY & ASSET COPY
|
|
1636
2195
|
// ═══════════════════════════════════════════════════════════
|
|
1637
2196
|
|
|
1638
|
-
// === v0.0
|
|
2197
|
+
// === v0.1.0: findSinthPages skips outDir to prevent infinite watcher loops ===
|
|
1639
2198
|
function findSinthPages(dir: string, outDir?: string): string[] {
|
|
1640
2199
|
const results: string[] = [];
|
|
1641
2200
|
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
|
|
@@ -1651,7 +2210,7 @@ function findSinthPages(dir: string, outDir?: string): string[] {
|
|
|
1651
2210
|
return results;
|
|
1652
2211
|
}
|
|
1653
2212
|
|
|
1654
|
-
// === v0.0
|
|
2213
|
+
// === v0.1.0: Recursive directory copy for assets/ ===
|
|
1655
2214
|
function copyDir(src: string, dest: string): void {
|
|
1656
2215
|
if (!fs.existsSync(src)) return;
|
|
1657
2216
|
fs.mkdirSync(dest, { recursive: true });
|
|
@@ -1710,7 +2269,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
|
|
|
1710
2269
|
|
|
1711
2270
|
compileAll();
|
|
1712
2271
|
|
|
1713
|
-
// === v0.0
|
|
2272
|
+
// === v0.1.0: Watch ignores changes whose absolute path is inside outDir ===
|
|
1714
2273
|
const resolvedOut = path.resolve(opts.outDir);
|
|
1715
2274
|
// Use fs.watch with fs.watchFile fallback for Windows reliability
|
|
1716
2275
|
let watchReady = false;
|
|
@@ -1872,7 +2431,7 @@ async function main(): Promise<void> {
|
|
|
1872
2431
|
}
|
|
1873
2432
|
}
|
|
1874
2433
|
|
|
1875
|
-
// === v0.0
|
|
2434
|
+
// === v0.1.0: Copy assets/ to outDir/assets/ ===
|
|
1876
2435
|
const assetsIn = path.join(cwd, "assets");
|
|
1877
2436
|
const assetsOut = path.join(outDir, "assets");
|
|
1878
2437
|
if (fs.existsSync(assetsIn)) {
|
|
@@ -1924,7 +2483,7 @@ async function main(): Promise<void> {
|
|
|
1924
2483
|
break;
|
|
1925
2484
|
}
|
|
1926
2485
|
|
|
1927
|
-
// === v0.0
|
|
2486
|
+
// === v0.1.0: sinth version command ===
|
|
1928
2487
|
case "version":
|
|
1929
2488
|
case "--version":
|
|
1930
2489
|
case "-v": {
|
|
@@ -1942,7 +2501,7 @@ async function main(): Promise<void> {
|
|
|
1942
2501
|
|
|
1943
2502
|
default: {
|
|
1944
2503
|
process.stdout.write(`
|
|
1945
|
-
\x1b[1mSinth Compiler v0.0
|
|
2504
|
+
\x1b[1mSinth Compiler v0.1.0\x1b[0m
|
|
1946
2505
|
|
|
1947
2506
|
\x1b[1mCommands:\x1b[0m
|
|
1948
2507
|
sinth build [--out ./dist] [--prod] Compile all .sinth pages + copy assets/
|