Skip to content

Commit

Permalink
nifc: fixes top level var decls with non-literals (#322)
Browse files Browse the repository at this point in the history
* nifc: fixes top level var decls with non-literals

* adds AconstrC, OconstrC

* fixes

* implements `isLiteral`
  • Loading branch information
ringabout authored Jan 7, 2025
1 parent 4eed499 commit f0506a4
Show file tree
Hide file tree
Showing 2 changed files with 53 additions and 5 deletions.
41 changes: 36 additions & 5 deletions src/nifc/codegen.nim
Original file line number Diff line number Diff line change
Expand Up @@ -331,6 +331,25 @@ type
VarKind = enum
IsLocal, IsGlobal, IsThreadlocal, IsConst

proc isLiteral(t: Tree; n: NodePos): bool =
case t[n].kind
of IntLit, UIntLit, FloatLit,
CharLit, StrLit, FalseC, TrueC, InfC, NegInfC, NanC, SufC:
result = true
of AconstrC:
result = true
for ch in sonsFromX(t, n):
if not isLiteral(t, ch):
return false
of OconstrC:
result = true
for ch in sonsFromX(t, n):
let (_, value) = sons2(t, ch)
if not isLiteral(t, value):
return false
else:
result = false

proc genVarDecl(c: var GeneratedCode; t: Tree; n: NodePos; vk: VarKind; toExtern = false) =
let d = asVarDecl(t, n)
genCLineDir(c, t, info(t, n))
Expand All @@ -350,11 +369,23 @@ proc genVarDecl(c: var GeneratedCode; t: Tree; n: NodePos; vk: VarKind; toExtern
if vis == StaticC:
c.code.insert(Token(StaticKeyword), beforeDecl)
if t[d.value].kind != Empty:
c.add AsgnOpr
if vk != IsLocal: inc c.inSimpleInit
genx c, t, d.value
if vk != IsLocal: dec c.inSimpleInit
c.add Semicolon
if vk == IsGlobal and not isLiteral(t, d.value):
c.add Semicolon
moveToInitSection:
c.add name
c.add AsgnOpr
inc c.inSimpleInit
genx c, t, d.value
dec c.inSimpleInit
c.add Semicolon
else:
c.add AsgnOpr
if vk != IsLocal: inc c.inSimpleInit
genx c, t, d.value
if vk != IsLocal: dec c.inSimpleInit
c.add Semicolon
else:
c.add Semicolon
else:
error c.m, "expected SymbolDef but got: ", t, n

Expand Down
17 changes: 17 additions & 0 deletions tests/nimony/sysbasics/ttoplevelvars.nim
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
var x = 1
var y = 2
x = y
var z = x

const a = 1
var m = a

let s = x
let n = 3

proc foo =
var m = a
let g = x
const s = a

foo()

0 comments on commit f0506a4

Please sign in to comment.