case consistency: cs:partial bootstraps on windows

This commit is contained in:
Araq 2013-12-29 03:19:10 +01:00
commit b731e6ef1c
58 changed files with 384 additions and 377 deletions

View file

@ -546,7 +546,7 @@ type
typ*: PType typ*: PType
info*: TLineInfo info*: TLineInfo
flags*: TNodeFlags flags*: TNodeFlags
case Kind*: TNodeKind case kind*: TNodeKind
of nkCharLit..nkUInt64Lit: of nkCharLit..nkUInt64Lit:
intVal*: BiggestInt intVal*: BiggestInt
of nkFloatLit..nkFloat128Lit: of nkFloatLit..nkFloat128Lit:
@ -822,7 +822,7 @@ const
# imported via 'importc: "fullname"' and no format string. # imported via 'importc: "fullname"' and no format string.
# creator procs: # creator procs:
proc newSym*(symKind: TSymKind, Name: PIdent, owner: PSym, proc newSym*(symKind: TSymKind, name: PIdent, owner: PSym,
info: TLineInfo): PSym info: TLineInfo): PSym
proc newType*(kind: TTypeKind, owner: PSym): PType proc newType*(kind: TTypeKind, owner: PSym): PType
proc newNode*(kind: TNodeKind): PNode proc newNode*(kind: TNodeKind): PNode
@ -1108,7 +1108,7 @@ proc assignType(dest, src: PType) =
for i in countup(0, sonsLen(src) - 1): dest.sons[i] = src.sons[i] for i in countup(0, sonsLen(src) - 1): dest.sons[i] = src.sons[i]
proc copyType(t: PType, owner: PSym, keepId: bool): PType = proc copyType(t: PType, owner: PSym, keepId: bool): PType =
result = newType(t.Kind, owner) result = newType(t.kind, owner)
assignType(result, t) assignType(result, t)
if keepId: if keepId:
result.id = t.id result.id = t.id
@ -1148,12 +1148,12 @@ proc createModuleAlias*(s: PSym, newIdent: PIdent, info: TLineInfo): PSym =
# XXX once usedGenerics is used, ensure module aliases keep working! # XXX once usedGenerics is used, ensure module aliases keep working!
assert s.usedGenerics == nil assert s.usedGenerics == nil
proc newSym(symKind: TSymKind, Name: PIdent, owner: PSym, proc newSym(symKind: TSymKind, name: PIdent, owner: PSym,
info: TLineInfo): PSym = info: TLineInfo): PSym =
# generates a symbol and initializes the hash field too # generates a symbol and initializes the hash field too
new(result) new(result)
result.Name = Name result.name = name
result.Kind = symKind result.kind = symKind
result.flags = {} result.flags = {}
result.info = info result.info = info
result.options = gOptions result.options = gOptions
@ -1270,7 +1270,7 @@ proc copyNode(src: PNode): PNode =
when defined(useNodeIds): when defined(useNodeIds):
if result.id == nodeIdToDebug: if result.id == nodeIdToDebug:
echo "COMES FROM ", src.id echo "COMES FROM ", src.id
case src.Kind case src.kind
of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
of nkSym: result.sym = src.sym of nkSym: result.sym = src.sym
@ -1288,7 +1288,7 @@ proc shallowCopy*(src: PNode): PNode =
when defined(useNodeIds): when defined(useNodeIds):
if result.id == nodeIdToDebug: if result.id == nodeIdToDebug:
echo "COMES FROM ", src.id echo "COMES FROM ", src.id
case src.Kind case src.kind
of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
of nkSym: result.sym = src.sym of nkSym: result.sym = src.sym
@ -1307,7 +1307,7 @@ proc copyTree(src: PNode): PNode =
when defined(useNodeIds): when defined(useNodeIds):
if result.id == nodeIdToDebug: if result.id == nodeIdToDebug:
echo "COMES FROM ", src.id echo "COMES FROM ", src.id
case src.Kind case src.kind
of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
of nkSym: result.sym = src.sym of nkSym: result.sym = src.sym

View file

@ -626,7 +626,7 @@ proc strTableGet(t: TStrTable, name: PIdent): PSym =
proc initIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym = proc initIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym =
ti.h = s.h ti.h = s.h
ti.name = s ti.name = s
if tab.Counter == 0: result = nil if tab.counter == 0: result = nil
else: result = nextIdentIter(ti, tab) else: result = nextIdentIter(ti, tab)
proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym =
@ -635,7 +635,7 @@ proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym =
start = h start = h
result = tab.data[h] result = tab.data[h]
while result != nil: while result != nil:
if result.Name.id == ti.name.id: break if result.name.id == ti.name.id: break
h = nextTry(h, high(tab.data)) h = nextTry(h, high(tab.data))
if h == start: if h == start:
result = nil result = nil
@ -649,7 +649,7 @@ proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable,
var start = h var start = h
result = tab.data[h] result = tab.data[h]
while result != nil: while result != nil:
if result.Name.id == ti.name.id and not contains(excluding, result.id): if result.name.id == ti.name.id and not contains(excluding, result.id):
break break
h = nextTry(h, high(tab.data)) h = nextTry(h, high(tab.data))
if h == start: if h == start:
@ -663,7 +663,7 @@ proc firstIdentExcluding*(ti: var TIdentIter, tab: TStrTable, s: PIdent,
excluding: TIntSet): PSym = excluding: TIntSet): PSym =
ti.h = s.h ti.h = s.h
ti.name = s ti.name = s
if tab.Counter == 0: result = nil if tab.counter == 0: result = nil
else: result = nextIdentExcluding(ti, tab, excluding) else: result = nextIdentExcluding(ti, tab, excluding)
proc initTabIter(ti: var TTabIter, tab: TStrTable): PSym = proc initTabIter(ti: var TTabIter, tab: TStrTable): PSym =

View file

@ -13,7 +13,7 @@ import parseutils, strutils, strtabs, os, options, msgs, lists
proc addPath*(path: string, info: TLineInfo) = proc addPath*(path: string, info: TLineInfo) =
if not contains(options.searchPaths, path): if not contains(options.searchPaths, path):
lists.PrependStr(options.searchPaths, path) lists.prependStr(options.searchPaths, path)
proc versionSplitPos(s: string): int = proc versionSplitPos(s: string): int =
result = s.len-2 result = s.len-2
@ -61,7 +61,7 @@ iterator chosen(packages: PStringTable): string =
proc addBabelPath(p: string, info: TLineInfo) = proc addBabelPath(p: string, info: TLineInfo) =
if not contains(options.searchPaths, p): if not contains(options.searchPaths, p):
if gVerbosity >= 1: message(info, hintPath, p) if gVerbosity >= 1: message(info, hintPath, p)
lists.PrependStr(options.lazyPaths, p) lists.prependStr(options.lazyPaths, p)
proc addPathWithNimFiles(p: string, info: TLineInfo) = proc addPathWithNimFiles(p: string, info: TLineInfo) =
proc hasNimFile(dir: string): bool = proc hasNimFile(dir: string): bool =

View file

@ -436,7 +436,7 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
else: else:
var storage: PRope var storage: PRope
var size = getSize(t) var size = getSize(t)
if size < platform.IntSize: if size < platform.intSize:
storage = toRope("NI") storage = toRope("NI")
else: else:
storage = getTypeDesc(p.module, t) storage = getTypeDesc(p.module, t)
@ -444,7 +444,7 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
linefmt(p, cpsLocals, "$1 $2;$n", storage, tmp) linefmt(p, cpsLocals, "$1 $2;$n", storage, tmp)
lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n", lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n",
tmp, toRope(prc[m]), rdLoc(a), rdLoc(b)) tmp, toRope(prc[m]), rdLoc(a), rdLoc(b))
if size < platform.IntSize or t.kind in {tyRange, tyEnum, tySet}: if size < platform.intSize or t.kind in {tyRange, tyEnum, tySet}:
linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n",
tmp, intLiteral(firstOrd(t)), intLiteral(lastOrd(t))) tmp, intLiteral(firstOrd(t)), intLiteral(lastOrd(t)))
putIntoDest(p, d, e.typ, ropef("(NI$1)($2)", [toRope(getSize(t)*8), tmp])) putIntoDest(p, d, e.typ, ropef("(NI$1)($2)", [toRope(getSize(t)*8), tmp]))
@ -838,7 +838,7 @@ proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
proc genEcho(p: BProc, n: PNode) = proc genEcho(p: BProc, n: PNode) =
# this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)`` # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)``
# is threadsafe. # is threadsafe.
discard lists.IncludeStr(p.module.headerFiles, "<stdio.h>") discard lists.includeStr(p.module.headerFiles, "<stdio.h>")
var args: PRope = nil var args: PRope = nil
var a: TLoc var a: TLoc
for i in countup(1, n.len-1): for i in countup(1, n.len-1):
@ -872,7 +872,7 @@ proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
for i in countup(0, sonsLen(e) - 2): for i in countup(0, sonsLen(e) - 2):
# compute the length expression: # compute the length expression:
initLocExpr(p, e.sons[i + 1], a) initLocExpr(p, e.sons[i + 1], a)
if skipTypes(e.sons[i + 1].Typ, abstractVarRange).kind == tyChar: if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar:
inc(L) inc(L)
app(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a))) app(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a)))
else: else:
@ -910,7 +910,7 @@ proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
for i in countup(0, sonsLen(e) - 3): for i in countup(0, sonsLen(e) - 3):
# compute the length expression: # compute the length expression:
initLocExpr(p, e.sons[i + 2], a) initLocExpr(p, e.sons[i + 2], a)
if skipTypes(e.sons[i + 2].Typ, abstractVarRange).kind == tyChar: if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar:
inc(L) inc(L)
app(appends, rfmt(p.module, "#appendChar($1, $2);$n", app(appends, rfmt(p.module, "#appendChar($1, $2);$n",
rdLoc(dest), rdLoc(a))) rdLoc(dest), rdLoc(a)))
@ -940,7 +940,7 @@ proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) =
lineCg(p, cpsStmts, seqAppendPattern, [ lineCg(p, cpsStmts, seqAppendPattern, [
rdLoc(a), rdLoc(a),
getTypeDesc(p.module, skipTypes(e.sons[1].typ, abstractVar)), getTypeDesc(p.module, skipTypes(e.sons[1].typ, abstractVar)),
getTypeDesc(p.module, skipTypes(e.sons[2].Typ, abstractVar))]) getTypeDesc(p.module, skipTypes(e.sons[2].typ, abstractVar))])
keepAlive(p, a) keepAlive(p, a)
initLoc(dest, locExpr, b.t, OnHeap) initLoc(dest, locExpr, b.t, OnHeap)
dest.r = rfmt(nil, "$1->data[$1->$2-1]", rdLoc(a), lenField()) dest.r = rfmt(nil, "$1->data[$1->$2-1]", rdLoc(a), lenField())
@ -1191,7 +1191,7 @@ proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) =
proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) = proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
var a = e.sons[1] var a = e.sons[1]
if a.kind == nkHiddenAddr: a = a.sons[0] if a.kind == nkHiddenAddr: a = a.sons[0]
var typ = skipTypes(a.Typ, abstractVar) var typ = skipTypes(a.typ, abstractVar)
case typ.kind case typ.kind
of tyOpenArray, tyVarargs: of tyOpenArray, tyVarargs:
if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)") if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)")
@ -1259,7 +1259,7 @@ proc fewCmps(s: PNode): bool =
if s.kind != nkCurly: internalError(s.info, "fewCmps") if s.kind != nkCurly: internalError(s.info, "fewCmps")
if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags): if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags):
result = false # it is better to emit the set generation code result = false # it is better to emit the set generation code
elif elemType(s.typ).Kind in {tyInt, tyInt16..tyInt64}: elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}:
result = true # better not emit the set if int is basetype! result = true # better not emit the set if int is basetype!
else: else:
result = sonsLen(s) <= 8 # 8 seems to be a good value result = sonsLen(s) <= 8 # 8 seems to be a good value
@ -1284,7 +1284,7 @@ proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) =
proc genInOp(p: BProc, e: PNode, d: var TLoc) = proc genInOp(p: BProc, e: PNode, d: var TLoc) =
var a, b, x, y: TLoc var a, b, x, y: TLoc
if (e.sons[1].Kind == nkCurly) and fewCmps(e.sons[1]): if (e.sons[1].kind == nkCurly) and fewCmps(e.sons[1]):
# a set constructor but not a constant set: # a set constructor but not a constant set:
# do not emit the set, but generate a bunch of comparisons; and if we do # do not emit the set, but generate a bunch of comparisons; and if we do
# so, we skip the unnecessary range check: This is a semantical extension # so, we skip the unnecessary range check: This is a semantical extension
@ -1298,7 +1298,7 @@ proc genInOp(p: BProc, e: PNode, d: var TLoc) =
b.r = toRope("(") b.r = toRope("(")
var length = sonsLen(e.sons[1]) var length = sonsLen(e.sons[1])
for i in countup(0, length - 1): for i in countup(0, length - 1):
if e.sons[1].sons[i].Kind == nkRange: if e.sons[1].sons[i].kind == nkRange:
initLocExpr(p, e.sons[1].sons[i].sons[0], x) initLocExpr(p, e.sons[1].sons[i].sons[0], x)
initLocExpr(p, e.sons[1].sons[i].sons[1], y) initLocExpr(p, e.sons[1].sons[i].sons[1], y)
appf(b.r, "$1 >= $2 && $1 <= $3", appf(b.r, "$1 >= $2 && $1 <= $3",
@ -1326,7 +1326,7 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
"if ($3) $3 = (memcmp($4, $5, $2) != 0);$n", "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n",
"&", "|", "& ~", "^"] "&", "|", "& ~", "^"]
var a, b, i: TLoc var a, b, i: TLoc
var setType = skipTypes(e.sons[1].Typ, abstractVar) var setType = skipTypes(e.sons[1].typ, abstractVar)
var size = int(getSize(setType)) var size = int(getSize(setType))
case size case size
of 1, 2, 4, 8: of 1, 2, 4, 8:
@ -1512,25 +1512,25 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
of mGetTypeInfo: genGetTypeInfo(p, e, d) of mGetTypeInfo: genGetTypeInfo(p, e, d)
of mSwap: genSwap(p, e, d) of mSwap: genSwap(p, e, d)
of mUnaryLt: of mUnaryLt:
if not (optOverflowCheck in p.Options): unaryExpr(p, e, d, "$1 - 1") if not (optOverflowCheck in p.options): unaryExpr(p, e, d, "$1 - 1")
else: unaryExpr(p, e, d, "#subInt($1, 1)") else: unaryExpr(p, e, d, "#subInt($1, 1)")
of mPred: of mPred:
# XXX: range checking? # XXX: range checking?
if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 - $2") if not (optOverflowCheck in p.options): binaryExpr(p, e, d, "$1 - $2")
else: binaryExpr(p, e, d, "#subInt($1, $2)") else: binaryExpr(p, e, d, "#subInt($1, $2)")
of mSucc: of mSucc:
# XXX: range checking? # XXX: range checking?
if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 + $2") if not (optOverflowCheck in p.options): binaryExpr(p, e, d, "$1 + $2")
else: binaryExpr(p, e, d, "#addInt($1, $2)") else: binaryExpr(p, e, d, "#addInt($1, $2)")
of mInc: of mInc:
if not (optOverflowCheck in p.Options): if not (optOverflowCheck in p.options):
binaryStmt(p, e, d, "$1 += $2;$n") binaryStmt(p, e, d, "$1 += $2;$n")
elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64: elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64:
binaryStmt(p, e, d, "$1 = #addInt64($1, $2);$n") binaryStmt(p, e, d, "$1 = #addInt64($1, $2);$n")
else: else:
binaryStmt(p, e, d, "$1 = #addInt($1, $2);$n") binaryStmt(p, e, d, "$1 = #addInt($1, $2);$n")
of ast.mDec: of ast.mDec:
if not (optOverflowCheck in p.Options): if not (optOverflowCheck in p.options):
binaryStmt(p, e, d, "$1 -= $2;$n") binaryStmt(p, e, d, "$1 -= $2;$n")
elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64: elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64:
binaryStmt(p, e, d, "$1 = #subInt64($1, $2);$n") binaryStmt(p, e, d, "$1 = #subInt64($1, $2);$n")
@ -1778,7 +1778,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) =
case n.kind case n.kind
of nkSym: of nkSym:
var sym = n.sym var sym = n.sym
case sym.Kind case sym.kind
of skMethod: of skMethod:
if sym.getBody.kind == nkEmpty or sfDispatcher in sym.flags: if sym.getBody.kind == nkEmpty or sfDispatcher in sym.flags:
# we cannot produce code for the dispatcher yet: # we cannot produce code for the dispatcher yet:
@ -1990,7 +1990,7 @@ proc genConstSeq(p: BProc, n: PNode, t: PType): PRope =
result = ropef("(($1)&$2)", [getTypeDesc(p.module, t), result]) result = ropef("(($1)&$2)", [getTypeDesc(p.module, t), result])
proc genConstExpr(p: BProc, n: PNode): PRope = proc genConstExpr(p: BProc, n: PNode): PRope =
case n.Kind case n.kind
of nkHiddenStdConv, nkHiddenSubConv: of nkHiddenStdConv, nkHiddenSubConv:
result = genConstExpr(p, n.sons[1]) result = genConstExpr(p, n.sons[1])
of nkCurly: of nkCurly:

View file

@ -108,7 +108,7 @@ proc genMergeInfo*(m: BModule): PRope =
s.add("labels:") s.add("labels:")
encodeVInt(m.labels, s) encodeVInt(m.labels, s)
s.add(" hasframe:") s.add(" hasframe:")
encodeVInt(ord(m.FrameDeclared), s) encodeVInt(ord(m.frameDeclared), s)
s.add(tnl) s.add(tnl)
s.add("*/") s.add("*/")
result = s.toRope result = s.toRope
@ -119,8 +119,8 @@ proc skipWhite(L: var TBaseLexer) =
var pos = L.bufpos var pos = L.bufpos
while true: while true:
case ^pos case ^pos
of CR: pos = nimlexbase.HandleCR(L, pos) of CR: pos = nimlexbase.handleCR(L, pos)
of LF: pos = nimlexbase.HandleLF(L, pos) of LF: pos = nimlexbase.handleLF(L, pos)
of ' ': inc pos of ' ': inc pos
else: break else: break
L.bufpos = pos L.bufpos = pos
@ -129,8 +129,8 @@ proc skipUntilCmd(L: var TBaseLexer) =
var pos = L.bufpos var pos = L.bufpos
while true: while true:
case ^pos case ^pos
of CR: pos = nimlexbase.HandleCR(L, pos) of CR: pos = nimlexbase.handleCR(L, pos)
of LF: pos = nimlexbase.HandleLF(L, pos) of LF: pos = nimlexbase.handleLF(L, pos)
of '\0': break of '\0': break
of '/': of '/':
if ^(pos+1) == '*' and ^(pos+2) == '\t': if ^(pos+1) == '*' and ^(pos+2) == '\t':
@ -179,11 +179,11 @@ proc readVerbatimSection(L: var TBaseLexer): PRope =
while true: while true:
case buf[pos] case buf[pos]
of CR: of CR:
pos = nimlexbase.HandleCR(L, pos) pos = nimlexbase.handleCR(L, pos)
buf = L.buf buf = L.buf
r.add(tnl) r.add(tnl)
of LF: of LF:
pos = nimlexbase.HandleLF(L, pos) pos = nimlexbase.handleLF(L, pos)
buf = L.buf buf = L.buf
r.add(tnl) r.add(tnl)
of '\0': of '\0':
@ -249,7 +249,7 @@ proc processMergeInfo(L: var TBaseLexer, m: BModule) =
of "declared": readIntSet(L, m.declaredThings) of "declared": readIntSet(L, m.declaredThings)
of "typeInfo": readIntSet(L, m.typeInfoMarker) of "typeInfo": readIntSet(L, m.typeInfoMarker)
of "labels": m.labels = decodeVInt(L.buf, L.bufpos) of "labels": m.labels = decodeVInt(L.buf, L.bufpos)
of "hasframe": m.FrameDeclared = decodeVInt(L.buf, L.bufpos) != 0 of "hasframe": m.frameDeclared = decodeVInt(L.buf, L.bufpos) != 0
else: internalError("ccgmerge: unkown key: " & k) else: internalError("ccgmerge: unkown key: " & k)
when not defined(nimhygiene): when not defined(nimhygiene):

View file

@ -126,7 +126,7 @@ proc genGotoState(p: BProc, n: PNode) =
var a: TLoc var a: TLoc
initLocExpr(p, n.sons[0], a) initLocExpr(p, n.sons[0], a)
lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)]) lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)])
p.BeforeRetNeeded = true p.beforeRetNeeded = true
lineF(p, cpsStmts, "case -1: goto BeforeRet;$n", []) lineF(p, cpsStmts, "case -1: goto BeforeRet;$n", [])
for i in 0 .. lastOrd(n.sons[0].typ): for i in 0 .. lastOrd(n.sons[0].typ):
lineF(p, cpsStmts, "case $1: goto STATE$1;$n", [toRope(i)]) lineF(p, cpsStmts, "case $1: goto STATE$1;$n", [toRope(i)])
@ -588,7 +588,7 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) =
proc branchHasTooBigRange(b: PNode): bool = proc branchHasTooBigRange(b: PNode): bool =
for i in countup(0, sonsLen(b)-2): for i in countup(0, sonsLen(b)-2):
# last son is block # last son is block
if (b.sons[i].Kind == nkRange) and if (b.sons[i].kind == nkRange) and
b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit: b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit:
return true return true
@ -706,7 +706,7 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) =
expr(p, t.sons[0], d) expr(p, t.sons[0], d)
length = sonsLen(t) length = sonsLen(t)
endBlock(p, ropecg(p.module, "} catch (NimException& $1) {$n", [exc])) endBlock(p, ropecg(p.module, "} catch (NimException& $1) {$n", [exc]))
if optStackTrace in p.Options: if optStackTrace in p.options:
linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n") linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n")
inc p.inExceptBlock inc p.inExceptBlock
i = 1 i = 1
@ -779,7 +779,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) =
# #
if not isEmptyType(t.typ) and d.k == locNone: if not isEmptyType(t.typ) and d.k == locNone:
getTemp(p, t.typ, d) getTemp(p, t.typ, d)
discard lists.IncludeStr(p.module.headerFiles, "<setjmp.h>") discard lists.includeStr(p.module.headerFiles, "<setjmp.h>")
genLineDir(p, t) genLineDir(p, t)
var safePoint = getTempName() var safePoint = getTempName()
discard cgsym(p.module, "E_Base") discard cgsym(p.module, "E_Base")
@ -794,7 +794,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) =
endBlock(p) endBlock(p)
startBlock(p, "else {$n") startBlock(p, "else {$n")
linefmt(p, cpsStmts, "#popSafePoint();$n") linefmt(p, cpsStmts, "#popSafePoint();$n")
if optStackTrace in p.Options: if optStackTrace in p.options:
linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n") linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n")
inc p.inExceptBlock inc p.inExceptBlock
var i = 1 var i = 1
@ -833,7 +833,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) =
proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): PRope = proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): PRope =
var res = "" var res = ""
for i in countup(0, sonsLen(t) - 1): for i in countup(0, sonsLen(t) - 1):
case t.sons[i].Kind case t.sons[i].kind
of nkStrLit..nkTripleStrLit: of nkStrLit..nkTripleStrLit:
res.add(t.sons[i].strVal) res.add(t.sons[i].strVal)
of nkSym: of nkSym:
@ -892,7 +892,7 @@ var
proc genBreakPoint(p: BProc, t: PNode) = proc genBreakPoint(p: BProc, t: PNode) =
var name: string var name: string
if optEndb in p.Options: if optEndb in p.options:
if t.kind == nkExprColonExpr: if t.kind == nkExprColonExpr:
assert(t.sons[1].kind in {nkStrLit..nkTripleStrLit}) assert(t.sons[1].kind in {nkStrLit..nkTripleStrLit})
name = normalize(t.sons[1].strVal) name = normalize(t.sons[1].strVal)
@ -906,7 +906,7 @@ proc genBreakPoint(p: BProc, t: PNode) =
makeCString(name)]) makeCString(name)])
proc genWatchpoint(p: BProc, n: PNode) = proc genWatchpoint(p: BProc, n: PNode) =
if optEndb notin p.Options: return if optEndb notin p.options: return
var a: TLoc var a: TLoc
initLocExpr(p, n.sons[1], a) initLocExpr(p, n.sons[1], a)
let typ = skipTypes(n.sons[1].typ, abstractVarRange) let typ = skipTypes(n.sons[1].typ, abstractVarRange)

View file

@ -16,7 +16,7 @@ proc emulatedThreadVars(): bool =
result = {optThreads, optTlsEmulation} <= gGlobalOptions result = {optThreads, optTlsEmulation} <= gGlobalOptions
proc accessThreadLocalVar(p: BProc, s: PSym) = proc accessThreadLocalVar(p: BProc, s: PSym) =
if emulatedThreadVars() and not p.ThreadVarAccessed: if emulatedThreadVars() and not p.threadVarAccessed:
p.threadVarAccessed = true p.threadVarAccessed = true
p.module.usesThreadVars = true p.module.usesThreadVars = true
appf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV;$n") appf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV;$n")

View file

@ -246,7 +246,7 @@ proc ccgIntroducedPtr(s: PSym): bool =
assert skResult != s.kind assert skResult != s.kind
if tfByRef in pt.flags: return true if tfByRef in pt.flags: return true
elif tfByCopy in pt.flags: return false elif tfByCopy in pt.flags: return false
case pt.Kind case pt.kind
of tyObject: of tyObject:
if (optByRef in s.options) or (getSize(pt) > platform.floatSize * 2): if (optByRef in s.options) or (getSize(pt) > platform.floatSize * 2):
result = true # requested anyway result = true # requested anyway
@ -305,7 +305,7 @@ proc genProcParams(m: BModule, t: PType, rettype, params: var PRope,
var arr = param.typ var arr = param.typ
if arr.kind == tyVar: arr = arr.sons[0] if arr.kind == tyVar: arr = arr.sons[0]
var j = 0 var j = 0
while arr.Kind in {tyOpenArray, tyVarargs}: while arr.kind in {tyOpenArray, tyVarargs}:
# this fixes the 'sort' bug: # this fixes the 'sort' bug:
if param.typ.kind == tyVar: param.loc.s = OnUnknown if param.typ.kind == tyVar: param.loc.s = OnUnknown
# need to pass hidden parameter: # need to pass hidden parameter:
@ -344,7 +344,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope =
"NI", "NI8", "NI16", "NI32", "NI64", "NI", "NI8", "NI16", "NI32", "NI64",
"NF", "NF32", "NF64", "NF128", "NF", "NF32", "NF64", "NF128",
"NU", "NU8", "NU16", "NU32", "NU64",] "NU", "NU8", "NU16", "NU32", "NU64",]
case typ.Kind case typ.kind
of tyPointer: of tyPointer:
result = typeNameOrLiteral(typ, "void*") result = typeNameOrLiteral(typ, "void*")
of tyEnum: of tyEnum:
@ -367,7 +367,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope =
of tyChar: result = typeNameOrLiteral(typ, "NIM_CHAR") of tyChar: result = typeNameOrLiteral(typ, "NIM_CHAR")
of tyNil: result = typeNameOrLiteral(typ, "0") of tyNil: result = typeNameOrLiteral(typ, "0")
of tyInt..tyUInt64: of tyInt..tyUInt64:
result = typeNameOrLiteral(typ, NumericalTypeToStr[typ.Kind]) result = typeNameOrLiteral(typ, NumericalTypeToStr[typ.kind])
of tyRange: result = getSimpleTypeDesc(m, typ.sons[0]) of tyRange: result = getSimpleTypeDesc(m, typ.sons[0])
else: result = nil else: result = nil
@ -509,14 +509,14 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope =
# XXX: this BUG is hard to fix -> we need to introduce helper structs, # XXX: this BUG is hard to fix -> we need to introduce helper structs,
# but determining when this needs to be done is hard. We should split # but determining when this needs to be done is hard. We should split
# C type generation into an analysis and a code generation phase somehow. # C type generation into an analysis and a code generation phase somehow.
case t.Kind case t.kind
of tyRef, tyPtr, tyVar: of tyRef, tyPtr, tyVar:
et = getUniqueType(t.sons[0]) et = getUniqueType(t.sons[0])
if et.kind in {tyArrayConstr, tyArray, tyOpenArray, tyVarargs}: if et.kind in {tyArrayConstr, tyArray, tyOpenArray, tyVarargs}:
# this is correct! sets have no proper base type, so we treat # this is correct! sets have no proper base type, so we treat
# ``var set[char]`` in `getParamTypeDesc` # ``var set[char]`` in `getParamTypeDesc`
et = getUniqueType(elemType(et)) et = getUniqueType(elemType(et))
case et.Kind case et.kind
of tyObject, tyTuple: of tyObject, tyTuple:
# no restriction! We have a forward declaration for structs # no restriction! We have a forward declaration for structs
name = getTypeForward(m, et) name = getTypeForward(m, et)

View file

@ -75,12 +75,12 @@ proc isSimpleConst(typ: PType): bool =
proc useStringh(m: BModule) = proc useStringh(m: BModule) =
if not m.includesStringh: if not m.includesStringh:
m.includesStringh = true m.includesStringh = true
discard lists.IncludeStr(m.headerFiles, "<string.h>") discard lists.includeStr(m.headerFiles, "<string.h>")
proc useHeader(m: BModule, sym: PSym) = proc useHeader(m: BModule, sym: PSym) =
if lfHeader in sym.loc.Flags: if lfHeader in sym.loc.flags:
assert(sym.annex != nil) assert(sym.annex != nil)
discard lists.IncludeStr(m.headerFiles, getStr(sym.annex.path)) discard lists.includeStr(m.headerFiles, getStr(sym.annex.path))
proc cgsym(m: BModule, name: string): PRope proc cgsym(m: BModule, name: string): PRope
@ -279,11 +279,11 @@ proc genLineDir(p: BProc, t: PNode) =
if optEmbedOrigSrc in gGlobalOptions: if optEmbedOrigSrc in gGlobalOptions:
app(p.s(cpsStmts), con(~"//", t.info.sourceLine, rnl)) app(p.s(cpsStmts), con(~"//", t.info.sourceLine, rnl))
genCLineDir(p.s(cpsStmts), t.info.toFullPath, line) genCLineDir(p.s(cpsStmts), t.info.toFullPath, line)
if ({optStackTrace, optEndb} * p.Options == {optStackTrace, optEndb}) and if ({optStackTrace, optEndb} * p.options == {optStackTrace, optEndb}) and
(p.prc == nil or sfPure notin p.prc.flags): (p.prc == nil or sfPure notin p.prc.flags):
linefmt(p, cpsStmts, "#endb($1, $2);$n", linefmt(p, cpsStmts, "#endb($1, $2);$n",
line.toRope, makeCString(toFilename(t.info))) line.toRope, makeCString(toFilename(t.info)))
elif ({optLineTrace, optStackTrace} * p.Options == elif ({optLineTrace, optStackTrace} * p.options ==
{optLineTrace, optStackTrace}) and {optLineTrace, optStackTrace}) and
(p.prc == nil or sfPure notin p.prc.flags): (p.prc == nil or sfPure notin p.prc.flags):
linefmt(p, cpsStmts, "nimln($1, $2);$n", linefmt(p, cpsStmts, "nimln($1, $2);$n",
@ -724,7 +724,7 @@ proc generateHeaders(m: BModule) =
appf(m.s[cfsHeaders], "$N#include \"$1\"$N", [toRope(it.data)]) appf(m.s[cfsHeaders], "$N#include \"$1\"$N", [toRope(it.data)])
else: else:
appf(m.s[cfsHeaders], "$N#include $1$N", [toRope(it.data)]) appf(m.s[cfsHeaders], "$N#include $1$N", [toRope(it.data)])
it = PStrEntry(it.Next) it = PStrEntry(it.next)
proc retIsNotVoid(s: PSym): bool = proc retIsNotVoid(s: PSym): bool =
result = (s.typ.sons[0] != nil) and not isInvalidReturnType(s.typ.sons[0]) result = (s.typ.sons[0] != nil) and not isInvalidReturnType(s.typ.sons[0])
@ -784,7 +784,7 @@ proc genProcAux(m: BModule, prc: PSym) =
genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. genStmts(p, prc.getBody) # modifies p.locals, p.init, etc.
var generatedProc: PRope var generatedProc: PRope
if sfPure in prc.flags: if sfPure in prc.flags:
if hasNakedDeclspec in extccomp.CC[extccomp.ccompiler].props: if hasNakedDeclspec in extccomp.CC[extccomp.cCompiler].props:
header = con("__declspec(naked) ", header) header = con("__declspec(naked) ", header)
generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N", generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N",
header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)) header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts))
@ -811,8 +811,8 @@ proc genProcAux(m: BModule, prc: PSym) =
proc genProcPrototype(m: BModule, sym: PSym) = proc genProcPrototype(m: BModule, sym: PSym) =
useHeader(m, sym) useHeader(m, sym)
if lfNoDecl in sym.loc.Flags: return if lfNoDecl in sym.loc.flags: return
if lfDynamicLib in sym.loc.Flags: if lfDynamicLib in sym.loc.flags:
if getModule(sym).id != m.module.id and if getModule(sym).id != m.module.id and
not containsOrIncl(m.declaredThings, sym.id): not containsOrIncl(m.declaredThings, sym.id):
app(m.s[cfsVars], rfmt(nil, "extern $1 $2;$n", app(m.s[cfsVars], rfmt(nil, "extern $1 $2;$n",
@ -832,7 +832,7 @@ proc genProcNoForward(m: BModule, prc: PSym) =
discard cgsym(m, prc.name.s) discard cgsym(m, prc.name.s)
return return
genProcPrototype(m, prc) genProcPrototype(m, prc)
if lfNoDecl in prc.loc.Flags: nil if lfNoDecl in prc.loc.flags: nil
elif prc.typ.callConv == ccInline: elif prc.typ.callConv == ccInline:
# We add inline procs to the calling module to enable C based inlining. # We add inline procs to the calling module to enable C based inlining.
# This also means that a check with ``q.declaredThings`` is wrong, we need # This also means that a check with ``q.declaredThings`` is wrong, we need
@ -854,7 +854,7 @@ proc requestConstImpl(p: BProc, sym: PSym) =
useHeader(m, sym) useHeader(m, sym)
if sym.loc.k == locNone: if sym.loc.k == locNone:
fillLoc(sym.loc, locData, sym.typ, mangleName(sym), OnUnknown) fillLoc(sym.loc, locData, sym.typ, mangleName(sym), OnUnknown)
if lfNoDecl in sym.loc.Flags: return if lfNoDecl in sym.loc.flags: return
# declare implementation: # declare implementation:
var q = findPendingModule(m, sym) var q = findPendingModule(m, sym)
if q != nil and not containsOrIncl(q.declaredThings, sym.id): if q != nil and not containsOrIncl(q.declaredThings, sym.id):
@ -879,7 +879,7 @@ proc genProc(m: BModule, prc: PSym) =
else: else:
genProcNoForward(m, prc) genProcNoForward(m, prc)
if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and
generatedHeader != nil and lfNoDecl notin prc.loc.Flags: generatedHeader != nil and lfNoDecl notin prc.loc.flags:
genProcPrototype(generatedHeader, prc) genProcPrototype(generatedHeader, prc)
if prc.typ.callConv == ccInline: if prc.typ.callConv == ccInline:
if not containsOrIncl(generatedHeader.declaredThings, prc.id): if not containsOrIncl(generatedHeader.declaredThings, prc.id):
@ -889,7 +889,7 @@ proc genVarPrototypeAux(m: BModule, sym: PSym) =
assert(sfGlobal in sym.flags) assert(sfGlobal in sym.flags)
useHeader(m, sym) useHeader(m, sym)
fillLoc(sym.loc, locGlobalVar, sym.typ, mangleName(sym), OnHeap) fillLoc(sym.loc, locGlobalVar, sym.typ, mangleName(sym), OnHeap)
if (lfNoDecl in sym.loc.Flags) or containsOrIncl(m.declaredThings, sym.id): if (lfNoDecl in sym.loc.flags) or containsOrIncl(m.declaredThings, sym.id):
return return
if sym.owner.id != m.module.id: if sym.owner.id != m.module.id:
# else we already have the symbol generated! # else we already have the symbol generated!
@ -930,7 +930,7 @@ proc getCopyright(cfilenoext: string): PRope =
"; Command for LLVM compiler:$n $5$n", [toRope(VersionAsString), "; Command for LLVM compiler:$n $5$n", [toRope(VersionAsString),
toRope(platform.OS[targetOS].name), toRope(platform.OS[targetOS].name),
toRope(platform.CPU[targetCPU].name), toRope(platform.CPU[targetCPU].name),
toRope(extccomp.CC[extccomp.ccompiler].name), toRope(extccomp.CC[extccomp.cCompiler].name),
toRope(getCompileCFileCmd(cfilenoext))]) toRope(getCompileCFileCmd(cfilenoext))])
proc getFileHeader(cfilenoext: string): PRope = proc getFileHeader(cfilenoext: string): PRope =
@ -990,7 +990,7 @@ proc genMainProc(m: BModule) =
else: else:
nimMain = WinNimDllMain nimMain = WinNimDllMain
otherMain = WinCDllMain otherMain = WinCDllMain
discard lists.IncludeStr(m.headerFiles, "<windows.h>") discard lists.includeStr(m.headerFiles, "<windows.h>")
elif optGenDynLib in gGlobalOptions: elif optGenDynLib in gGlobalOptions:
nimMain = PosixNimDllMain nimMain = PosixNimDllMain
otherMain = PosixCDllMain otherMain = PosixCDllMain
@ -1053,11 +1053,11 @@ proc genInitCode(m: BModule) =
app(prc, m.postInitProc.s(cpsLocals)) app(prc, m.postInitProc.s(cpsLocals))
app(prc, genSectionEnd(cpsLocals)) app(prc, genSectionEnd(cpsLocals))
if optStackTrace in m.initProc.options and not m.FrameDeclared: if optStackTrace in m.initProc.options and not m.frameDeclared:
# BUT: the generated init code might depend on a current frame, so # BUT: the generated init code might depend on a current frame, so
# declare it nevertheless: # declare it nevertheless:
m.FrameDeclared = true m.frameDeclared = true
if not m.PreventStackTrace: if not m.preventStackTrace:
var procname = cstringLit(m.initProc, prc, m.module.name.s) var procname = cstringLit(m.initProc, prc, m.module.name.s)
app(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename)) app(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename))
else: else:
@ -1074,7 +1074,7 @@ proc genInitCode(m: BModule) =
app(prc, m.initProc.s(cpsStmts)) app(prc, m.initProc.s(cpsStmts))
app(prc, m.postInitProc.s(cpsStmts)) app(prc, m.postInitProc.s(cpsStmts))
app(prc, genSectionEnd(cpsStmts)) app(prc, genSectionEnd(cpsStmts))
if optStackTrace in m.initProc.options and not m.PreventStackTrace: if optStackTrace in m.initProc.options and not m.preventStackTrace:
app(prc, deinitFrame(m.initProc)) app(prc, deinitFrame(m.initProc))
app(prc, deinitGCFrame(m.initProc)) app(prc, deinitGCFrame(m.initProc))
appf(prc, "}$N$N") appf(prc, "}$N$N")
@ -1148,7 +1148,7 @@ proc rawNewModule(module: PSym, filename: string): BModule =
# no line tracing for the init sections of the system module so that we # no line tracing for the init sections of the system module so that we
# don't generate a TFrame which can confuse the stack botton initialization: # don't generate a TFrame which can confuse the stack botton initialization:
if sfSystemModule in module.flags: if sfSystemModule in module.flags:
result.PreventStackTrace = true result.preventStackTrace = true
excl(result.preInitProc.options, optStackTrace) excl(result.preInitProc.options, optStackTrace)
excl(result.postInitProc.options, optStackTrace) excl(result.postInitProc.options, optStackTrace)
@ -1171,7 +1171,7 @@ proc resetModule*(m: var BModule) =
m.forwardedProcs = @[] m.forwardedProcs = @[]
m.typeNodesName = getTempName() m.typeNodesName = getTempName()
m.nimTypesName = getTempName() m.nimTypesName = getTempName()
m.PreventStackTrace = sfSystemModule in m.module.flags m.preventStackTrace = sfSystemModule in m.module.flags
nullify m.s nullify m.s
m.usesThreadVars = false m.usesThreadVars = false
m.typeNodes = 0 m.typeNodes = 0
@ -1275,7 +1275,7 @@ proc shouldRecompile(code: PRope, cfile, cfilenoext: string): bool =
if optForceFullMake notin gGlobalOptions: if optForceFullMake notin gGlobalOptions:
var objFile = toObjFile(cfilenoext) var objFile = toObjFile(cfilenoext)
if writeRopeIfNotEqual(code, cfile): return if writeRopeIfNotEqual(code, cfile): return
if existsFile(objFile) and os.FileNewer(objFile, cfile): result = false if existsFile(objFile) and os.fileNewer(objFile, cfile): result = false
else: else:
writeRope(code, cfile) writeRope(code, cfile)

View file

@ -61,8 +61,8 @@ type
TCProc{.final.} = object # represents C proc that is currently generated TCProc{.final.} = object # represents C proc that is currently generated
prc*: PSym # the Nimrod proc that this C proc belongs to prc*: PSym # the Nimrod proc that this C proc belongs to
BeforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed beforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed
ThreadVarAccessed*: bool # true if the proc already accessed some threadvar threadVarAccessed*: bool # true if the proc already accessed some threadvar
nestedTryStmts*: seq[PNode] # in how many nested try statements we are nestedTryStmts*: seq[PNode] # in how many nested try statements we are
# (the vars must be volatile then) # (the vars must be volatile then)
inExceptBlock*: int # are we currently inside an except block? inExceptBlock*: int # are we currently inside an except block?
@ -86,9 +86,9 @@ type
module*: PSym module*: PSym
filename*: string filename*: string
s*: TCFileSections # sections of the C file s*: TCFileSections # sections of the C file
PreventStackTrace*: bool # true if stack traces need to be prevented preventStackTrace*: bool # true if stack traces need to be prevented
usesThreadVars*: bool # true if the module uses a thread var usesThreadVars*: bool # true if the module uses a thread var
FrameDeclared*: bool # hack for ROD support so that we don't declare frameDeclared*: bool # hack for ROD support so that we don't declare
# a frame var twice in an init proc # a frame var twice in an init proc
isHeaderFile*: bool # C source file is the header file isHeaderFile*: bool # C source file is the header file
includesStringh*: bool # C source file already includes ``<string.h>`` includesStringh*: bool # C source file already includes ``<string.h>``

View file

@ -35,7 +35,7 @@ const
AdvancedUsage = slurp"doc/advopt.txt".replace("//", "") AdvancedUsage = slurp"doc/advopt.txt".replace("//", "")
proc getCommandLineDesc(): string = proc getCommandLineDesc(): string =
result = (HelpMessage % [VersionAsString, platform.os[platform.hostOS].name, result = (HelpMessage % [VersionAsString, platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name]) & Usage CPU[platform.hostCPU].name]) & Usage
proc helpOnError(pass: TCmdLinePass) = proc helpOnError(pass: TCmdLinePass) =
@ -46,14 +46,14 @@ proc helpOnError(pass: TCmdLinePass) =
proc writeAdvancedUsage(pass: TCmdLinePass) = proc writeAdvancedUsage(pass: TCmdLinePass) =
if pass == passCmd1: if pass == passCmd1:
msgWriteln(`%`(HelpMessage, [VersionAsString, msgWriteln(`%`(HelpMessage, [VersionAsString,
platform.os[platform.hostOS].name, platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name]) & AdvancedUsage) CPU[platform.hostCPU].name]) & AdvancedUsage)
quit(0) quit(0)
proc writeVersionInfo(pass: TCmdLinePass) = proc writeVersionInfo(pass: TCmdLinePass) =
if pass == passCmd1: if pass == passCmd1:
msgWriteln(`%`(HelpMessage, [VersionAsString, msgWriteln(`%`(HelpMessage, [VersionAsString,
platform.os[platform.hostOS].name, platform.OS[platform.hostOS].name,
CPU[platform.hostCPU].name])) CPU[platform.hostCPU].name]))
quit(0) quit(0)
@ -256,8 +256,8 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
of "excludepath": of "excludepath":
expectArg(switch, arg, pass, info) expectArg(switch, arg, pass, info)
let path = processPath(arg) let path = processPath(arg)
lists.ExcludeStr(options.searchPaths, path) lists.excludeStr(options.searchPaths, path)
lists.ExcludeStr(options.lazyPaths, path) lists.excludeStr(options.lazyPaths, path)
of "nimcache": of "nimcache":
expectArg(switch, arg, pass, info) expectArg(switch, arg, pass, info)
options.nimcacheDir = processPath(arg) options.nimcacheDir = processPath(arg)
@ -425,19 +425,19 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
of "os": of "os":
expectArg(switch, arg, pass, info) expectArg(switch, arg, pass, info)
if pass in {passCmd1, passPP}: if pass in {passCmd1, passPP}:
theOS = platform.NameToOS(arg) theOS = platform.nameToOS(arg)
if theOS == osNone: localError(info, errUnknownOS, arg) if theOS == osNone: localError(info, errUnknownOS, arg)
elif theOS != platform.hostOS: elif theOS != platform.hostOS:
setTarget(theOS, targetCPU) setTarget(theOS, targetCPU)
condsyms.InitDefines() condsyms.initDefines()
of "cpu": of "cpu":
expectArg(switch, arg, pass, info) expectArg(switch, arg, pass, info)
if pass in {passCmd1, passPP}: if pass in {passCmd1, passPP}:
cpu = platform.NameToCPU(arg) cpu = platform.nameToCPU(arg)
if cpu == cpuNone: localError(info, errUnknownCPU, arg) if cpu == cpuNone: localError(info, errUnknownCPU, arg)
elif cpu != platform.hostCPU: elif cpu != platform.hostCPU:
setTarget(targetOS, cpu) setTarget(targetOS, cpu)
condsyms.InitDefines() condsyms.initDefines()
of "run", "r": of "run", "r":
expectNoArg(switch, arg, pass, info) expectNoArg(switch, arg, pass, info)
incl(gGlobalOptions, optRun) incl(gGlobalOptions, optRun)

View file

@ -83,6 +83,6 @@ proc initDefines*() =
defineSymbol("cpu" & $CPU[targetCPU].bit) defineSymbol("cpu" & $CPU[targetCPU].bit)
defineSymbol(normalize(EndianToStr[CPU[targetCPU].endian])) defineSymbol(normalize(EndianToStr[CPU[targetCPU].endian]))
defineSymbol(CPU[targetCPU].name) defineSymbol(CPU[targetCPU].name)
defineSymbol(platform.os[targetOS].name) defineSymbol(platform.OS[targetOS].name)
if platform.OS[targetOS].props.contains(ospLacksThreadVars): if platform.OS[targetOS].props.contains(ospLacksThreadVars):
defineSymbol("emulatedthreadvars") defineSymbol("emulatedthreadvars")

View file

@ -46,13 +46,13 @@ proc parseRst(text, filename: string,
line, column: int, hasToc: var bool, line, column: int, hasToc: var bool,
rstOptions: TRstParseOptions): PRstNode = rstOptions: TRstParseOptions): PRstNode =
result = rstParse(text, filename, line, column, hasToc, rstOptions, result = rstParse(text, filename, line, column, hasToc, rstOptions,
options.FindFile, compilerMsgHandler) options.findFile, compilerMsgHandler)
proc newDocumentor*(filename: string, config: PStringTable): PDoc = proc newDocumentor*(filename: string, config: PStringTable): PDoc =
new(result) new(result)
initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex),
options.gConfigVars, filename, {roSupportRawDirective}, options.gConfigVars, filename, {roSupportRawDirective},
options.FindFile, compilerMsgHandler) options.findFile, compilerMsgHandler)
result.id = 100 result.id = 100
proc dispA(dest: var PRope, xml, tex: string, args: openArray[PRope]) = proc dispA(dest: var PRope, xml, tex: string, args: openArray[PRope]) =

View file

@ -335,8 +335,8 @@ proc getConfigVar(c: TSystemCC, suffix: string): string =
# for niminst support # for niminst support
if (platform.hostOS != targetOS or platform.hostCPU != targetCPU) and if (platform.hostOS != targetOS or platform.hostCPU != targetCPU) and
optCompileOnly notin gGlobalOptions: optCompileOnly notin gGlobalOptions:
let fullCCname = platform.cpu[targetCPU].name & '.' & let fullCCname = platform.CPU[targetCPU].name & '.' &
platform.os[targetOS].name & '.' & platform.OS[targetOS].name & '.' &
CC[c].name & suffix CC[c].name & suffix
result = getConfigVar(fullCCname) result = getConfigVar(fullCCname)
if result.len == 0: if result.len == 0:
@ -406,7 +406,7 @@ proc execExternalProgram*(cmd: string) =
proc generateScript(projectFile: string, script: PRope) = proc generateScript(projectFile: string, script: PRope) =
let (dir, name, ext) = splitFile(projectFile) let (dir, name, ext) = splitFile(projectFile)
writeRope(script, dir / addFileExt("compile_" & name, writeRope(script, dir / addFileExt("compile_" & name,
platform.os[targetOS].scriptExt)) platform.OS[targetOS].scriptExt))
proc getOptSpeed(c: TSystemCC): string = proc getOptSpeed(c: TSystemCC): string =
result = getConfigVar(c, ".options.speed") result = getConfigVar(c, ".options.speed")
@ -517,7 +517,7 @@ proc footprint(filename: string): TCrc32 =
result = crcFromFile(filename) >< result = crcFromFile(filename) ><
platform.OS[targetOS].name >< platform.OS[targetOS].name ><
platform.CPU[targetCPU].name >< platform.CPU[targetCPU].name ><
extccomp.CC[extccomp.ccompiler].name >< extccomp.CC[extccomp.cCompiler].name ><
getCompileCFileCmd(filename, true) getCompileCFileCmd(filename, true)
proc externalFileChanged(filename: string): bool = proc externalFileChanged(filename: string): bool =
@ -608,10 +608,10 @@ proc callCCompiler*(projectfile: string) =
else: buildgui = "" else: buildgui = ""
var exefile: string var exefile: string
if optGenDynLib in gGlobalOptions: if optGenDynLib in gGlobalOptions:
exefile = platform.os[targetOS].dllFrmt % splitFile(projectfile).name exefile = platform.OS[targetOS].dllFrmt % splitFile(projectfile).name
builddll = CC[c].buildDll builddll = CC[c].buildDll
else: else:
exefile = splitFile(projectfile).name & platform.os[targetOS].exeExt exefile = splitFile(projectfile).name & platform.OS[targetOS].exeExt
builddll = "" builddll = ""
if options.outFile.len > 0: if options.outFile.len > 0:
exefile = options.outFile exefile = options.outFile

View file

@ -27,7 +27,7 @@ type
indent, emitPar: int indent, emitPar: int
x: string # the current input line x: string # the current input line
outp: PLLStream # the ouput will be parsed by pnimsyn outp: PLLStream # the ouput will be parsed by pnimsyn
subsChar, NimDirective: char subsChar, nimDirective: char
emit, conc, toStr: string emit, conc, toStr: string
curly, bracket, par: int curly, bracket, par: int
pendingExprLine: bool pendingExprLine: bool
@ -67,9 +67,9 @@ proc parseLine(p: var TTmplParser) =
keyw: string keyw: string
j = 0 j = 0
while p.x[j] == ' ': inc(j) while p.x[j] == ' ': inc(j)
if (p.x[0] == p.NimDirective) and (p.x[0 + 1] == '!'): if (p.x[0] == p.nimDirective) and (p.x[0 + 1] == '!'):
newLine(p) newLine(p)
elif (p.x[j] == p.NimDirective): elif (p.x[j] == p.nimDirective):
newLine(p) newLine(p)
inc(j) inc(j)
while p.x[j] == ' ': inc(j) while p.x[j] == ' ': inc(j)

View file

@ -63,8 +63,8 @@ proc rawImportSymbol(c: PContext, s: PSym) =
if check != nil and check.id != s.id: if check != nil and check.id != s.id:
if s.kind notin OverloadableSyms: if s.kind notin OverloadableSyms:
# s and check need to be qualified: # s and check need to be qualified:
incl(c.AmbiguousSymbols, s.id) incl(c.ambiguousSymbols, s.id)
incl(c.AmbiguousSymbols, check.id) incl(c.ambiguousSymbols, check.id)
# thanks to 'export' feature, it could be we import the same symbol from # thanks to 'export' feature, it could be we import the same symbol from
# multiple sources, so we need to call 'StrTableAdd' here: # multiple sources, so we need to call 'StrTableAdd' here:
strTableAdd(c.importTable.symbols, s) strTableAdd(c.importTable.symbols, s)
@ -73,7 +73,7 @@ proc rawImportSymbol(c: PContext, s: PSym) =
if etyp.kind in {tyBool, tyEnum} and sfPure notin s.flags: if etyp.kind in {tyBool, tyEnum} and sfPure notin s.flags:
for j in countup(0, sonsLen(etyp.n) - 1): for j in countup(0, sonsLen(etyp.n) - 1):
var e = etyp.n.sons[j].sym var e = etyp.n.sons[j].sym
if e.Kind != skEnumField: if e.kind != skEnumField:
internalError(s.info, "rawImportSymbol") internalError(s.info, "rawImportSymbol")
# BUGFIX: because of aliases for enums the symbol may already # BUGFIX: because of aliases for enums the symbol may already
# have been put into the symbol table # have been put into the symbol table
@ -99,16 +99,16 @@ proc importSymbol(c: PContext, n: PNode, fromMod: PSym) =
localError(n.info, errUndeclaredIdentifier, ident.s) localError(n.info, errUndeclaredIdentifier, ident.s)
else: else:
if s.kind == skStub: loadStub(s) if s.kind == skStub: loadStub(s)
if s.Kind notin ExportableSymKinds: if s.kind notin ExportableSymKinds:
internalError(n.info, "importSymbol: 2") internalError(n.info, "importSymbol: 2")
# for an enumeration we have to add all identifiers # for an enumeration we have to add all identifiers
case s.Kind case s.kind
of skProc, skMethod, skIterator, skMacro, skTemplate, skConverter: of skProc, skMethod, skIterator, skMacro, skTemplate, skConverter:
# for a overloadable syms add all overloaded routines # for a overloadable syms add all overloaded routines
var it: TIdentIter var it: TIdentIter
var e = initIdentIter(it, fromMod.tab, s.name) var e = initIdentIter(it, fromMod.tab, s.name)
while e != nil: while e != nil:
if e.name.id != s.Name.id: internalError(n.info, "importSymbol: 3") if e.name.id != s.name.id: internalError(n.info, "importSymbol: 3")
rawImportSymbol(c, e) rawImportSymbol(c, e)
e = nextIdentIter(it, fromMod.tab) e = nextIdentIter(it, fromMod.tab)
else: rawImportSymbol(c, s) else: rawImportSymbol(c, s)
@ -119,7 +119,7 @@ proc importAllSymbolsExcept(c: PContext, fromMod: PSym, exceptSet: TIntSet) =
while s != nil: while s != nil:
if s.kind != skModule: if s.kind != skModule:
if s.kind != skEnumField: if s.kind != skEnumField:
if s.Kind notin ExportableSymKinds: if s.kind notin ExportableSymKinds:
internalError(s.info, "importAllSymbols: " & $s.kind) internalError(s.info, "importAllSymbols: " & $s.kind)
if exceptSet.empty or s.name.id notin exceptSet: if exceptSet.empty or s.name.id notin exceptSet:
rawImportSymbol(c, s) rawImportSymbol(c, s)

View file

@ -64,7 +64,7 @@ type
options: TOptions options: TOptions
module: BModule module: BModule
g: PGlobals g: PGlobals
BeforeRetNeeded: bool beforeRetNeeded: bool
target: TTarget # duplicated here for faster dispatching target: TTarget # duplicated here for faster dispatching
unique: int # for temp identifier generation unique: int # for temp identifier generation
blocks: seq[TBlock] blocks: seq[TBlock]
@ -485,14 +485,14 @@ proc arith(p: PProc, n: PNode, r: var TCompRes, op: TMagic) =
proc genLineDir(p: PProc, n: PNode) = proc genLineDir(p: PProc, n: PNode) =
let line = toLinenumber(n.info) let line = toLinenumber(n.info)
if optLineDir in p.Options: if optLineDir in p.options:
appf(p.body, "// line $2 \"$1\"$n" | "-- line $2 \"$1\"$n", appf(p.body, "// line $2 \"$1\"$n" | "-- line $2 \"$1\"$n",
[toRope(toFilename(n.info)), toRope(line)]) [toRope(toFilename(n.info)), toRope(line)])
if {optStackTrace, optEndb} * p.Options == {optStackTrace, optEndb} and if {optStackTrace, optEndb} * p.options == {optStackTrace, optEndb} and
((p.prc == nil) or sfPure notin p.prc.flags): ((p.prc == nil) or sfPure notin p.prc.flags):
useMagic(p, "endb") useMagic(p, "endb")
appf(p.body, "endb($1);$n", [toRope(line)]) appf(p.body, "endb($1);$n", [toRope(line)])
elif ({optLineTrace, optStackTrace} * p.Options == elif ({optLineTrace, optStackTrace} * p.options ==
{optLineTrace, optStackTrace}) and {optLineTrace, optStackTrace}) and
((p.prc == nil) or not (sfPure in p.prc.flags)): ((p.prc == nil) or not (sfPure in p.prc.flags)):
appf(p.body, "F.line = $1;$n", [toRope(line)]) appf(p.body, "F.line = $1;$n", [toRope(line)])
@ -555,7 +555,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) =
"var $1 = {prev: excHandler, exc: null};$nexcHandler = $1;$n" | "var $1 = {prev: excHandler, exc: null};$nexcHandler = $1;$n" |
"local $1 = pcall(", "local $1 = pcall(",
[safePoint]) [safePoint])
if optStackTrace in p.Options: app(p.body, "framePtr = F;" & tnl) if optStackTrace in p.options: app(p.body, "framePtr = F;" & tnl)
appf(p.body, "try {$n" | "function()$n") appf(p.body, "try {$n" | "function()$n")
var length = sonsLen(n) var length = sonsLen(n)
var a: TCompRes var a: TCompRes
@ -747,7 +747,7 @@ proc genAsmStmt(p: PProc, n: PNode) =
genLineDir(p, n) genLineDir(p, n)
assert(n.kind == nkAsmStmt) assert(n.kind == nkAsmStmt)
for i in countup(0, sonsLen(n) - 1): for i in countup(0, sonsLen(n) - 1):
case n.sons[i].Kind case n.sons[i].kind
of nkStrLit..nkTripleStrLit: app(p.body, n.sons[i].strVal) of nkStrLit..nkTripleStrLit: app(p.body, n.sons[i].strVal)
of nkSym: app(p.body, mangleName(n.sons[i].sym)) of nkSym: app(p.body, mangleName(n.sons[i].sym))
else: internalError(n.sons[i].info, "jsgen: genAsmStmt()") else: internalError(n.sons[i].info, "jsgen: genAsmStmt()")
@ -1298,15 +1298,15 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
of mSwap: genSwap(p, n) of mSwap: genSwap(p, n)
of mUnaryLt: of mUnaryLt:
# XXX: range checking? # XXX: range checking?
if not (optOverflowCheck in p.Options): unaryExpr(p, n, r, "", "$1 - 1") if not (optOverflowCheck in p.options): unaryExpr(p, n, r, "", "$1 - 1")
else: unaryExpr(p, n, r, "subInt", "subInt($1, 1)") else: unaryExpr(p, n, r, "subInt", "subInt($1, 1)")
of mPred: of mPred:
# XXX: range checking? # XXX: range checking?
if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 - $2") if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 - $2")
else: binaryExpr(p, n, r, "subInt", "subInt($1, $2)") else: binaryExpr(p, n, r, "subInt", "subInt($1, $2)")
of mSucc: of mSucc:
# XXX: range checking? # XXX: range checking?
if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 - $2") if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 - $2")
else: binaryExpr(p, n, r, "addInt", "addInt($1, $2)") else: binaryExpr(p, n, r, "addInt", "addInt($1, $2)")
of mAppendStrCh: binaryExpr(p, n, r, "addChar", "addChar($1, $2)") of mAppendStrCh: binaryExpr(p, n, r, "addChar", "addChar($1, $2)")
of mAppendStrStr: of mAppendStrStr:
@ -1335,10 +1335,10 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
else: else:
unaryExpr(p, n, r, "", "($1.length-1)") unaryExpr(p, n, r, "", "($1.length-1)")
of mInc: of mInc:
if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 += $2") if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 += $2")
else: binaryExpr(p, n, r, "addInt", "$1 = addInt($1, $2)") else: binaryExpr(p, n, r, "addInt", "$1 = addInt($1, $2)")
of ast.mDec: of ast.mDec:
if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 -= $2") if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 -= $2")
else: binaryExpr(p, n, r, "subInt", "$1 = subInt($1, $2)") else: binaryExpr(p, n, r, "subInt", "$1 = subInt($1, $2)")
of mSetLengthStr: binaryExpr(p, n, r, "", "$1.length = ($2)-1") of mSetLengthStr: binaryExpr(p, n, r, "", "$1.length = ($2)-1")
of mSetLengthSeq: binaryExpr(p, n, r, "", "$1.length = $2") of mSetLengthSeq: binaryExpr(p, n, r, "", "$1.length = $2")
@ -1470,7 +1470,7 @@ proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) =
proc genReturnStmt(p: PProc, n: PNode) = proc genReturnStmt(p: PProc, n: PNode) =
if p.procDef == nil: internalError(n.info, "genReturnStmt") if p.procDef == nil: internalError(n.info, "genReturnStmt")
p.BeforeRetNeeded = true p.beforeRetNeeded = true
if (n.sons[0].kind != nkEmpty): if (n.sons[0].kind != nkEmpty):
genStmt(p, n.sons[0]) genStmt(p, n.sons[0])
else: else:

View file

@ -119,7 +119,7 @@ proc genTypeInfo(p: PProc, typ: PType): PRope =
var t = typ var t = typ
if t.kind == tyGenericInst: t = lastSon(t) if t.kind == tyGenericInst: t = lastSon(t)
result = ropef("NTI$1", [toRope(t.id)]) result = ropef("NTI$1", [toRope(t.id)])
if containsOrIncl(p.g.TypeInfoGenerated, t.id): return if containsOrIncl(p.g.typeInfoGenerated, t.id): return
case t.kind case t.kind
of tyDistinct: of tyDistinct:
result = genTypeInfo(p, typ.sons[0]) result = genTypeInfo(p, typ.sons[0])

View file

@ -180,18 +180,18 @@ proc printTok*(tok: TToken) =
var dummyIdent: PIdent var dummyIdent: PIdent
proc initToken*(L: var TToken) = proc initToken*(L: var TToken) =
L.TokType = tkInvalid L.tokType = tkInvalid
L.iNumber = 0 L.iNumber = 0
L.Indent = 0 L.indent = 0
L.literal = "" L.literal = ""
L.fNumber = 0.0 L.fNumber = 0.0
L.base = base10 L.base = base10
L.ident = dummyIdent L.ident = dummyIdent
proc fillToken(L: var TToken) = proc fillToken(L: var TToken) =
L.TokType = tkInvalid L.tokType = tkInvalid
L.iNumber = 0 L.iNumber = 0
L.Indent = 0 L.indent = 0
setLen(L.literal, 0) setLen(L.literal, 0)
L.fNumber = 0.0 L.fNumber = 0.0
L.base = base10 L.base = base10
@ -201,24 +201,24 @@ proc openLexer(lex: var TLexer, fileIdx: int32, inputstream: PLLStream) =
openBaseLexer(lex, inputstream) openBaseLexer(lex, inputstream)
lex.fileIdx = fileidx lex.fileIdx = fileidx
lex.indentAhead = - 1 lex.indentAhead = - 1
inc(lex.Linenumber, inputstream.lineOffset) inc(lex.lineNumber, inputstream.lineOffset)
proc closeLexer(lex: var TLexer) = proc closeLexer(lex: var TLexer) =
inc(gLinesCompiled, lex.LineNumber) inc(gLinesCompiled, lex.lineNumber)
closeBaseLexer(lex) closeBaseLexer(lex)
proc getColumn(L: TLexer): int = proc getColumn(L: TLexer): int =
result = getColNumber(L, L.bufPos) result = getColNumber(L, L.bufpos)
proc getLineInfo(L: TLexer): TLineInfo = proc getLineInfo(L: TLexer): TLineInfo =
result = newLineInfo(L.fileIdx, L.linenumber, getColNumber(L, L.bufpos)) result = newLineInfo(L.fileIdx, L.lineNumber, getColNumber(L, L.bufpos))
proc lexMessage(L: TLexer, msg: TMsgKind, arg = "") = proc lexMessage(L: TLexer, msg: TMsgKind, arg = "") =
msgs.Message(getLineInfo(L), msg, arg) msgs.message(getLineInfo(L), msg, arg)
proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") = proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") =
var info = newLineInfo(L.fileIdx, L.linenumber, pos - L.lineStart) var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart)
msgs.Message(info, msg, arg) msgs.message(info, msg, arg)
proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) = proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) =
var pos = L.bufpos # use registers for pos, buf var pos = L.bufpos # use registers for pos, buf
@ -235,7 +235,7 @@ proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) =
break break
add(tok.literal, '_') add(tok.literal, '_')
inc(pos) inc(pos)
L.bufPos = pos L.bufpos = pos
proc matchTwoChars(L: TLexer, first: char, second: TCharSet): bool = proc matchTwoChars(L: TLexer, first: char, second: TCharSet): bool =
result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second) result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second)
@ -408,7 +408,7 @@ proc getNumber(L: var TLexer): TToken =
else: internalError(getLineInfo(L), "getNumber") else: internalError(getLineInfo(L), "getNumber")
elif isFloatLiteral(result.literal) or (result.tokType == tkFloat32Lit) or elif isFloatLiteral(result.literal) or (result.tokType == tkFloat32Lit) or
(result.tokType == tkFloat64Lit): (result.tokType == tkFloat64Lit):
result.fnumber = parseFloat(result.literal) result.fNumber = parseFloat(result.literal)
if result.tokType == tkIntLit: result.tokType = tkFloatLit if result.tokType == tkIntLit: result.tokType = tkFloatLit
else: else:
result.iNumber = parseBiggestInt(result.literal) result.iNumber = parseBiggestInt(result.literal)
@ -445,7 +445,7 @@ proc getEscapedChar(L: var TLexer, tok: var TToken) =
inc(L.bufpos) # skip '\' inc(L.bufpos) # skip '\'
case L.buf[L.bufpos] case L.buf[L.bufpos]
of 'n', 'N': of 'n', 'N':
if tok.toktype == tkCharLit: lexMessage(L, errNnotAllowedInCharacter) if tok.tokType == tkCharLit: lexMessage(L, errNnotAllowedInCharacter)
add(tok.literal, tnl) add(tok.literal, tnl)
inc(L.bufpos) inc(L.bufpos)
of 'r', 'R', 'c', 'C': of 'r', 'R', 'c', 'C':
@ -514,16 +514,16 @@ proc handleCRLF(L: var TLexer, pos: int): int =
case L.buf[pos] case L.buf[pos]
of CR: of CR:
registerLine() registerLine()
result = nimlexbase.HandleCR(L, pos) result = nimlexbase.handleCR(L, pos)
of LF: of LF:
registerLine() registerLine()
result = nimlexbase.HandleLF(L, pos) result = nimlexbase.handleLF(L, pos)
else: result = pos else: result = pos
proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = proc getString(L: var TLexer, tok: var TToken, rawMode: bool) =
var pos = L.bufPos + 1 # skip " var pos = L.bufpos + 1 # skip "
var buf = L.buf # put `buf` in a register var buf = L.buf # put `buf` in a register
var line = L.linenumber # save linenumber for better error message var line = L.lineNumber # save linenumber for better error message
if buf[pos] == '\"' and buf[pos+1] == '\"': if buf[pos] == '\"' and buf[pos+1] == '\"':
tok.tokType = tkTripleStrLit # long string literal: tok.tokType = tkTripleStrLit # long string literal:
inc(pos, 2) # skip "" inc(pos, 2) # skip ""
@ -544,10 +544,10 @@ proc getString(L: var TLexer, tok: var TToken, rawMode: bool) =
buf = L.buf buf = L.buf
add(tok.literal, tnl) add(tok.literal, tnl)
of nimlexbase.EndOfFile: of nimlexbase.EndOfFile:
var line2 = L.linenumber var line2 = L.lineNumber
L.LineNumber = line L.lineNumber = line
lexMessagePos(L, errClosingTripleQuoteExpected, L.lineStart) lexMessagePos(L, errClosingTripleQuoteExpected, L.lineStart)
L.LineNumber = line2 L.lineNumber = line2
break break
else: else:
add(tok.literal, buf[pos]) add(tok.literal, buf[pos])
@ -569,9 +569,9 @@ proc getString(L: var TLexer, tok: var TToken, rawMode: bool) =
lexMessage(L, errClosingQuoteExpected) lexMessage(L, errClosingQuoteExpected)
break break
elif (c == '\\') and not rawMode: elif (c == '\\') and not rawMode:
L.bufPos = pos L.bufpos = pos
getEscapedChar(L, tok) getEscapedChar(L, tok)
pos = L.bufPos pos = L.bufpos
else: else:
add(tok.literal, c) add(tok.literal, c)
inc(pos) inc(pos)
@ -707,7 +707,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) =
tok.indent = -1 tok.indent = -1
skip(L, tok) skip(L, tok)
var c = L.buf[L.bufpos] var c = L.buf[L.bufpos]
tok.line = L.linenumber tok.line = L.lineNumber
tok.col = getColNumber(L, L.bufpos) tok.col = getColNumber(L, L.bufpos)
if c in SymStartChars - {'r', 'R', 'l'}: if c in SymStartChars - {'r', 'R', 'l'}:
getSymbol(L, tok) getSymbol(L, tok)
@ -724,7 +724,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) =
else: else:
getOperator(L, tok) getOperator(L, tok)
of ',': of ',':
tok.toktype = tkComma tok.tokType = tkComma
inc(L.bufpos) inc(L.bufpos)
of 'l': of 'l':
# if we parsed exactly one character and its a small L (l), this # if we parsed exactly one character and its a small L (l), this
@ -733,55 +733,55 @@ proc rawGetTok(L: var TLexer, tok: var TToken) =
lexMessage(L, warnSmallLshouldNotBeUsed) lexMessage(L, warnSmallLshouldNotBeUsed)
getSymbol(L, tok) getSymbol(L, tok)
of 'r', 'R': of 'r', 'R':
if L.buf[L.bufPos + 1] == '\"': if L.buf[L.bufpos + 1] == '\"':
inc(L.bufPos) inc(L.bufpos)
getString(L, tok, true) getString(L, tok, true)
else: else:
getSymbol(L, tok) getSymbol(L, tok)
of '(': of '(':
inc(L.bufpos) inc(L.bufpos)
if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
tok.toktype = tkParDotLe tok.tokType = tkParDotLe
inc(L.bufpos) inc(L.bufpos)
else: else:
tok.toktype = tkParLe tok.tokType = tkParLe
of ')': of ')':
tok.toktype = tkParRi tok.tokType = tkParRi
inc(L.bufpos) inc(L.bufpos)
of '[': of '[':
inc(L.bufpos) inc(L.bufpos)
if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
tok.toktype = tkBracketDotLe tok.tokType = tkBracketDotLe
inc(L.bufpos) inc(L.bufpos)
else: else:
tok.toktype = tkBracketLe tok.tokType = tkBracketLe
of ']': of ']':
tok.toktype = tkBracketRi tok.tokType = tkBracketRi
inc(L.bufpos) inc(L.bufpos)
of '.': of '.':
if L.buf[L.bufPos+1] == ']': if L.buf[L.bufpos+1] == ']':
tok.tokType = tkBracketDotRi tok.tokType = tkBracketDotRi
inc(L.bufpos, 2) inc(L.bufpos, 2)
elif L.buf[L.bufPos+1] == '}': elif L.buf[L.bufpos+1] == '}':
tok.tokType = tkCurlyDotRi tok.tokType = tkCurlyDotRi
inc(L.bufpos, 2) inc(L.bufpos, 2)
elif L.buf[L.bufPos+1] == ')': elif L.buf[L.bufpos+1] == ')':
tok.tokType = tkParDotRi tok.tokType = tkParDotRi
inc(L.bufpos, 2) inc(L.bufpos, 2)
else: else:
getOperator(L, tok) getOperator(L, tok)
of '{': of '{':
inc(L.bufpos) inc(L.bufpos)
if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.':
tok.toktype = tkCurlyDotLe tok.tokType = tkCurlyDotLe
inc(L.bufpos) inc(L.bufpos)
else: else:
tok.toktype = tkCurlyLe tok.tokType = tkCurlyLe
of '}': of '}':
tok.toktype = tkCurlyRi tok.tokType = tkCurlyRi
inc(L.bufpos) inc(L.bufpos)
of ';': of ';':
tok.toktype = tkSemiColon tok.tokType = tkSemiColon
inc(L.bufpos) inc(L.bufpos)
of '`': of '`':
tok.tokType = tkAccent tok.tokType = tkAccent
@ -804,7 +804,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) =
if c in OpChars: if c in OpChars:
getOperator(L, tok) getOperator(L, tok)
elif c == nimlexbase.EndOfFile: elif c == nimlexbase.EndOfFile:
tok.toktype = tkEof tok.tokType = tkEof
tok.indent = 0 tok.indent = 0
else: else:
tok.literal = $c tok.literal = $c

View file

@ -135,14 +135,14 @@ proc wrongRedefinition*(info: TLineInfo, s: string) =
proc addDecl*(c: PContext, sym: PSym) = proc addDecl*(c: PContext, sym: PSym) =
if c.currentScope.addUniqueSym(sym) == Failure: if c.currentScope.addUniqueSym(sym) == Failure:
wrongRedefinition(sym.info, sym.Name.s) wrongRedefinition(sym.info, sym.name.s)
proc addPrelimDecl*(c: PContext, sym: PSym) = proc addPrelimDecl*(c: PContext, sym: PSym) =
discard c.currentScope.addUniqueSym(sym) discard c.currentScope.addUniqueSym(sym)
proc addDeclAt*(scope: PScope, sym: PSym) = proc addDeclAt*(scope: PScope, sym: PSym) =
if scope.addUniqueSym(sym) == Failure: if scope.addUniqueSym(sym) == Failure:
wrongRedefinition(sym.info, sym.Name.s) wrongRedefinition(sym.info, sym.name.s)
proc addInterfaceDeclAux(c: PContext, sym: PSym) = proc addInterfaceDeclAux(c: PContext, sym: PSym) =
if sfExported in sym.flags: if sfExported in sym.flags:
@ -159,8 +159,8 @@ proc addOverloadableSymAt*(scope: PScope, fn: PSym) =
internalError(fn.info, "addOverloadableSymAt") internalError(fn.info, "addOverloadableSymAt")
return return
var check = strTableGet(scope.symbols, fn.name) var check = strTableGet(scope.symbols, fn.name)
if check != nil and check.Kind notin OverloadableSyms: if check != nil and check.kind notin OverloadableSyms:
wrongRedefinition(fn.info, fn.Name.s) wrongRedefinition(fn.info, fn.name.s)
else: else:
scope.addSym(fn) scope.addSym(fn)
@ -193,7 +193,7 @@ proc lookUp*(c: PContext, n: PNode): PSym =
else: else:
internalError(n.info, "lookUp") internalError(n.info, "lookUp")
return return
if contains(c.AmbiguousSymbols, result.id): if contains(c.ambiguousSymbols, result.id):
localError(n.info, errUseQualifier, result.name.s) localError(n.info, errUseQualifier, result.name.s)
if result.kind == skStub: loadStub(result) if result.kind == skStub: loadStub(result)
@ -210,11 +210,11 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym =
localError(n.info, errUndeclaredIdentifier, ident.s) localError(n.info, errUndeclaredIdentifier, ident.s)
result = errorSym(c, n) result = errorSym(c, n)
elif checkAmbiguity in flags and result != nil and elif checkAmbiguity in flags and result != nil and
contains(c.AmbiguousSymbols, result.id): contains(c.ambiguousSymbols, result.id):
localError(n.info, errUseQualifier, ident.s) localError(n.info, errUseQualifier, ident.s)
of nkSym: of nkSym:
result = n.sym result = n.sym
if checkAmbiguity in flags and contains(c.AmbiguousSymbols, result.id): if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id):
localError(n.info, errUseQualifier, n.sym.name.s) localError(n.info, errUseQualifier, n.sym.name.s)
of nkDotExpr: of nkDotExpr:
result = nil result = nil

View file

@ -134,7 +134,7 @@ proc addSonSkipIntLit*(father, son: PType) =
proc setIntLitType*(result: PNode) = proc setIntLitType*(result: PNode) =
let i = result.intVal let i = result.intVal
case platform.IntSize case platform.intSize
of 8: result.typ = getIntLitType(result) of 8: result.typ = getIntLitType(result)
of 4: of 4:
if i >= low(int32) and i <= high(int32): if i >= low(int32) and i <= high(int32):

View file

@ -18,7 +18,7 @@ import
tables, docgen2, service, parser, modules, ccgutils, sigmatch, ropes, lists, tables, docgen2, service, parser, modules, ccgutils, sigmatch, ropes, lists,
pretty pretty
from magicsys import SystemModule, resetSysTypes from magicsys import systemModule, resetSysTypes
const const
hasLLVM_Backend = false hasLLVM_Backend = false
@ -73,7 +73,7 @@ proc commandCompileToC =
compileProject() compileProject()
cgenWriteModules() cgenWriteModules()
if gCmd != cmdRun: if gCmd != cmdRun:
extccomp.CallCCompiler(changeFileExt(gProjectFull, "")) extccomp.callCCompiler(changeFileExt(gProjectFull, ""))
if isServing: if isServing:
# caas will keep track only of the compilation commands # caas will keep track only of the compilation commands

View file

@ -164,7 +164,7 @@ proc importModule*(s: PSym, fileIdx: int32): PSym {.procvar.} =
result = compileModule(fileIdx, {}) result = compileModule(fileIdx, {})
if optCaasEnabled in gGlobalOptions: addDep(s, fileIdx) if optCaasEnabled in gGlobalOptions: addDep(s, fileIdx)
if sfSystemModule in result.flags: if sfSystemModule in result.flags:
localError(result.info, errAttemptToRedefine, result.Name.s) localError(result.info, errAttemptToRedefine, result.name.s)
proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} = proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} =
result = syntaxes.parseFile(fileIdx) result = syntaxes.parseFile(fileIdx)
@ -180,7 +180,7 @@ proc `==^`(a, b: string): bool =
result = false result = false
proc compileSystemModule* = proc compileSystemModule* =
if magicsys.SystemModule == nil: if magicsys.systemModule == nil:
systemFileIdx = fileInfoIdx(options.libpath/"system.nim") systemFileIdx = fileInfoIdx(options.libpath/"system.nim")
discard compileModule(systemFileIdx, {sfSystemModule}) discard compileModule(systemFileIdx, {sfSystemModule})

View file

@ -845,7 +845,7 @@ proc quotedFilename*(i: TLineInfo): PRope =
internalAssert i.fileIndex >= 0 internalAssert i.fileIndex >= 0
result = fileInfos[i.fileIndex].quotedName result = fileInfos[i.fileIndex].quotedName
ropes.ErrorHandler = proc (err: TRopesError, msg: string, useWarning: bool) = ropes.errorHandler = proc (err: TRopesError, msg: string, useWarning: bool) =
case err case err
of rInvalidFormatStr: of rInvalidFormatStr:
internalError("ropes: invalid format string: " & msg) internalError("ropes: invalid format string: " & msg)

View file

@ -121,7 +121,7 @@ proc parseDirective(L: var TLexer, tok: var TToken) =
of wEnd: doEnd(L, tok) of wEnd: doEnd(L, tok)
of wWrite: of wWrite:
ppGetTok(L, tok) ppGetTok(L, tok)
msgs.MsgWriteln(tokToStr(tok)) msgs.msgWriteln(tokToStr(tok))
ppGetTok(L, tok) ppGetTok(L, tok)
else: else:
case tok.ident.s.normalize case tok.ident.s.normalize
@ -135,13 +135,13 @@ proc parseDirective(L: var TLexer, tok: var TToken) =
ppGetTok(L, tok) ppGetTok(L, tok)
var key = tokToStr(tok) var key = tokToStr(tok)
ppGetTok(L, tok) ppGetTok(L, tok)
os.putEnv(key, tokToStr(tok) & os.getenv(key)) os.putEnv(key, tokToStr(tok) & os.getEnv(key))
ppGetTok(L, tok) ppGetTok(L, tok)
of "appendenv": of "appendenv":
ppGetTok(L, tok) ppGetTok(L, tok)
var key = tokToStr(tok) var key = tokToStr(tok)
ppGetTok(L, tok) ppGetTok(L, tok)
os.putEnv(key, os.getenv(key) & tokToStr(tok)) os.putEnv(key, os.getEnv(key) & tokToStr(tok))
ppGetTok(L, tok) ppGetTok(L, tok)
else: lexMessage(L, errInvalidDirectiveX, tokToStr(tok)) else: lexMessage(L, errInvalidDirectiveX, tokToStr(tok))

View file

@ -42,7 +42,7 @@ type
buf*: cstring buf*: cstring
bufLen*: int # length of buffer in characters bufLen*: int # length of buffer in characters
stream*: PLLStream # we read from this stream stream*: PLLStream # we read from this stream
LineNumber*: int # the current line number lineNumber*: int # the current line number
# private data: # private data:
sentinel*: int sentinel*: int
lineStart*: int # index of last line start in buffer lineStart*: int # index of last line start in buffer
@ -80,7 +80,7 @@ proc fillBuffer(L: var TBaseLexer) =
# we know here that pos == L.sentinel, but not if this proc # we know here that pos == L.sentinel, but not if this proc
# is called the first time by initBaseLexer() # is called the first time by initBaseLexer()
assert(L.sentinel < L.bufLen) assert(L.sentinel < L.bufLen)
toCopy = L.BufLen - L.sentinel - 1 toCopy = L.bufLen - L.sentinel - 1
assert(toCopy >= 0) assert(toCopy >= 0)
if toCopy > 0: if toCopy > 0:
moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize)
@ -104,8 +104,8 @@ proc fillBuffer(L: var TBaseLexer) =
else: else:
# rather than to give up here because the line is too long, # rather than to give up here because the line is too long,
# double the buffer's size and try again: # double the buffer's size and try again:
oldBufLen = L.BufLen oldBufLen = L.bufLen
L.bufLen = L.BufLen * 2 L.bufLen = L.bufLen * 2
L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize))
assert(L.bufLen - oldBufLen == oldBufLen) assert(L.bufLen - oldBufLen == oldBufLen)
charsRead = llStreamRead(L.stream, addr(L.buf[oldBufLen]), charsRead = llStreamRead(L.stream, addr(L.buf[oldBufLen]),
@ -128,14 +128,14 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int =
proc handleCR(L: var TBaseLexer, pos: int): int = proc handleCR(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == CR) assert(L.buf[pos] == CR)
inc(L.linenumber) inc(L.lineNumber)
result = fillBaseLexer(L, pos) result = fillBaseLexer(L, pos)
if L.buf[result] == LF: if L.buf[result] == LF:
result = fillBaseLexer(L, result) result = fillBaseLexer(L, result)
proc handleLF(L: var TBaseLexer, pos: int): int = proc handleLF(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == LF) assert(L.buf[pos] == LF)
inc(L.linenumber) inc(L.lineNumber)
result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result;
proc skipUTF8BOM(L: var TBaseLexer) = proc skipUTF8BOM(L: var TBaseLexer) =
@ -150,7 +150,7 @@ proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) =
L.buf = cast[cstring](alloc(bufLen * chrSize)) L.buf = cast[cstring](alloc(bufLen * chrSize))
L.sentinel = bufLen - 1 L.sentinel = bufLen - 1
L.lineStart = 0 L.lineStart = 0
L.linenumber = 1 # lines start at 1 L.lineNumber = 1 # lines start at 1
L.stream = inputstream L.stream = inputstream
fillBuffer(L) fillBuffer(L)
skipUTF8BOM(L) skipUTF8BOM(L)

View file

@ -81,7 +81,7 @@ when defined(GC_setMaxPause):
when compileOption("gc", "v2") or compileOption("gc", "refc"): when compileOption("gc", "v2") or compileOption("gc", "refc"):
# the new correct mark&sweet collector is too slow :-/ # the new correct mark&sweet collector is too slow :-/
GC_disableMarkAndSweep() GC_disableMarkAndSweep()
condsyms.InitDefines() condsyms.initDefines()
when not defined(selftest): when not defined(selftest):
handleCmdLine() handleCmdLine()

View file

@ -58,7 +58,7 @@ proc overlap(a, b: PNode): bool =
else: else:
result = sameValue(a, b) result = sameValue(a, b)
proc SomeInSet(s: PNode, a, b: PNode): bool = proc someInSet(s: PNode, a, b: PNode): bool =
# checks if some element of a..b is in the set s # checks if some element of a..b is in the set s
if s.kind != nkCurly: if s.kind != nkCurly:
internalError(s.info, "SomeInSet") internalError(s.info, "SomeInSet")

View file

@ -254,11 +254,11 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string =
result = joinPath(subdir, tail) result = joinPath(subdir, tail)
#echo "completeGeneratedFilePath(", f, ") = ", result #echo "completeGeneratedFilePath(", f, ") = ", result
iterator iterSearchPath*(SearchPaths: TLinkedList): string = iterator iterSearchPath*(searchPaths: TLinkedList): string =
var it = PStrEntry(SearchPaths.head) var it = PStrEntry(searchPaths.head)
while it != nil: while it != nil:
yield it.data yield it.data
it = PStrEntry(it.Next) it = PStrEntry(it.next)
proc rawFindFile(f: string): string = proc rawFindFile(f: string): string =
for it in iterSearchPath(searchPaths): for it in iterSearchPath(searchPaths):
@ -274,7 +274,7 @@ proc rawFindFile2(f: string): string =
if existsFile(result): if existsFile(result):
bringToFront(lazyPaths, it) bringToFront(lazyPaths, it)
return result.canonicalizePath return result.canonicalizePath
it = PStrEntry(it.Next) it = PStrEntry(it.next)
result = "" result = ""
proc findFile*(f: string): string {.procvar.} = proc findFile*(f: string): string {.procvar.} =

View file

@ -61,7 +61,7 @@ proc newIdentNodeP*(ident: PIdent, p: TParser): PNode
proc expectIdentOrKeyw*(p: TParser) proc expectIdentOrKeyw*(p: TParser)
proc expectIdent*(p: TParser) proc expectIdent*(p: TParser)
proc parLineInfo*(p: TParser): TLineInfo proc parLineInfo*(p: TParser): TLineInfo
proc eat*(p: var TParser, TokType: TTokType) proc eat*(p: var TParser, tokType: TTokType)
proc skipInd*(p: var TParser) proc skipInd*(p: var TParser)
proc optPar*(p: var TParser) proc optPar*(p: var TParser)
proc optInd*(p: var TParser, n: PNode) proc optInd*(p: var TParser, n: PNode)
@ -139,9 +139,9 @@ proc expectIdent(p: TParser) =
if p.tok.tokType != tkSymbol: if p.tok.tokType != tkSymbol:
lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok)) lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok))
proc eat(p: var TParser, TokType: TTokType) = proc eat(p: var TParser, tokType: TTokType) =
if p.tok.TokType == TokType: getTok(p) if p.tok.tokType == tokType: getTok(p)
else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[TokType]) else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType])
proc parLineInfo(p: TParser): TLineInfo = proc parLineInfo(p: TParser): TLineInfo =
result = getLineInfo(p.lex, p.tok) result = getLineInfo(p.lex, p.tok)
@ -1060,7 +1060,7 @@ proc parseExprStmt(p: var TParser): PNode =
result = makeCall(result) result = makeCall(result)
getTok(p) getTok(p)
skipComment(p, result) skipComment(p, result)
if p.tok.TokType notin {tkOf, tkElif, tkElse, tkExcept}: if p.tok.tokType notin {tkOf, tkElif, tkElse, tkExcept}:
let body = parseStmt(p) let body = parseStmt(p)
addSon(result, newProcNode(nkDo, body.info, body)) addSon(result, newProcNode(nkDo, body.info, body))
while sameInd(p): while sameInd(p):
@ -1638,7 +1638,7 @@ proc parseTypeClass(p: var TParser): PNode =
var args = newNode(nkArgList) var args = newNode(nkArgList)
addSon(result, args) addSon(result, args)
addSon(args, p.parseTypeClassParam) addSon(args, p.parseTypeClassParam)
while p.tok.TokType == tkComma: while p.tok.tokType == tkComma:
getTok(p) getTok(p)
addSon(args, p.parseTypeClassParam) addSon(args, p.parseTypeClassParam)
if p.tok.tokType == tkCurlyDotLe and p.validInd: if p.tok.tokType == tkCurlyDotLe and p.validInd:
@ -1818,7 +1818,7 @@ proc parseStmt(p: var TParser): PNode =
if p.tok.indent > p.currInd: if p.tok.indent > p.currInd:
parMessage(p, errInvalidIndentation) parMessage(p, errInvalidIndentation)
break break
if p.tok.toktype in {tkCurlyRi, tkParRi, tkCurlyDotRi, tkBracketRi}: if p.tok.tokType in {tkCurlyRi, tkParRi, tkCurlyDotRi, tkBracketRi}:
# XXX this ensures tnamedparamanonproc still compiles; # XXX this ensures tnamedparamanonproc still compiles;
# deprecate this syntax later # deprecate this syntax later
break break

View file

@ -209,13 +209,13 @@ proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib =
var it = PLib(c.libs.head) var it = PLib(c.libs.head)
while it != nil: while it != nil:
if it.kind == kind: if it.kind == kind:
if trees.ExprStructuralEquivalent(it.path, path): return it if trees.exprStructuralEquivalent(it.path, path): return it
it = PLib(it.next) it = PLib(it.next)
result = newLib(kind) result = newLib(kind)
result.path = path result.path = path
append(c.libs, result) append(c.libs, result)
if path.kind in {nkStrLit..nkTripleStrLit}: if path.kind in {nkStrLit..nkTripleStrLit}:
result.isOverriden = options.isDynLibOverride(path.strVal) result.isOverriden = options.isDynlibOverride(path.strVal)
proc expectDynlibNode(c: PContext, n: PNode): PNode = proc expectDynlibNode(c: PContext, n: PNode): PNode =
if n.kind != nkExprColonExpr: if n.kind != nkExprColonExpr:
@ -505,11 +505,11 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
if key.kind == nkIdent: if key.kind == nkIdent:
var userPragma = strTableGet(c.userPragmas, key.ident) var userPragma = strTableGet(c.userPragmas, key.ident)
if userPragma != nil: if userPragma != nil:
inc c.InstCounter inc c.instCounter
if c.InstCounter > 100: if c.instCounter > 100:
globalError(it.info, errRecursiveDependencyX, userPragma.name.s) globalError(it.info, errRecursiveDependencyX, userPragma.name.s)
pragma(c, sym, userPragma.ast, validPragmas) pragma(c, sym, userPragma.ast, validPragmas)
dec c.InstCounter dec c.instCounter
else: else:
var k = whichKeyword(key.ident) var k = whichKeyword(key.ident)
if k in validPragmas: if k in validPragmas:
@ -547,7 +547,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
sym.typ.size = size sym.typ.size = size
of wNodecl: of wNodecl:
noVal(it) noVal(it)
incl(sym.loc.Flags, lfNoDecl) incl(sym.loc.flags, lfNoDecl)
of wPure, wNoStackFrame: of wPure, wNoStackFrame:
noVal(it) noVal(it)
if sym != nil: incl(sym.flags, sfPure) if sym != nil: incl(sym.flags, sfPure)
@ -566,7 +566,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
of wCompileTime: of wCompileTime:
noVal(it) noVal(it)
incl(sym.flags, sfCompileTime) incl(sym.flags, sfCompileTime)
incl(sym.loc.Flags, lfNoDecl) incl(sym.loc.flags, lfNoDecl)
of wGlobal: of wGlobal:
noVal(it) noVal(it)
incl(sym.flags, sfGlobal) incl(sym.flags, sfGlobal)
@ -579,7 +579,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
addToLib(lib, sym) addToLib(lib, sym)
incl(sym.flags, sfImportc) incl(sym.flags, sfImportc)
incl(sym.loc.flags, lfHeader) incl(sym.loc.flags, lfHeader)
incl(sym.loc.Flags, lfNoDecl) incl(sym.loc.flags, lfNoDecl)
# implies nodecl, because otherwise header would not make sense # implies nodecl, because otherwise header would not make sense
if sym.loc.r == nil: sym.loc.r = toRope(sym.name.s) if sym.loc.r == nil: sym.loc.r = toRope(sym.name.s)
of wDestructor: of wDestructor:
@ -735,7 +735,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
proc implictPragmas*(c: PContext, sym: PSym, n: PNode, proc implictPragmas*(c: PContext, sym: PSym, n: PNode,
validPragmas: TSpecialWords) = validPragmas: TSpecialWords) =
if sym != nil and sym.kind != skModule: if sym != nil and sym.kind != skModule:
var it = POptionEntry(c.optionstack.head) var it = POptionEntry(c.optionStack.head)
while it != nil: while it != nil:
let o = it.otherPragmas let o = it.otherPragmas
if not o.isNil: if not o.isNil:
@ -746,7 +746,7 @@ proc implictPragmas*(c: PContext, sym: PSym, n: PNode,
if lfExportLib in sym.loc.flags and sfExportc notin sym.flags: if lfExportLib in sym.loc.flags and sfExportc notin sym.flags:
localError(n.info, errDynlibRequiresExportc) localError(n.info, errDynlibRequiresExportc)
var lib = POptionEntry(c.optionstack.tail).dynlib var lib = POptionEntry(c.optionStack.tail).dynlib
if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and
sfImportc in sym.flags and lib != nil: sfImportc in sym.flags and lib != nil:
incl(sym.loc.flags, lfDynamicLib) incl(sym.loc.flags, lfDynamicLib)

View file

@ -20,7 +20,6 @@ const
type type
TGen = object of TPassContext TGen = object of TPassContext
module*: PSym module*: PSym
checkExtern: bool
PGen = ref TGen PGen = ref TGen
TSourceFile = object TSourceFile = object
@ -30,6 +29,7 @@ type
var var
gSourceFiles: seq[TSourceFile] = @[] gSourceFiles: seq[TSourceFile] = @[]
gCheckExtern: bool
rules: PStringTable rules: PStringTable
proc loadFile(info: TLineInfo) = proc loadFile(info: TLineInfo) =
@ -118,8 +118,7 @@ proc beautifyName(s: string, k: TSymKind): string =
proc checkStyle*(info: TLineInfo, s: string, k: TSymKind) = proc checkStyle*(info: TLineInfo, s: string, k: TSymKind) =
let beau = beautifyName(s, k) let beau = beautifyName(s, k)
if s != beau: if s != beau:
message(info, errGenerated, message(info, errGenerated, "name should be: " & beau)
"name does not adhere to naming convention; should be: " & beau)
const const
Letters = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'} Letters = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'}
@ -138,17 +137,18 @@ proc differ(line: string, a, b: int, x: string): bool =
inc j inc j
return false return false
proc checkDef(c: PGen; n: PNode) = proc checkDef*(n: PNode; s: PSym) =
if n.kind != nkSym: return
let s = n.sym
# operators stay as they are: # operators stay as they are:
if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return
if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return
if {sfImportc, sfExportc} * s.flags == {} or c.checkExtern: if {sfImportc, sfExportc} * s.flags == {} or gCheckExtern:
checkStyle(n.info, s.name.s, s.kind) checkStyle(n.info, s.name.s, s.kind)
proc checkDef(c: PGen; n: PNode) =
if n.kind != nkSym: return
checkDef(n, n.sym)
proc checkUse*(n: PNode, s: PSym) = proc checkUse*(n: PNode, s: PSym) =
if n.info.fileIndex < 0: return if n.info.fileIndex < 0: return
# we simply convert it to what it looks like in the definition # we simply convert it to what it looks like in the definition
@ -306,7 +306,7 @@ proc myOpen(module: PSym): PPassContext =
var g: PGen var g: PGen
new(g) new(g)
g.module = module g.module = module
g.checkExtern = options.getConfigVar("pretty.checkextern").normalize == "on" gCheckExtern = options.getConfigVar("pretty.checkextern").normalize == "on"
result = g result = g
if rules.isNil: if rules.isNil:
rules = newStringTable(modeStyleInsensitive) rules = newStringTable(modeStyleInsensitive)

View file

@ -35,13 +35,13 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym =
# in the symbol table. If the parameter lists are exactly # in the symbol table. If the parameter lists are exactly
# the same the sym in the symbol table is returned, else nil. # the same the sym in the symbol table is returned, else nil.
var it: TIdentIter var it: TIdentIter
result = initIdentIter(it, scope.symbols, fn.Name) result = initIdentIter(it, scope.symbols, fn.name)
if isGenericRoutine(fn): if isGenericRoutine(fn):
# we simply check the AST; this is imprecise but nearly the best what # we simply check the AST; this is imprecise but nearly the best what
# can be done; this doesn't work either though as type constraints are # can be done; this doesn't work either though as type constraints are
# not kept in the AST .. # not kept in the AST ..
while result != nil: while result != nil:
if result.Kind == fn.kind and isGenericRoutine(result): if result.kind == fn.kind and isGenericRoutine(result):
let genR = result.ast.sons[genericParamsPos] let genR = result.ast.sons[genericParamsPos]
let genF = fn.ast.sons[genericParamsPos] let genF = fn.ast.sons[genericParamsPos]
if exprStructuralEquivalent(genR, genF) and if exprStructuralEquivalent(genR, genF) and
@ -52,7 +52,7 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym =
result = nextIdentIter(it, scope.symbols) result = nextIdentIter(it, scope.symbols)
else: else:
while result != nil: while result != nil:
if result.Kind == fn.kind and not isGenericRoutine(result): if result.kind == fn.kind and not isGenericRoutine(result):
case equalParams(result.typ.n, fn.typ.n) case equalParams(result.typ.n, fn.typ.n)
of paramsEqual: of paramsEqual:
return return

View file

@ -658,7 +658,7 @@ proc newRodReader(modfilename: string, crc: TCrc32,
readerIndex: int): PRodReader = readerIndex: int): PRodReader =
new(result) new(result)
try: try:
result.memFile = memfiles.open(modfilename) result.memfile = memfiles.open(modfilename)
except EOS: except EOS:
return nil return nil
result.files = @[] result.files = @[]
@ -673,7 +673,7 @@ proc newRodReader(modfilename: string, crc: TCrc32,
initIdTable(r.syms) initIdTable(r.syms)
# we terminate the file explicitely with ``\0``, so the cast to `cstring` # we terminate the file explicitely with ``\0``, so the cast to `cstring`
# is safe: # is safe:
r.s = cast[cstring](r.memFile.mem) r.s = cast[cstring](r.memfile.mem)
if startsWith(r.s, "NIM:"): if startsWith(r.s, "NIM:"):
initIiTable(r.index.tab) initIiTable(r.index.tab)
initIiTable(r.imports.tab) # looks like a ROD file initIiTable(r.imports.tab) # looks like a ROD file
@ -736,7 +736,7 @@ proc getReader(moduleId: int): PRodReader =
# problems: # problems:
for i in 0 .. <gMods.len: for i in 0 .. <gMods.len:
result = gMods[i].rd result = gMods[i].rd
if result != nil and result.moduleId == moduleId: return result if result != nil and result.moduleID == moduleId: return result
return nil return nil
proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym =
@ -845,7 +845,7 @@ proc checkDep(fileIdx: int32): TReasonForRecompile =
rawMessage(hintProcessing, reasonToFrmt[result] % filename) rawMessage(hintProcessing, reasonToFrmt[result] % filename)
if result != rrNone or optForceFullMake in gGlobalOptions: if result != rrNone or optForceFullMake in gGlobalOptions:
# recompilation is necessary: # recompilation is necessary:
if r != nil: memfiles.close(r.memFile) if r != nil: memfiles.close(r.memfile)
r = nil r = nil
gMods[fileIdx].rd = r gMods[fileIdx].rd = r
gMods[fileIdx].reason = result # now we know better gMods[fileIdx].reason = result # now we know better

View file

@ -15,7 +15,7 @@ import
magicsys, parser, nversion, nimsets, semfold, importer, magicsys, parser, nversion, nimsets, semfold, importer,
procfind, lookups, rodread, pragmas, passes, semdata, semtypinst, sigmatch, procfind, lookups, rodread, pragmas, passes, semdata, semtypinst, sigmatch,
semthreads, intsets, transf, vmdef, vm, idgen, aliases, cgmeth, lambdalifting, semthreads, intsets, transf, vmdef, vm, idgen, aliases, cgmeth, lambdalifting,
evaltempl, patterns, parampatterns, sempass2 evaltempl, patterns, parampatterns, sempass2, pretty
# implementation # implementation
@ -47,7 +47,7 @@ proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode
proc typeMismatch(n: PNode, formal, actual: PType) = proc typeMismatch(n: PNode, formal, actual: PType) =
if formal.kind != tyError and actual.kind != tyError: if formal.kind != tyError and actual.kind != tyError:
localError(n.Info, errGenerated, msgKindToString(errTypeMismatch) & localError(n.info, errGenerated, msgKindToString(errTypeMismatch) &
typeToString(actual) & ") " & typeToString(actual) & ") " &
`%`(msgKindToString(errButExpectedX), [typeToString(formal)])) `%`(msgKindToString(errButExpectedX), [typeToString(formal)]))
@ -291,10 +291,10 @@ proc myOpen(module: PSym): PPassContext =
c.importTable = openScope(c) c.importTable = openScope(c)
c.importTable.addSym(module) # a module knows itself c.importTable.addSym(module) # a module knows itself
if sfSystemModule in module.flags: if sfSystemModule in module.flags:
magicsys.SystemModule = module # set global variable! magicsys.systemModule = module # set global variable!
else: else:
c.importTable.addSym magicsys.SystemModule # import the "System" identifier c.importTable.addSym magicsys.systemModule # import the "System" identifier
importAllSymbols(c, magicsys.SystemModule) importAllSymbols(c, magicsys.systemModule)
c.topLevelScope = openScope(c) c.topLevelScope = openScope(c)
result = c result = c
@ -332,12 +332,12 @@ proc myProcess(context: PPassContext, n: PNode): PNode =
result = semStmtAndGenerateGenerics(c, n) result = semStmtAndGenerateGenerics(c, n)
else: else:
let oldContextLen = msgs.getInfoContextLen() let oldContextLen = msgs.getInfoContextLen()
let oldInGenericInst = c.InGenericInst let oldInGenericInst = c.inGenericInst
try: try:
result = semStmtAndGenerateGenerics(c, n) result = semStmtAndGenerateGenerics(c, n)
except ERecoverableError, ESuggestDone: except ERecoverableError, ESuggestDone:
recoverContext(c) recoverContext(c)
c.InGenericInst = oldInGenericInst c.inGenericInst = oldInGenericInst
msgs.setInfoContextLen(oldContextLen) msgs.setInfoContextLen(oldContextLen)
if getCurrentException() of ESuggestDone: result = nil if getCurrentException() of ESuggestDone: result = nil
else: result = ast.emptyNode else: result = ast.emptyNode
@ -346,7 +346,7 @@ proc myProcess(context: PPassContext, n: PNode): PNode =
proc checkThreads(c: PContext) = proc checkThreads(c: PContext) =
if not needsGlobalAnalysis(): return if not needsGlobalAnalysis(): return
for i in 0 .. c.threadEntries.len-1: for i in 0 .. c.threadEntries.len-1:
semthreads.AnalyseThreadProc(c.threadEntries[i]) semthreads.analyseThreadProc(c.threadEntries[i])
proc myClose(context: PPassContext, n: PNode): PNode = proc myClose(context: PPassContext, n: PNode): PNode =
var c = PContext(context) var c = PContext(context)

View file

@ -93,7 +93,7 @@ proc notFoundError*(c: PContext, n: PNode, errors: seq[string]) =
if candidates != "": if candidates != "":
add(result, "\n" & msgKindToString(errButExpected) & "\n" & candidates) add(result, "\n" & msgKindToString(errButExpected) & "\n" & candidates)
localError(n.Info, errGenerated, result) localError(n.info, errGenerated, result)
proc gatherUsedSyms(c: PContext, usedSyms: var seq[PNode]) = proc gatherUsedSyms(c: PContext, usedSyms: var seq[PNode]) =
for scope in walkScopes(c.currentScope): for scope in walkScopes(c.currentScope):
@ -169,7 +169,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode,
#writeMatches(alt) #writeMatches(alt)
if c.inCompilesContext > 0: if c.inCompilesContext > 0:
# quick error message for performance of 'compiles' built-in: # quick error message for performance of 'compiles' built-in:
globalError(n.Info, errGenerated, "ambiguous call") globalError(n.info, errGenerated, "ambiguous call")
elif gErrorCounter == 0: elif gErrorCounter == 0:
# don't cascade errors # don't cascade errors
var args = "(" var args = "("
@ -178,7 +178,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode,
add(args, typeToString(n.sons[i].typ)) add(args, typeToString(n.sons[i].typ))
add(args, ")") add(args, ")")
localError(n.Info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [ localError(n.info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [
getProcHeader(result.calleeSym), getProcHeader(alt.calleeSym), getProcHeader(result.calleeSym), getProcHeader(alt.calleeSym),
args]) args])

View file

@ -160,7 +160,7 @@ proc newOptionEntry(): POptionEntry =
proc newContext(module: PSym): PContext = proc newContext(module: PSym): PContext =
new(result) new(result)
result.AmbiguousSymbols = initIntSet() result.ambiguousSymbols = initIntSet()
initLinkedList(result.optionStack) initLinkedList(result.optionStack)
initLinkedList(result.libs) initLinkedList(result.libs)
append(result.optionStack, newOptionEntry()) append(result.optionStack, newOptionEntry())
@ -172,7 +172,7 @@ proc newContext(module: PSym): PContext =
result.includedFiles = initIntSet() result.includedFiles = initIntSet()
initStrTable(result.userPragmas) initStrTable(result.userPragmas)
result.generics = @[] result.generics = @[]
result.UnknownIdents = initIntSet() result.unknownIdents = initIntSet()
proc inclSym(sq: var TSymSeq, s: PSym) = proc inclSym(sq: var TSymSeq, s: PSym) =
var L = len(sq) var L = len(sq)

View file

@ -151,15 +151,15 @@ proc checkConvertible(castDest, src: PType): TConvStatus =
return return
var d = skipTypes(castDest, abstractVar) var d = skipTypes(castDest, abstractVar)
var s = skipTypes(src, abstractVar-{tyTypeDesc}) var s = skipTypes(src, abstractVar-{tyTypeDesc})
while (d != nil) and (d.Kind in {tyPtr, tyRef}) and (d.Kind == s.Kind): while (d != nil) and (d.kind in {tyPtr, tyRef}) and (d.kind == s.kind):
d = base(d) d = base(d)
s = base(s) s = base(s)
if d == nil: if d == nil:
result = convNotLegal result = convNotLegal
elif d.Kind == tyObject and s.Kind == tyObject: elif d.kind == tyObject and s.kind == tyObject:
result = checkConversionBetweenObjects(d, s) result = checkConversionBetweenObjects(d, s)
elif (skipTypes(castDest, abstractVarRange).Kind in IntegralTypes) and elif (skipTypes(castDest, abstractVarRange).kind in IntegralTypes) and
(skipTypes(src, abstractVarRange-{tyTypeDesc}).Kind in IntegralTypes): (skipTypes(src, abstractVarRange-{tyTypeDesc}).kind in IntegralTypes):
# accept conversion between integral types # accept conversion between integral types
else: else:
# we use d, s here to speed up that operation a bit: # we use d, s here to speed up that operation a bit:
@ -228,9 +228,9 @@ proc semCast(c: PContext, n: PNode): PNode =
result.typ = semTypeNode(c, n.sons[0], nil) result.typ = semTypeNode(c, n.sons[0], nil)
addSon(result, copyTree(n.sons[0])) addSon(result, copyTree(n.sons[0]))
addSon(result, semExprWithType(c, n.sons[1])) addSon(result, semExprWithType(c, n.sons[1]))
if not isCastable(result.typ, result.sons[1].Typ): if not isCastable(result.typ, result.sons[1].typ):
localError(result.info, errExprCannotBeCastedToX, localError(result.info, errExprCannotBeCastedToX,
typeToString(result.Typ)) typeToString(result.typ))
proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode = proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode =
const const
@ -240,7 +240,7 @@ proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode =
else: else:
n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType}) n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType})
var typ = skipTypes(n.sons[1].typ, abstractVarRange) var typ = skipTypes(n.sons[1].typ, abstractVarRange)
case typ.Kind case typ.kind
of tySequence, tyString, tyOpenArray, tyVarargs: of tySequence, tyString, tyOpenArray, tyVarargs:
n.typ = getSysType(tyInt) n.typ = getSysType(tyInt)
of tyArrayConstr, tyArray: of tyArrayConstr, tyArray:
@ -711,7 +711,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
if m.state != csMatch: if m.state != csMatch:
if c.inCompilesContext > 0: if c.inCompilesContext > 0:
# speed up error generation: # speed up error generation:
globalError(n.Info, errTypeMismatch, "") globalError(n.info, errTypeMismatch, "")
return emptyNode return emptyNode
else: else:
var hasErrorType = false var hasErrorType = false
@ -726,7 +726,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
if not hasErrorType: if not hasErrorType:
add(msg, ")\n" & msgKindToString(errButExpected) & "\n" & add(msg, ")\n" & msgKindToString(errButExpected) & "\n" &
typeToString(n.sons[0].typ)) typeToString(n.sons[0].typ))
localError(n.Info, errGenerated, msg) localError(n.info, errGenerated, msg)
return errorNode(c, n) return errorNode(c, n)
result = nil result = nil
else: else:
@ -771,7 +771,7 @@ proc afterCallActions(c: PContext; n, orig: PNode, flags: TExprFlags): PNode =
analyseIfAddressTakenInCall(c, result) analyseIfAddressTakenInCall(c, result)
if callee.magic != mNone: if callee.magic != mNone:
result = magicsAfterOverloadResolution(c, result, flags) result = magicsAfterOverloadResolution(c, result, flags)
if c.InTypeClass == 0: if c.inTypeClass == 0:
result = evalAtCompileTime(c, result) result = evalAtCompileTime(c, result)
proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
@ -810,7 +810,7 @@ proc semEcho(c: PContext, n: PNode): PNode =
proc buildEchoStmt(c: PContext, n: PNode): PNode = proc buildEchoStmt(c: PContext, n: PNode): PNode =
# we MUST not check 'n' for semantics again here! # we MUST not check 'n' for semantics again here!
result = newNodeI(nkCall, n.info) result = newNodeI(nkCall, n.info)
var e = strTableGet(magicsys.systemModule.Tab, getIdent"echo") var e = strTableGet(magicsys.systemModule.tab, getIdent"echo")
if e != nil: if e != nil:
addSon(result, newSymNode(e)) addSon(result, newSymNode(e))
else: else:
@ -908,6 +908,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared})
if s != nil: if s != nil:
markUsed(n.sons[1], s)
return semSym(c, n, s, flags) return semSym(c, n, s, flags)
n.sons[0] = semExprWithType(c, n.sons[0], flags+{efDetermineType}) n.sons[0] = semExprWithType(c, n.sons[0], flags+{efDetermineType})
@ -950,7 +951,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
return return
# XXX: This is probably not relevant any more # XXX: This is probably not relevant any more
# reset to prevent 'nil' bug: see "tests/reject/tenumitems.nim": # reset to prevent 'nil' bug: see "tests/reject/tenumitems.nim":
ty = n.sons[0].Typ ty = n.sons[0].typ
ty = skipTypes(ty, {tyGenericInst, tyVar, tyPtr, tyRef}) ty = skipTypes(ty, {tyGenericInst, tyVar, tyPtr, tyRef})
var check: PNode = nil var check: PNode = nil
@ -1446,7 +1447,7 @@ proc tryExpr(c: PContext, n: PNode,
# watch out, hacks ahead: # watch out, hacks ahead:
let oldErrorCount = msgs.gErrorCounter let oldErrorCount = msgs.gErrorCounter
let oldErrorMax = msgs.gErrorMax let oldErrorMax = msgs.gErrorMax
inc c.InCompilesContext inc c.inCompilesContext
# do not halt after first error: # do not halt after first error:
msgs.gErrorMax = high(int) msgs.gErrorMax = high(int)
@ -1459,9 +1460,9 @@ proc tryExpr(c: PContext, n: PNode,
errorOutputs = if bufferErrors: {eInMemory} else: {} errorOutputs = if bufferErrors: {eInMemory} else: {}
let oldContextLen = msgs.getInfoContextLen() let oldContextLen = msgs.getInfoContextLen()
let oldInGenericContext = c.InGenericContext let oldInGenericContext = c.inGenericContext
let oldInUnrolledContext = c.InUnrolledContext let oldInUnrolledContext = c.inUnrolledContext
let oldInGenericInst = c.InGenericInst let oldInGenericInst = c.inGenericInst
let oldProcCon = c.p let oldProcCon = c.p
c.generics = @[] c.generics = @[]
try: try:
@ -1471,14 +1472,14 @@ proc tryExpr(c: PContext, n: PNode,
nil nil
# undo symbol table changes (as far as it's possible): # undo symbol table changes (as far as it's possible):
c.generics = oldGenerics c.generics = oldGenerics
c.InGenericContext = oldInGenericContext c.inGenericContext = oldInGenericContext
c.InUnrolledContext = oldInUnrolledContext c.inUnrolledContext = oldInUnrolledContext
c.InGenericInst = oldInGenericInst c.inGenericInst = oldInGenericInst
c.p = oldProcCon c.p = oldProcCon
msgs.setInfoContextLen(oldContextLen) msgs.setInfoContextLen(oldContextLen)
setLen(gOwners, oldOwnerLen) setLen(gOwners, oldOwnerLen)
c.currentScope = oldScope c.currentScope = oldScope
dec c.InCompilesContext dec c.inCompilesContext
errorOutputs = oldErrorOutputs errorOutputs = oldErrorOutputs
msgs.gErrorCounter = oldErrorCount msgs.gErrorCounter = oldErrorCount
msgs.gErrorMax = oldErrorMax msgs.gErrorMax = oldErrorMax
@ -1893,6 +1894,8 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
let mode = if nfDelegate in n.flags: {} else: {checkUndeclared} let mode = if nfDelegate in n.flags: {} else: {checkUndeclared}
var s = qualifiedLookUp(c, n.sons[0], mode) var s = qualifiedLookUp(c, n.sons[0], mode)
if s != nil: if s != nil:
if gCmd == cmdPretty and n.sons[0].kind == nkDotExpr:
pretty.checkUse(n.sons[0].sons[1], s)
case s.kind case s.kind
of skMacro: of skMacro:
if sfImmediate notin s.flags: if sfImmediate notin s.flags:
@ -1912,7 +1915,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode =
result = semConv(c, n) result = semConv(c, n)
elif n.len == 1: elif n.len == 1:
result = semObjConstr(c, n, flags) result = semObjConstr(c, n, flags)
elif contains(c.AmbiguousSymbols, s.id): elif contains(c.ambiguousSymbols, s.id):
localError(n.info, errUseQualifier, s.name.s) localError(n.info, errUseQualifier, s.name.s)
elif s.magic == mNone: result = semDirectOp(c, n, flags) elif s.magic == mNone: result = semDirectOp(c, n, flags)
else: result = semMagic(c, n, s, flags) else: result = semMagic(c, n, s, flags)

View file

@ -88,7 +88,7 @@ proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind)
proc instantiateBody(c: PContext, n: PNode, result: PSym) = proc instantiateBody(c: PContext, n: PNode, result: PSym) =
if n.sons[bodyPos].kind != nkEmpty: if n.sons[bodyPos].kind != nkEmpty:
inc c.InGenericInst inc c.inGenericInst
# add it here, so that recursive generic procs are possible: # add it here, so that recursive generic procs are possible:
addDecl(c, result) addDecl(c, result)
pushProcCon(c, result) pushProcCon(c, result)
@ -109,7 +109,7 @@ proc instantiateBody(c: PContext, n: PNode, result: PSym) =
#echo "code instantiated ", result.name.s #echo "code instantiated ", result.name.s
excl(result.flags, sfForward) excl(result.flags, sfForward)
popProcCon(c) popProcCon(c)
dec c.InGenericInst dec c.inGenericInst
proc fixupInstantiatedSymbols(c: PContext, s: PSym) = proc fixupInstantiatedSymbols(c: PContext, s: PSym) =
for i in countup(0, c.generics.len - 1): for i in countup(0, c.generics.len - 1):
@ -265,8 +265,8 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable,
if fn.kind in {skTemplate, skMacro}: return fn if fn.kind in {skTemplate, skMacro}: return fn
# generates an instantiated proc # generates an instantiated proc
if c.InstCounter > 1000: internalError(fn.ast.info, "nesting too deep") if c.instCounter > 1000: internalError(fn.ast.info, "nesting too deep")
inc(c.InstCounter) inc(c.instCounter)
# careful! we copy the whole AST including the possibly nil body! # careful! we copy the whole AST including the possibly nil body!
var n = copyTree(fn.ast) var n = copyTree(fn.ast)
# NOTE: for access of private fields within generics from a different module # NOTE: for access of private fields within generics from a different module
@ -309,5 +309,5 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable,
popOwner() popOwner()
#c.currentScope = oldScope #c.currentScope = oldScope
c.friendModule = oldFriend c.friendModule = oldFriend
dec(c.InstCounter) dec(c.instCounter)
if result.kind == skMethod: finishMethod(c, result) if result.kind == skMethod: finishMethod(c, result)

View file

@ -367,7 +367,7 @@ proc trackCase(tracked: PEffects, n: PNode) =
for i in oldState.. <tracked.init.len: for i in oldState.. <tracked.init.len:
addToIntersection(inter, tracked.init[i]) addToIntersection(inter, tracked.init[i])
let exh = case skipTypes(n.sons[0].Typ, abstractVarRange-{tyTypeDesc}).Kind let exh = case skipTypes(n.sons[0].typ, abstractVarRange-{tyTypeDesc}).kind
of tyFloat..tyFloat128, tyString: of tyFloat..tyFloat128, tyString:
lastSon(n).kind == nkElse lastSon(n).kind == nkElse
else: else:

View file

@ -142,7 +142,7 @@ proc discardCheck(c: PContext, result: PNode) =
while n.kind in skipForDiscardable: while n.kind in skipForDiscardable:
n = n.lastSon n = n.lastSon
n.typ = nil n.typ = nil
elif c.InTypeClass > 0 and result.typ.kind == tyBool: elif c.inTypeClass > 0 and result.typ.kind == tyBool:
let verdict = semConstExpr(c, result) let verdict = semConstExpr(c, result)
if verdict.intVal == 0: if verdict.intVal == 0:
localError(result.info, "type class predicate failed.") localError(result.info, "type class predicate failed.")
@ -193,7 +193,7 @@ proc semCase(c: PContext, n: PNode): PNode =
var covered: BiggestInt = 0 var covered: BiggestInt = 0
var typ = commonTypeBegin var typ = commonTypeBegin
var hasElse = false var hasElse = false
case skipTypes(n.sons[0].Typ, abstractVarRange-{tyTypeDesc}).Kind case skipTypes(n.sons[0].typ, abstractVarRange-{tyTypeDesc}).kind
of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32: of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32:
chckCovered = true chckCovered = true
of tyFloat..tyFloat128, tyString, tyError: of tyFloat..tyFloat128, tyString, tyError:
@ -375,7 +375,7 @@ proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode =
var v = semIdentDef(c, a.sons[j], symkind) var v = semIdentDef(c, a.sons[j], symkind)
if sfGenSym notin v.flags: addInterfaceDecl(c, v) if sfGenSym notin v.flags: addInterfaceDecl(c, v)
when oKeepVariableNames: when oKeepVariableNames:
if c.InUnrolledContext > 0: v.flags.incl(sfShadowed) if c.inUnrolledContext > 0: v.flags.incl(sfShadowed)
else: else:
let shadowed = findShadowedVar(c, v) let shadowed = findShadowedVar(c, v)
if shadowed != nil: if shadowed != nil:
@ -496,10 +496,10 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) =
fc.field = typ.sym fc.field = typ.sym
fc.replaceByFieldName = c.m == mFieldPairs fc.replaceByFieldName = c.m == mFieldPairs
openScope(c.c) openScope(c.c)
inc c.c.InUnrolledContext inc c.c.inUnrolledContext
let body = instFieldLoopBody(fc, lastSon(forLoop), forLoop) let body = instFieldLoopBody(fc, lastSon(forLoop), forLoop)
father.add(semStmt(c.c, body)) father.add(semStmt(c.c, body))
dec c.c.InUnrolledContext dec c.c.inUnrolledContext
closeScope(c.c) closeScope(c.c)
of nkNilLit: discard of nkNilLit: discard
of nkRecCase: of nkRecCase:
@ -535,7 +535,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode =
# so that 'break' etc. work as expected, we produce # so that 'break' etc. work as expected, we produce
# a 'while true: stmt; break' loop ... # a 'while true: stmt; break' loop ...
result = newNodeI(nkWhileStmt, n.info, 2) result = newNodeI(nkWhileStmt, n.info, 2)
var trueSymbol = strTableGet(magicsys.systemModule.Tab, getIdent"true") var trueSymbol = strTableGet(magicsys.systemModule.tab, getIdent"true")
if trueSymbol == nil: if trueSymbol == nil:
localError(n.info, errSystemNeeds, "true") localError(n.info, errSystemNeeds, "true")
trueSymbol = newSym(skUnknown, getIdent"true", getCurrOwner(), n.info) trueSymbol = newSym(skUnknown, getIdent"true", getCurrOwner(), n.info)
@ -570,9 +570,9 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode =
fc.tupleIndex = i fc.tupleIndex = i
fc.replaceByFieldName = m == mFieldPairs fc.replaceByFieldName = m == mFieldPairs
var body = instFieldLoopBody(fc, loopBody, n) var body = instFieldLoopBody(fc, loopBody, n)
inc c.InUnrolledContext inc c.inUnrolledContext
stmts.add(semStmt(c, body)) stmts.add(semStmt(c, body))
dec c.InUnrolledContext dec c.inUnrolledContext
closeScope(c) closeScope(c)
else: else:
var fc: TFieldsCtx var fc: TFieldsCtx
@ -744,9 +744,9 @@ proc typeSectionRightSidePass(c: PContext, n: PNode) =
var body: PType = nil var body: PType = nil
s.typScope = c.currentScope.parent s.typScope = c.currentScope.parent
else: else:
inc c.InGenericContext inc c.inGenericContext
var body = semTypeNode(c, a.sons[2], nil) var body = semTypeNode(c, a.sons[2], nil)
dec c.InGenericContext dec c.inGenericContext
if body != nil: if body != nil:
body.sym = s body.sym = s
body.size = -1 # could not be computed properly body.size = -1 # could not be computed properly
@ -1267,7 +1267,7 @@ proc semStmtList(c: PContext, n: PNode): PNode =
# "Last expression must be explicitly returned if it " & # "Last expression must be explicitly returned if it " &
# "is discardable or discarded") # "is discardable or discarded")
proc SemStmt(c: PContext, n: PNode): PNode = proc semStmt(c: PContext, n: PNode): PNode =
# now: simply an alias: # now: simply an alias:
result = semExprNoType(c, n) result = semExprNoType(c, n)

View file

@ -153,7 +153,7 @@ proc semRangeAux(c: PContext, n: PNode, prev: PType): PType =
result = newOrPrevType(tyRange, prev, c) result = newOrPrevType(tyRange, prev, c)
result.n = newNodeI(nkRange, n.info) result.n = newNodeI(nkRange, n.info)
if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty): if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty):
localError(n.Info, errRangeIsEmpty) localError(n.info, errRangeIsEmpty)
var a = semConstExpr(c, n[1]) var a = semConstExpr(c, n[1])
var b = semConstExpr(c, n[2]) var b = semConstExpr(c, n[2])
if not sameType(a.typ, b.typ): if not sameType(a.typ, b.typ):
@ -163,7 +163,7 @@ proc semRangeAux(c: PContext, n: PNode, prev: PType): PType =
localError(n.info, errOrdinalTypeExpected) localError(n.info, errOrdinalTypeExpected)
elif enumHasHoles(a.typ): elif enumHasHoles(a.typ):
localError(n.info, errEnumXHasHoles, a.typ.sym.name.s) localError(n.info, errEnumXHasHoles, a.typ.sym.name.s)
elif not leValue(a, b): localError(n.Info, errRangeIsEmpty) elif not leValue(a, b): localError(n.info, errRangeIsEmpty)
addSon(result.n, a) addSon(result.n, a)
addSon(result.n, b) addSon(result.n, b)
addSonSkipIntLit(result, b.typ) addSonSkipIntLit(result, b.typ)
@ -198,7 +198,7 @@ proc semArray(c: PContext, n: PNode, prev: PType): PType =
indx = makeRangeType(c, 0, e.intVal-1, n.info, e.typ) indx = makeRangeType(c, 0, e.intVal-1, n.info, e.typ)
elif e.kind == nkSym and e.typ.kind == tyExpr: elif e.kind == nkSym and e.typ.kind == tyExpr:
if e.sym.ast != nil: return semArray(c, e.sym.ast, nil) if e.sym.ast != nil: return semArray(c, e.sym.ast, nil)
internalAssert c.InGenericContext > 0 internalAssert c.inGenericContext > 0
if not isOrdinalType(e.typ.lastSon): if not isOrdinalType(e.typ.lastSon):
localError(n[1].info, errOrdinalTypeExpected) localError(n[1].info, errOrdinalTypeExpected)
indx = e.typ indx = e.typ
@ -240,7 +240,7 @@ proc semTypeIdent(c: PContext, n: PNode): PSym =
# This is a typedesc param. is it already bound? # This is a typedesc param. is it already bound?
# it's not bound when it's used multiple times in the # it's not bound when it's used multiple times in the
# proc signature for example # proc signature for example
if c.InGenericInst > 0: if c.inGenericInst > 0:
let bound = result.typ.sons[0].sym let bound = result.typ.sons[0].sym
if bound != nil: return bound if bound != nil: return bound
return result return result
@ -300,6 +300,7 @@ proc semTuple(c: PContext, n: PNode, prev: PType): PType =
else: else:
addSon(result.n, newSymNode(field)) addSon(result.n, newSymNode(field))
addSonSkipIntLit(result, typ) addSonSkipIntLit(result, typ)
if gCmd == cmdPretty: checkDef(a.sons[j], field)
proc semIdentVis(c: PContext, kind: TSymKind, n: PNode, proc semIdentVis(c: PContext, kind: TSymKind, n: PNode,
allowed: TSymFlags): PSym = allowed: TSymFlags): PSym =
@ -334,6 +335,7 @@ proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
else: discard else: discard
else: else:
result = semIdentVis(c, kind, n, allowed) result = semIdentVis(c, kind, n, allowed)
if gCmd == cmdPretty: checkDef(n, result)
proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) = proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) =
let ex = t[branchIndex][currentEx].skipConv let ex = t[branchIndex][currentEx].skipConv
@ -412,7 +414,7 @@ proc semRecordCase(c: PContext, n: PNode, check: var TIntSet, pos: var int,
return return
incl(a.sons[0].sym.flags, sfDiscriminant) incl(a.sons[0].sym.flags, sfDiscriminant)
var covered: BiggestInt = 0 var covered: BiggestInt = 0
var typ = skipTypes(a.sons[0].Typ, abstractVar-{tyTypeDesc}) var typ = skipTypes(a.sons[0].typ, abstractVar-{tyTypeDesc})
if not isOrdinalType(typ): if not isOrdinalType(typ):
localError(n.info, errSelectorMustBeOrdinal) localError(n.info, errSelectorMustBeOrdinal)
elif firstOrd(typ) < 0: elif firstOrd(typ) < 0:
@ -450,7 +452,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int,
case it.kind case it.kind
of nkElifBranch: of nkElifBranch:
checkSonsLen(it, 2) checkSonsLen(it, 2)
if c.InGenericContext == 0: if c.inGenericContext == 0:
var e = semConstBoolExpr(c, it.sons[0]) var e = semConstBoolExpr(c, it.sons[0])
if e.kind != nkIntLit: internalError(e.info, "semRecordNodeAux") if e.kind != nkIntLit: internalError(e.info, "semRecordNodeAux")
elif e.intVal != 0 and branch == nil: branch = it.sons[1] elif e.intVal != 0 and branch == nil: branch = it.sons[1]
@ -461,7 +463,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int,
if branch == nil: branch = it.sons[0] if branch == nil: branch = it.sons[0]
idx = 0 idx = 0
else: illFormedAst(n) else: illFormedAst(n)
if c.InGenericContext > 0: if c.inGenericContext > 0:
# use a new check intset here for each branch: # use a new check intset here for each branch:
var newCheck: TIntSet var newCheck: TIntSet
assign(newCheck, check) assign(newCheck, check)
@ -469,7 +471,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int,
var newf = newNodeI(nkRecList, n.info) var newf = newNodeI(nkRecList, n.info)
semRecordNodeAux(c, it.sons[idx], newCheck, newPos, newf, rectype) semRecordNodeAux(c, it.sons[idx], newCheck, newPos, newf, rectype)
it.sons[idx] = if newf.len == 1: newf[0] else: newf it.sons[idx] = if newf.len == 1: newf[0] else: newf
if c.InGenericContext > 0: if c.inGenericContext > 0:
addSon(father, n) addSon(father, n)
elif branch != nil: elif branch != nil:
semRecordNodeAux(c, branch, check, pos, father, rectype) semRecordNodeAux(c, branch, check, pos, father, rectype)
@ -761,6 +763,8 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode,
addSon(result.n, newSymNode(arg)) addSon(result.n, newSymNode(arg))
rawAddSon(result, finalType) rawAddSon(result, finalType)
addParamOrResult(c, arg, kind) addParamOrResult(c, arg, kind)
if gCmd == cmdPretty: checkDef(a.sons[j], arg)
if n.sons[0].kind != nkEmpty: if n.sons[0].kind != nkEmpty:
var r = semTypeNode(c, n.sons[0], nil) var r = semTypeNode(c, n.sons[0], nil)

View file

@ -226,7 +226,7 @@ proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType =
for i in countup(0, sonsLen(result) - 1): for i in countup(0, sonsLen(result) - 1):
result.sons[i] = replaceTypeVarsT(cl, result.sons[i]) result.sons[i] = replaceTypeVarsT(cl, result.sons[i])
result.n = replaceTypeVarsN(cl, result.n) result.n = replaceTypeVarsN(cl, result.n)
if result.Kind in GenericTypes: if result.kind in GenericTypes:
localError(cl.info, errCannotInstantiateX, typeToString(t, preferName)) localError(cl.info, errCannotInstantiateX, typeToString(t, preferName))
if result.kind == tyProc and result.sons[0] != nil: if result.kind == tyProc and result.sons[0] != nil:
if result.sons[0].kind == tyEmpty: if result.sons[0].kind == tyEmpty:

View file

@ -354,9 +354,9 @@ proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation =
return isNone return isNone
elif f.flags * {tfIterator} != a.flags * {tfIterator}: elif f.flags * {tfIterator} != a.flags * {tfIterator}:
return isNone return isNone
elif f.callconv != a.callconv: elif f.callConv != a.callConv:
# valid to pass a 'nimcall' thingie to 'closure': # valid to pass a 'nimcall' thingie to 'closure':
if f.callconv == ccClosure and a.callconv == ccDefault: if f.callConv == ccClosure and a.callConv == ccDefault:
result = isConvertible result = isConvertible
else: else:
return isNone return isNone
@ -509,7 +509,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation =
elif lengthOrd(fRange) != lengthOrd(a): result = isNone elif lengthOrd(fRange) != lengthOrd(a): result = isNone
else: nil else: nil
of tyOpenArray, tyVarargs: of tyOpenArray, tyVarargs:
case a.Kind case a.kind
of tyOpenArray, tyVarargs: of tyOpenArray, tyVarargs:
result = typeRel(c, base(f), base(a)) result = typeRel(c, base(f), base(a))
if result < isGeneric: result = isNone if result < isGeneric: result = isNone
@ -530,7 +530,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation =
result = isConvertible result = isConvertible
else: nil else: nil
of tySequence: of tySequence:
case a.Kind case a.kind
of tySequence: of tySequence:
if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty): if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty):
result = isSubtype result = isSubtype
@ -620,7 +620,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation =
else: nil else: nil
of tyCString: of tyCString:
# conversion from string to cstring is automatic: # conversion from string to cstring is automatic:
case a.Kind case a.kind
of tyCString: of tyCString:
if tfNotNil in f.flags and tfNotNil notin a.flags: if tfNotNil in f.flags and tfNotNil notin a.flags:
result = isNilConversion result = isNilConversion
@ -849,10 +849,10 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate,
# pushInfoContext(arg.info) # pushInfoContext(arg.info)
openScope(c) openScope(c)
inc c.InTypeClass inc c.inTypeClass
finally: finally:
dec c.InTypeClass dec c.inTypeClass
closeScope(c) closeScope(c)
for param in f.n[0]: for param in f.n[0]:
@ -894,7 +894,7 @@ proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType,
arg = argSemantized arg = argSemantized
let let
a = if c.InTypeClass > 0: argType.skipTypes({tyTypeDesc}) a = if c.inTypeClass > 0: argType.skipTypes({tyTypeDesc})
else: argType else: argType
fMaybeExpr = f.skipTypes({tyDistinct}) fMaybeExpr = f.skipTypes({tyDistinct})

View file

@ -151,7 +151,7 @@ proc suggestEverything(c: PContext, n: PNode, outputs: var int) =
proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) =
# special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but
# ``myObj``. # ``myObj``.
var typ = n.Typ var typ = n.typ
if typ == nil: if typ == nil:
# a module symbol has no type for example: # a module symbol has no type for example:
if n.kind == nkSym and n.sym.kind == skModule: if n.kind == nkSym and n.sym.kind == skModule:
@ -338,8 +338,8 @@ proc suggestExpr*(c: PContext, node: PNode) =
if cp == cpNone: return if cp == cpNone: return
var outputs = 0 var outputs = 0
# This keeps semExpr() from coming here recursively: # This keeps semExpr() from coming here recursively:
if c.InCompilesContext > 0: return if c.inCompilesContext > 0: return
inc(c.InCompilesContext) inc(c.inCompilesContext)
if optSuggest in gGlobalOptions: if optSuggest in gGlobalOptions:
var n = findClosestDot(node) var n = findClosestDot(node)
@ -369,7 +369,7 @@ proc suggestExpr*(c: PContext, node: PNode) =
addSon(a, x) addSon(a, x)
suggestCall(c, a, n, outputs) suggestCall(c, a, n, outputs)
dec(c.InCompilesContext) dec(c.inCompilesContext)
if outputs > 0 and optUsages notin gGlobalOptions: suggestQuit() if outputs > 0 and optUsages notin gGlobalOptions: suggestQuit()
proc suggestStmt*(c: PContext, n: PNode) = proc suggestStmt*(c: PContext, n: PNode) =

View file

@ -513,7 +513,7 @@ proc transformCase(c: PTransf, n: PNode): PTransNode =
elseBranch[0] = ifs elseBranch[0] = ifs
result.add(elseBranch) result.add(elseBranch)
elif result.PNode.lastSon.kind != nkElse and not ( elif result.PNode.lastSon.kind != nkElse and not (
skipTypes(n.sons[0].Typ, abstractVarRange).Kind in skipTypes(n.sons[0].typ, abstractVarRange).kind in
{tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32}): {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32}):
# fix a stupid code gen bug by normalizing: # fix a stupid code gen bug by normalizing:
var elseBranch = newTransNode(nkElse, n.info, 1) var elseBranch = newTransNode(nkElse, n.info, 1)
@ -533,7 +533,7 @@ proc getMergeOp(n: PNode): PSym =
case n.kind case n.kind
of nkCall, nkHiddenCallConv, nkCommand, nkInfix, nkPrefix, nkPostfix, of nkCall, nkHiddenCallConv, nkCommand, nkInfix, nkPrefix, nkPostfix,
nkCallStrLit: nkCallStrLit:
if (n.sons[0].Kind == nkSym) and (n.sons[0].sym.kind == skProc) and if (n.sons[0].kind == nkSym) and (n.sons[0].sym.kind == skProc) and
(sfMerge in n.sons[0].sym.flags): (sfMerge in n.sons[0].sym.flags):
result = n.sons[0].sym result = n.sons[0].sym
else: nil else: nil

View file

@ -88,13 +88,13 @@ proc getOpSym*(op: PNode): PSym =
result = nil result = nil
else: else:
if sonsLen(op) <= 0: internalError(op.info, "getOpSym") if sonsLen(op) <= 0: internalError(op.info, "getOpSym")
elif op.sons[0].Kind == nkSym: result = op.sons[0].sym elif op.sons[0].kind == nkSym: result = op.sons[0].sym
else: result = nil else: result = nil
proc getMagic*(op: PNode): TMagic = proc getMagic*(op: PNode): TMagic =
case op.kind case op.kind
of nkCallKinds: of nkCallKinds:
case op.sons[0].Kind case op.sons[0].kind
of nkSym: result = op.sons[0].sym.magic of nkSym: result = op.sons[0].sym.magic
else: result = mNone else: result = mNone
else: result = mNone else: result = mNone

View file

@ -155,14 +155,14 @@ proc skipTypes(t: PType, kinds: TTypeKinds): PType =
proc isOrdinalType(t: PType): bool = proc isOrdinalType(t: PType): bool =
assert(t != nil) assert(t != nil)
# caution: uint, uint64 are no ordinal types! # caution: uint, uint64 are no ordinal types!
result = t.Kind in {tyChar,tyInt..tyInt64,tyUInt8..tyUInt32,tyBool,tyEnum} or result = t.kind in {tyChar,tyInt..tyInt64,tyUInt8..tyUInt32,tyBool,tyEnum} or
(t.Kind in {tyRange, tyOrdinal, tyConst, tyMutable, tyGenericInst}) and (t.kind in {tyRange, tyOrdinal, tyConst, tyMutable, tyGenericInst}) and
isOrdinalType(t.sons[0]) isOrdinalType(t.sons[0])
proc enumHasHoles(t: PType): bool = proc enumHasHoles(t: PType): bool =
var b = t var b = t
while b.kind in {tyConst, tyMutable, tyRange, tyGenericInst}: b = b.sons[0] while b.kind in {tyConst, tyMutable, tyRange, tyGenericInst}: b = b.sons[0]
result = b.Kind == tyEnum and tfEnumHasHoles in b.flags result = b.kind == tyEnum and tfEnumHasHoles in b.flags
proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter,
closure: PObject): bool closure: PObject): bool
@ -429,9 +429,9 @@ proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string =
if t == nil: return if t == nil: return
if prefer == preferName and t.sym != nil and sfAnon notin t.sym.flags: if prefer == preferName and t.sym != nil and sfAnon notin t.sym.flags:
if t.kind == tyInt and isIntLit(t): if t.kind == tyInt and isIntLit(t):
return t.sym.Name.s & " literal(" & $t.n.intVal & ")" return t.sym.name.s & " literal(" & $t.n.intVal & ")"
return t.sym.Name.s return t.sym.name.s
case t.Kind case t.kind
of tyInt: of tyInt:
if not isIntLit(t) or prefer == preferExported: if not isIntLit(t) or prefer == preferExported:
result = typeToStr[t.kind] result = typeToStr[t.kind]
@ -746,7 +746,7 @@ template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} =
# TA[T] = object # TA[T] = object
# TB[T] = object # TB[T] = object
# --> TA[int] != TB[int] # --> TA[int] != TB[int]
if tfFromGeneric in a.flags * b.flags and a.sym.Id == b.sym.Id: if tfFromGeneric in a.flags * b.flags and a.sym.id == b.sym.id:
# ok, we need the expensive structural check # ok, we need the expensive structural check
body body
@ -827,7 +827,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool =
of dcEqOrDistinctOf: of dcEqOrDistinctOf:
while a.kind == tyDistinct: a = a.sons[0] while a.kind == tyDistinct: a = a.sons[0]
if a.kind != b.kind: return false if a.kind != b.kind: return false
case a.Kind case a.kind
of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString, of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString,
tyInt..tyBigNum, tyStmt: tyInt..tyBigNum, tyStmt:
result = sameFlags(a, b) result = sameFlags(a, b)

View file

@ -144,7 +144,7 @@ proc copyValue(src: PNode): PNode =
when defined(useNodeIds): when defined(useNodeIds):
if result.id == nodeIdToDebug: if result.id == nodeIdToDebug:
echo "COMES FROM ", src.id echo "COMES FROM ", src.id
case src.Kind case src.kind
of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkCharLit..nkUInt64Lit: result.intVal = src.intVal
of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal
of nkSym: result.sym = src.sym of nkSym: result.sym = src.sym

View file

@ -32,16 +32,16 @@ proc `!$`*(h: THash): THash {.inline.} =
result = result xor (result shr 11) result = result xor (result shr 11)
result = result +% result shl 15 result = result +% result shl 15
proc hashData*(Data: pointer, Size: int): THash = proc hashData*(data: pointer, size: int): THash =
## hashes an array of bytes of size `size` ## hashes an array of bytes of size `size`
var h: THash = 0 var h: THash = 0
when defined(js): when defined(js):
var p: cstring var p: cstring
asm """`p` = `Data`;""" asm """`p` = `Data`;"""
else: else:
var p = cast[cstring](Data) var p = cast[cstring](data)
var i = 0 var i = 0
var s = Size var s = size
while s > 0: while s > 0:
h = h !& ord(p[i]) h = h !& ord(p[i])
inc(i) inc(i)

View file

@ -151,11 +151,11 @@ proc kind*(my: TJsonParser): TJsonEventKind {.inline.} =
proc getColumn*(my: TJsonParser): int {.inline.} = proc getColumn*(my: TJsonParser): int {.inline.} =
## get the current column the parser has arrived at. ## get the current column the parser has arrived at.
result = getColNumber(my, my.bufPos) result = getColNumber(my, my.bufpos)
proc getLine*(my: TJsonParser): int {.inline.} = proc getLine*(my: TJsonParser): int {.inline.} =
## get the current line the parser has arrived at. ## get the current line the parser has arrived at.
result = my.linenumber result = my.lineNumber
proc getFilename*(my: TJsonParser): string {.inline.} = proc getFilename*(my: TJsonParser): string {.inline.} =
## get the filename of the file that the parser processes. ## get the filename of the file that the parser processes.
@ -227,11 +227,11 @@ proc parseString(my: var TJsonParser): TTokKind =
add(my.a, buf[pos]) add(my.a, buf[pos])
inc(pos) inc(pos)
of '\c': of '\c':
pos = lexbase.HandleCR(my, pos) pos = lexbase.handleCR(my, pos)
buf = my.buf buf = my.buf
add(my.a, '\c') add(my.a, '\c')
of '\L': of '\L':
pos = lexbase.HandleLF(my, pos) pos = lexbase.handleLF(my, pos)
buf = my.buf buf = my.buf
add(my.a, '\L') add(my.a, '\L')
else: else:
@ -253,11 +253,11 @@ proc skip(my: var TJsonParser) =
of '\0': of '\0':
break break
of '\c': of '\c':
pos = lexbase.HandleCR(my, pos) pos = lexbase.handleCR(my, pos)
buf = my.buf buf = my.buf
break break
of '\L': of '\L':
pos = lexbase.HandleLF(my, pos) pos = lexbase.handleLF(my, pos)
buf = my.buf buf = my.buf
break break
else: else:
@ -271,10 +271,10 @@ proc skip(my: var TJsonParser) =
my.err = errEOC_Expected my.err = errEOC_Expected
break break
of '\c': of '\c':
pos = lexbase.HandleCR(my, pos) pos = lexbase.handleCR(my, pos)
buf = my.buf buf = my.buf
of '\L': of '\L':
pos = lexbase.HandleLF(my, pos) pos = lexbase.handleLF(my, pos)
buf = my.buf buf = my.buf
of '*': of '*':
inc(pos) inc(pos)
@ -288,10 +288,10 @@ proc skip(my: var TJsonParser) =
of ' ', '\t': of ' ', '\t':
inc(pos) inc(pos)
of '\c': of '\c':
pos = lexbase.HandleCR(my, pos) pos = lexbase.handleCR(my, pos)
buf = my.buf buf = my.buf
of '\L': of '\L':
pos = lexbase.HandleLF(my, pos) pos = lexbase.handleLF(my, pos)
buf = my.buf buf = my.buf
else: else:
break break

View file

@ -31,7 +31,7 @@ type
buf*: cstring ## the buffer itself buf*: cstring ## the buffer itself
bufLen*: int ## length of buffer in characters bufLen*: int ## length of buffer in characters
input: PStream ## the input stream input: PStream ## the input stream
LineNumber*: int ## the current line number lineNumber*: int ## the current line number
sentinel: int sentinel: int
lineStart: int # index of last line start in buffer lineStart: int # index of last line start in buffer
fileOpened: bool fileOpened: bool
@ -75,7 +75,7 @@ proc fillBuffer(L: var TBaseLexer) =
# we know here that pos == L.sentinel, but not if this proc # we know here that pos == L.sentinel, but not if this proc
# is called the first time by initBaseLexer() # is called the first time by initBaseLexer()
assert(L.sentinel < L.bufLen) assert(L.sentinel < L.bufLen)
toCopy = L.BufLen - L.sentinel - 1 toCopy = L.bufLen - L.sentinel - 1
assert(toCopy >= 0) assert(toCopy >= 0)
if toCopy > 0: if toCopy > 0:
moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize)
@ -99,8 +99,8 @@ proc fillBuffer(L: var TBaseLexer) =
else: else:
# rather than to give up here because the line is too long, # rather than to give up here because the line is too long,
# double the buffer's size and try again: # double the buffer's size and try again:
oldBufLen = L.BufLen oldBufLen = L.bufLen
L.bufLen = L.BufLen * 2 L.bufLen = L.bufLen * 2
L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize))
assert(L.bufLen - oldBufLen == oldBufLen) assert(L.bufLen - oldBufLen == oldBufLen)
charsRead = readData(L.input, addr(L.buf[oldBufLen]), charsRead = readData(L.input, addr(L.buf[oldBufLen]),
@ -123,14 +123,14 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int =
proc handleCR(L: var TBaseLexer, pos: int): int = proc handleCR(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == '\c') assert(L.buf[pos] == '\c')
inc(L.linenumber) inc(L.lineNumber)
result = fillBaseLexer(L, pos) result = fillBaseLexer(L, pos)
if L.buf[result] == '\L': if L.buf[result] == '\L':
result = fillBaseLexer(L, result) result = fillBaseLexer(L, result)
proc handleLF(L: var TBaseLexer, pos: int): int = proc handleLF(L: var TBaseLexer, pos: int): int =
assert(L.buf[pos] == '\L') assert(L.buf[pos] == '\L')
inc(L.linenumber) inc(L.lineNumber)
result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result;
proc skipUtf8Bom(L: var TBaseLexer) = proc skipUtf8Bom(L: var TBaseLexer) =
@ -147,7 +147,7 @@ proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) =
L.buf = cast[cstring](alloc(bufLen * chrSize)) L.buf = cast[cstring](alloc(bufLen * chrSize))
L.sentinel = bufLen - 1 L.sentinel = bufLen - 1
L.lineStart = 0 L.lineStart = 0
L.linenumber = 1 # lines start at 1 L.lineNumber = 1 # lines start at 1
fillBuffer(L) fillBuffer(L)
skipUtf8Bom(L) skipUtf8Bom(L)

View file

@ -356,8 +356,8 @@ when defined(windows):
proc skipFindData(f: TWIN32_FIND_DATA): bool {.inline.} = proc skipFindData(f: TWIN32_FIND_DATA): bool {.inline.} =
const dot = ord('.') const dot = ord('.')
result = f.cFilename[0].int == dot and(f.cFilename[1].int == 0 or result = f.cFileName[0].int == dot and(f.cFileName[1].int == 0 or
f.cFilename[1].int == dot and f.cFilename[2].int == 0) f.cFileName[1].int == dot and f.cFileName[2].int == 0)
proc existsFile*(filename: string): bool {.rtl, extern: "nos$1", proc existsFile*(filename: string): bool {.rtl, extern: "nos$1",
tags: [FReadDir].} = tags: [FReadDir].} =

View file

@ -23,7 +23,7 @@ else:
type type
TProcess = object of TObject TProcess = object of TObject
when defined(windows): when defined(windows):
FProcessHandle: THandle fProcessHandle: THandle
inHandle, outHandle, errHandle: TFileHandle inHandle, outHandle, errHandle: TFileHandle
id: THandle id: THandle
else: else:
@ -336,7 +336,7 @@ when defined(Windows) and not defined(useNimRtl):
var s = PFileHandleStream(s) var s = PFileHandleStream(s)
if s.atTheEnd: return 0 if s.atTheEnd: return 0
var br: int32 var br: int32
var a = winlean.ReadFile(s.handle, buffer, bufLen.cint, br, nil) var a = winlean.readFile(s.handle, buffer, bufLen.cint, br, nil)
# TRUE and zero bytes returned (EOF). # TRUE and zero bytes returned (EOF).
# TRUE and n (>0) bytes returned (good data). # TRUE and n (>0) bytes returned (good data).
# FALSE and bytes returned undefined (system error). # FALSE and bytes returned undefined (system error).
@ -383,12 +383,12 @@ when defined(Windows) and not defined(useNimRtl):
# O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int # O_WRONLY {.importc: "_O_WRONLY", header: "<fcntl.h>".}: int
# O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int # O_RDONLY {.importc: "_O_RDONLY", header: "<fcntl.h>".}: int
proc createPipeHandles(Rdhandle, WrHandle: var THandle) = proc createPipeHandles(rdHandle, wrHandle: var THandle) =
var piInheritablePipe: TSECURITY_ATTRIBUTES var piInheritablePipe: TSECURITY_ATTRIBUTES
piInheritablePipe.nlength = sizeof(TSECURITY_ATTRIBUTES).cint piInheritablePipe.nLength = sizeof(TSECURITY_ATTRIBUTES).cint
piInheritablePipe.lpSecurityDescriptor = nil piInheritablePipe.lpSecurityDescriptor = nil
piInheritablePipe.Binherithandle = 1 piInheritablePipe.bInheritHandle = 1
if createPipe(Rdhandle, WrHandle, piInheritablePipe, 1024) == 0'i32: if createPipe(rdHandle, wrHandle, piInheritablePipe, 1024) == 0'i32:
osError(osLastError()) osError(osLastError())
proc fileClose(h: THandle) {.inline.} = proc fileClose(h: THandle) {.inline.} =
@ -440,11 +440,11 @@ when defined(Windows) and not defined(useNimRtl):
var tmp = newWideCString(cmdl) var tmp = newWideCString(cmdl)
var ee = newWideCString(e) var ee = newWideCString(e)
var wwd = newWideCString(wd) var wwd = newWideCString(wd)
success = winlean.CreateProcessW(nil, success = winlean.createProcessW(nil,
tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT, tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT,
ee, wwd, si, procInfo) ee, wwd, si, procInfo)
else: else:
success = winlean.CreateProcessA(nil, success = winlean.createProcessA(nil,
cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo) cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo)
let lastError = osLastError() let lastError = osLastError()
@ -459,45 +459,45 @@ when defined(Windows) and not defined(useNimRtl):
if success == 0: osError(lastError) if success == 0: osError(lastError)
# Close the handle now so anyone waiting is woken: # Close the handle now so anyone waiting is woken:
discard closeHandle(procInfo.hThread) discard closeHandle(procInfo.hThread)
result.FProcessHandle = procInfo.hProcess result.fProcessHandle = procInfo.hProcess
result.id = procInfo.dwProcessID result.id = procInfo.dwProcessId
proc close(p: PProcess) = proc close(p: PProcess) =
when false: when false:
# somehow this does not work on Windows: # somehow this does not work on Windows:
discard CloseHandle(p.inHandle) discard closeHandle(p.inHandle)
discard CloseHandle(p.outHandle) discard closeHandle(p.outHandle)
discard CloseHandle(p.errHandle) discard closeHandle(p.errHandle)
discard CloseHandle(p.FProcessHandle) discard closeHandle(p.FProcessHandle)
proc suspend(p: PProcess) = proc suspend(p: PProcess) =
discard suspendThread(p.FProcessHandle) discard suspendThread(p.fProcessHandle)
proc resume(p: PProcess) = proc resume(p: PProcess) =
discard resumeThread(p.FProcessHandle) discard resumeThread(p.fProcessHandle)
proc running(p: PProcess): bool = proc running(p: PProcess): bool =
var x = waitForSingleObject(p.FProcessHandle, 50) var x = waitForSingleObject(p.fProcessHandle, 50)
return x == WAIT_TIMEOUT return x == WAIT_TIMEOUT
proc terminate(p: PProcess) = proc terminate(p: PProcess) =
if running(p): if running(p):
discard terminateProcess(p.FProcessHandle, 0) discard terminateProcess(p.fProcessHandle, 0)
proc waitForExit(p: PProcess, timeout: int = -1): int = proc waitForExit(p: PProcess, timeout: int = -1): int =
discard waitForSingleObject(p.FProcessHandle, timeout.int32) discard waitForSingleObject(p.fProcessHandle, timeout.int32)
var res: int32 var res: int32
discard getExitCodeProcess(p.FProcessHandle, res) discard getExitCodeProcess(p.fProcessHandle, res)
result = res result = res
discard closeHandle(p.FProcessHandle) discard closeHandle(p.fProcessHandle)
proc peekExitCode(p: PProcess): int = proc peekExitCode(p: PProcess): int =
var b = waitForSingleObject(p.FProcessHandle, 50) == WAIT_TIMEOUT var b = waitForSingleObject(p.fProcessHandle, 50) == WAIT_TIMEOUT
if b: result = -1 if b: result = -1
else: else:
var res: int32 var res: int32
discard getExitCodeProcess(p.FProcessHandle, res) discard getExitCodeProcess(p.fProcessHandle, res)
return res return res
proc inputStream(p: PProcess): PStream = proc inputStream(p: PProcess): PStream =
@ -521,10 +521,10 @@ when defined(Windows) and not defined(useNimRtl):
si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE) si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE)
when useWinUnicode: when useWinUnicode:
var c = newWideCString(command) var c = newWideCString(command)
var res = winlean.CreateProcessW(nil, c, nil, nil, 0, var res = winlean.createProcessW(nil, c, nil, nil, 0,
NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo) NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
else: else:
var res = winlean.CreateProcessA(nil, command, nil, nil, 0, var res = winlean.createProcessA(nil, command, nil, nil, 0,
NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo)
if res == 0: if res == 0:
osError(osLastError()) osError(osLastError())
@ -542,7 +542,7 @@ when defined(Windows) and not defined(useNimRtl):
assert readfds.len <= MAXIMUM_WAIT_OBJECTS assert readfds.len <= MAXIMUM_WAIT_OBJECTS
var rfds: TWOHandleArray var rfds: TWOHandleArray
for i in 0..readfds.len()-1: for i in 0..readfds.len()-1:
rfds[i] = readfds[i].FProcessHandle rfds[i] = readfds[i].fProcessHandle
var ret = waitForMultipleObjects(readfds.len.int32, var ret = waitForMultipleObjects(readfds.len.int32,
addr(rfds), 0'i32, timeout.int32) addr(rfds), 0'i32, timeout.int32)

View file

@ -37,7 +37,7 @@ type
## or the argument, ``value`` is not "" if ## or the argument, ``value`` is not "" if
## the option was given a value ## the option was given a value
when defined(os.ParamCount): when defined(os.paramCount):
# we cannot provide this for NimRtl creation on Posix, because we can't # we cannot provide this for NimRtl creation on Posix, because we can't
# access the command line arguments then! # access the command line arguments then!

View file

@ -445,7 +445,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {.
hints.ai_socktype = toInt(SOCK_STREAM) hints.ai_socktype = toInt(SOCK_STREAM)
hints.ai_protocol = toInt(IPPROTO_TCP) hints.ai_protocol = toInt(IPPROTO_TCP)
gaiNim(address, port, hints, aiList) gaiNim(address, port, hints, aiList)
if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32: if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrlen.TSockLen) < 0'i32:
osError(osLastError()) osError(osLastError())
proc getSockName*(socket: TSocket): TPort = proc getSockName*(socket: TSocket): TPort =
@ -628,7 +628,7 @@ proc accept*(server: TSocket): TSocket {.deprecated, tags: [FReadIO].} =
proc close*(socket: TSocket) = proc close*(socket: TSocket) =
## closes a socket. ## closes a socket.
when defined(windows): when defined(windows):
discard winlean.closeSocket(socket.fd) discard winlean.closesocket(socket.fd)
else: else:
discard posix.close(socket.fd) discard posix.close(socket.fd)
# TODO: These values should not be discarded. An EOS should be raised. # TODO: These values should not be discarded. An EOS should be raised.
@ -687,7 +687,7 @@ proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
result.name = $s.h_name result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases) result.aliases = cstringArrayToSeq(s.h_aliases)
when defined(windows): when defined(windows):
result.addrType = TDomain(s.h_addrtype) result.addrtype = TDomain(s.h_addrtype)
else: else:
if s.h_addrtype == posix.AF_INET: if s.h_addrtype == posix.AF_INET:
result.addrType = AF_INET result.addrType = AF_INET
@ -708,7 +708,7 @@ proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
result.name = $s.h_name result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases) result.aliases = cstringArrayToSeq(s.h_aliases)
when defined(windows): when defined(windows):
result.addrType = TDomain(s.h_addrtype) result.addrtype = TDomain(s.h_addrtype)
else: else:
if s.h_addrtype == posix.AF_INET: if s.h_addrtype == posix.AF_INET:
result.addrType = AF_INET result.addrType = AF_INET
@ -1058,7 +1058,7 @@ proc readIntoBuf(socket: TSocket, flags: int32): int =
else: else:
result = recv(socket.fd, addr(socket.buffer), cint(socket.buffer.high), flags) result = recv(socket.fd, addr(socket.buffer), cint(socket.buffer.high), flags)
if result <= 0: if result <= 0:
socket.buflen = 0 socket.bufLen = 0
socket.currPos = 0 socket.currPos = 0
return result return result
socket.bufLen = result socket.bufLen = result

View file

@ -345,11 +345,11 @@ when not defined(JS):
monthday: int(tm.monthday), monthday: int(tm.monthday),
month: TMonth(tm.month), month: TMonth(tm.month),
year: tm.year + 1900'i32, year: tm.year + 1900'i32,
weekday: weekDays[int(tm.weekDay)], weekday: weekDays[int(tm.weekday)],
yearday: int(tm.yearday), yearday: int(tm.yearday),
isDST: tm.isDST > 0, isDST: tm.isdst > 0,
tzname: if local: tzname: if local:
if tm.isDST > 0: if tm.isdst > 0:
getTzname().DST getTzname().DST
else: else:
getTzname().nonDST getTzname().nonDST
@ -367,7 +367,7 @@ when not defined(JS):
result.monthday = t.monthday result.monthday = t.monthday
result.month = ord(t.month) result.month = ord(t.month)
result.year = t.year - 1900 result.year = t.year - 1900
result.weekday = weekDays[t.weekDay] result.weekday = weekDays[t.weekday]
result.yearday = t.yearday result.yearday = t.yearday
result.isdst = if t.isDST: 1 else: 0 result.isdst = if t.isDST: 1 else: 0
@ -532,7 +532,7 @@ proc getDateStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} =
## gets the current date as a string of the format ``YYYY-MM-DD``. ## gets the current date as a string of the format ``YYYY-MM-DD``.
var ti = getLocalTime(getTime()) var ti = getLocalTime(getTime())
result = $ti.year & '-' & intToStr(ord(ti.month)+1, 2) & result = $ti.year & '-' & intToStr(ord(ti.month)+1, 2) &
'-' & intToStr(ti.monthDay, 2) '-' & intToStr(ti.monthday, 2)
proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} = proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} =
## gets the current clock time as a string of the format ``HH:MM:SS``. ## gets the current clock time as a string of the format ``HH:MM:SS``.

View file

@ -132,9 +132,9 @@ when BitsPerPage mod (sizeof(int)*8) != 0:
template color(c): expr = c.refCount and colorMask template color(c): expr = c.refCount and colorMask
template setColor(c, col) = template setColor(c, col) =
when col == rcBlack: when col == rcBlack:
c.refcount = c.refCount and not colorMask c.refcount = c.refcount and not colorMask
else: else:
c.refcount = c.refCount and not colorMask or col c.refcount = c.refcount and not colorMask or col
proc writeCell(msg: cstring, c: PCell) = proc writeCell(msg: cstring, c: PCell) =
var kind = -1 var kind = -1
@ -211,7 +211,7 @@ proc decRef(c: PCell) {.inline.} =
proc incRef(c: PCell) {.inline.} = proc incRef(c: PCell) {.inline.} =
gcAssert(isAllocatedPtr(gch.region, c), "incRef: interiorPtr") gcAssert(isAllocatedPtr(gch.region, c), "incRef: interiorPtr")
c.refcount = c.refCount +% rcIncrement c.refcount = c.refcount +% rcIncrement
# and not colorMask # and not colorMask
#writeCell("incRef", c) #writeCell("incRef", c)
if canbeCycleRoot(c): if canbeCycleRoot(c):
@ -582,7 +582,7 @@ proc markRoots(gch: var TGcHeap) =
for s in elements(gch.cycleRoots): for s in elements(gch.cycleRoots):
#writeCell("markRoot", s) #writeCell("markRoot", s)
inc tabSize inc tabSize
if s.color == rcPurple and s.refCount >=% rcIncrement: if s.color == rcPurple and s.refcount >=% rcIncrement:
markGray(s) markGray(s)
else: else:
excl(gch.cycleRoots, s) excl(gch.cycleRoots, s)