Skip to content

Commit

Permalink
impr(tonim): no list init-ed for unpack an array; tonim runs alone now
Browse files Browse the repository at this point in the history
  • Loading branch information
litlighilit committed Jan 1, 2025
1 parent da8681d commit c5da721
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
17 changes: 12 additions & 5 deletions src/pylib/pysugar/stmt/exprRewrite.nim
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,11 @@ template asisIfEmpty(e) =
func getTypeof(e: NimNode): NimNode =
newCall("typeof", e)

proc rewriteEachEle(e: NimNode; bracketNode = nnkBracket): NimNode =
result = newNimNode bracketNode
for i in e:
result.add i.toPyExpr

template mapEleCall(
initCall, e: NimNode;
bracketNode = nnkBracket,
Expand All @@ -94,9 +99,7 @@ template mapEleCall(
with original `PyTComplex` type (a.k.a. being regarded as a new type)
]#
e.asisIfEmpty
var res = newNimNode bracketNode
for i in e:
res.add i.toPyExpr
let res = rewriteEachEle(e, bracketNode)
let eleTyp = getTypeof res[0]
newCall(
nnkBracketExpr.newTree(
Expand Down Expand Up @@ -137,7 +140,7 @@ proc toDict(e): NimNode =
)


proc toPyExpr*(atm: NimNode): NimNode =
template toPyExprImpl(atm: NimNode; toListCb): NimNode =
case atm.kind
of nnkBracketExpr:
rewriteSliceInBracket atm
Expand All @@ -151,8 +154,12 @@ proc toPyExpr*(atm: NimNode): NimNode =
# NOTE: f"xxx" does perform `translateEscape`
# so we don't perform translation here

of nnkBracket: atm.toList
of nnkBracket: atm.toListCb
of nnkCurly: atm.toSet
of nnkTableConstr:atm.toDict
else:
atm

proc toPyExpr*(atm: NimNode): NimNode = toPyExprImpl atm, toList
proc toPyExprNoList*(atm: NimNode): NimNode = toPyExprImpl atm, rewriteEachEle

12 changes: 7 additions & 5 deletions src/pylib/pysugar/stmt/tonim.nim
Original file line number Diff line number Diff line change
Expand Up @@ -75,17 +75,19 @@ proc parsePyStmt*(mparser; statement: NimNode): NimNode =
result.add newVarStmt(varName, varValue)
mparser.add $varName

let (varName, varValue) = (statement[0], statement[1].toPyExpr)
let (varName, varValue) = (statement[0], statement[1])
case varName.kind
of nnkIdent:
handleVar varName, varValue
handleVar varName, varValue.toPyExpr
of nnkTupleConstr:
unpackImplRec(data=varValue, symbols=varName, res=result, receiver=handleVar)
# no need to construct list if meeting `nnkBracket`
unpackImplRec(data=varValue.toPyExprNoList,
symbols=varName, res=result, receiver=handleVar)
of nnkBracketExpr:
result.add newAssignment(varName.toPyExpr, varValue)
result.add newAssignment(varName.toPyExpr, varValue.toPyExpr)
else:
# varName may be `nnkDotExpr`. e.g.`a.b=1`
result.add statement.copyNimNode.add(varName, varValue)
result.add statement.copyNimNode.add(varName, varValue.toPyExpr)
of nnkCommand:
let preCmd = $statement[0]
case preCmd
Expand Down

0 comments on commit c5da721

Please sign in to comment.