Skip to content

Commit

Permalink
feat(sugar): equal sign minus like x=-1/x==-1
Browse files Browse the repository at this point in the history
p.s. such a ast will be parsed as `=-`(x,1) in Nim
  • Loading branch information
litlighilit committed Jan 19, 2025
1 parent 62a0c81 commit 9823443
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 6 deletions.
34 changes: 32 additions & 2 deletions src/pylib/pysugar/stmt/exprRewrite.nim
Original file line number Diff line number Diff line change
Expand Up @@ -147,13 +147,34 @@ proc toDict(e): NimNode =
), eles
)


template toPyExprImpl(atm: NimNode; toListCb): NimNode =
proc rewriteEqualMinus(e; k=nnkAsgn): NimNode =
## x==-1 -> x == -1
## x=-1 -> x = -1

let lhs = e[1].toPyExpr
template rhs: NimNode = newCall("-", e[2].toPyExpr)
if e[0].eqIdent"=-":
k.newTree lhs, rhs
elif e[0].eqIdent"==-":
newCall "==", lhs, rhs
else: e

proc callToPyExpr*(e): NimNode

template toPyExprImpl(atm: NimNode; toListCb; equalMinusAs=nnkAsgn): NimNode =
case atm.kind
of nnkBracketExpr:
rewriteSliceInBracket atm
of nnkCommand:
rewriteStrLitCat atm
of nnkCall:
callToPyExpr atm
of nnkPrefix:
nnkPrefix.newTree atm[0], atm[1].toPyExpr
of nnkPar:
nnkPar.newTree atm[0].toPyExpr
of nnkInfix:
rewriteEqualMinus atm, equalMinusAs

of nnkTripleStrLit,
nnkStrLit, nnkRStrLit:
Expand All @@ -171,3 +192,12 @@ template toPyExprImpl(atm: NimNode; toListCb): NimNode =
proc toPyExpr*(atm: NimNode): NimNode = toPyExprImpl atm, toList
proc toPyExprNoList*(atm: NimNode): NimNode = toPyExprImpl atm, rewriteEachEle

proc argInCallToPyExpr(atm: NimNode): NimNode =
## f(x=-1) needs to be rewritten as Call(ExprEqExpr(Ident"x", -1))
toPyExprImpl atm, toList, nnkExprEqExpr

proc callToPyExpr*(e): NimNode =
result = e.copyNimNode
for i in e:
result.add i.argInCallToPyExpr

5 changes: 1 addition & 4 deletions src/pylib/pysugar/stmt/tonim.nim
Original file line number Diff line number Diff line change
Expand Up @@ -162,10 +162,7 @@ proc parsePyStmt*(mparser; statement: NimNode): NimNode =
if statement[^1].kind == nnkStmtList:
result.add parseBodyOnlyLast statement
else:
var nStmt = statement.copyNimNode
for i in statement:
nStmt.add i.toPyExpr
result.add nStmt
result.add statement.callToPyExpr
of nnkForStmt, nnkWhileStmt:
result.add parseBodyOnlyLast statement
elif statement.len == 0:
Expand Down
23 changes: 23 additions & 0 deletions tests/testaments/pysugar/equalMinus.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@

discard """
output: '''
-1
'''
"""

import pylib


def g():
def f(x):
return x

print(f(x=-1))

x = 3==-1
assert not(5==-1) ## NOTE: par is a must!
## or it'll be `not(5) == -1` in Nim
assert not x

g()

0 comments on commit 9823443

Please sign in to comment.