Skip to content

Commit

Permalink
cbuilder: add array vars, use for openarray init
Browse files Browse the repository at this point in the history
  • Loading branch information
metagn committed Oct 17, 2024
1 parent d0b6b93 commit 6d2acd4
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 7 deletions.
26 changes: 26 additions & 0 deletions compiler/cbuilderdecls.nim
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,32 @@ template addVarWithTypeAndInitializer(builder: var Builder, kind: VarKind = Loca
initializerBody
builder.add(";\n")

proc addArrayVar(builder: var Builder, kind: VarKind = Local, name: string, elementType: Snippet, len: int, initializer: Snippet = "") =
## adds an array variable declaration to the builder
builder.addVarHeader(kind)
builder.add(elementType)
builder.add(" ")
builder.add(name)
builder.add("[")
builder.addInt(len)
builder.add("]")
if initializer.len != 0:
builder.add(" = ")
builder.add(initializer)
builder.add(";\n")

template addArrayVarWithInitializer(builder: var Builder, kind: VarKind = Local, name: string, elementType: Snippet, len: int, body: typed) =
## adds an array variable declaration to the builder with the initializer built according to `body`
builder.addVarHeader(kind)
builder.add(elementType)
builder.add(" ")
builder.add(name)
builder.add("[")
builder.addInt(len)
builder.add("] = ")
initializerBody
builder.add(";\n")

template addTypedef(builder: var Builder, name: string, typeBody: typed) =
## adds a typedef declaration to the builder with name `name` and type as
## built in `typeBody`
Expand Down
13 changes: 6 additions & 7 deletions compiler/ccgexprs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -3524,16 +3524,15 @@ proc genBracedInit(p: BProc, n: PNode; isConst: bool; optionalType: PType; resul
if n.kind != nkBracket:
internalError(p.config, n.info, "const openArray expression is not an array construction")

var data = newRopeAppender()
genConstSimpleList(p, n, isConst, data)

let payload = getTempName(p.module)
let ctype = getTypeDesc(p.module, typ.elementType)
let arrLen = n.len
appcg(p.module, cfsStrData,
"static $5 $1 $3[$2] = $4;$n", [
ctype, arrLen, payload, data,
if isConst: "const" else: ""])
var data = newBuilder("")
data.addArrayVarWithInitializer(
kind = if isConst: AlwaysConst else: Global,
name = payload, elementType = ctype, len = arrLen):
genConstSimpleList(p, n, isConst, data)
p.module.s[cfsStrData].add(data)
var openArrInit: StructInitializer
result.addStructInitializer(openArrInit, kind = siOrderedStruct):
result.addField(openArrInit, name = "Field0"):
Expand Down

0 comments on commit 6d2acd4

Please sign in to comment.