@yannosay/sinth 0.1.0 → 0.2.1

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 +160 -24
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.1.0",
3
+ "version": "0.2.1",
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
@@ -13,7 +13,7 @@ interface Loc { file: string; line: number; col: number }
13
13
 
14
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,
@@ -245,7 +245,8 @@ export class Lexer {
245
245
  if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
246
246
  if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
247
247
  if (ch === "=") { tokens.push(this.single(TT.EQUALS, loc)); continue; }
248
- 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; }
249
250
 
250
251
  // v0.1.0: Logic operators
251
252
  if (ch === "+") { tokens.push(this.single(TT.OP_PLUS, loc)); continue; }
@@ -470,6 +471,7 @@ export class Lexer {
470
471
 
471
472
  export class Parser {
472
473
  private pos = 0;
474
+ private loopVar: string | null = null;
473
475
 
474
476
  constructor(private tokens: Token[], private file: string) {}
475
477
 
@@ -483,6 +485,7 @@ export class Parser {
483
485
  const styles: StyleBlock[] = [];
484
486
  const scripts: ScriptBlock[] = [];
485
487
  const customEls: CustomElDecl[] = [];
488
+ const varDecls: VarDeclaration[] = [];
486
489
 
487
490
  // 1. Optional page keyword
488
491
  if (this.check(TT.KW_PAGE)) { this.consume(TT.KW_PAGE); isPage = true; }
@@ -492,6 +495,10 @@ export class Parser {
492
495
 
493
496
  // 3. Metadata — key = value pairs (lexer has already stripped comments/whitespace)
494
497
  while (this.isMetaStart()) {
498
+ const keyName = this.tokens[this.pos].value;
499
+ if (varDecls.some(v => v.name === keyName)) {
500
+ break;
501
+ }
495
502
  const entry = this.parseMeta();
496
503
  meta.push(entry);
497
504
  if (entry.key === "title") isPage = true;
@@ -499,7 +506,6 @@ export class Parser {
499
506
 
500
507
  // 4. Body: component definitions, usages, style, script, custom-element
501
508
  // 4a. Variable declarations (v0.1.0 logic)
502
- const varDecls: VarDeclaration[] = [];
503
509
  while (this.check(TT.IDENT) && this.peek().value === "var") {
504
510
  const vd = this.parseVarDeclaration();
505
511
  if (vd) varDecls.push(vd);
@@ -511,7 +517,30 @@ export class Parser {
511
517
  else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
512
518
  else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
513
519
  else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
514
- else if (this.check(TT.IDENT)) { uses.push(this.parseCompUse()); }
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
+ }
515
544
  else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
516
545
  }
517
546
 
@@ -564,14 +593,31 @@ export class Parser {
564
593
  this.consume(TT.IDENT); // 'var'
565
594
 
566
595
  const typeTok = this.consume(TT.IDENT);
567
- const typeStr = typeTok.value;
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
+
568
603
  if (!["int", "str", "bool", "str[]"].includes(typeStr)) {
569
604
  throw new SinthError(`Unknown type '${typeStr}'. Expected int, str, bool, or str[]`, typeTok.loc);
570
605
  }
571
606
 
572
607
  const nameTok = this.consume(TT.IDENT);
573
- this.consume(TT.EQUALS);
574
- const val = this.parseLiteral();
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
+ }
575
621
 
576
622
  return {
577
623
  kind: "var",
@@ -582,11 +628,39 @@ export class Parser {
582
628
  };
583
629
  }
584
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
+
585
659
 
586
660
  // ── Expression parsing (v0.1.0) ────────────────────────
587
661
  private parseExpression(): Expression | null {
588
662
  const tok = this.peek();
589
-
663
+
590
664
  // Unary 'not'
591
665
  if (tok.type === TT.IDENT && tok.value === "not") {
592
666
  this.consume(TT.IDENT); // consume 'not'
@@ -656,18 +730,17 @@ export class Parser {
656
730
  if (this.check(TT.OP_PLUS) || this.check(TT.OP_MINUS) || this.check(TT.EQUALS)) {
657
731
  const opTok = this.peek();
658
732
 
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);
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) {
663
736
  const right = this.parseExpression();
664
737
  if (!right) throw new SinthError("Expected expression after +=", this.peek().loc);
665
738
  return { kind: "assign", target: name, op: "+=", right };
666
739
  }
667
740
 
668
741
  // -=
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);
742
+ if (opTok.type === TT.OP_MINUS && nextTok && nextTok.type === TT.EQUALS) {
743
+ this.consume(TT.OP_MINUS);
671
744
  this.consume(TT.EQUALS);
672
745
  const right = this.parseExpression();
673
746
  if (!right) throw new SinthError("Expected expression after -=", this.peek().loc);
@@ -729,7 +802,9 @@ export class Parser {
729
802
  this.consume(TT.LPAREN);
730
803
  while (!this.check(TT.RPAREN)) {
731
804
  const ploc = this.peek().loc;
732
- const pname = this.consume(TT.IDENT).value;
805
+ // allow keywords as parameter names (e.g., "for" in custom-element declarations)
806
+ const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
807
+ const pname = nameTok.value;
733
808
  let defaultVal: Literal | undefined;
734
809
  if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
735
810
  params.push({ name: pname, defaultVal, loc: ploc });
@@ -850,7 +925,9 @@ export class Parser {
850
925
  let body: Child[];
851
926
  if (this.check(TT.LBRACE)) {
852
927
  this.consume(TT.LBRACE);
928
+ this.loopVar = itemVar;
853
929
  body = this.parseChildList();
930
+ this.loopVar = null;
854
931
  this.consume(TT.RBRACE);
855
932
  } else {
856
933
  body = [];
@@ -869,18 +946,16 @@ export class Parser {
869
946
  if (this.check(TT.STRING)) {
870
947
  const loc = this.peek().loc;
871
948
  const strVal = this.consume(TT.STRING).value;
872
- // Check if followed by +
873
949
  if (this.check(TT.OP_PLUS)) {
874
950
  this.consume(TT.OP_PLUS);
875
951
  const rightExpr = this.parseExpression();
876
952
  if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
877
- const expr: Expression = {
953
+ children.push({ kind: "expr", expression: {
878
954
  kind: "binary",
879
955
  left: { kind: "literal", value: { kind: "str", value: strVal } },
880
956
  op: "+",
881
957
  right: rightExpr,
882
- };
883
- children.push({ kind: "expr", expression: expr, loc });
958
+ }, loc });
884
959
  } else {
885
960
  children.push({ kind: "text", value: strVal, loc });
886
961
  }
@@ -889,7 +964,39 @@ export class Parser {
889
964
  } else if (this.check(TT.KW_FOR)) {
890
965
  children.push(this.parseForLoop());
891
966
  } else if (this.check(TT.IDENT)) {
892
- children.push(this.parseCompUse());
967
+ // Check if next token is + (variable + something)
968
+ if (this.tokens[this.pos + 1]?.type === TT.OP_PLUS) {
969
+ const loc = this.peek().loc;
970
+ const varName = this.consume(TT.IDENT).value;
971
+ this.consume(TT.OP_PLUS); // consume +
972
+ // Check if what follows is a string
973
+ if (this.check(TT.STRING)) {
974
+ const rightStr = this.consume(TT.STRING).value;
975
+ children.push({ kind: "expr", expression: {
976
+ kind: "binary",
977
+ left: { kind: "variable", name: varName },
978
+ op: "+",
979
+ right: { kind: "literal", value: { kind: "str", value: rightStr } },
980
+ }, loc });
981
+ } else {
982
+ // variable + expression
983
+ const rightExpr = this.parseExpression();
984
+ if (rightExpr) {
985
+ children.push({ kind: "expr", expression: {
986
+ kind: "binary",
987
+ left: { kind: "variable", name: varName },
988
+ op: "+",
989
+ right: rightExpr,
990
+ }, loc });
991
+ }
992
+ }
993
+ } else if (this.loopVar && this.peek().value === this.loopVar) {
994
+ const loc = this.peek().loc;
995
+ const name = this.consume(TT.IDENT).value;
996
+ children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
997
+ } else {
998
+ children.push(this.parseCompUse());
999
+ }
893
1000
  } else {
894
1001
  throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
895
1002
  }
@@ -942,6 +1049,7 @@ export class Parser {
942
1049
 
943
1050
  private parseLiteral(): Literal {
944
1051
  const tok = this.peek();
1052
+ if (this.check(TT.LBRACKET)) { return this.parseArrayLiteral(); }
945
1053
  if (this.check(TT.STRING)) { this.consume(TT.STRING); return { kind: "str", value: tok.value }; }
946
1054
  if (this.check(TT.NUMBER)) { this.consume(TT.NUMBER); return { kind: "num", value: parseFloat(tok.value) }; }
947
1055
  if (this.check(TT.BOOL_TRUE)) { this.consume(TT.BOOL_TRUE); return { kind: "bool", value: true }; }
@@ -1593,8 +1701,19 @@ function renderChild(
1593
1701
  (elseHTML ? `<template data-sinth-else>${elseHTML}</template>` : "");
1594
1702
  }
1595
1703
  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>`;
1704
+ let bodyHTML = child.body.map(c => renderChild(c, ctx, params, depth + 1)).join("");
1705
+ // Replace component tags for the loop variable with expression spans
1706
+ const itemVar = child.itemVar;
1707
+ bodyHTML = bodyHTML.replace(
1708
+ new RegExp(`<${itemVar}[^>]*>(.*?)</${itemVar}>`, 'g'),
1709
+ (_, content) => {
1710
+ if (!content || content.trim() === '') {
1711
+ return `<span class="sinth-expr" data-expr="${itemVar}"></span>`;
1712
+ }
1713
+ return `<span class="sinth-expr" data-expr="${itemVar}">${content}</span>`;
1714
+ }
1715
+ );
1716
+ return `<template data-sinth-for="${escAttr(child.arrayVar)}" data-sinth-item="${escAttr(itemVar)}">${bodyHTML}</template>`;
1598
1717
  }
1599
1718
  return renderCompUse(child, ctx, params, depth);
1600
1719
  }
@@ -1975,7 +2094,20 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
1975
2094
  `<script>
1976
2095
  // v0.2.0: Sinth variable declarations
1977
2096
  ${file.varDecls.map(v => {
2097
+ if (!v.value) return `let ${v.name};`; // uninitialized
1978
2098
  const val = litToString(v.value);
2099
+
2100
+ // Variable reference: __VAR__count → count
2101
+ if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
2102
+ const refName = val.slice(7);
2103
+ return `let ${v.name} = ${refName};`;
2104
+ }
2105
+
2106
+ // Array literal: __ARR__["a","b"]
2107
+ if (val.startsWith("__ARR__")) {
2108
+ return `let ${v.name} = ${val.slice(7)};`;
2109
+ }
2110
+
1979
2111
  if (v.varType === "str") return `let ${v.name} = ${JSON.stringify(val)};`;
1980
2112
  return `let ${v.name} = ${val};`;
1981
2113
  }).join("\n")}
@@ -2012,10 +2144,14 @@ function sinthRender() {
2012
2144
  root.querySelectorAll('template[data-sinth-for]').forEach(t => {
2013
2145
  const arr = eval(t.dataset.sinthFor);
2014
2146
  if (arr && Array.isArray(arr)) {
2147
+ const itemName = t.dataset.sinthItem;
2015
2148
  const frag = document.createDocumentFragment();
2016
2149
  arr.forEach(item => {
2017
- window[t.dataset.sinthItem] = item;
2018
- frag.append(document.createRange().createContextualFragment(t.innerHTML));
2150
+ // Fill the expression spans with the actual loop value BEFORE adding to DOM
2151
+ let itemHTML = t.innerHTML;
2152
+ const regex = new RegExp('<span class="sinth-expr" data-expr="' + itemName + '"></span>', 'g');
2153
+ itemHTML = itemHTML.replace(regex, '<span class="sinth-expr" data-expr="' + itemName + '">' + item + '</span>');
2154
+ frag.append(document.createRange().createContextualFragment(itemHTML));
2019
2155
  });
2020
2156
  t.replaceWith(frag);
2021
2157
  processTemplates(root);