Skip to content

Design of rewriting for some sugars

lit edited this page Apr 20, 2025 · 1 revision

Design

__getitem__ & __setitem__

I used to think term like ls[1:3] (a.k.a. __getitem__(slice|tuple[slice, ...])) cannot be implemented,

as : is not a operator that user can customly defines.

However, once I found ls[1:3] is not a invalid AST, I realized it could be done via rewrite.

That's, to rewrite AST BracketExpr(ls, ExprColonExpr(a, b)) as BracketExpr(ls, Call(slice, a, b)).

That's what'll be done within def macro, on each expression.


However, none of ls[:b], ls[b:], ls[:] is valid Nim AST.

str literal concatenate

You may once write some code like following:

i = 9
s = "pre" f"{i}" fr"{i+1}\n"
assert s == "pre910\\n"

However, str literal concatenate (we call it strlitCat here) is not supported in Nim naturally, where you're told to concatenate string with &.

NimPyLib is responsible to implement it in Nim.

Technologically speaking, strlitCat is valid AST in Nim, regarded as command (nnkCommand).

Thus the following is simple:

loop up AST in form of Command(Strlit, ...) and rewrite it with & as a infix.

See pysugar/stmt/exprRewrite.nim:rewriteStrLitCat for implementation details.

Clone this wiki locally