@yannosay/sinth 0.0.18 → 0.1.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.
Files changed (2) hide show
  1. package/package.json +1 -1
  2. package/src/sinth.ts +477 -47
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.0.18",
3
+ "version": "0.1.0",
4
4
  "description": "A declarative language that compiles to pure HTML, CSS, and JavaScript.",
5
5
  "author": "Yannosay Productions",
6
6
  "license": "AGPL-3.0",
package/src/sinth.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
- // Sinth Compiler v0.0.15 — enum fix, raw-block detection, import resolution, CSS conversion, slot escaping, custom-elements, HTML5 map
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,7 +11,7 @@ import * as http from "http";
11
11
 
12
12
  interface Loc { file: string; line: number; col: number }
13
13
 
14
- // === v0.0.15: Must be plain `enum TT`, NOT `const enum TT` — const enum breaks TT[t] string indexing ===
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
16
  LBRACE, RBRACE, LPAREN, RPAREN, COLON, COMMA, EQUALS, DOT,
17
17
  STRING, NUMBER, BOOL_TRUE, BOOL_FALSE, NULL_LIT,
@@ -20,9 +20,13 @@ enum TT {
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
- type Child = TextNode | CompUse;
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.15: Attach source line to produce error preview ===
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.15: custom-element and custom lexed as hyphenated identifier ===
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,8 +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; }
247
+ if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
204
248
  if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
205
249
 
250
+ // v0.1.0: Logic operators
251
+ if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
252
+ if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) { tokens.push(this.single(TT.OP_MINUS, loc)); continue; }
253
+ if (ch === "*") { tokens.push(this.single(TT.OP_STAR, loc)); continue; }
254
+ if (ch === "/") { tokens.push(this.single(TT.OP_SLASH, loc)); continue; }
255
+ if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
256
+ if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
257
+ if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
258
+
206
259
  if (ch === "{") {
207
260
  if (this.rawBlockPending) {
208
261
  this.rawBlockPending = false;
@@ -221,7 +274,7 @@ export class Lexer {
221
274
 
222
275
  if (this.isIdentStart(ch)) {
223
276
  const tok = this.readIdent(loc);
224
- // === v0.0.15: Also set rawBlockPending for component, custom-element, custom ===
277
+ // === v0.1.0: Also set rawBlockPending for component, custom-element, custom ===
225
278
  if (
226
279
  tok.type === TT.KW_STYLE ||
227
280
  tok.type === TT.KW_SCRIPT ||
@@ -386,7 +439,7 @@ export class Lexer {
386
439
 
387
440
  private readIdent(loc: Loc): Token {
388
441
  let s = "";
389
- // === v0.0.15: isIdentCont includes '-' so "custom-element" is read as one token ===
442
+ // === v0.1.0: isIdentCont includes '-' so "custom-element" is read as one token ===
390
443
  while (this.pos < this.src.length && this.isIdentCont(this.src[this.pos])) {
391
444
  s += this.src[this.pos]; this.adv();
392
445
  }
@@ -407,7 +460,7 @@ export class Lexer {
407
460
  private loc(): Loc { return { file: this.file, line: this.line, col: this.col }; }
408
461
  private isDigit(c: string) { return c >= "0" && c <= "9"; }
409
462
  private isIdentStart(c: string) { return /[a-zA-Z_\u00C0-\uFFFF]/.test(c); }
410
- // === v0.0.15: '-' allowed in identifiers so "custom-element" is a single token ===
463
+ // === v0.1.0: '-' allowed in identifiers so "custom-element" is a single token ===
411
464
  private isIdentCont(c: string) { return /[a-zA-Z0-9_\-\u00C0-\uFFFF]/.test(c); }
412
465
  }
413
466
 
@@ -445,6 +498,14 @@ export class Parser {
445
498
  }
446
499
 
447
500
  // 4. Body: component definitions, usages, style, script, custom-element
501
+ // 4a. Variable declarations (v0.1.0 logic)
502
+ const varDecls: VarDeclaration[] = [];
503
+ while (this.check(TT.IDENT) && this.peek().value === "var") {
504
+ const vd = this.parseVarDeclaration();
505
+ if (vd) varDecls.push(vd);
506
+ }
507
+
508
+ // 4b. Body: component definitions, usages, style, script, custom-element
448
509
  while (!this.check(TT.EOF)) {
449
510
  if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
450
511
  else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
@@ -454,7 +515,7 @@ export class Parser {
454
515
  else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
455
516
  }
456
517
 
457
- return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls };
518
+ return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
458
519
  }
459
520
 
460
521
  // ── Imports ──────────────────────────────────────────────
@@ -490,27 +551,167 @@ export class Parser {
490
551
  return this.tokens[this.pos + 1]?.type === TT.EQUALS;
491
552
  }
492
553
 
493
- private parseMeta(): MetaEntry {
554
+ private parseMeta(): MetaEntry {
494
555
  const loc = this.peek().loc;
495
556
  const key = this.consume(TT.IDENT).value;
496
557
  this.consume(TT.EQUALS);
497
558
  return { key, value: this.parseLiteral(), loc };
498
559
  }
499
560
 
561
+ // === v0.1.0: Parse variable declaration ===
562
+ private parseVarDeclaration(): VarDeclaration | null {
563
+ const loc = this.peek().loc;
564
+ this.consume(TT.IDENT); // 'var'
565
+
566
+ const typeTok = this.consume(TT.IDENT);
567
+ const typeStr = typeTok.value;
568
+ if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
569
+ throw new SinthError(`Unknown type '${typeStr}'. Expected int, str, bool, or str[]`, typeTok.loc);
570
+ }
571
+
572
+ const nameTok = this.consume(TT.IDENT);
573
+ this.consume(TT.EQUALS);
574
+ const val = this.parseLiteral();
575
+
576
+ return {
577
+ kind: "var",
578
+ name: nameTok.value,
579
+ varType: typeStr as VarType,
580
+ value: val,
581
+ loc,
582
+ };
583
+ }
584
+
585
+
586
+ // ── Expression parsing (v0.1.0) ────────────────────────
587
+ private parseExpression(): Expression | null {
588
+ const tok = this.peek();
589
+
590
+ // Unary 'not'
591
+ if (tok.type === TT.IDENT && tok.value === "not") {
592
+ this.consume(TT.IDENT); // consume 'not'
593
+ const operand = this.parseExpression();
594
+ if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
595
+ return { kind: "unary", op: "not", operand };
596
+ }
597
+
598
+ // Literal
599
+ if (this.check(TT.STRING) || this.check(TT.NUMBER) || this.check(TT.BOOL_TRUE) || this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
600
+ const lit = this.parseLiteral();
601
+ if (lit) return { kind: "literal", value: lit };
602
+ }
603
+
604
+ // Variable — check for assignment operators after it
605
+ if (tok.type === TT.IDENT) {
606
+ const name = this.consume(TT.IDENT).value;
607
+
608
+
609
+ // Check for == (comparison)
610
+ if (this.check(TT.OP_EQEQ)) {
611
+ this.consume(TT.OP_EQEQ);
612
+ const right = this.parseExpression();
613
+ if (!right) throw new SinthError("Expected expression after ==", this.peek().loc);
614
+ return { kind: "binary", left: { kind: "variable", name }, op: "==", right };
615
+ }
616
+
617
+ // Check for !=
618
+ if (this.check(TT.OP_NEQ)) {
619
+ this.consume(TT.OP_NEQ);
620
+ const right = this.parseExpression();
621
+ if (!right) throw new SinthError("Expected expression after !=", this.peek().loc);
622
+ return { kind: "binary", left: { kind: "variable", name }, op: "!=", right };
623
+ }
624
+
625
+ // Check for <
626
+ if (this.check(TT.OP_LT)) {
627
+ this.consume(TT.OP_LT);
628
+ const right = this.parseExpression();
629
+ if (!right) throw new SinthError("Expected expression after <", this.peek().loc);
630
+ return { kind: "binary", left: { kind: "variable", name }, op: "<", right };
631
+ }
632
+ // Check for >
633
+ if (this.check(TT.OP_GT)) {
634
+ this.consume(TT.OP_GT);
635
+ const right = this.parseExpression();
636
+ if (!right) throw new SinthError("Expected expression after >", this.peek().loc);
637
+ return { kind: "binary", left: { kind: "variable", name }, op: ">", right };
638
+ }
639
+
640
+ // Check for >=
641
+ if (this.check(TT.OP_GTEQ)) {
642
+ this.consume(TT.OP_GTEQ);
643
+ const right = this.parseExpression();
644
+ if (!right) throw new SinthError("Expected expression after >= ", this.peek().loc);
645
+ return { kind: "binary", left: { kind: "variable", name }, op: ">=", right };
646
+ }
647
+ // Check for <=
648
+ if (this.check(TT.OP_LTEQ)) {
649
+ this.consume(TT.OP_LTEQ);
650
+ const right = this.parseExpression();
651
+ if (!right) throw new SinthError("Expected expression after <=", this.peek().loc);
652
+ return { kind: "binary", left: { kind: "variable", name }, op: "<=", right };
653
+ }
654
+
655
+ // Check for +=, -=, =
656
+ if (this.check(TT.OP_PLUS) || this.check(TT.OP_MINUS) || this.check(TT.EQUALS)) {
657
+ const opTok = this.peek();
658
+
659
+ // +=
660
+ if (opTok.type === TT.OP_PLUS && this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === TT.EQUALS) {
661
+ this.consume(TT.OP_PLUS);
662
+ this.consume(TT.EQUALS);
663
+ const right = this.parseExpression();
664
+ if (!right) throw new SinthError("Expected expression after +=", this.peek().loc);
665
+ return { kind: "assign", target: name, op: "+=", right };
666
+ }
667
+
668
+ // -=
669
+ if (opTok.type === TT.OP_MINUS && this.pos + 1 < this.tokens.length && this.tokens[this.pos + 1].type === TT.EQUALS) {
670
+ this.consume(TT.OP_MINUS);
671
+ this.consume(TT.EQUALS);
672
+ const right = this.parseExpression();
673
+ if (!right) throw new SinthError("Expected expression after -=", this.peek().loc);
674
+ return { kind: "assign", target: name, op: "-=", right };
675
+ }
676
+
677
+ // =
678
+ if (opTok.type === TT.EQUALS) {
679
+ this.consume(TT.EQUALS);
680
+ const right = this.parseExpression();
681
+ if (!right) throw new SinthError("Expected expression after =", this.peek().loc);
682
+ return { kind: "assign", target: name, op: "=", right };
683
+ }
684
+
685
+ // Plain + or - (binary operator)
686
+ if (opTok.type === TT.OP_PLUS || opTok.type === TT.OP_MINUS) {
687
+ const op = this.consume(opTok.type).value as "+" | "-";
688
+ const right = this.parseExpression();
689
+ if (!right) throw new SinthError("Expected expression after " + op, this.peek().loc);
690
+ return { kind: "binary", left: { kind: "variable", name }, op, right };
691
+ }
692
+ }
693
+
694
+ // Just a variable reference
695
+ return { kind: "variable", name };
696
+ }
697
+
698
+ return null;
699
+ }
700
+
500
701
  // ── Component definitions ─────────────────────────────────
501
702
 
502
703
  private parseCompDef(): CompDef {
503
704
  const loc = this.consume(TT.KW_COMPONENT).loc;
504
705
  const name = this.consume(TT.IDENT).value;
505
706
  const params = this.parseParamDecls();
506
- // === v0.0.15: rawBlockPending was set by the lexer when KW_COMPONENT was read;
707
+ // === v0.1.0: rawBlockPending was set by the lexer when KW_COMPONENT was read;
507
708
  // the next token is therefore RAW_BLOCK, not LBRACE ===
508
709
  const rawTok = this.consume(TT.RAW_BLOCK);
509
710
  const { body, styles, scripts } = this.parseCompBody(rawTok.value, rawTok.loc);
510
711
  return { name, params, body, styles, scripts, loc };
511
712
  }
512
713
 
513
- // === v0.0.15: Parse custom-element / custom declarations ===
714
+ // === v0.1.0: Parse custom-element / custom declarations ===
514
715
  private parseCustomEl(): CustomElDecl {
515
716
  const loc = this.peek().loc;
516
717
  if (this.check(TT.KW_CUSTOM_EL)) this.consume(TT.KW_CUSTOM_EL);
@@ -571,7 +772,27 @@ export class Parser {
571
772
  const aloc = this.peek().loc;
572
773
  const aname = this.consume(TT.IDENT).value;
573
774
  let value: Literal | null = null;
574
- if (this.check(TT.COLON)) { this.consume(TT.COLON); value = this.parseLiteral(); }
775
+ if (this.check(TT.COLON)) {
776
+ this.consume(TT.COLON);
777
+ // For event attributes, try parsing the rest as an expression
778
+ if (this.isEventAttribute(aname)) {
779
+ const startTokens = this.pos;
780
+ let expr = this.parseExpression();
781
+ if (expr && !this.check(TT.COMMA) && !this.check(TT.RPAREN) && !this.check(TT.EOF)) {
782
+ // If there are more tokens, it's probably not a simple expression
783
+ this.pos = startTokens;
784
+ expr = null;
785
+ }
786
+ if (expr) {
787
+ value = { kind: "str", value: "__EXPR__" + JSON.stringify(expr) };
788
+ } else {
789
+ this.pos = startTokens;
790
+ value = this.parseLiteral();
791
+ }
792
+ } else {
793
+ value = this.parseLiteral();
794
+ }
795
+ }
575
796
  attrs.push({ name: aname, value, loc: aloc });
576
797
  if (!this.check(TT.RPAREN)) this.consume(TT.COMMA);
577
798
  }
@@ -592,12 +813,81 @@ export class Parser {
592
813
  return { kind: "use", name, attrs, children, loc };
593
814
  }
594
815
 
816
+ private parseIfBlock(): IfBlock {
817
+ const loc = this.consume(TT.KW_IF).loc;
818
+ const condition = this.parseExpression();
819
+ if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
820
+
821
+ let body: Child[];
822
+ if (this.check(TT.LBRACE)) {
823
+ this.consume(TT.LBRACE);
824
+ body = this.parseChildList();
825
+ this.consume(TT.RBRACE);
826
+ } else {
827
+ body = [];
828
+ }
829
+
830
+ let elseBody: Child[] | undefined;
831
+ if (this.check(TT.KW_ELSE)) {
832
+ this.consume(TT.KW_ELSE);
833
+ if (this.check(TT.LBRACE)) {
834
+ this.consume(TT.LBRACE);
835
+ elseBody = this.parseChildList();
836
+ this.consume(TT.RBRACE);
837
+ }
838
+ }
839
+
840
+ return { kind: "if", condition, body, elseBody, loc };
841
+ }
842
+
843
+ private parseForLoop(): ForLoop {
844
+ const loc = this.consume(TT.KW_FOR).loc;
845
+ const itemVar = this.consume(TT.IDENT).value;
846
+ if (!this.check(TT.KW_IN)) throw new SinthError("Expected 'in' after loop variable", this.peek().loc);
847
+ this.consume(TT.KW_IN);
848
+ const arrayVar = this.consume(TT.IDENT).value;
849
+
850
+ let body: Child[];
851
+ if (this.check(TT.LBRACE)) {
852
+ this.consume(TT.LBRACE);
853
+ body = this.parseChildList();
854
+ this.consume(TT.RBRACE);
855
+ } else {
856
+ body = [];
857
+ }
858
+
859
+ return { kind: "for", itemVar, arrayVar, body, loc };
860
+ }
861
+
862
+ private isEventAttribute(name: string): boolean {
863
+ return name.startsWith("on") && name.length > 2 && name[2] === name[2].toUpperCase();
864
+ }
865
+
595
866
  private parseChildList(): Child[] {
596
867
  const children: Child[] = [];
597
868
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
598
869
  if (this.check(TT.STRING)) {
599
870
  const loc = this.peek().loc;
600
- children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
871
+ const strVal = this.consume(TT.STRING).value;
872
+ // Check if followed by +
873
+ if (this.check(TT.OP_PLUS)) {
874
+ this.consume(TT.OP_PLUS);
875
+ const rightExpr = this.parseExpression();
876
+ if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
877
+ const expr: Expression = {
878
+ kind: "binary",
879
+ left: { kind: "literal", value: { kind: "str", value: strVal } },
880
+ op: "+",
881
+ right: rightExpr,
882
+ };
883
+ children.push({ kind: "expr", expression: expr, loc });
884
+ } else {
885
+ children.push({ kind: "text", value: strVal, loc });
886
+ }
887
+ } else if (this.check(TT.KW_IF)) {
888
+ children.push(this.parseIfBlock());
889
+ } else if (this.check(TT.KW_FOR)) {
890
+ children.push(this.parseForLoop());
601
891
  } else if (this.check(TT.IDENT)) {
602
892
  children.push(this.parseCompUse());
603
893
  } else {
@@ -690,7 +980,7 @@ interface ResolvedImports {
690
980
  // Module-level import stack for circular detection
691
981
  const IMPORT_STACK: string[] = [];
692
982
 
693
- // === v0.0.15: parseFile catches errors and attaches source line preview ===
983
+ // === v0.1.0: parseFile catches errors and attaches source line preview ===
694
984
  function parseFile(filePath: string): SinthFile {
695
985
  if (!fs.existsSync(filePath)) throw new SinthError(`File not found: ${filePath}`);
696
986
  const src = fs.readFileSync(filePath, "utf-8");
@@ -744,7 +1034,7 @@ function resolveImports(
744
1034
  const src = resolveLibrary(imp.name, cfg);
745
1035
  jsLinks.push({ src, attrs: {} });
746
1036
 
747
- // === v0.0.15: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
1037
+ // === v0.1.0: Auto-import companion .sinth for JS libraries (e.g. sinthui.sinth) ===
748
1038
  for (const libDir of cfg.libraryPaths) {
749
1039
  const companion = path.join(libDir, imp.name + ".sinth");
750
1040
  if (fs.existsSync(companion) && !visited.has(companion)) {
@@ -802,7 +1092,7 @@ function resolveLibrary(name: string, cfg: ResolverConfig): string {
802
1092
  return `/libraries/${base}`;
803
1093
  }
804
1094
 
805
- // === v0.0.15: resolveSinthPath — first try relative to importing file, then library paths ===
1095
+ // === v0.1.0: resolveSinthPath — first try relative to importing file, then library paths ===
806
1096
  function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): string {
807
1097
  // Explicit relative path
808
1098
  if (p.startsWith("./") || p.startsWith("../")) {
@@ -813,7 +1103,7 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
813
1103
  throw new SinthError(`Cannot resolve import '${p}' from '${fromFile}'`);
814
1104
  }
815
1105
 
816
- // === v0.0.15: Non-relative paths (e.g. "components/Card.sinth"): try relative to importing
1106
+ // === v0.1.0: Non-relative paths (e.g. "components/Card.sinth"): try relative to importing
817
1107
  // file's directory FIRST, then fall back to library paths ===
818
1108
  const relToFile = path.resolve(path.dirname(fromFile), p);
819
1109
  if (fs.existsSync(relToFile)) return relToFile;
@@ -839,7 +1129,7 @@ function resolveSinthPath(p: string, fromFile: string, cfg: ResolverConfig): str
839
1129
 
840
1130
  interface BuiltinInfo { tag: string; defaultClass?: string; voidEl?: boolean }
841
1131
 
842
- // === v0.0.15: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
1132
+ // === v0.1.0: Complete HTML5 map; Col = void <col>; Column = grid div; added SubHeading, CardGrid ===
843
1133
  const BUILTIN_MAP: Record<string, BuiltinInfo> = {
844
1134
  // ── Structural ──────────────────────────────────────────
845
1135
  Main: { tag: "main" },
@@ -857,12 +1147,12 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
857
1147
  Flex: { tag: "div", defaultClass: "flex" },
858
1148
  Stack: { tag: "div", defaultClass: "stack" },
859
1149
  Row: { tag: "div", defaultClass: "row" },
860
- // === v0.0.15: Column = grid helper div; Col = HTML void table col ===
1150
+ // === v0.1.0: Column = grid helper div; Col = HTML void table col ===
861
1151
  Column: { tag: "div", defaultClass: "col" },
862
1152
  // ── Typography ────────────────────────────────────────────
863
1153
  Heading: { tag: "h1" }, // resolved dynamically by level attr
864
1154
  Paragraph: { tag: "p" },
865
- // === v0.0.15: SubHeading convenience component ===
1155
+ // === v0.1.0: SubHeading convenience component ===
866
1156
  SubHeading: { tag: "p", defaultClass: "subheading" },
867
1157
  Lead: { tag: "p", defaultClass: "lead" },
868
1158
  Small: { tag: "small" },
@@ -929,7 +1219,7 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
929
1219
  Wbr: { tag: "wbr", voidEl: true },
930
1220
  Source: { tag: "source", voidEl: true },
931
1221
  Embed: { tag: "embed", voidEl: true },
932
- // === v0.0.15: Col = HTML void table column (NOT the grid div) ===
1222
+ // === v0.1.0: Col = HTML void table column (NOT the grid div) ===
933
1223
  Col: { tag: "col", voidEl: true },
934
1224
  Area: { tag: "area", voidEl: true },
935
1225
  // ── Lists ─────────────────────────────────────────────────
@@ -949,9 +1239,9 @@ const BUILTIN_MAP: Record<string, BuiltinInfo> = {
949
1239
  Template: { tag: "template" },
950
1240
  Slot: { tag: "slot" },
951
1241
  NoScript: { tag: "noscript" },
952
- // === v0.0.15: CardGrid convenience layout wrapper ===
1242
+ // === v0.1.0: CardGrid convenience layout wrapper ===
953
1243
  CardGrid: { tag: "div", defaultClass: "card-grid" },
954
- // === v0.0.15: RawHTML marker — handled specially in renderCompUse ===
1244
+ // === v0.1.0: RawHTML marker — handled specially in renderCompUse ===
955
1245
  RawHTML: { tag: "__RAW__" },
956
1246
  };
957
1247
 
@@ -970,7 +1260,7 @@ function eventAttrName(name: string): string | null {
970
1260
  // SECTION 7: STYLE PROCESSOR
971
1261
  // ═══════════════════════════════════════════════════════════
972
1262
 
973
- // === v0.0.15: Completely rewritten convertCSSProps — bulletproof line-by-line approach ===
1263
+ // === v0.1.0: Completely rewritten convertCSSProps — bulletproof line-by-line approach ===
974
1264
  // Rules:
975
1265
  // - Match lines of the form: [whitespace] camelCaseProp : "value" [;]
976
1266
  // - Convert property name camelCase → kebab-case
@@ -1024,7 +1314,7 @@ function convertCSSProps(css: string): string {
1024
1314
  }).join("\n");
1025
1315
  }
1026
1316
 
1027
- // === v0.0.15: processStyleBlock — correct order: interpolate {param} → camelCase convert → SCSS → scope ===
1317
+ // === v0.1.0: processStyleBlock — correct order: interpolate {param} → camelCase convert → SCSS → scope ===
1028
1318
  function processStyleBlock(
1029
1319
  block: StyleBlock,
1030
1320
  hash: string,
@@ -1193,14 +1483,30 @@ function resolveBuiltinTag(
1193
1483
  function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
1194
1484
  const { name, value } = attr;
1195
1485
 
1196
- if (value === null) return name; // shorthand boolean true
1197
- if (value.kind === "null") return ""; // omit attribute entirely
1198
- if (value.kind === "bool") return value.value ? name : ""; // true → name, false → omit
1486
+ if (value === null) return name;
1487
+ if (value.kind === "null") return "";
1488
+ if (value.kind === "bool") return value.value ? name : "";
1199
1489
  if (value.kind === "num") return `${name}="${value.value}"`;
1200
1490
 
1201
- // String value — interpolate {param}, then emit
1202
1491
  let raw = value.value;
1203
- raw = interpolateAttr(raw, paramMap);
1492
+
1493
+ // Check for inline expression
1494
+ if (raw.startsWith("__EXPR__")) {
1495
+ const exprJson = raw.substring("__EXPR__".length);
1496
+ try {
1497
+ const expr: Expression = JSON.parse(exprJson);
1498
+ const jsExpr = compileExprToJS(expr);
1499
+ const ev = eventAttrName(name);
1500
+ if (ev) {
1501
+ return `${ev}="(function(){ ${jsExpr}; })()"`;
1502
+ }
1503
+ return `${name}="${escAttr(jsExpr)}"`;
1504
+ } catch {
1505
+ // Fall through to normal handling
1506
+ }
1507
+ }
1508
+
1509
+ raw = interpolateAttr(raw, paramMap);
1204
1510
 
1205
1511
  const ev = eventAttrName(name);
1206
1512
  if (ev) {
@@ -1210,7 +1516,7 @@ function renderAttr(attr: Attr, paramMap: Map<string, string>): string {
1210
1516
  return `${name}="${escAttr(raw)}"`;
1211
1517
  }
1212
1518
 
1213
- // === v0.0.15: renderText — "$slot" protected from double-escaping via placeholder approach ===
1519
+ // === v0.1.0: renderText — "$slot" protected from double-escaping via placeholder approach ===
1214
1520
  function renderText(text: string, params: Map<string, string>): string {
1215
1521
  // Map of placeholder → raw HTML for slot-like params
1216
1522
  const rawSlots = new Map<string, string>();
@@ -1248,7 +1554,7 @@ function renderText(text: string, params: Map<string, string>): string {
1248
1554
  // Step 5: Restore \$ → $
1249
1555
  s = s.replace(/\x00DOLLAR\x00/g, "$");
1250
1556
 
1251
- // === v0.0.15: Warn about {identifier} patterns remaining after substitution ===
1557
+ // === v0.1.0: Warn about {identifier} patterns remaining after substitution ===
1252
1558
  const braceRe = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g;
1253
1559
  let m: RegExpExecArray | null;
1254
1560
  while ((m = braceRe.exec(s)) !== null) {
@@ -1275,6 +1581,21 @@ function renderChild(
1275
1581
  ): string {
1276
1582
  if (depth > 64) throw new SinthError("Maximum component nesting depth (64) exceeded.");
1277
1583
  if (child.kind === "text") return renderText(child.value, params);
1584
+ if (child.kind === "expr") {
1585
+ const jsExpr = compileExprToJS(child.expression);
1586
+ return `<span class="sinth-expr" data-expr="${escAttr(jsExpr)}"></span>`;
1587
+ }
1588
+ if (child.kind === "if") {
1589
+ const condJS = compileExprToJS(child.condition);
1590
+ const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1591
+ const elseHTML = child.elseBody ? child.elseBody.map(c => renderChild(c, ctx, params, depth + 1)).join("") : "";
1592
+ return `<template data-sinth-if="${escAttr(condJS)}">${bodyHTML}</template>` +
1593
+ (elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "");
1594
+ }
1595
+ if (child.kind === "for") {
1596
+ const bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1597
+ return `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(child.itemVar)}">${bodyHTML}</template>`;
1598
+ }
1278
1599
  return renderCompUse(child, ctx, params, depth);
1279
1600
  }
1280
1601
 
@@ -1284,7 +1605,7 @@ function renderCompUse(
1284
1605
  params: Map<string, string>,
1285
1606
  depth: number,
1286
1607
  ): string {
1287
- // === v0.0.15: RawHTML — output content attribute verbatim, no wrapping tag, no scoping ===
1608
+ // === v0.1.0: RawHTML — output content attribute verbatim, no wrapping tag, no scoping ===
1288
1609
  if (use.name === "RawHTML") {
1289
1610
  const ca = use.attrs.find(a => a.name === "content");
1290
1611
  if (!ca || !ca.value) return "";
@@ -1329,7 +1650,7 @@ function renderCompUse(
1329
1650
  const classes = [defaultClass, userClass].filter(Boolean).join(" ");
1330
1651
  if (classes) attrParts.push(`class="${escAttr(classes)}"`);
1331
1652
 
1332
- // === v0.0.15: Default type="button" for <button> elements ===
1653
+ // === v0.1.0: Default type="button" for <button> elements ===
1333
1654
  if (tag === "button" && !use.attrs.some(a => a.name === "type")) {
1334
1655
  attrParts.push(`type="button"`);
1335
1656
  }
@@ -1391,7 +1712,7 @@ function expandUserComp(
1391
1712
  const slotHTML = use.children.map(c => renderChild(c, ctx, params, depth)).join("");
1392
1713
  local.set("slot", slotHTML);
1393
1714
 
1394
- // === v0.0.15: Process component style blocks with instance params and push to extraCSS ===
1715
+ // === v0.1.0: Process component style blocks with instance params and push to extraCSS ===
1395
1716
  for (const block of def.styles) {
1396
1717
  ctx.extraCSS.push(processStyleBlock(block, ctx.scopeHash, local));
1397
1718
  }
@@ -1399,6 +1720,38 @@ function expandUserComp(
1399
1720
  return def.body.map(c => renderChild(c, ctx, local, depth)).join("");
1400
1721
  }
1401
1722
 
1723
+ // === v0.1.0: Expression to JS helper ===
1724
+ function compileExprToJS(expr: Expression): string {
1725
+ switch (expr.kind) {
1726
+ case "literal":
1727
+ if (!expr.value) return "null";
1728
+ if (expr.value.kind === "str") return JSON.stringify((expr.value as LitStr).value);
1729
+ if (expr.value.kind === "num") return String((expr.value as LitNum).value);
1730
+ if (expr.value.kind === "bool") return String((expr.value as LitBool).value);
1731
+ return "null";
1732
+ case "variable":
1733
+ return expr.name || "undefined";
1734
+ case "binary": {
1735
+ const left = compileExprToJS(expr.left!);
1736
+ const right = compileExprToJS(expr.right!);
1737
+ const op = expr.op === "and" ? "&&" : expr.op === "or" ? "||" : expr.op;
1738
+ return `(${left} ${op} ${right})`;
1739
+ }
1740
+ case "unary": {
1741
+ const op = expr.op === "not" ? "!" : expr.op;
1742
+ return `${op}(${compileExprToJS(expr.operand!)})`;
1743
+ }
1744
+ case "assign": {
1745
+ const val = expr.right ? compileExprToJS(expr.right) : "null";
1746
+ return `${expr.target} ${expr.op} ${val}`;
1747
+ }
1748
+ case "postfix":
1749
+ return `${expr.target}${expr.op}`;
1750
+ default:
1751
+ return "";
1752
+ }
1753
+ }
1754
+
1402
1755
  // ═══════════════════════════════════════════════════════════
1403
1756
  // SECTION 9: SCRIPT COLLECTOR
1404
1757
  // ═══════════════════════════════════════════════════════════
@@ -1492,7 +1845,7 @@ function buildHeadData(meta: MetaEntry[]): HeadData {
1492
1845
  return { title, fav, lang, charset, viewport, metaTags, metaProps };
1493
1846
  }
1494
1847
 
1495
- // === v0.0.15: .jpg and .jpeg return "image/jpeg" ===
1848
+ // === v0.1.0: .jpg and .jpeg return "image/jpeg" ===
1496
1849
  function faviconType(p: string): string {
1497
1850
  const ext = path.extname(p).toLowerCase();
1498
1851
  switch (ext) {
@@ -1555,7 +1908,7 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
1555
1908
  const { allDefs, customEls, cssLinks, jsLinks } = resolveImports(file, cfg);
1556
1909
  const hash = fnv1a(absPath);
1557
1910
 
1558
- // === v0.0.15: extraCSS collected during rendering (per-instance component styles) ===
1911
+ // === v0.1.0: extraCSS collected during rendering (per-instance component styles) ===
1559
1912
  const ctx: CompileCtx = {
1560
1913
  allDefs, customEls, cssLinks, jsLinks,
1561
1914
  scopeHash: hash, pageFile: absPath, extraCSS: [],
@@ -1619,8 +1972,80 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
1619
1972
  head,
1620
1973
  `<body data-s="${hash}">`,
1621
1974
  bodyHTML,
1622
- scriptTags.join("\n"),
1623
- "</body>",
1975
+ `<script>
1976
+ // v0.2.0: Sinth variable declarations
1977
+ ${file.varDecls.map(v => {
1978
+ const val = litToString(v.value);
1979
+ if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
1980
+ return `let ${v.name} = ${val};`;
1981
+ }).join("\n")}
1982
+
1983
+ // v0.2.0: Store original page HTML for full re-render
1984
+ const _sinthBodyHTML = document.body.innerHTML;
1985
+
1986
+ function sinthRender() {
1987
+ // Save current scroll position
1988
+ const scrollX = window.scrollX;
1989
+ const scrollY = window.scrollY;
1990
+
1991
+ // Re-render the entire body from the original HTML
1992
+ document.body.innerHTML = _sinthBodyHTML;
1993
+
1994
+ // Re-process all templates recursively
1995
+ function processTemplates(root) {
1996
+ root.querySelectorAll('template[data-sinth-if]').forEach(t => {
1997
+ const cond = new Function('return ' + t.dataset.sinthIf)();
1998
+ if (cond) {
1999
+ const frag = document.createRange().createContextualFragment(t.innerHTML);
2000
+ t.replaceWith(frag);
2001
+ processTemplates(root); // Re-process in case templates were nested
2002
+ } else {
2003
+ const elseT = t.nextElementSibling;
2004
+ if (elseT && elseT.matches && elseT.matches('template[data-sinth-else]')) {
2005
+ const frag = document.createRange().createContextualFragment(elseT.innerHTML);
2006
+ elseT.replaceWith(frag);
2007
+ processTemplates(root);
2008
+ }
2009
+ t.remove();
2010
+ }
2011
+ });
2012
+ root.querySelectorAll('template[data-sinth-for]').forEach(t => {
2013
+ const arr = eval(t.dataset.sinthFor);
2014
+ if (arr && Array.isArray(arr)) {
2015
+ const frag = document.createDocumentFragment();
2016
+ arr.forEach(item => {
2017
+ window[t.dataset.sinthItem] = item;
2018
+ frag.append(document.createRange().createContextualFragment(t.innerHTML));
2019
+ });
2020
+ t.replaceWith(frag);
2021
+ processTemplates(root);
2022
+ }
2023
+ });
2024
+ }
2025
+ processTemplates(document.body);
2026
+
2027
+ // Update all expression spans
2028
+ document.querySelectorAll('.sinth-expr').forEach(el => {
2029
+ try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2030
+ });
2031
+
2032
+ // Update onclick handlers
2033
+ document.querySelectorAll('[onclick]').forEach(el => {
2034
+ const oc = el.getAttribute('onclick');
2035
+ if (oc && oc.startsWith('(function(){') && !oc.includes('sinthRender()')) {
2036
+ const inner = oc.slice(12, -4);
2037
+ el.setAttribute('onclick', '(function(){' + inner + ';sinthRender();})()');
2038
+ }
2039
+ });
2040
+
2041
+ // Restore scroll
2042
+ window.scrollTo(scrollX, scrollY);
2043
+ }
2044
+
2045
+ // Initial render
2046
+ sinthRender();
2047
+ </script>`,
2048
+ scriptTags.join("\n"), "</body>",
1624
2049
  "</html>",
1625
2050
  ].join("\n");
1626
2051
 
@@ -1635,7 +2060,7 @@ function minifyHTML(html: string): string {
1635
2060
  // SECTION 12: FILE DISCOVERY & ASSET COPY
1636
2061
  // ═══════════════════════════════════════════════════════════
1637
2062
 
1638
- // === v0.0.15: findSinthPages skips outDir to prevent infinite watcher loops ===
2063
+ // === v0.1.0: findSinthPages skips outDir to prevent infinite watcher loops ===
1639
2064
  function findSinthPages(dir: string, outDir?: string): string[] {
1640
2065
  const results: string[] = [];
1641
2066
  for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
@@ -1651,7 +2076,7 @@ function findSinthPages(dir: string, outDir?: string): string[] {
1651
2076
  return results;
1652
2077
  }
1653
2078
 
1654
- // === v0.0.15: Recursive directory copy for assets/ ===
2079
+ // === v0.1.0: Recursive directory copy for assets/ ===
1655
2080
  function copyDir(src: string, dest: string): void {
1656
2081
  if (!fs.existsSync(src)) return;
1657
2082
  fs.mkdirSync(dest, { recursive: true });
@@ -1710,7 +2135,7 @@ async function startDevServer(opts: CompileOptions & { port: number, files?: str
1710
2135
 
1711
2136
  compileAll();
1712
2137
 
1713
- // === v0.0.15: Watch ignores changes whose absolute path is inside outDir ===
2138
+ // === v0.1.0: Watch ignores changes whose absolute path is inside outDir ===
1714
2139
  const resolvedOut = path.resolve(opts.outDir);
1715
2140
  // Use fs.watch with fs.watchFile fallback for Windows reliability
1716
2141
  let watchReady = false;
@@ -1872,7 +2297,7 @@ async function main(): Promise<void> {
1872
2297
  }
1873
2298
  }
1874
2299
 
1875
- // === v0.0.18: Copy assets/ to outDir/assets/ ===
2300
+ // === v0.1.0: Copy assets/ to outDir/assets/ ===
1876
2301
  const assetsIn = path.join(cwd, "assets");
1877
2302
  const assetsOut = path.join(outDir, "assets");
1878
2303
  if (fs.existsSync(assetsIn)) {
@@ -1893,6 +2318,11 @@ async function main(): Promise<void> {
1893
2318
  process.stdout.write(` \x1b[32m✓\x1b[0m libraries/ → ${path.relative(cwd, libOut)}/\n`);
1894
2319
  }
1895
2320
 
2321
+ process.stdout.write(`\n\x1b[1mBuilt ${built} page(s)\x1b[0m${hadError ? " with errors" : ""}\n`);
2322
+ process.exit(hadError ? 1 : 0);
2323
+ break;
2324
+ }
2325
+
1896
2326
  case "dev": {
1897
2327
  const fileArgs = cleanArgs.filter(a => a.endsWith(".sinth"));
1898
2328
  const files = fileArgs.length > 0
@@ -1919,7 +2349,7 @@ async function main(): Promise<void> {
1919
2349
  break;
1920
2350
  }
1921
2351
 
1922
- // === v0.0.15: sinth version command ===
2352
+ // === v0.1.0: sinth version command ===
1923
2353
  case "version":
1924
2354
  case "--version":
1925
2355
  case "-v": {
@@ -1937,7 +2367,7 @@ async function main(): Promise<void> {
1937
2367
 
1938
2368
  default: {
1939
2369
  process.stdout.write(`
1940
- \x1b[1mSinth Compiler v0.0.15\x1b[0m
2370
+ \x1b[1mSinth Compiler v0.1.0\x1b[0m
1941
2371
 
1942
2372
  \x1b[1mCommands:\x1b[0m
1943
2373
  sinth build [--out ./dist] [--prod] Compile all .sinth pages + copy assets/