parser + codegen-js: anonymous function literals (lambda syntax)

fn(params) -> RetType { body } is now valid in expression position.
The parser produces a Lambda AST node. codegen-js emits a hoisted
JS function declaration with a generated name (__lambda_N) and returns
the name as the expression value, so inline callbacks compose cleanly:

  dom_listen(btn, "click", fn(event: Any) -> Void { handle(event) })

emits:

  function __lambda_1(event) { handle(event); }
  dom_listen(btn, "click", __lambda_1);

The hoisted-declaration strategy is debuggable, has no closure-capture
issues, and requires no string-buffer mode in the codegen.
This commit is contained in:
Will Anderson
2026-05-04 10:59:17 -05:00
parent 01fee9396a
commit e23319fe0b
2 changed files with 91 additions and 0 deletions
+24
View File
@@ -279,6 +279,30 @@ fn parse_primary(tokens: [Map<String, Any>], pos: Int) -> Map<String, Any> {
return r
}
// Anonymous function literal (lambda): fn(params) -> RetType { body }
// Used for inline callbacks: dom_listen(el, "click", fn(e: Any) -> Void { ... })
// Produces a Lambda expression node (distinct from a named FnDef statement).
if k == "Fn" {
let p = pos + 1
let r = parse_params(tokens, p)
let params = r["params"]
let p = r["pos"]
let ret_type = ""
let k2 = tok_kind(tokens, p)
if k2 == "Arrow" {
let p = p + 1
let kt = tok_kind(tokens, p)
if kt == "Ident" {
let ret_type = tok_value(tokens, p)
}
let p = skip_type(tokens, p)
}
let r2 = parse_block(tokens, p)
let body = r2["stmts"]
let p = r2["pos"]
return make_result({ "expr": "Lambda", "params": params, "body": body, "ret_type": ret_type }, p)
}
// Unary not
if k == "Not" {
let r = parse_primary(tokens, pos + 1)