@yannosay/sinth 0.9.0 → 0.10.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
@@ -25,6 +25,21 @@ Button(onClick: "deletePost()") { "Delete" }
25
25
  }
26
26
  ```
27
27
 
28
+ #### Functions - easy as you know it
29
+ ```ts
30
+ page
31
+
32
+ title = "Function test"
33
+
34
+ function greet(str name) -> str { -- New! (0.10.0)
35
+ "Hello, " + name
36
+ }
37
+
38
+ Div {
39
+ (greet("Sinth")) + " - welcome!"
40
+ }
41
+ ```
42
+
28
43
  No JSX ternaries. No v-if. No separate script tags. Mixed logic. Clean.
29
44
 
30
45
  #### Animations that make sense.
@@ -137,6 +152,7 @@ Sinth's reactive runtime does not use eval(). Every expression is pre-compiled i
137
152
  - GitHub: [Official Sinth Repo](https://github.com/yannosay/sinth)
138
153
  - Website: [Sinth](https://sinth.yannosay.com) (not active at this moment)
139
154
  - Discord: [Join here!](https://discord.gg/SUvcrafTQm)
155
+ - VS Code Extension: [Download here](https://marketplace.visualstudio.com/items?itemName=YannosayProductions.sinth-vscode)
140
156
 
141
157
 
142
158
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@yannosay/sinth",
3
- "version": "0.9.0",
3
+ "version": "0.10.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",
@@ -4,6 +4,7 @@ import { Loc, Literal, Expression, Child, Attr, CompUse, IfBlock, ForLoop, Remov
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";
7
+ import { FunctionDef } from "./types.ts";
7
8
  import { parseFile, resolveImports, ResolverConfig, ResolvedImports } from "../resolver.ts";
8
9
 
9
10
 
@@ -1031,6 +1032,29 @@ export function renderHead(
1031
1032
 
1032
1033
  // sinth runtime
1033
1034
 
1035
+ function compileFunctionDef(fn: FunctionDef): string {
1036
+ const paramsJS = fn.params.map(p => p.name).join(", ");
1037
+ const bodyStatements: string[] = [];
1038
+ for (const child of fn.body) {
1039
+ switch (child.kind) {
1040
+ case "text":
1041
+ break;
1042
+ case "expr":
1043
+ bodyStatements.push(`return ${compileExprToJS(child.expression)};`);
1044
+ break;
1045
+ case "assign_stmt":
1046
+ bodyStatements.push(`${compileExprToJS(child.expression)};`);
1047
+ break;
1048
+ case "if":
1049
+ bodyStatements.push(compileIfToJS(child as IfBlock));
1050
+ break;
1051
+ case "for":
1052
+ break;
1053
+ }
1054
+ }
1055
+ return `function ${fn.name}(${paramsJS}) {\n${bodyStatements.map(s => ` ${s}`).join("\n")}\n}`;
1056
+ }
1057
+
1034
1058
  export function buildRuntime(opts: {
1035
1059
  varDecls: VarDeclaration[];
1036
1060
  bodyHTML: string;
@@ -1039,8 +1063,9 @@ export function buildRuntime(opts: {
1039
1063
  assignedVars: Set<string>;
1040
1064
  exprRegistry: string[];
1041
1065
  sharedRuntime: boolean;
1066
+ functionsJS: string;
1042
1067
  }): string | { page: string; shared: string } {
1043
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
1068
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
1044
1069
 
1045
1070
  const needsExpr = bodyHTML.includes("sinth-expr");
1046
1071
  const needsIf = bodyHTML.includes("data-sinth-if");
@@ -1420,7 +1445,7 @@ ${helpers}`;
1420
1445
 
1421
1446
  return `// Sinth compiled runtime
1422
1447
  ${varLines}
1423
- ${helpers}
1448
+ ${functionsJS ? functionsJS + "\n" : ""}${helpers}
1424
1449
  ${exprArrayJS}
1425
1450
  ${renderFunc}`;
1426
1451
  }
@@ -1445,6 +1470,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1445
1470
  const hash = fnv1a(absPath);
1446
1471
 
1447
1472
  const allVarDecls: VarDeclaration[] = file.varDecls;
1473
+ const functionDefs: FunctionDef[] = file.functions; // ← new
1448
1474
 
1449
1475
  const ctx: CompileCtx = {
1450
1476
  allDefs, customEls, cssLinks, jsLinks,
@@ -1480,6 +1506,9 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1480
1506
  }
1481
1507
  for (const v of file.varDecls) { if (v.value) assignedVars.add(v.name); }
1482
1508
 
1509
+ // compile function definitions to JS
1510
+ const compiledFunctions = functionDefs.map(f => compileFunctionDef(f)).join("\n");
1511
+
1483
1512
  // companion JS file (needs same name as .sinth, adds support for JS libraries)
1484
1513
  const companionJS = (() => {
1485
1514
  const base = absPath.replace(/\.sinth$/, ".js");
@@ -1506,6 +1535,7 @@ export function compileFile(filePath: string, opts: CompileOptions): { html: str
1506
1535
  assignedVars,
1507
1536
  exprRegistry: ctx.exprRegistry,
1508
1537
  sharedRuntime: opts.sharedRuntime,
1538
+ functionsJS: compiledFunctions, // ← pass compiled functions
1509
1539
  });
1510
1540
  const runtimeJS = typeof runtimeResult === 'string' ? runtimeResult : runtimeResult.page;
1511
1541
  const sharedJS = typeof runtimeResult === 'string' ? null : runtimeResult.shared;
package/src/core/expr.ts CHANGED
@@ -31,6 +31,11 @@ export function compileExprToJS(expr: Expression, loopVars?: Set<string>): strin
31
31
  return `${compileExprToJS(expr.object!, loopVars)}[${compileExprToJS(expr.key!, loopVars)}]`;
32
32
  case "postfix":
33
33
  return `${expr.target}${expr.op}`;
34
+ case "call": {
35
+ const callee = compileExprToJS(expr.callee!, loopVars);
36
+ const args = (expr.args ?? []).map(a => compileExprToJS(a, loopVars)).join(", ");
37
+ return `${callee}(${args})`;
38
+ }
34
39
  default:
35
40
  return "";
36
41
  }
package/src/core/lexer.ts CHANGED
@@ -21,6 +21,7 @@ const KEYWORDS: Record<string, TT> = {
21
21
  "for": TT.KW_FOR,
22
22
  "in": TT.KW_IN,
23
23
  "remove": TT.KW_REMOVE,
24
+ "function": TT.KW_FUNCTION,
24
25
  };
25
26
 
26
27
  export class Lexer {
@@ -62,6 +63,11 @@ export class Lexer {
62
63
  if (ch === ";") { tokens.push(this.single(TT.OP_SEMI, loc)); continue; }
63
64
  if (ch === "<") { tokens.push(this.single(TT.OP_LT, loc)); continue; }
64
65
  if (ch === ">") { tokens.push(this.single(TT.OP_GT, loc)); continue; }
66
+ if (ch === "-" && this.src[this.pos + 1] === ">") {
67
+ this.adv(); this.adv();
68
+ tokens.push({ type: TT.OP_ARROW, value: "->", loc });
69
+ continue;
70
+ }
65
71
  if (ch === "-" && !this.isDigit(this.src[this.pos + 1] ?? "")) {
66
72
  tokens.push(this.single(TT.OP_MINUS, loc)); continue;
67
73
  }
@@ -1,27 +1,24 @@
1
- import { TT, Token, Loc, Literal, Expression, Attr, Child, CompUse, IfBlock, ForLoop, RemoveStmt, ParamDecl, StyleBlock, ScriptBlock, CompDef, CustomElDecl, VarDeclaration, ImportNode, MetaEntry, SinthFile, SinthError, SinthWarning, AssignOp, VarType } from "./types.ts";
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";
2
2
  import { Lexer } from "./lexer.ts";
3
3
  import { compileExprToJS, compileIfToJS } from "./expr.ts";
4
+ import { tagNameToPascal } from "../utils.ts";
4
5
 
5
6
 
6
7
 
7
-
8
- // parser
9
-
10
8
  export class Parser {
11
9
  private pos = 0;
12
10
  private loopVar: string | null = null;
13
- /** Accumulated var declarations for type-checking in bodies. */
14
11
  private _varDecls: VarDeclaration[] = [];
15
12
 
16
13
  constructor(private tokens: Token[], private file: string) {}
17
14
 
18
15
 
19
- // top-level file parse
20
16
  parse(): SinthFile {
21
17
  let isPage = false;
22
18
  const imports: ImportNode[] = [];
23
19
  const meta: MetaEntry[] = [];
24
20
  const defs: CompDef[] = [];
21
+ const functions: FunctionDef[] = [];
25
22
  const uses: CompUse[] = [];
26
23
  const styles: StyleBlock[] = [];
27
24
  const scripts: ScriptBlock[] = [];
@@ -48,6 +45,7 @@ export class Parser {
48
45
 
49
46
  while (!this.check(TT.EOF)) {
50
47
  if (this.check(TT.KW_COMPONENT)) { defs.push(this.parseCompDef()); }
48
+ else if (this.check(TT.KW_FUNCTION)) { functions.push(this.parseFunctionDef()); } // ← new
51
49
  else if (this.check(TT.KW_STYLE)) { styles.push(this.parseStyleBlock()); }
52
50
  else if (this.check(TT.KW_SCRIPT)) { scripts.push(this.parseScriptBlock()); }
53
51
  else if (this.check(TT.KW_CUSTOM_EL) || this.check(TT.KW_CUSTOM)) { customEls.push(this.parseCustomEl()); }
@@ -107,7 +105,7 @@ uses.push(this.parseCompUse());
107
105
  );
108
106
  }
109
107
 
110
- return { filePath: this.file, isPage, imports, meta, defs, uses, styles, scripts, customEls, varDecls };
108
+ return { filePath: this.file, isPage, imports, meta, defs, functions, uses, styles, scripts, customEls, varDecls };
111
109
  }
112
110
 
113
111
  private flattenIfToUses(ifNode: IfBlock, scripts: ScriptBlock[]): CompUse[] {
@@ -260,7 +258,7 @@ private parseArrayLiteral(): Literal {
260
258
  const operand = this.parseExpression();
261
259
  if (!operand) throw new SinthError("Expected expression after 'not'", tok.loc);
262
260
  const unaryExpr: Expression = { kind: "unary", op: "not", operand };
263
- return this.parseBinaryRHS(this.parsePostfix(unaryExpr));
261
+ return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(unaryExpr)));
264
262
  }
265
263
 
266
264
  if (this.check(TT.LPAREN)) {
@@ -269,7 +267,7 @@ private parseArrayLiteral(): Literal {
269
267
  if (!inner) throw new SinthError("Expected expression after '('", this.peek().loc);
270
268
  if (!this.check(TT.RPAREN)) throw new SinthError("Expected closing ')'", this.peek().loc);
271
269
  this.consume(TT.RPAREN);
272
- return this.parseBinaryRHS(this.parsePostfix(inner));
270
+ return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(inner)));
273
271
  }
274
272
 
275
273
  // literal
@@ -277,7 +275,7 @@ private parseArrayLiteral(): Literal {
277
275
  this.check(TT.BOOL_FALSE) || this.check(TT.NULL_LIT)) {
278
276
  const lit = this.parseLiteral();
279
277
  const base: Expression = { kind: "literal", value: lit };
280
- return this.parseBinaryRHS(this.parsePostfix(base));
278
+ return this.parseBinaryRHS(this.parseCallExpr(this.parsePostfix(base)));
281
279
  }
282
280
 
283
281
  // var or assignment
@@ -298,9 +296,9 @@ private parseArrayLiteral(): Literal {
298
296
  // apply bracket postfixes (e.g. data[key], data["x"])
299
297
  const indexedExpr = this.parsePostfix(varExpr);
300
298
 
301
- // if indexing was applied, we don't allow assignment, just binary RHS
299
+ // if indexing was applied, we don't allow assignment, just binary RHS (after possible call)
302
300
  if (indexedExpr !== varExpr) {
303
- return this.parseBinaryRHS(indexedExpr);
301
+ return this.parseBinaryRHS(this.parseCallExpr(indexedExpr));
304
302
  }
305
303
 
306
304
  // no indexing – check for assignment operators
@@ -324,7 +322,7 @@ private parseArrayLiteral(): Literal {
324
322
  return { kind: "assign", target: varExpr.name!, op: "=", right: rhs };
325
323
  }
326
324
 
327
- return this.parseBinaryRHS(varExpr);
325
+ return this.parseBinaryRHS(this.parseCallExpr(varExpr));
328
326
  }
329
327
 
330
328
  return null;
@@ -366,9 +364,47 @@ private parseArrayLiteral(): Literal {
366
364
  return expr;
367
365
  }
368
366
 
367
+ private parseCallExpr(expr: Expression): Expression {
368
+ while (this.check(TT.LPAREN)) {
369
+ this.consume(TT.LPAREN);
370
+ const args: Expression[] = [];
371
+ if (!this.check(TT.RPAREN)) {
372
+ args.push(this.parseExpression()!);
373
+ while (this.check(TT.COMMA)) {
374
+ this.consume(TT.COMMA);
375
+ args.push(this.parseExpression()!);
376
+ }
377
+ }
378
+ if (!this.check(TT.RPAREN)) throw new SinthError("Expected ')' after arguments", this.peek().loc);
379
+ this.consume(TT.RPAREN);
380
+ expr = { kind: "call", callee: expr, args };
381
+ }
382
+ return expr;
383
+ }
384
+
369
385
 
370
386
  // component definitions
371
387
 
388
+ private parseFunctionDef(): FunctionDef {
389
+ const loc = this.consume(TT.KW_FUNCTION).loc;
390
+ const name = this.consume(TT.IDENT).value;
391
+ const params = this.parseParamDecls();
392
+ let returnType: VarType | undefined;
393
+ if (this.check(TT.OP_ARROW)) {
394
+ this.consume(TT.OP_ARROW);
395
+ const typeTok = this.consume(TT.IDENT);
396
+ if (!["int","str","bool","str[]","obj"].includes(typeTok.value)) {
397
+ throw new SinthError(`Unknown return type '${typeTok.value}'. Expected: int, str, bool, str[], obj`, typeTok.loc);
398
+ }
399
+ returnType = typeTok.value as VarType;
400
+ }
401
+ if (!this.check(TT.LBRACE)) throw new SinthError("Expected '{' after function signature", this.peek().loc);
402
+ this.consume(TT.LBRACE);
403
+ const body = this.parseChildList();
404
+ this.consume(TT.RBRACE);
405
+ return { name, params, returnType, body, loc };
406
+ }
407
+
372
408
  private parseCompDef(): CompDef {
373
409
  const loc = this.consume(TT.KW_COMPONENT).loc;
374
410
  const name = this.consume(TT.IDENT).value;
@@ -394,8 +430,15 @@ private parseArrayLiteral(): Literal {
394
430
  this.consume(TT.LPAREN);
395
431
  while (!this.check(TT.RPAREN)) {
396
432
  const ploc = this.peek().loc;
397
- const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
398
- const pname = nameTok.value;
433
+ let pname: string;
434
+ if (this.check(TT.IDENT) && ["int","str","bool","str[]","obj"].includes(this.peek().value) &&
435
+ this.tokens[this.pos + 1]?.type === TT.IDENT) {
436
+ this.consume(TT.IDENT); // consume type
437
+ pname = this.consume(TT.IDENT).value;
438
+ } else {
439
+ const nameTok = this.check(TT.IDENT) ? this.consume(TT.IDENT) : this.consume(this.peek().type);
440
+ pname = nameTok.value;
441
+ }
399
442
  let defaultVal: Literal | undefined;
400
443
  if (this.check(TT.EQUALS)) { this.consume(TT.EQUALS); defaultVal = this.parseLiteral(); }
401
444
  params.push({ name: pname, defaultVal, loc: ploc });
@@ -761,8 +804,30 @@ private parseArrayLiteral(): Literal {
761
804
  while (!this.check(TT.EOF) && !this.check(TT.RBRACE)) {
762
805
  if (this.check(TT.LPAREN)) {
763
806
  const loc = this.peek().loc;
764
- const expr = this.parseExpression();
807
+ let expr = this.parseExpression();
765
808
  if (expr) {
809
+ while (this.check(TT.OP_PLUS)) {
810
+ this.consume(TT.OP_PLUS);
811
+ let rhs: Expression | null = null;
812
+ if (this.check(TT.STRING)) {
813
+ rhs = { kind: "literal", value: { kind: "str", value: this.consume(TT.STRING).value } };
814
+ } else if (this.check(TT.IDENT)) {
815
+ const rhsName = this.consume(TT.IDENT).value;
816
+ if (this.check(TT.DOT)) {
817
+ this.consume(TT.DOT);
818
+ rhs = { kind: "variable", name: rhsName + "." + this.consume(TT.IDENT).value };
819
+ } else if (this.check(TT.LBRACKET)) {
820
+ const rhsVar: Expression = { kind: "variable", name: rhsName };
821
+ rhs = this.parsePostfix(rhsVar);
822
+ } else {
823
+ rhs = { kind: "variable", name: rhsName };
824
+ }
825
+ } else {
826
+ rhs = this.parseExpression();
827
+ }
828
+ if (!rhs) throw new SinthError("Expected expression after +", this.peek().loc);
829
+ expr = { kind: "binary", left: expr, op: "+", right: rhs };
830
+ }
766
831
  children.push({ kind: "expr", expression: expr, loc });
767
832
  }
768
833
  continue;
@@ -11,8 +11,9 @@ export function buildRuntime(opts: {
11
11
  assignedVars: Set<string>;
12
12
  exprRegistry: string[];
13
13
  sharedRuntime: boolean;
14
+ functionsJS: string; // ← new
14
15
  }): string | { page: string; shared: string } {
15
- const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry } = opts;
16
+ const { varDecls, bodyHTML, logicBlocks, mixedBlocks, assignedVars, exprRegistry, functionsJS } = opts;
16
17
 
17
18
  const needsExpr = bodyHTML.includes("sinth-expr");
18
19
  const needsIf = bodyHTML.includes("data-sinth-if");
@@ -381,7 +382,7 @@ function sinthMixedBlock(el, condId, ifJS, ifHTML, elseJS, elseHTML) {
381
382
 
382
383
  const pageCode = `// Sinth page runtime
383
384
  ${varLines}
384
- ${exprArrayJS}
385
+ ${functionsJS ? functionsJS + "\n" : ""}${exprArrayJS}
385
386
  ${renderFunc}`;
386
387
 
387
388
  if (opts.sharedRuntime && helpers.trim()) {
@@ -392,7 +393,7 @@ ${helpers}`;
392
393
 
393
394
  return `// Sinth compiled runtime
394
395
  ${varLines}
395
- ${helpers}
396
+ ${functionsJS ? functionsJS + "\n" : ""}${helpers}
396
397
  ${exprArrayJS}
397
398
  ${renderFunc}`;
398
399
  }
package/src/core/types.ts CHANGED
@@ -19,8 +19,10 @@ 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
23
  OP_PLUS, OP_MINUS, OP_STAR, OP_SLASH, OP_SEMI,
23
24
  OP_LT, OP_GT, OP_NEQ, OP_EQEQ, OP_LTEQ, OP_GTEQ,
25
+ OP_ARROW,
24
26
  EOF,
25
27
  }
26
28
 
@@ -38,7 +40,7 @@ export type AssignOp = "=" | "+=" | "-=";
38
40
  export type PostfixOp = "++" | "--";
39
41
 
40
42
  export interface Expression {
41
- kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index";
43
+ kind: "literal" | "variable" | "unary" | "binary" | "assign" | "postfix" | "index" | "call";
42
44
  value?: Literal;
43
45
  name?: string;
44
46
  op?: UnaryOp | BinaryOp | AssignOp | PostfixOp;
@@ -48,6 +50,8 @@ export interface Expression {
48
50
  target?: string;
49
51
  object?: Expression;
50
52
  key?: Expression;
53
+ callee?: Expression;
54
+ args?: Expression[];
51
55
  }
52
56
 
53
57
  export interface Attr { name: string; value: Literal | null; loc: Loc }
@@ -88,12 +92,21 @@ export type ImportNode =
88
92
 
89
93
  export interface MetaEntry { key: string; value: Literal; loc: Loc }
90
94
 
95
+ export interface FunctionDef {
96
+ name: string;
97
+ params: ParamDecl[];
98
+ returnType?: VarType;
99
+ body: Child[];
100
+ loc: Loc;
101
+ }
102
+
91
103
  export interface SinthFile {
92
104
  filePath: string;
93
105
  isPage: boolean;
94
106
  imports: ImportNode[];
95
107
  meta: MetaEntry[];
96
108
  defs: CompDef[];
109
+ functions: FunctionDef[];
97
110
  uses: CompUse[];
98
111
  styles: StyleBlock[];
99
112
  scripts: ScriptBlock[];
package/src/resolver.ts CHANGED
@@ -7,9 +7,9 @@ import { BUILTIN_MAP } from "./core/compiler.ts";
7
7
 
8
8
 
9
9
 
10
- interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
10
+ export interface ResolverConfig { projectRoot: string; libraryPaths: string[] }
11
11
 
12
- interface ResolvedImports {
12
+ export interface ResolvedImports {
13
13
  allDefs: Map<string, CompDef>;
14
14
  customEls: Map<string, CustomElInfo>;
15
15
  cssLinks: string[];