improve cliBuilder macro readability

This commit is contained in:
andri lim 2019-09-24 10:29:41 +07:00
parent d2d5661e11
commit 578c2bd857
No known key found for this signature in database
GPG Key ID: 31702AE10541E6B9

View File

@ -12,28 +12,43 @@ proc executeMyself(numModules: int) =
for i in 0..<numModules: for i in 0..<numModules:
discard execCmd appName & " " & $i discard execCmd appName & " " & $i
macro cliBuilder(stmtList: typed): untyped = proc getImportStmt(stmtList: NimNode): NimNode =
let importStmt = stmtList[0] result = stmtList[0]
importStmt.expectKind nnkImportStmt result.expectKind nnkImportStmt
let moduleCount = importStmt.len
var caseStmt = newNimNode(nnkCaseStmt) proc ofStmt(idx: int, singleModule: NimNode): NimNode =
caseStmt.add quote do: paramStr(1).parseInt
for idx, singleModule in importStmt:
# remove the "test_" prefix # remove the "test_" prefix
let moduleName = normalize(singleModule.toStrLit.strVal).substr(4) let moduleName = normalize(singleModule.toStrLit.strVal).substr(4)
let moduleMain = newIdentNode(moduleName & "Main") let moduleMain = newIdentNode(moduleName & "Main")
# construct `of` branch
let branchNode = newNimNode(nnkOfBranch)
branchNode.add newIntLitNode(idx)
branchNode.add newCall(moduleMain)
caseStmt.add branchNode
var elseBranch = newNimNode(nnkElse) # construct `of` branch
elseBranch.add quote do: # of idx: moduleMain()
echo "invalid argument" result = nnkOfBranch.newTree(
caseStmt.add elseBranch newLit(idx),
newCall(moduleMain)
)
macro cliBuilder(stmtList: typed): untyped =
let importStmt = stmtList.getImportStmt
let moduleCount = importStmt.len
# case paramStr(1).parseInt
var caseStmt = nnkCaseStmt.newTree(
quote do: paramStr(1).parseInt
)
# of 0: codeStreamMain()
# of 1: gasMeterMain()
# of 2: memoryMain()
# ...
for idx, singleModule in importStmt:
caseStmt.add ofStmt(idx, singleModule)
# else:
# echo "invalid argument"
caseStmt.add nnkElse.newTree(
quote do: echo "invalid argument"
)
result = quote do: result = quote do:
if paramCount() == 0: if paramCount() == 0: