@yannosay/sinth 0.11.0 → 0.13.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/README.md CHANGED
@@ -1,7 +1,9 @@
1
1
  # Sinth
2
2
 
3
3
  The language that fixes HTML. Declarative. Reactive. Compiles to pure HTML.
4
+
4
5
  Find out more: https://www.youtube.com/watch?v=W0tOMTiIF0Q
6
+ Discord: [Join here!](https://discord.gg/SUvcrafTQm)
5
7
 
6
8
 
7
9
  [![npm version](https://img.shields.io/npm/v/@yannosay/sinth)](https://www.npmjs.com/package/@yannosay/sinth)
@@ -52,7 +54,32 @@ Div {
52
54
  (renderHeading(userName))
53
55
  (renderHeading("This renders!"))
54
56
  ```
57
+ or
58
+
59
+ ```ts
60
+ page
61
+
62
+ title = "Checkbox Test"
63
+
64
+ var bool isAdmin = false
65
+
66
+ function toggleAdmin() {
67
+ isAdmin = not isAdmin
68
+ }
69
+
70
+ function getStatus() -> str {
71
+ if (isAdmin) {
72
+ return "ON"
73
+ }
74
+ return "OFF"
75
+ }
55
76
 
77
+ Checkbox(checked: isAdmin, onChange: toggleAdmin(), label: "Admin mode?")
78
+
79
+ Paragraph {
80
+ "Admin mode is " + (getStatus()) + "! :D"
81
+ }
82
+ ```
56
83
 
57
84
 
58
85
  #### Animations that make sense.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.11.0",
3
+ "version": "0.13.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",
@@ -1,6 +1,6 @@
1
1
  import * as path from "path";
2
2
  import * as fs from "fs";
3
- import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";import { Lexer } from "./lexer.ts";
3
+ import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, StyleBlock, CompDef, ParamDecl, VarDeclaration, SinthFile, CompileCtx, MixedBlockEntry, SinthError, SinthWarning, TT, AssignStmt, MetaEntry } from "./types.ts";
4
4
  import { Parser } from "./parser.ts";
5
5
  import { fnv1a, camelToKebab, esc, escAttr, litToString, tagNameToPascal } from "../utils.ts";
6
6
  import { compileExprToJS, compileIfToJS, bodyToJS } from "./expr.ts";
@@ -637,15 +637,49 @@ export function renderChild(
637
637
  localParams.set(fnDef.params[i].name, "__VAR__" + arg.name);
638
638
  }
639
639
  }
640
- return fnDef.body.map(c => {
641
- if (c.kind === "expr" && c.expression.kind === "variable" && localParams.has(c.expression.name!)) {
642
- return localParams.get(c.expression.name!)!;
640
+ const substituteExpr = (expr: Expression, pm: Map<string, string>): Expression => {
641
+ if (expr.kind === "variable" && pm.has(expr.name!)) {
642
+ const pv = pm.get(expr.name!)!;
643
+ if (pv.startsWith("__LIT__")) return { kind: "literal", value: { kind: "str", value: pv.slice(7) } };
644
+ return { kind: "variable", name: pv.slice(7) };
645
+ }
646
+ if (expr.kind === "binary") return { ...expr, left: substituteExpr(expr.left!, pm), right: substituteExpr(expr.right!, pm) };
647
+ if (expr.kind === "unary") return { ...expr, operand: substituteExpr(expr.operand!, pm) };
648
+ if (expr.kind === "call") return { ...expr, callee: substituteExpr(expr.callee!, pm), args: expr.args?.map(a => substituteExpr(a, pm)) };
649
+ if (expr.kind === "index") return { ...expr, object: substituteExpr(expr.object!, pm), key: substituteExpr(expr.key!, pm) };
650
+ if (expr.kind === "assign") return { ...expr, right: expr.right ? substituteExpr(expr.right, pm) : undefined };
651
+ return expr;
652
+ };
653
+ const substituteChild = (c: Child, pm: Map<string, string>): Child => {
654
+ if (c.kind === "expr") return { ...c, expression: substituteExpr(c.expression, pm) };
655
+ if (c.kind === "assign_stmt") return { ...c, expression: substituteExpr(c.expression, pm) as Expression };
656
+ if (c.kind === "return" && (c as ReturnStmt).expression) return { ...c, expression: substituteExpr((c as ReturnStmt).expression!, pm) } as Child;
657
+ if (c.kind === "if") {
658
+ const ib = c as IfBlock;
659
+ return { ...ib, condition: substituteExpr(ib.condition, pm), body: ib.body.map(bc => substituteChild(bc, pm)), elseBody: ib.elseBody?.map(bc => substituteChild(bc, pm)) };
660
+ }
661
+ if (c.kind === "for") {
662
+ const fl = c as ForLoop;
663
+ return { ...fl, body: fl.body.map(bc => substituteChild(bc, pm)) };
643
664
  }
644
665
  if (c.kind === "use") {
645
- return renderCompUse(c, ctx, localParams, depth + 1);
666
+ const u = c as CompUse;
667
+ const sa: Attr[] = u.attrs.map(a => {
668
+ if (a.value?.kind === "str") {
669
+ let raw = a.value.value;
670
+ for (const [pn, pv] of pm) {
671
+ if (pv.startsWith("__LIT__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
672
+ if (pv.startsWith("__VAR__")) raw = raw.replace(new RegExp(`\\b${pn}\\b`, 'g'), pv.slice(7));
673
+ }
674
+ return { ...a, value: { kind: "str" as const, value: raw } };
675
+ }
676
+ return a;
677
+ });
678
+ return { ...u, attrs: sa, children: u.children.map(cc => substituteChild(cc, pm)) };
646
679
  }
647
- return renderChild(c, ctx, localParams, depth + 1);
648
- }).join("");
680
+ return c;
681
+ };
682
+ return fnDef.body.map(c => renderChild(substituteChild(c, localParams), ctx, localParams, depth + 1)).join("");
649
683
  }
650
684
  }
651
685
  if (child.expression.kind === "literal" && child.expression.value) {
@@ -666,7 +700,12 @@ export function renderChild(
666
700
 
667
701
  case "remove": {
668
702
  return `<span data-sinth-remove="${esc((child as RemoveStmt).target)}"></span>`;
669
- }
703
+ }
704
+
705
+ case "return":
706
+ return "";
707
+
708
+
670
709
 
671
710
  case "if":
672
711
  return renderIfBlock(child, ctx, params, depth);
@@ -847,6 +886,7 @@ export function renderCompUse(
847
886
  if (attr.value?.kind === "str") userClass = interpolateAttr(attr.value.value, params);
848
887
  continue;
849
888
  }
889
+ if (use.name === "Checkbox" && (attr.name === "checked" || attr.name === "onChange" || attr.name === "label")) continue;
850
890
  const rendered = renderAttr(attr, params, ctx);
851
891
  if (rendered) attrParts.push(rendered);
852
892
  }
@@ -874,17 +914,61 @@ export function renderCompUse(
874
914
  }
875
915
  if (use.name === "Checkbox") {
876
916
  if (!use.attrs.some(a => a.name === "type")) attrParts.push(`type="checkbox"`);
877
- const bindAttr = use.attrs.find(a => a.name === "bind");
878
- if (bindAttr?.value?.kind === "str") {
879
- let vName = bindAttr.value.value;
880
- if (vName.startsWith("__EXPR__")) {
917
+
918
+ const checkedAttr = use.attrs.find(a => a.name === "checked");
919
+ if (checkedAttr && checkedAttr.value) {
920
+ if (checkedAttr.value.kind === "bool") {
921
+ if (checkedAttr.value.value) attrParts.push(`checked`);
922
+ } else if (checkedAttr.value.kind === "str") {
923
+ let raw = checkedAttr.value.value;
924
+ if (raw.startsWith("__EXPR__")) {
925
+ try {
926
+ const expr: Expression = JSON.parse(raw.substring(8));
927
+ if (expr.kind === "variable" && expr.name) {
928
+ attrParts.push(`data-sinth-checked="${escAttr(expr.name)}"`);
929
+ } else {
930
+ const exprId = registerExpr(ctx, expr);
931
+ attrParts.push(`data-sinth-checked-expr="${exprId}"`);
932
+ }
933
+ } catch {}
934
+ } else {
935
+ attrParts.push(`data-sinth-checked="${escAttr(raw)}"`);
936
+ }
937
+ }
938
+ }
939
+
940
+ const onChangeAttr = use.attrs.find(a => a.name === "onChange");
941
+ if (onChangeAttr && onChangeAttr.value?.kind === "str") {
942
+ let raw = onChangeAttr.value.value;
943
+ if (raw.startsWith("__EXPR__")) {
881
944
  try {
882
- const expr: Expression = JSON.parse(vName.substring(8));
883
- if (expr.kind === "variable" && expr.name) vName = expr.name;
945
+ const expr: Expression = JSON.parse(raw.substring(8));
946
+ const jsExpr = compileExprToJS(expr);
947
+ attrParts.push(`onchange="(function(){ ${jsExpr}; sinthRender(); })(event)"`);
884
948
  } catch {}
949
+ } else {
950
+ attrParts.push(`onchange="${escAttr(raw)};sinthRender()"`);
885
951
  }
886
- attrParts.push(`onchange="(function(e){ ${vName} = e.target.checked; sinthRender(); })(event)"`);
887
- attrParts.push(`data-sinth-checked="${escAttr(vName)}"`);
952
+ } else if (!onChangeAttr && checkedAttr) {
953
+ const raw = checkedAttr.value?.kind === "str" ? checkedAttr.value.value : "";
954
+ if (raw.startsWith("__EXPR__")) {
955
+ try {
956
+ const expr: Expression = JSON.parse(raw.substring(8));
957
+ if (expr.kind === "variable" && expr.name) {
958
+ attrParts.push(`onchange="(function(e){ ${expr.name} = e.target.checked; sinthRender(); })(event)"`);
959
+ }
960
+ } catch {}
961
+ } else if (raw.match(/^[a-zA-Z_][a-zA-Z0-9_]*$/)) {
962
+ attrParts.push(`onchange="(function(e){ ${raw} = e.target.checked; sinthRender(); })(event)"`);
963
+ }
964
+ }
965
+
966
+ const labelAttr = use.attrs.find(a => a.name === "label");
967
+ const labelText = labelAttr?.value?.kind === "str" ? esc(interpolateAttr(labelAttr.value.value, params)) : "";
968
+
969
+ if (labelText) {
970
+ const checkAttrStr = attrParts.length ? " " + attrParts.join(" ") : "";
971
+ return `<label data-s="${ctx.scopeHash}"><input${checkAttrStr}> ${labelText}</label>`;
888
972
  }
889
973
  }
890
974
 
@@ -1074,8 +1158,7 @@ function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
1074
1158
  const paramsJS = fn.params.map(p => p.name).join(", ");
1075
1159
 
1076
1160
  if (fn.returnType === "ui") {
1077
- const childHTMLs = fn.body.map(c => renderChild(c, ctx, new Map(), 0));
1078
- return `function ${fn.name}(${paramsJS}) {\n return [${childHTMLs.map(h => JSON.stringify(h)).join(", ")}];\n}`;
1161
+ return "";
1079
1162
  }
1080
1163
 
1081
1164
  const bodyStatements: string[] = [];
@@ -1094,6 +1177,9 @@ function compileFunctionDef(fn: FunctionDef, ctx: CompileCtx): string {
1094
1177
  break;
1095
1178
  case "for":
1096
1179
  break;
1180
+ case "return":
1181
+ bodyStatements.push(`return ${child.expression ? compileExprToJS(child.expression) : ""};`);
1182
+ break;
1097
1183
  }
1098
1184
  }
1099
1185
  return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
@@ -1190,7 +1276,7 @@ function sinthReplaceInsert(t, anchor, ifId, replaceId) {
1190
1276
  frag.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1191
1277
  if (${needsDelay}) {
1192
1278
  frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1193
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
1279
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
1194
1280
  }
1195
1281
  var fragFirst = frag.firstChild;
1196
1282
  var fragLast = frag.lastChild;
@@ -1217,15 +1303,24 @@ function sinthDelay(el) {
1217
1303
  el.dataset.sinthDelayDone = '1';
1218
1304
  var ms = parseInt(el.dataset.sinthDelay) || 0;
1219
1305
  el.style.display = 'none';
1220
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
1221
- else el.style.display = '';
1306
+ var show = function() {
1307
+ el.style.display = '';
1308
+ el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1309
+ };
1310
+ if (ms > 0) setTimeout(show, ms);
1311
+ else show();
1222
1312
  }
1223
- function sinthDelayExpr(el) {
1313
+ function sinthDelayExpr(el, _ctx) {
1314
+ _ctx = _ctx || {};
1224
1315
  try {
1225
1316
  var fn = __X[el.dataset.sinthDelayExprId];
1226
- var ms = fn ? parseInt(fn()) || 0 : 0;
1227
- el.style.display = '';
1228
- if (ms > 0) setTimeout(function() { el.style.display = ''; }, ms);
1317
+ var ms = fn ? parseInt(fn(_ctx)) || 0 : 0;
1318
+ var show = function() {
1319
+ el.style.display = '';
1320
+ el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1321
+ };
1322
+ if (ms > 0) setTimeout(show, ms);
1323
+ else show();
1229
1324
  } catch(e) {}
1230
1325
  }
1231
1326
  `;
@@ -1284,7 +1379,7 @@ function sinthIfBlock(t) {
1284
1379
  ef.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1285
1380
  if (${needsDelay}) {
1286
1381
  ef.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1287
- ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
1382
+ ef.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });
1288
1383
  }
1289
1384
  t.parentNode.insertBefore(ef, t);
1290
1385
  } else {
@@ -1350,33 +1445,28 @@ function sinthForBlock(t) {
1350
1445
  var _rp = document.getElementById(t.dataset.sinthIfReplace);
1351
1446
  if (_rp) _rp.parentNode.removeChild(_rp);
1352
1447
  }
1448
+ var loopCtx = {};
1449
+ if (_item) loopCtx[_item] = _v;
1450
+ if (_key) loopCtx[_key] = _k;
1451
+ if (_idx) loopCtx[_idx] = _loopIdx - 1;
1353
1452
  var frag = document.createRange().createContextualFragment(t.innerHTML);
1354
1453
  frag.querySelectorAll('.sinth-expr').forEach(function(el) {
1355
1454
  try {
1356
1455
  var exprFn = __X[el.dataset.exprId];
1357
- if (!exprFn) return;
1358
- var _ctx = {};
1359
- if (_item) _ctx[_item] = _v;
1360
- if (_key) _ctx[_key] = _k;
1361
- if (_idx) _ctx[_idx] = _loopIdx - 1;
1362
- el.textContent = exprFn(_ctx);
1363
- el.classList.remove('sinth-expr');
1456
+ if (exprFn) el.textContent = exprFn(loopCtx);
1364
1457
  } catch(e) {}
1458
+ el.classList.remove('sinth-expr');
1365
1459
  });
1366
1460
  frag.querySelectorAll('template[data-sinth-if-expr]').forEach(function(ifT) {
1367
1461
  var condFn = __X[ifT.dataset.sinthIfExpr];
1368
- var _ctx = {};
1369
- if (_item) _ctx[_item] = _v;
1370
- if (_key) _ctx[_key] = _k;
1371
- if (_idx) _ctx[_idx] = _loopIdx - 1;
1372
1462
  var cond = false;
1373
- try { if (condFn) cond = condFn(_ctx); } catch(e) {}
1463
+ try { if (condFn) cond = condFn(loopCtx); } catch(e) {}
1374
1464
  if (cond) {
1375
1465
  var ifContent = document.createRange().createContextualFragment(ifT.innerHTML);
1376
1466
  ifContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
1377
1467
  try {
1378
1468
  var exprFn2 = __X[el2.dataset.exprId];
1379
- if (exprFn2) el2.textContent = exprFn2(_ctx);
1469
+ if (exprFn2) el2.textContent = exprFn2(loopCtx);
1380
1470
  } catch(e) {}
1381
1471
  });
1382
1472
  ifT.parentNode.insertBefore(ifContent, ifT);
@@ -1387,7 +1477,7 @@ function sinthForBlock(t) {
1387
1477
  elseContent.querySelectorAll('.sinth-expr').forEach(function(el2) {
1388
1478
  try {
1389
1479
  var exprFn2 = __X[el2.dataset.exprId];
1390
- if (exprFn2) el2.textContent = exprFn2(_ctx);
1480
+ if (exprFn2) el2.textContent = exprFn2(loopCtx);
1391
1481
  } catch(e) {}
1392
1482
  });
1393
1483
  ifT.parentNode.insertBefore(elseContent, ifT);
@@ -1396,7 +1486,7 @@ function sinthForBlock(t) {
1396
1486
  });
1397
1487
  if (${needsDelay}) {
1398
1488
  frag.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1399
- frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
1489
+ frag.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, loopCtx); });
1400
1490
  }
1401
1491
  t.parentNode && t.parentNode.insertBefore(frag, t);
1402
1492
  });
@@ -1435,7 +1525,7 @@ function sinthForBlock(t) {
1435
1525
  __el.querySelectorAll('.sinth-expr').forEach(sinthExpr);
1436
1526
  __el.querySelectorAll('template[data-sinth-if-expr]').forEach(sinthIfBlock);
1437
1527
  ${needsDelay ? `__el.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1438
- __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);` : ""}
1528
+ __el.querySelectorAll('[data-sinth-delay-expr-id]').forEach(function(el) { sinthDelayExpr(el, {}); });` : ""}
1439
1529
  }
1440
1530
  })();\n`;
1441
1531
  }
@@ -1458,13 +1548,20 @@ function sinthForBlock(t) {
1458
1548
  renderBody += ` document.querySelectorAll('[data-sinth-checked]').forEach(function(el) {
1459
1549
  try { el.checked = !!window[el.dataset.sinthChecked]; } catch(e) {}
1460
1550
  });\n`;
1551
+ if (bodyHTML.includes("data-sinth-checked-expr")) {
1552
+ renderBody += ` document.querySelectorAll('[data-sinth-checked-expr]').forEach(function(el) {
1553
+ try {
1554
+ var exprFn = __X[el.dataset.sinthCheckedExpr];
1555
+ if (exprFn) el.checked = !!exprFn({});
1556
+ } catch(e) {}
1557
+ });\n`;
1558
+ }
1461
1559
  if (needsExpr) {
1462
1560
  renderBody += ` document.querySelectorAll('.sinth-expr').forEach(sinthExpr);\n`;
1463
1561
  }
1464
1562
  if (needsDelay) {
1465
1563
  renderBody += ` setTimeout(function() {
1466
1564
  document.querySelectorAll('[data-sinth-delay]').forEach(sinthDelay);
1467
- document.querySelectorAll('[data-sinth-delay-expr-id]').forEach(sinthDelayExpr);
1468
1565
  }, 0);\n`;
1469
1566
  }
1470
1567
  renderBody += ` window.scrollTo(_sx, _sy);\n`;
package/src/core/expr.ts CHANGED
@@ -1,4 +1,5 @@
1
- import { Expression, Child, AssignStmt, IfBlock, LitStr, LitNum, LitBool } from "./types.ts";
1
+ import { Expression, Child, AssignStmt, IfBlock, ReturnStmt, LitStr, LitNum, LitBool } from "./types.ts";
2
+
2
3
 
3
4
  export function compileExprToJS(expr: Expression, loopVars?: Set<string>): string {
4
5
  switch (expr.kind) {
@@ -55,9 +56,10 @@ export function compileIfToJS(ifBlock: IfBlock): string {
55
56
 
56
57
  export function bodyToJS(children: Child[]): string {
57
58
  return children
58
- .filter(c => c.kind === "assign_stmt" || c.kind === "if")
59
+ .filter(c => c.kind === "assign_stmt" || c.kind === "if" || c.kind === "return")
59
60
  .map(c => {
60
61
  if (c.kind === "assign_stmt") return ` ${compileExprToJS((c as AssignStmt).expression)};\n`;
62
+ if (c.kind === "return") return ` return ${(c as ReturnStmt).expression ? compileExprToJS((c as ReturnStmt).expression!) : ""};\n`;
61
63
  if (c.kind === "if") return compileIfToJS(c as IfBlock).replace(/^/gm, " ") + "\n";
62
64
  return "";
63
65
  })
package/src/core/lexer.ts CHANGED
@@ -22,6 +22,7 @@ const KEYWORDS: Record<string, TT> = {
22
22
  "in": TT.KW_IN,
23
23
  "remove": TT.KW_REMOVE,
24
24
  "function": TT.KW_FUNCTION,
25
+ "return": TT.KW_RETURN,
25
26
  };
26
27
 
27
28
  export class Lexer {
@@ -53,6 +54,7 @@ export class Lexer {
53
54
  // two-character operators ->
54
55
  if (ch === "=" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_EQEQ, value: "==", loc }); continue; }
55
56
  if (ch === "!" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_NEQ, value: "!=", loc }); continue; }
57
+ if (ch === "!") { tokens.push(this.single(TT.OP_NOT, loc)); continue; }
56
58
  if (ch === ">" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_GTEQ, value: ">=", loc }); continue; }
57
59
  if (ch === "<" && this.src[this.pos + 1] === "=") { this.adv(); this.adv(); tokens.push({ type: TT.OP_LTEQ, value: "<=", loc }); continue; }
58
60
 
@@ -1,4 +1,4 @@
1
- import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
1
+ import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ReturnStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, FunctionDef, SinthFile, SinthError, SinthWarning, AssignOp, VarType, BinaryOp } from "./types.ts";
2
2
  import { Lexer } from "./lexer.ts";
3
3
  import { compileExprToJS, compileIfToJS } from "./expr.ts";
4
4
  import { tagNameToPascal } from "../utils.ts";
@@ -262,8 +262,8 @@ private parseArrayLiteral(): Literal {
262
262
  const tok = this.peek();
263
263
 
264
264
  // Unary 'not'
265
- if (tok.type === TT.IDENT && tok.value === "not") {
266
- this.consume(TT.IDENT);
265
+ if ((tok.type === TT.IDENT && tok.value === "not") || tok.type === TT.OP_NOT) {
266
+ if (tok.type === TT.IDENT) this.consume(TT.IDENT); else this.consume(TT.OP_NOT);
267
267
  const operand = this.parseExpression();
268
268
  if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
269
269
  const unaryExpr: Expression = { kind: "unary", op: "not", operand };
@@ -433,6 +433,15 @@ private parseArrayLiteral(): Literal {
433
433
  return { sinthName, tagName, params, loc };
434
434
  }
435
435
 
436
+ private parseReturnStmt(): ReturnStmt {
437
+ const loc = this.consume(TT.KW_RETURN).loc;
438
+ let expression: Expression | undefined;
439
+ if (!this.check(TT.RBRACE) && !this.check(TT.EOF) && !this.check(TT.KW_IF) && !this.check(TT.KW_FOR) && !this.check(TT.KW_RETURN)) {
440
+ expression = this.parseExpression() ?? undefined;
441
+ }
442
+ return { kind: "return", expression, loc };
443
+ }
444
+
436
445
  private parseParamDecls(): ParamDecl[] {
437
446
  const params: ParamDecl[] = [];
438
447
  if (!this.check(TT.LPAREN)) return params;
@@ -481,6 +490,7 @@ private parseArrayLiteral(): Literal {
481
490
  if (vd) this._varDecls.push(vd);
482
491
  continue;
483
492
  }
493
+ else if (this.check(TT.KW_RETURN)){ body.push(this.parseReturnStmt()); }
484
494
  else if (this.check(TT.KW_IF)) { body.push(this.parseIfBlock()); }
485
495
  else if (this.check(TT.KW_FOR)) { body.push(this.parseForLoop()); }
486
496
  else if (this.check(TT.IDENT)) { body.push(this.parseCompUse()); }
@@ -524,6 +534,7 @@ private parseArrayLiteral(): Literal {
524
534
  const children: Child[] = [];
525
535
 
526
536
  while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
537
+ if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
527
538
  if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); continue; }
528
539
  if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); continue; }
529
540
  if (this.check(TT.LPAREN)) {
@@ -534,6 +545,23 @@ private parseArrayLiteral(): Literal {
534
545
  }
535
546
  continue;
536
547
  }
548
+ if (this.check(TT.IDENT)) {
549
+ const savedPos = this.pos;
550
+ const name = this.peek().value;
551
+ const nextType = this.tokens[this.pos + 1]?.type;
552
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
553
+ this.consume(TT.IDENT);
554
+ let op: AssignOp = "=";
555
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
556
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
557
+ this.consume(TT.EQUALS);
558
+ const rhs = this.parseExpression();
559
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
560
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: name, op, right: rhs }, loc: this.peek().loc });
561
+ continue;
562
+ }
563
+ this.pos = savedPos;
564
+ }
537
565
  if (this.check(TT.STRING)) {
538
566
  const loc = this.peek().loc;
539
567
  children.push({ kind: "text", value: this.consume(TT.STRING).value, loc });
@@ -875,6 +903,7 @@ private parseArrayLiteral(): Literal {
875
903
  if (vd) this._varDecls.push(vd);
876
904
  continue;
877
905
  }
906
+ else if (this.check(TT.KW_RETURN)) { children.push(this.parseReturnStmt()); continue; }
878
907
  else if (this.check(TT.KW_IF)) { children.push(this.parseIfBlock()); }
879
908
  else if (this.check(TT.KW_FOR)) { children.push(this.parseForLoop()); }
880
909
  else if (this.check(TT.IDENT)) {
@@ -882,6 +911,18 @@ private parseArrayLiteral(): Literal {
882
911
  const rawName = this.peek().value;
883
912
  const nextType = this.tokens[this.pos + 1]?.type;
884
913
 
914
+ if (nextType === TT.EQUALS || (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) || (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS)) {
915
+ this.consume(TT.IDENT);
916
+ let op: AssignOp = "=";
917
+ if (this.check(TT.OP_PLUS)) { this.consume(TT.OP_PLUS); op = "+="; }
918
+ else if (this.check(TT.OP_MINUS)) { this.consume(TT.OP_MINUS); op = "-="; }
919
+ this.consume(TT.EQUALS);
920
+ const rhs = this.parseExpression();
921
+ if (!rhs) throw new SinthError("Expected expression after assignment", this.peek().loc);
922
+ children.push({ kind: "assign_stmt", expression: { kind: "assign", target: rawName, op, right: rhs }, loc });
923
+ continue;
924
+ }
925
+
885
926
  if (nextType === TT.DOT) {
886
927
  let fullName = this.consume(TT.IDENT).value;
887
928
  this.consume(TT.DOT);
package/src/core/types.ts CHANGED
@@ -19,10 +19,11 @@ export enum TT {
19
19
  KW_GLOBAL, KW_PAGE, KW_LANG,
20
20
  KW_CUSTOM_EL, KW_CUSTOM,
21
21
  KW_IF, KW_ELSE, KW_FOR, KW_IN, KW_REMOVE,
22
- KW_FUNCTION,
22
+ KW_FUNCTION, KW_RETURN,
23
23
  OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
24
24
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
25
25
  OP_ARROW,
26
+ OP_NOT,
26
27
  EOF,
27
28
  }
28
29
 
@@ -62,10 +63,11 @@ export interface AssignStmt { kind: "assign_stmt"; expression: Expression;
62
63
  export interface IfBlock { kind: "if"; condition: Expression; body: Child[]; elseBody?: Child[]; loc: Loc }
63
64
  export interface ForLoop { kind: "for"; keyVar?: string; itemVar: string; indexVar?: string; arrayVar: string; body: Child[]; loc: Loc }
64
65
  export interface RemoveStmt { kind: "remove"; target: string; loc: Loc }
66
+ export interface ReturnStmt { kind: "return"; expression?: Expression; loc: Loc }
65
67
  export interface ComponentExpr { kind: "component_expr"; children: Child[]; loc: Loc }
66
68
 
67
69
 
68
- export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ComponentExpr;
70
+ export type Child = TextNode | CompUse | ExprNode | AssignStmt | IfBlock | ForLoop | RemoveStmt | ReturnStmt | ComponentExpr;
69
71
 
70
72
  export interface ParamDecl { name: string; defaultVal?: Literal; loc: Loc }
71
73