From 6d2acd464dec1771be2f8e340950136c0eedbb86 Mon Sep 17 00:00:00 2001 From: metagn Date: Thu, 17 Oct 2024 21:55:53 +0300 Subject: [PATCH] cbuilder: add array vars, use for openarray init --- compiler/cbuilderdecls.nim | 26 ++++++++++++++++++++++++++ compiler/ccgexprs.nim | 13 ++++++------- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/compiler/cbuilderdecls.nim b/compiler/cbuilderdecls.nim index e5032d743116..f4abe5d107c1 100644 --- a/compiler/cbuilderdecls.nim +++ b/compiler/cbuilderdecls.nim @@ -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` diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 88d177800ba2..bbc9647310e5 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -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"):