Generate procs for constants

This commit is contained in:
Emery Hemingway 2021-09-06 18:33:20 +02:00
parent 58a9f5dde4
commit 41675a2daf
1 changed files with 24 additions and 13 deletions

View File

@ -240,21 +240,35 @@ proc nimTypeOf(scm: Schema; known: var TypeTable; sn: SchemaNode; name = ""): PN
result = nkCommentStmt.newNode
result.comment.add("Missing type generator for " & $sn.kind & " " & $sn)
proc toConst(name: string; def: SchemaNode): Pnode =
proc exportIdent(id: string): PNode = nn(nkPostFix, ident"*", ident(id))
proc generateConstProcs(result: var seq[PNode]; name: string; def: SchemaNode) =
case def.kind
of snkLiteral:
result = nkConstDef.newNode.add(
name.ident.accQuote, newEmpty())
var stmts = nn(nkStmtList)
case def.value.kind
of pkSignedInteger:
discard result.add newIntNode(nkIntLit, def.value.int)
discard stmts.add newIntNode(nkIntLit, def.value.int)
of pkSymbol:
discard result.add nn(nkCall,
discard stmts.add nn(nkCall,
ident"symbol",
PNode(kind: nkStrLit, strVal: def.value.symbol),
ident"EmbeddedType")
PNode(kind: nkStrLit,
strVal: def.value.symbol),
ident"EmbeddedType")
else:
raiseAssert("cannot convert " & $def & " to a Nim literal")
raiseAssert("conversion of " & $def & " to a Nim literal is not implemented")
var procId = name
procId[0] = procId[0].toLowerAscii
let constProc= nn(nkProcDef,
exportIdent(procId),
newEmpty(),
newEmpty(),
nn(nkFormalParams, ident"Preserve"),
newEmpty(),
newEmpty(),
stmts)
constProc.comment = $def
result.add constProc
else: discard
proc toNimLit(sn: SchemaNode): PNode =
@ -336,7 +350,6 @@ proc preserveTypeOf(scm: Schema; known: var TypeTable; sn: SchemaNode; name = ""
result = nimTypeOf(scm, known, sn, name)
proc generateProcs(result: var seq[PNode]; name: string; sn: SchemaNode) =
proc exportIdent(id: string): PNode = nn(nkPostFix, ident"*", ident(id))
case sn.kind
of snkRecord:
var
@ -409,7 +422,6 @@ proc generateNimFile*(scm: Schema; path: string) =
var
knownTypes: TypeTable
typeSection = newNode nkTypeSection
constSection = newNode nkLetSection
procs: seq[PNode]
if scm.embeddedType == "":
typeSection.add nn(nkTypeDef,
@ -429,7 +441,7 @@ proc generateNimFile*(scm: Schema; path: string) =
ident"EmbeddedType"))
for name, def in scm.definitions.pairs:
if isConst(scm, def):
constSection.add toConst(name, def)
generateConstProcs(procs, name, def)
else:
var name = name
name[0] = name[0].toUpperAscii
@ -481,8 +493,7 @@ proc generateNimFile*(scm: Schema; path: string) =
collectRefImports(imports, scm)
var module = newNode(nkStmtList).add(
imports,
typeSection,
constSection
typeSection
).add(procs)
writeFile(path, renderTree(module, {renderNone, renderIr}))