Skip to content

Commit

Permalink
compilerEs: refactor code generation for once and static once methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Matthew Giannini authored and Matthew Giannini committed Jul 15, 2024
1 parent 9b62739 commit 382f5bf
Show file tree
Hide file tree
Showing 3 changed files with 30 additions and 3 deletions.
14 changes: 14 additions & 0 deletions src/compilerEs/fan/ast/JsExpr.fan
Original file line number Diff line number Diff line change
Expand Up @@ -267,6 +267,20 @@ class JsExpr : JsNode
leave := x.leave
isAssign := x.assignTarget != null

// convert binary expressions testing for equivalence to
// synthetic str "_once_" to undefined
if (lhs.expr is FieldExpr)
{
fe := (FieldExpr)lhs.expr
if (rhs.expr.id === ExprId.strLiteral &&
symbol == "===" && rhs.expr->val == "_once_")
{
lhs.write
js.w(" ${symbol} undefined", loc)
return
}
}

if (isAssign && lhs.expr is FieldExpr)
{
fe := (FieldExpr)lhs.expr
Expand Down
3 changes: 2 additions & 1 deletion src/compilerEs/fan/ast/JsNode.fan
Original file line number Diff line number Diff line change
Expand Up @@ -247,10 +247,11 @@ abstract class JsNode
"sys::Str": true
]

Void writeBlock(Block? block)
Void writeBlock(Block? block, |Stmt->Bool|? filter := null)
{
if (block == null) return
block.stmts.each |stmt| {
if (filter?.call(stmt) ?: false) return
writeStmt(stmt)
js.wl(";")
}
Expand Down
16 changes: 14 additions & 2 deletions src/compilerEs/fan/ast/JsType.fan
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ class JsType : JsNode
if (instanceInit != null)
{
plugin.curMethod = instanceInit
writeBlock(instanceInit.code)
writeBlock(instanceInit.code) |stmt| { stmt.isOnceFieldInit ? true : false }
plugin.curMethod = null
}
js.unindent
Expand Down Expand Up @@ -235,6 +235,9 @@ class JsType : JsNode

private static Str fieldDefVal(FieldDef f)
{
// once fields are initialized to undefined
if (f.isOnce) return "undefined"

defVal := "null"
fieldType := f.fieldType
if (!fieldType.isNullable)
Expand Down Expand Up @@ -269,6 +272,13 @@ class JsType : JsNode
// we generate our own special version of this
if (f.parent.isEnum && accessName == "vals") return

// special handling for static once fields
if (f.isOnce)
{
js.wl("static ${accessName}(it) { if (it === undefined) return ${target}.${privName}; else ${target}.${privName} = it; }").nl
return
}

js.wl("static ${accessName}() {").indent

fieldAccess := "${target}.${privName}"
Expand Down Expand Up @@ -388,7 +398,9 @@ class JsType : JsNode
}

// method body
writeBlock(m.code)
|Stmt s->Bool|? filter := null
if (m.isStatic) filter = |Stmt s->Bool| { s.isOnceFieldInit ? true : false }
writeBlock(m.code, filter)
}

js.unindent
Expand Down

0 comments on commit 382f5bf

Please sign in to comment.