Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[WIP] investigate tryExpr proposed by krux02 #71

Closed
wants to merge 2 commits into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 55 additions & 0 deletions lib/std/tryexprs.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
# adapted from http://ix.io/2eL3

import macros

macro tryCompile*(expr, elseBody: untyped): untyped =
var name: NimNode

if expr.kind in nnkCallKinds:
if expr[0].kind == nnkDotExpr:
name = expr[0][1]
else:
name = expr[0]
else:
if expr.kind == nnkDotExpr:
name = expr[1]
else:
name = expr

expectKind(expr[0], nnkIdent)
let templateDef = nnkTemplateDef.newTree(
name,
newEmptyNode(),
newEmptyNode(),
nnkFormalParams.newTree(
newIdentNode("untyped"),
nnkIdentDefs.newTree(
newIdentNode("arg"),
newIdentNode("untyped"),
newEmptyNode()
)
),
newEmptyNode(),
newEmptyNode(),
nnkStmtList.newTree(
elseBody
)
)

result = quote do:
`templateDef`
`expr`

when isMainModule:
type
MyObject = object

var myInt: int = 123
var mySeq = @['a','b','c']
var myString = "abcdef"
var myObject: MyObject

doAssert tryCompile(myInt.len, 10) == 10
doAssert tryCompile(mySeq.len, 11) == 3
doAssert tryCompile(myString.len, 12) == 6
doAssert tryCompile(myObject.len, 13) == 13