@yannosay/sinth 0.3.2 → 0.4.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 +249 -19
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.3.2",
3
+ "version": "0.4.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
@@ -510,6 +510,8 @@ export class Parser {
510
510
  const vd = this.parseVarDeclaration();
511
511
  if (vd) varDecls.push(vd);
512
512
  }
513
+ // Store var declarations for type checking in inline logic
514
+ (this as any)._varDecls = varDecls;
513
515
 
514
516
  // 4b. Body: component definitions, usages, style, script, custom-element
515
517
  while (!this.check(TT.EOF)) {
@@ -544,6 +546,9 @@ export class Parser {
544
546
  else throw new SinthError(`Unexpected token '${this.peek().value}'`, this.peek().loc);
545
547
  }
546
548
 
549
+ if ((this as any)._logicScripts) {
550
+ scripts.push(...(this as any)._logicScripts);
551
+ }
547
552
  return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
548
553
  }
549
554
 
@@ -933,6 +938,97 @@ private parseCompUse(): CompUse {
933
938
  return { kind: "if", condition, body, elseBody, loc };
934
939
  }
935
940
 
941
+ private parseLogicBody(condition: Expression): string {
942
+ let js = "if (" + compileExprToJS(condition) + ") {\n";
943
+ while (!this.check(TT.RBRACE) && !this.check(TT.EOF)) {
944
+ if (this.check(TT.IDENT)) {
945
+ const name = this.consume(TT.IDENT).value;
946
+
947
+ // Assignment: name = value
948
+ if (this.check(TT.EQUALS)) {
949
+ this.consume(TT.EQUALS);
950
+ const expr = this.parseExpression();
951
+ if (expr) {
952
+ // Type check: look up the variable's declared type
953
+ const varDecl = (this as any)._varDecls?.find((v: any) => v.name === name);
954
+ if (varDecl) {
955
+ const exprJS = compileExprToJS(expr);
956
+ // Check type compatibility
957
+ const valueKind = expr.kind;
958
+ const valueLiteralKind = expr.kind === "literal" ? expr.value?.kind : null;
959
+
960
+ if (varDecl.varType === "int" && valueLiteralKind === "str") {
961
+ SinthWarning.emit(`Type mismatch: '${name}' is declared as int but assigned a string value`);
962
+ } else if (varDecl.varType === "str" && valueLiteralKind === "num") {
963
+ SinthWarning.emit(`Type mismatch: '${name}' is declared as str but assigned a number value`);
964
+ } else if (varDecl.varType === "bool" && valueLiteralKind !== "bool" && valueLiteralKind !== null) {
965
+ SinthWarning.emit(`Type mismatch: '${name}' is declared as bool but assigned a non-boolean value`);
966
+ }
967
+ }
968
+ js += " " + compileExprToJS({ kind: "assign", target: name, op: "=", right: expr }) + ";\n";
969
+ }
970
+ }
971
+ // Addition assignment: name += value
972
+ else if (this.check(TT.OP_PLUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
973
+ this.consume(TT.OP_PLUS);
974
+ this.consume(TT.EQUALS);
975
+ const expr = this.parseExpression();
976
+ if (expr) {
977
+ js += " " + compileExprToJS({ kind: "assign", target: name, op: "+=", right: expr }) + ";\n";
978
+ }
979
+ }
980
+ // Subtraction assignment: name -= value
981
+ else if (this.check(TT.OP_MINUS) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
982
+ this.consume(TT.OP_MINUS);
983
+ this.consume(TT.EQUALS);
984
+ const expr = this.parseExpression();
985
+ if (expr) {
986
+ js += " " + compileExprToJS({ kind: "assign", target: name, op: "-=", right: expr }) + ";\n";
987
+ }
988
+ }
989
+ // Function call: name()
990
+ else if (this.check(TT.LPAREN)) {
991
+ this.consume(TT.LPAREN);
992
+ let args = "";
993
+ while (!this.check(TT.RPAREN) && !this.check(TT.EOF)) {
994
+ const arg = this.parseExpression();
995
+ if (arg) {
996
+ args += (args ? ", " : "") + compileExprToJS(arg);
997
+ }
998
+ if (this.check(TT.COMMA)) this.consume(TT.COMMA);
999
+ }
1000
+ this.consume(TT.RPAREN);
1001
+ js += " " + name + "(" + args + ");\n";
1002
+ }
1003
+ }
1004
+ // Nested if
1005
+ else if (this.check(TT.KW_IF)) {
1006
+ this.consume(TT.KW_IF);
1007
+ const innerCond = this.parseExpression();
1008
+ if (innerCond && this.check(TT.LBRACE)) {
1009
+ this.consume(TT.LBRACE);
1010
+ js += " " + this.parseLogicBody(innerCond);
1011
+ }
1012
+ }
1013
+ // var declaration (skip in logic body)
1014
+ else if (this.check(TT.IDENT) && this.peek().value === "var") {
1015
+ this.consume(TT.IDENT); // var
1016
+ this.consume(TT.IDENT); // type
1017
+ this.consume(TT.IDENT); // name
1018
+ if (this.check(TT.EQUALS)) {
1019
+ this.consume(TT.EQUALS);
1020
+ this.parseExpression();
1021
+ }
1022
+ }
1023
+ else {
1024
+ break;
1025
+ }
1026
+ }
1027
+ this.consume(TT.RBRACE);
1028
+ js += "}\n";
1029
+ return js;
1030
+ }
1031
+
936
1032
  private parseForLoop(): ForLoop {
937
1033
  const loc = this.consume(TT.KW_FOR).loc;
938
1034
  const itemVar = this.consume(TT.IDENT).value;
@@ -961,24 +1057,119 @@ private parseCompUse(): CompUse {
961
1057
  private parseChildList(): Child[] {
962
1058
  const children: Child[] = [];
963
1059
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
964
- if (this.check(TT.STRING)) {
965
- const loc = this.peek().loc;
966
- const strVal = this.consume(TT.STRING).value;
967
- if (this.check(TT.OP_PLUS)) {
968
- this.consume(TT.OP_PLUS);
969
- const rightExpr = this.parseExpression();
970
- if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
971
- children.push({ kind: "expr", expression: {
1060
+ if (this.check(TT.STRING)) {
1061
+ const loc = this.peek().loc;
1062
+ let leftExpr: Expression = {
1063
+ kind: "literal",
1064
+ value: { kind: "str", value: this.consume(TT.STRING).value }
1065
+ };
1066
+ // Keep chaining while there's a + operator
1067
+ while (this.check(TT.OP_PLUS)) {
1068
+ this.consume(TT.OP_PLUS);
1069
+ let rightExpr: Expression | null = null;
1070
+ if (this.check(TT.STRING)) {
1071
+ rightExpr = {
1072
+ kind: "literal",
1073
+ value: { kind: "str", value: this.consume(TT.STRING).value }
1074
+ };
1075
+ } else if (this.check(TT.IDENT)) {
1076
+ const varName = this.consume(TT.IDENT).value;
1077
+ rightExpr = { kind: "variable", name: varName };
1078
+ } else {
1079
+ rightExpr = this.parseExpression();
1080
+ }
1081
+ if (!rightExpr) throw new SinthError("Expected expression after +", this.peek().loc);
1082
+ leftExpr = {
972
1083
  kind: "binary",
973
- left: { kind: "literal", value: { kind: "str", value: strVal } },
1084
+ left: leftExpr,
974
1085
  op: "+",
975
1086
  right: rightExpr,
976
- }, loc });
1087
+ };
1088
+ }
1089
+ children.push({ kind: "expr", expression: leftExpr, loc });
1090
+ } else if (this.check(TT.KW_IF)) {
1091
+ const ifStart = this.pos;
1092
+ this.consume(TT.KW_IF);
1093
+ const condition = this.parseExpression();
1094
+ if (!condition) throw new SinthError("Expected condition after 'if'", this.peek().loc);
1095
+
1096
+ if (!this.check(TT.LBRACE)) {
1097
+ throw new SinthError("Expected '{' after if condition", this.peek().loc);
1098
+ }
1099
+
1100
+ this.consume(TT.LBRACE);
1101
+
1102
+
1103
+ // Determine if this is inline logic or DOM rendering
1104
+ let isInlineLogic = false;
1105
+
1106
+ // Check first token inside the body
1107
+ if (this.check(TT.IDENT)) {
1108
+ const identName = this.peek().value;
1109
+ const nextType = this.tokens[this.pos + 1]?.type;
1110
+
1111
+
1112
+
1113
+ // Assignment operators: =, +=, -=
1114
+ if (nextType === TT.EQUALS) {
1115
+ isInlineLogic = true;
1116
+ } else if (nextType === TT.OP_PLUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) {
1117
+ isInlineLogic = true;
1118
+ } else if (nextType === TT.OP_MINUS && this.tokens[this.pos + 2]?.type === TT.EQUALS) {
1119
+ isInlineLogic = true;
1120
+ }
1121
+ // Not a built-in component or keyword
1122
+ else if (identName === "if" || identName === "for" || identName === "var" ||
1123
+ BUILTIN_MAP[identName]) {
1124
+ isInlineLogic = false;
1125
+ }
1126
+ // If next token is not (, it might still be logic (like standalone variable for sinthRender)
1127
+ // But if it's a component usage (IDENT followed by LPAREN or LBRACE), it's DOM
1128
+ else if (nextType === TT.LPAREN || nextType === TT.LBRACE || nextType === TT.RAW_BLOCK) {
1129
+ isInlineLogic = false;
1130
+ }
1131
+ }
1132
+ // Also check for nested if (could be inline or DOM)
1133
+ else if (this.check(TT.KW_IF)) {
1134
+ // Peek ahead to see if nested if contains assignment
1135
+ const nestedStart = this.pos;
1136
+ this.consume(TT.KW_IF);
1137
+ const nestedCond = this.parseExpression();
1138
+ if (nestedCond && this.check(TT.LBRACE)) {
1139
+ this.consume(TT.LBRACE);
1140
+ if (this.check(TT.IDENT) && this.tokens[this.pos + 1]?.type === TT.EQUALS) {
1141
+ isInlineLogic = true;
1142
+ }
1143
+ }
1144
+ // Reset position
1145
+ while (this.pos > nestedStart) {
1146
+ this.pos--;
1147
+ }
1148
+ this.pos = nestedStart;
1149
+ }
1150
+ // Keywords that indicate DOM rendering
1151
+ else if (this.check(TT.KW_STYLE) || this.check(TT.KW_SCRIPT) ||
1152
+ this.check(TT.STRING) || this.check(TT.KW_FOR)) {
1153
+ isInlineLogic = false;
1154
+ }
1155
+
1156
+ if (isInlineLogic) {
1157
+ // Parse as inline logic
1158
+ const jsCode = this.parseLogicBody(condition);
1159
+ const scriptBlock: ScriptBlock = {
1160
+ raw: jsCode,
1161
+ attrs: {},
1162
+ loc: this.peek().loc
1163
+ };
1164
+ children.push({ kind: "text", value: "", loc: this.peek().loc });
1165
+ (this as any)._logicScripts = (this as any)._logicScripts || [];
1166
+ (this as any)._logicScripts.push(scriptBlock);
977
1167
  } else {
978
- children.push({ kind: "text", value: strVal, loc });
1168
+ // Parse as DOM if — reset and use existing parser
1169
+ this.pos = ifStart;
1170
+ children.push(this.parseIfBlock());
979
1171
  }
980
- } else if (this.check(TT.KW_IF)) {
981
- children.push(this.parseIfBlock());
1172
+
982
1173
  } else if (this.check(TT.KW_FOR)) {
983
1174
  children.push(this.parseForLoop());
984
1175
  } else if (this.check(TT.IDENT)) {
@@ -1012,8 +1203,14 @@ private parseCompUse(): CompUse {
1012
1203
  const loc = this.peek().loc;
1013
1204
  const name = this.consume(TT.IDENT).value;
1014
1205
  children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1015
- } else {
1206
+ } else if (this.tokens[this.pos + 1]?.type === TT.LPAREN ||
1207
+ this.tokens[this.pos + 1]?.type === TT.LBRACE ||
1208
+ this.tokens[this.pos + 1]?.type === TT.RAW_BLOCK) {
1016
1209
  children.push(this.parseCompUse());
1210
+ } else {
1211
+ const loc = this.peek().loc;
1212
+ const name = this.consume(TT.IDENT).value;
1213
+ children.push({ kind: "expr", expression: { kind: "variable", name }, loc });
1017
1214
  }
1018
1215
  } else {
1019
1216
  throw new SinthError(`Unexpected token '${this.peek().value}' in children`, this.peek().loc);
@@ -2087,6 +2284,15 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2087
2284
 
2088
2285
  const { componentScripts, pageScripts } = collectScripts(file, allDefs);
2089
2286
 
2287
+ const assignedVars = new Set<string>();
2288
+ for (const s of file.scripts) {
2289
+ const matches = s.raw.matchAll(/(\w+)\s*=/g);
2290
+ for (const m of matches) assignedVars.add(m[1]);
2291
+ }
2292
+ for (const v of file.varDecls) {
2293
+ if (v.value) assignedVars.add(v.name);
2294
+ }
2295
+
2090
2296
  const companionJS = (() => {
2091
2297
  const base = absPath.replace(/\.sinth$/, ".js");
2092
2298
  return fs.existsSync(base) ? path.basename(base) : undefined;
@@ -2113,14 +2319,20 @@ function compileFile(filePath: string, opts: CompileOptions): string | null {
2113
2319
  if (componentScripts.length > 0) {
2114
2320
  scriptTags.push(`<script>\n${componentScripts.join("\n\n")}\n</script>`);
2115
2321
  }
2322
+ let logicScriptsRaw = "";
2116
2323
  for (const s of pageScripts) {
2117
2324
  const extra = Object.entries(s.attrs)
2118
2325
  .map(([k, v]) => v === "true" ? k : `${k}="${escAttr(v)}"`)
2119
2326
  .join(" ");
2120
2327
  // Convert let/const to var for global accessibility
2121
2328
  const globalRaw = s.raw.replace(/\b(let|const)\b/g, 'var');
2122
- scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalRaw}\n</script>`);
2123
- }
2329
+ // Check if this is an inline logic script (starts with "if (")
2330
+ if (globalRaw.trim().startsWith("if (")) {
2331
+ logicScriptsRaw += globalRaw + "\n";
2332
+ } else {
2333
+ scriptTags.push(`<script${extra ? " " + extra : ""}>\n${globalRaw}\n</script>`);
2334
+ }
2335
+ }
2124
2336
 
2125
2337
  const html = [
2126
2338
  "<!DOCTYPE html>",
@@ -2129,17 +2341,31 @@ for (const s of pageScripts) {
2129
2341
  `<body data-s="${hash}">`,
2130
2342
  bodyHTML,
2131
2343
  `<script>
2132
- // v0.2.0: Sinth variable declarations (global scope)
2344
+ //Compiled using Sinth Logic
2133
2345
  ${file.varDecls.map(v => {
2134
- if (!v.value) return `var ${v.name};`;
2346
+ if (!v.value) {
2347
+ if (!assignedVars.has(v.name)) {
2348
+ const defaults: Record<string, string> = { str: '""', int: "0", bool: "false", "str[]": "[]" };
2349
+ const defaultVal = defaults[v.varType] || "undefined";
2350
+ SinthWarning.emit(`Variable '${v.name}' is declared but never assigned. Using default value ${defaultVal}.`, v.loc);
2351
+ }
2352
+ if (v.varType === "str") return `var ${v.name} = "";`;
2353
+ if (v.varType === "int") return `var ${v.name} = 0;`;
2354
+ if (v.varType === "bool") return `var ${v.name} = false;`;
2355
+ if (v.varType === "str[]") return `var ${v.name} = [];`;
2356
+ return `var ${v.name};`;
2357
+ }
2135
2358
  const val = litToString(v.value);
2359
+
2136
2360
  if (v.varType !== "str[]" && val.startsWith("__VAR__")) {
2137
2361
  const refName = val.slice(7);
2138
2362
  return `var ${v.name} = ${refName};`;
2139
2363
  }
2364
+
2140
2365
  if (val.startsWith("__ARR__")) {
2141
2366
  return `var ${v.name} = ${val.slice(7)};`;
2142
2367
  }
2368
+
2143
2369
  if (v.varType === "str") return `var ${v.name} = ${JSON.stringify(val)};`;
2144
2370
  return `var ${v.name} = ${val};`;
2145
2371
  }).join("\n")}
@@ -2220,7 +2446,10 @@ ${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for')) ?
2220
2446
  }
2221
2447
  } catch(e) {}
2222
2448
  });
2223
- }, 0);` : ''}${bodyHTML.includes('sinth-expr') ? `
2449
+ }, 0);` : ''}
2450
+
2451
+ ${logicScriptsRaw}
2452
+ ${bodyHTML.includes('sinth-expr') ? `
2224
2453
  document.querySelectorAll('.sinth-expr').forEach(el => {
2225
2454
  try { el.textContent = eval(el.dataset.expr); } catch(e) {}
2226
2455
  });` : ''}
@@ -2228,6 +2457,7 @@ ${(bodyHTML.includes('data-sinth-if') || bodyHTML.includes('data-sinth-for')) ?
2228
2457
  }
2229
2458
 
2230
2459
  sinthRender();` : ''}
2460
+
2231
2461
  </script>`,
2232
2462
  scriptTags.join("\n"),
2233
2463
  "</body>",