case consistency: next steps

This commit is contained in:
Araq 2013-12-29 01:13:51 +01:00
commit 438703f59e
77 changed files with 513 additions and 514 deletions

View file

@ -1167,30 +1167,30 @@ proc newSym(symKind: TSymKind, Name: PIdent, owner: PSym,
proc initStrTable(x: var TStrTable) = proc initStrTable(x: var TStrTable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc newStrTable*: TStrTable = proc newStrTable*: TStrTable =
initStrTable(result) initStrTable(result)
proc initTable(x: var TTable) = proc initTable(x: var TTable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc initIdTable(x: var TIdTable) = proc initIdTable(x: var TIdTable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc initObjectSet(x: var TObjectSet) = proc initObjectSet(x: var TObjectSet) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc initIdNodeTable(x: var TIdNodeTable) = proc initIdNodeTable(x: var TIdNodeTable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc initNodeTable(x: var TNodeTable) = proc initNodeTable(x: var TNodeTable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
proc sonsLen(n: PType): int = proc sonsLen(n: PType): int =
if isNil(n.sons): result = 0 if isNil(n.sons): result = 0
@ -1402,7 +1402,7 @@ proc isGenericRoutine*(s: PSym): bool =
else: discard else: discard
proc skipGenericOwner*(s: PSym): PSym = proc skipGenericOwner*(s: PSym): PSym =
InternalAssert s.kind in skProcKinds internalAssert s.kind in skProcKinds
## Generic instantiations are owned by their originating generic ## Generic instantiations are owned by their originating generic
## symbol. This proc skips such owners and goes straigh to the owner ## symbol. This proc skips such owners and goes straigh to the owner
## of the generic itself (the module or the enclosing proc). ## of the generic itself (the module or the enclosing proc).

View file

@ -472,7 +472,7 @@ proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) =
proc objectSetEnlarge(t: var TObjectSet) = proc objectSetEnlarge(t: var TObjectSet) =
var n: TObjectSeq var n: TObjectSeq
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i] != nil: objectSetRawInsert(n, t.data[i]) if t.data[i] != nil: objectSetRawInsert(n, t.data[i])
swap(t.data, n) swap(t.data, n)
@ -535,7 +535,7 @@ proc tableRawInsert(data: var TPairSeq, key, val: PObject) =
proc tableEnlarge(t: var TTable) = proc tableEnlarge(t: var TTable) =
var n: TPairSeq var n: TPairSeq
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != nil: tableRawInsert(n, t.data[i].key, t.data[i].val) if t.data[i].key != nil: tableRawInsert(n, t.data[i].key, t.data[i].val)
swap(t.data, n) swap(t.data, n)
@ -583,7 +583,7 @@ proc symTabReplace*(t: var TStrTable, prevSym: PSym, newSym: PSym) =
proc strTableEnlarge(t: var TStrTable) = proc strTableEnlarge(t: var TStrTable) =
var n: TSymSeq var n: TSymSeq
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i] != nil: strTableRawInsert(n, t.data[i]) if t.data[i] != nil: strTableRawInsert(n, t.data[i])
swap(t.data, n) swap(t.data, n)
@ -742,7 +742,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) =
t.data[index].val = val t.data[index].val = val
else: else:
if mustRehash(len(t.data), t.counter): if mustRehash(len(t.data), t.counter):
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != nil: if t.data[i].key != nil:
idTableRawInsert(n, t.data[i].key, t.data[i].val) idTableRawInsert(n, t.data[i].key, t.data[i].val)
@ -792,7 +792,7 @@ proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) =
else: else:
if mustRehash(len(t.data), t.counter): if mustRehash(len(t.data), t.counter):
var n: TIdNodePairSeq var n: TIdNodePairSeq
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != nil: if t.data[i].key != nil:
idNodeTableRawInsert(n, t.data[i].key, t.data[i].val) idNodeTableRawInsert(n, t.data[i].key, t.data[i].val)
@ -810,8 +810,8 @@ iterator pairs*(t: TIdNodeTable): tuple[key: PIdObj, val: PNode] =
proc initIITable(x: var TIITable) = proc initIITable(x: var TIITable) =
x.counter = 0 x.counter = 0
newSeq(x.data, startSize) newSeq(x.data, StartSize)
for i in countup(0, startSize - 1): x.data[i].key = InvalidKey for i in countup(0, StartSize - 1): x.data[i].key = InvalidKey
proc iiTableRawGet(t: TIITable, key: int): int = proc iiTableRawGet(t: TIITable, key: int): int =
var h: THash var h: THash
@ -844,7 +844,7 @@ proc iiTablePut(t: var TIITable, key, val: int) =
else: else:
if mustRehash(len(t.data), t.counter): if mustRehash(len(t.data), t.counter):
var n: TIIPairSeq var n: TIIPairSeq
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(n)): n[i].key = InvalidKey for i in countup(0, high(n)): n[i].key = InvalidKey
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != InvalidKey: if t.data[i].key != InvalidKey:

View file

@ -11,7 +11,7 @@
# -------------------------- constant expressions ------------------------ # -------------------------- constant expressions ------------------------
proc intLiteral(i: biggestInt): PRope = proc intLiteral(i: BiggestInt): PRope =
if (i > low(int32)) and (i <= high(int32)): if (i > low(int32)) and (i <= high(int32)):
result = toRope(i) result = toRope(i)
elif i == low(int32): elif i == low(int32):
@ -419,10 +419,10 @@ proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) =
proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
const const
prc: array[mAddi..mModi64, string] = ["addInt", "subInt", "mulInt", prc: array[mAddI..mModI64, string] = ["addInt", "subInt", "mulInt",
"divInt", "modInt", "addInt64", "subInt64", "mulInt64", "divInt64", "divInt", "modInt", "addInt64", "subInt64", "mulInt64", "divInt64",
"modInt64"] "modInt64"]
opr: array[mAddi..mModi64, string] = ["+", "-", "*", "/", "%", "+", "-", opr: array[mAddI..mModI64, string] = ["+", "-", "*", "/", "%", "+", "-",
"*", "/", "%"] "*", "/", "%"]
var a, b: TLoc var a, b: TLoc
assert(e.sons[1].typ != nil) assert(e.sons[1].typ != nil)
@ -1040,7 +1040,7 @@ proc genObjConstr(p: BProc, e: PNode, d: var TLoc) =
app(tmp2.r, field.loc.r) app(tmp2.r, field.loc.r)
tmp2.k = locTemp tmp2.k = locTemp
tmp2.t = field.loc.t tmp2.t = field.loc.t
tmp2.s = onHeap tmp2.s = OnHeap
tmp2.heapRoot = tmp.r tmp2.heapRoot = tmp.r
expr(p, it.sons[1], tmp2) expr(p, it.sons[1], tmp2)
if d.k == locNone: if d.k == locNone:
@ -1196,7 +1196,7 @@ proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
of tyOpenArray, tyVarargs: of tyOpenArray, tyVarargs:
if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)") if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)")
else: unaryExpr(p, e, d, "$1Len0") else: unaryExpr(p, e, d, "$1Len0")
of tyCstring: of tyCString:
if op == mHigh: unaryExpr(p, e, d, "(strlen($1)-1)") if op == mHigh: unaryExpr(p, e, d, "(strlen($1)-1)")
else: unaryExpr(p, e, d, "strlen($1)") else: unaryExpr(p, e, d, "strlen($1)")
of tyString, tySequence: of tyString, tySequence:
@ -1481,7 +1481,7 @@ proc genStrEquals(p: BProc, e: PNode, d: var TLoc) =
binaryExpr(p, e, d, "#eqStrings($1, $2)") binaryExpr(p, e, d, "#eqStrings($1, $2)")
proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) = proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
if {optNanCheck, optInfCheck} * p.options != {}: if {optNaNCheck, optInfCheck} * p.options != {}:
const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"] const opr: array[mAddF64..mDivF64, string] = ["+", "-", "*", "/"]
var a, b: TLoc var a, b: TLoc
assert(e.sons[1].typ != nil) assert(e.sons[1].typ != nil)
@ -1491,7 +1491,7 @@ proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) =
putIntoDest(p, d, e.typ, rfmt(nil, "(($4)($2) $1 ($4)($3))", putIntoDest(p, d, e.typ, rfmt(nil, "(($4)($2) $1 ($4)($3))",
toRope(opr[m]), rdLoc(a), rdLoc(b), toRope(opr[m]), rdLoc(a), rdLoc(b),
getSimpleTypeDesc(p.module, e[1].typ))) getSimpleTypeDesc(p.module, e[1].typ)))
if optNanCheck in p.options: if optNaNCheck in p.options:
linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d)) linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d))
if optInfCheck in p.options: if optInfCheck in p.options:
linefmt(p, cpsStmts, "#infCheck($1);$n", rdLoc(d)) linefmt(p, cpsStmts, "#infCheck($1);$n", rdLoc(d))
@ -1507,7 +1507,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) =
of mAddF64..mDivF64: binaryFloatArith(p, e, d, op) of mAddF64..mDivF64: binaryFloatArith(p, e, d, op)
of mShrI..mXor: binaryArith(p, e, d, op) of mShrI..mXor: binaryArith(p, e, d, op)
of mEqProc: genEqProc(p, e, d) of mEqProc: genEqProc(p, e, d)
of mAddi..mModi64: binaryArithOverflow(p, e, d, op) of mAddI..mModI64: binaryArithOverflow(p, e, d, op)
of mRepr: genRepr(p, e, d) of mRepr: genRepr(p, e, d)
of mGetTypeInfo: genGetTypeInfo(p, e, d) of mGetTypeInfo: genGetTypeInfo(p, e, d)
of mSwap: genSwap(p, e, d) of mSwap: genSwap(p, e, d)

View file

@ -920,7 +920,7 @@ proc genPragma(p: BProc, n: PNode) =
case whichPragma(it) case whichPragma(it)
of wEmit: genEmit(p, it) of wEmit: genEmit(p, it)
of wBreakpoint: genBreakPoint(p, it) of wBreakpoint: genBreakPoint(p, it)
of wWatchpoint: genWatchpoint(p, it) of wWatchPoint: genWatchpoint(p, it)
of wInjectStmt: of wInjectStmt:
var p = newProc(nil, p.module) var p = newProc(nil, p.module)
p.options = p.options - {optLineTrace, optStackTrace} p.options = p.options - {optLineTrace, optStackTrace}
@ -977,4 +977,4 @@ proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) =
proc genStmts(p: BProc, t: PNode) = proc genStmts(p: BProc, t: PNode) =
var a: TLoc var a: TLoc
expr(p, t, a) expr(p, t, a)
InternalAssert a.k in {locNone, locTemp, locLocalVar} internalAssert a.k in {locNone, locTemp, locLocalVar}

View file

@ -111,7 +111,7 @@ proc genTraverseProc(m: BModule, typ: PType, reason: TTypeInfoReason): PRope =
lineF(p, cpsInit, "a = ($1)p;$n", t) lineF(p, cpsInit, "a = ($1)p;$n", t)
c.p = p c.p = p
assert typ.kind != tyTypedesc assert typ.kind != tyTypeDesc
if typ.kind == tySequence: if typ.kind == tySequence:
genTraverseProcSeq(c, "a".toRope, typ) genTraverseProcSeq(c, "a".toRope, typ)
else: else:

View file

@ -362,7 +362,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope =
of tyString: of tyString:
discard cgsym(m, "NimStringDesc") discard cgsym(m, "NimStringDesc")
result = typeNameOrLiteral(typ, "NimStringDesc*") result = typeNameOrLiteral(typ, "NimStringDesc*")
of tyCstring: result = typeNameOrLiteral(typ, "NCSTRING") of tyCString: result = typeNameOrLiteral(typ, "NCSTRING")
of tyBool: result = typeNameOrLiteral(typ, "NIM_BOOL") of tyBool: result = typeNameOrLiteral(typ, "NIM_BOOL")
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")
@ -559,7 +559,7 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope =
if not isImportedType(t): if not isImportedType(t):
appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result]) appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result])
idTablePut(m.forwTypeCache, t, result) idTablePut(m.forwTypeCache, t, result)
assert(CacheGetType(m.typeCache, t) == nil) assert(cacheGetType(m.typeCache, t) == nil)
idTablePut(m.typeCache, t, con(result, "*")) idTablePut(m.typeCache, t, con(result, "*"))
if not isImportedType(t): if not isImportedType(t):
if skipTypes(t.sons[0], typedescInst).kind != tyEmpty: if skipTypes(t.sons[0], typedescInst).kind != tyEmpty:

View file

@ -351,7 +351,7 @@ proc resetLoc(p: BProc, loc: var TLoc) =
if not isComplexValueType(skipTypes(loc.t, abstractVarRange)): if not isComplexValueType(skipTypes(loc.t, abstractVarRange)):
if containsGcRef: if containsGcRef:
var nilLoc: TLoc var nilLoc: TLoc
initLoc(nilLoc, locTemp, loc.t, onStack) initLoc(nilLoc, locTemp, loc.t, OnStack)
nilLoc.r = toRope("NIM_NIL") nilLoc.r = toRope("NIM_NIL")
genRefAssign(p, loc, nilLoc, {afSrcIsNil}) genRefAssign(p, loc, nilLoc, {afSrcIsNil})
else: else:
@ -665,7 +665,7 @@ proc symInDynamicLib(m: BModule, sym: PSym) =
params, cstringLit(m, m.s[cfsDynLibInit], ropeToStr(extname))]) params, cstringLit(m, m.s[cfsDynLibInit], ropeToStr(extname))])
var last = lastSon(n) var last = lastSon(n)
if last.kind == nkHiddenStdConv: last = last.sons[1] if last.kind == nkHiddenStdConv: last = last.sons[1]
InternalAssert(last.kind == nkStrLit) internalAssert(last.kind == nkStrLit)
let idx = last.strVal let idx = last.strVal
if idx.len == 0: if idx.len == 0:
app(m.initProc.s(cpsStmts), load) app(m.initProc.s(cpsStmts), load)
@ -917,7 +917,7 @@ proc getCopyright(cfilenoext: string): PRope =
"/* (c) 2012 Andreas Rumpf */$n" & "/* (c) 2012 Andreas Rumpf */$n" &
"/* The generated code is subject to the original license. */$n", "/* The generated code is subject to the original license. */$n",
"; Generated by Nimrod Compiler v$1$n" & "; Generated by Nimrod Compiler v$1$n" &
"; (c) 2012 Andreas Rumpf$n", [toRope(versionAsString)]) "; (c) 2012 Andreas Rumpf$n", [toRope(VersionAsString)])
else: else:
result = ropeff("/* Generated by Nimrod Compiler v$1 */$n" & result = ropeff("/* Generated by Nimrod Compiler v$1 */$n" &
"/* (c) 2012 Andreas Rumpf */$n" & "/* (c) 2012 Andreas Rumpf */$n" &
@ -927,7 +927,7 @@ proc getCopyright(cfilenoext: string): PRope =
"; Generated by Nimrod Compiler v$1$n" & "; Generated by Nimrod Compiler v$1$n" &
"; (c) 2012 Andreas Rumpf$n" & "; (c) 2012 Andreas Rumpf$n" &
"; Compiled for: $2, $3, $4$n" & "; Compiled for: $2, $3, $4$n" &
"; 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),
@ -992,8 +992,8 @@ proc genMainProc(m: BModule) =
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
elif platform.targetOS == osStandalone: elif platform.targetOS == osStandalone:
nimMain = PosixNimMain nimMain = PosixNimMain
otherMain = StandaloneCMain otherMain = StandaloneCMain
@ -1202,7 +1202,7 @@ proc rawNewModule(module: PSym): BModule =
proc newModule(module: PSym): BModule = proc newModule(module: PSym): BModule =
# we should create only one cgen module for each module sym # we should create only one cgen module for each module sym
InternalAssert getCgenModule(module) == nil internalAssert getCgenModule(module) == nil
result = rawNewModule(module) result = rawNewModule(module)
growCache gModules, module.position growCache gModules, module.position

View file

@ -27,7 +27,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo)
# implementation # implementation
const const
HelpMessage = "Nimrod Compiler Version $1 (" & compileDate & ") [$2: $3]\n" & HelpMessage = "Nimrod Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" &
"Copyright (c) 2004-2013 by Andreas Rumpf\n" "Copyright (c) 2004-2013 by Andreas Rumpf\n"
const const
@ -173,11 +173,11 @@ proc testCompileOption*(switch: string, info: TLineInfo): bool =
of "linetrace": result = contains(gOptions, optLineTrace) of "linetrace": result = contains(gOptions, optLineTrace)
of "debugger": result = contains(gOptions, optEndb) of "debugger": result = contains(gOptions, optEndb)
of "profiler": result = contains(gOptions, optProfiler) of "profiler": result = contains(gOptions, optProfiler)
of "checks", "x": result = gOptions * checksOptions == checksOptions of "checks", "x": result = gOptions * ChecksOptions == ChecksOptions
of "floatchecks": of "floatchecks":
result = gOptions * {optNanCheck, optInfCheck} == {optNanCheck, optInfCheck} result = gOptions * {optNaNCheck, optInfCheck} == {optNaNCheck, optInfCheck}
of "infchecks": result = contains(gOptions, optInfCheck) of "infchecks": result = contains(gOptions, optInfCheck)
of "nanchecks": result = contains(gOptions, optNanCheck) of "nanchecks": result = contains(gOptions, optNaNCheck)
of "objchecks": result = contains(gOptions, optObjCheck) of "objchecks": result = contains(gOptions, optObjCheck)
of "fieldchecks": result = contains(gOptions, optFieldCheck) of "fieldchecks": result = contains(gOptions, optFieldCheck)
of "rangechecks": result = contains(gOptions, optRangeCheck) of "rangechecks": result = contains(gOptions, optRangeCheck)
@ -239,7 +239,7 @@ proc dynlibOverride(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
expectArg(switch, arg, pass, info) expectArg(switch, arg, pass, info)
options.inclDynlibOverride(arg) options.inclDynlibOverride(arg)
proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) =
var var
theOS: TSystemOS theOS: TSystemOS
cpu: TSystemCPU cpu: TSystemCPU
@ -335,11 +335,11 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) =
processOnOffSwitch({optProfiler}, arg, pass, info) processOnOffSwitch({optProfiler}, arg, pass, info)
if optProfiler in gOptions: defineSymbol("profiler") if optProfiler in gOptions: defineSymbol("profiler")
else: undefSymbol("profiler") else: undefSymbol("profiler")
of "checks", "x": processOnOffSwitch(checksOptions, arg, pass, info) of "checks", "x": processOnOffSwitch(ChecksOptions, arg, pass, info)
of "floatchecks": of "floatchecks":
processOnOffSwitch({optNanCheck, optInfCheck}, arg, pass, info) processOnOffSwitch({optNaNCheck, optInfCheck}, arg, pass, info)
of "infchecks": processOnOffSwitch({optInfCheck}, arg, pass, info) of "infchecks": processOnOffSwitch({optInfCheck}, arg, pass, info)
of "nanchecks": processOnOffSwitch({optNanCheck}, arg, pass, info) of "nanchecks": processOnOffSwitch({optNaNCheck}, arg, pass, info)
of "objchecks": processOnOffSwitch({optObjCheck}, arg, pass, info) of "objchecks": processOnOffSwitch({optObjCheck}, arg, pass, info)
of "fieldchecks": processOnOffSwitch({optFieldCheck}, arg, pass, info) of "fieldchecks": processOnOffSwitch({optFieldCheck}, arg, pass, info)
of "rangechecks": processOnOffSwitch({optRangeCheck}, arg, pass, info) of "rangechecks": processOnOffSwitch({optRangeCheck}, arg, pass, info)

View file

@ -55,12 +55,12 @@ proc initDefines*() =
of cpuAmd64: defineSymbol("x8664") of cpuAmd64: defineSymbol("x8664")
else: discard else: discard
case targetOS case targetOS
of osDOS: of osDos:
defineSymbol("msdos") defineSymbol("msdos")
of osWindows: of osWindows:
defineSymbol("mswindows") defineSymbol("mswindows")
defineSymbol("win32") defineSymbol("win32")
of osLinux, osMorphOS, osSkyOS, osIrix, osPalmOS, osQNX, osAtari, osAix, of osLinux, osMorphos, osSkyos, osIrix, osPalmos, osQnx, osAtari, osAix,
osHaiku: osHaiku:
# these are all 'unix-like' # these are all 'unix-like'
defineSymbol("unix") defineSymbol("unix")
@ -69,13 +69,13 @@ proc initDefines*() =
defineSymbol("sunos") defineSymbol("sunos")
defineSymbol("unix") defineSymbol("unix")
defineSymbol("posix") defineSymbol("posix")
of osNetBSD, osFreeBSD, osOpenBSD: of osNetbsd, osFreebsd, osOpenbsd:
defineSymbol("unix") defineSymbol("unix")
defineSymbol("bsd") defineSymbol("bsd")
defineSymbol("posix") defineSymbol("posix")
of osMacOS: of osMacos:
defineSymbol("macintosh") defineSymbol("macintosh")
of osMacOSX: of osMacosx:
defineSymbol("macintosh") defineSymbol("macintosh")
defineSymbol("unix") defineSymbol("unix")
defineSymbol("posix") defineSymbol("posix")

View file

@ -78,7 +78,7 @@ proc updateCrc32(val: int8, crc: TCrc32): TCrc32 =
result = TCrc32(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and result = TCrc32(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and
0x000000FF]) xor (crc shr TCrc32(8)) 0x000000FF]) xor (crc shr TCrc32(8))
proc updateCrc32(val: Char, crc: TCrc32): TCrc32 = proc updateCrc32(val: char, crc: TCrc32): TCrc32 =
result = updateCrc32(toU8(ord(val)), crc) result = updateCrc32(toU8(ord(val)), crc)
proc strCrc32(s: string): TCrc32 = proc strCrc32(s: string): TCrc32 =
@ -93,7 +93,7 @@ type
TByteArray = array[0..10000000, int8] TByteArray = array[0..10000000, int8]
PByteArray = ref TByteArray PByteArray = ref TByteArray
proc crcFromBuf(buf: Pointer, length: int): TCrc32 = proc crcFromBuf(buf: pointer, length: int): TCrc32 =
var p = cast[PByteArray](buf) var p = cast[PByteArray](buf)
result = InitCrc32 result = InitCrc32
for i in countup(0, length - 1): result = updateCrc32(p[i], result) for i in countup(0, length - 1): result = updateCrc32(p[i], result)
@ -106,7 +106,7 @@ proc crcFromFile(filename: string): TCrc32 =
result = InitCrc32 result = InitCrc32
if not open(bin, filename): if not open(bin, filename):
return # not equal if file does not exist return # not equal if file does not exist
var buf = alloc(BufSize) var buf = alloc(bufSize)
var p = cast[PByteArray](buf) var p = cast[PByteArray](buf)
while true: while true:
var readBytes = readBuffer(bin, buf, bufSize) var readBytes = readBuffer(bin, buf, bufSize)

View file

@ -44,19 +44,19 @@ proc compilerMsgHandler(filename: string, line, col: int,
proc parseRst(text, filename: string, 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]) =
if gCmd != cmdRst2Tex: appf(dest, xml, args) if gCmd != cmdRst2tex: appf(dest, xml, args)
else: appf(dest, tex, args) else: appf(dest, tex, args)
proc getVarIdx(varnames: openArray[string], id: string): int = proc getVarIdx(varnames: openArray[string], id: string): int =
@ -186,7 +186,7 @@ proc getName(d: PDoc, n: PNode, splitAfter = -1): string =
internalError(n.info, "getName()") internalError(n.info, "getName()")
result = "" result = ""
proc getRstName(n: PNode): PRSTNode = proc getRstName(n: PNode): PRstNode =
case n.kind case n.kind
of nkPostfix: result = getRstName(n.sons[1]) of nkPostfix: result = getRstName(n.sons[1])
of nkPragmaExpr: result = getRstName(n.sons[0]) of nkPragmaExpr: result = getRstName(n.sons[0])
@ -408,7 +408,7 @@ proc genOutFile(d: PDoc): PRope =
proc generateIndex*(d: PDoc) = proc generateIndex*(d: PDoc) =
if optGenIndex in gGlobalOptions: if optGenIndex in gGlobalOptions:
writeIndexFile(d[], splitFile(options.outFile).dir / writeIndexFile(d[], splitFile(options.outFile).dir /
splitFile(d.filename).name & indexExt) splitFile(d.filename).name & IndexExt)
proc writeOutput*(d: PDoc, filename, outExt: string, useWarning = false) = proc writeOutput*(d: PDoc, filename, outExt: string, useWarning = false) =
var content = genOutFile(d) var content = genOutFile(d)

View file

@ -36,7 +36,7 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) =
else: else:
result.add copyTree(x) result.add copyTree(x)
else: else:
InternalAssert sfGenSym in s.flags internalAssert sfGenSym in s.flags
var x = PSym(idTableGet(c.mapping, s)) var x = PSym(idTableGet(c.mapping, s))
if x == nil: if x == nil:
x = copySym(s, false) x = copySym(s, false)

View file

@ -35,7 +35,7 @@ proc getArg(n: PNode, name: string, pos: int): PNode =
elif i == pos: elif i == pos:
return n.sons[i] return n.sons[i]
proc charArg(n: PNode, name: string, pos: int, default: Char): Char = proc charArg(n: PNode, name: string, pos: int, default: char): char =
var x = getArg(n, name, pos) var x = getArg(n, name, pos)
if x == nil: result = default if x == nil: result = default
elif x.kind == nkCharLit: result = chr(int(x.intVal)) elif x.kind == nkCharLit: result = chr(int(x.intVal))

View file

@ -254,7 +254,7 @@ proc valuesUnequal(a, b: PNode): bool =
result = not sameValue(a, b) result = not sameValue(a, b)
proc pred(n: PNode): PNode = proc pred(n: PNode): PNode =
if n.kind in {nkCharLit..nkUInt64Lit} and n.intVal != low(biggestInt): if n.kind in {nkCharLit..nkUInt64Lit} and n.intVal != low(BiggestInt):
result = copyNode(n) result = copyNode(n)
dec result.intVal dec result.intVal
else: else:
@ -366,7 +366,7 @@ proc impliesIsNil(fact, eq: PNode): TImplication =
else: discard else: discard
proc impliesGe(fact, x, c: PNode): TImplication = proc impliesGe(fact, x, c: PNode): TImplication =
InternalAssert isLocation(x) internalAssert isLocation(x)
case fact.sons[0].sym.magic case fact.sons[0].sym.magic
of someEq: of someEq:
if sameTree(fact.sons[1], x): if sameTree(fact.sons[1], x):

View file

@ -12,7 +12,7 @@
proc hlo(c: PContext, n: PNode): PNode proc hlo(c: PContext, n: PNode): PNode
proc evalPattern(c: PContext, n, orig: PNode): PNode = proc evalPattern(c: PContext, n, orig: PNode): PNode =
InternalAssert n.kind == nkCall and n.sons[0].kind == nkSym internalAssert n.kind == nkCall and n.sons[0].kind == nkSym
# we need to ensure that the resulting AST is semchecked. However, it's # we need to ensure that the resulting AST is semchecked. However, it's
# aweful to semcheck before macro invocation, so we don't and treat # aweful to semcheck before macro invocation, so we don't and treat
# templates and macros as immediate in this context. # templates and macros as immediate in this context.

View file

@ -22,7 +22,7 @@ when debugIds:
var usedIds = InitIntSet() var usedIds = InitIntSet()
proc registerID*(id: PIdObj) = proc registerID*(id: PIdObj) =
when debugIDs: when debugIds:
if id.id == -1 or containsOrIncl(usedIds, id.id): if id.id == -1 or containsOrIncl(usedIds, id.id):
internalError("ID already used: " & $id.id) internalError("ID already used: " & $id.id)

View file

@ -111,7 +111,7 @@ proc mapType(typ: PType): TJSTypeKind =
let t = skipTypes(typ, abstractInst) let t = skipTypes(typ, abstractInst)
case t.kind case t.kind
of tyVar, tyRef, tyPtr: of tyVar, tyRef, tyPtr:
if skipTypes(t.sons[0], abstractInst).kind in mappedToObject: if skipTypes(t.sons[0], abstractInst).kind in MappedToObject:
result = etyObject result = etyObject
else: else:
result = etyBaseIndex result = etyBaseIndex
@ -240,7 +240,7 @@ proc genOr(p: PProc, a, b: PNode, r: var TCompRes) =
type type
TMagicFrmt = array[0..3, string] TMagicFrmt = array[0..3, string]
TMagicOps = array[mAddi..mStrToStr, TMagicFrmt] TMagicOps = array[mAddI..mStrToStr, TMagicFrmt]
const # magic checked op; magic unchecked op; checked op; unchecked op const # magic checked op; magic unchecked op; checked op; unchecked op
jsOps: TMagicOps = [ jsOps: TMagicOps = [
@ -865,7 +865,7 @@ proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) =
var f = b.sons[1].sym var f = b.sons[1].sym
if f.loc.r == nil: f.loc.r = mangleName(f) if f.loc.r == nil: f.loc.r = mangleName(f)
r.res = makeJSString(ropeToStr(f.loc.r)) r.res = makeJSString(ropeToStr(f.loc.r))
InternalAssert a.typ != etyBaseIndex internalAssert a.typ != etyBaseIndex
r.address = a.res r.address = a.res
r.kind = resExpr r.kind = resExpr
@ -894,7 +894,7 @@ proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) =
r.typ = etyBaseIndex r.typ = etyBaseIndex
gen(p, n.sons[0], a) gen(p, n.sons[0], a)
gen(p, n.sons[1], b) gen(p, n.sons[1], b)
InternalAssert a.typ != etyBaseIndex and b.typ != etyBaseIndex internalAssert a.typ != etyBaseIndex and b.typ != etyBaseIndex
r.address = a.res r.address = a.res
var typ = skipTypes(n.sons[0].typ, abstractPtrs) var typ = skipTypes(n.sons[0].typ, abstractPtrs)
if typ.kind in {tyArray, tyArrayConstr}: first = firstOrd(typ.sons[0]) if typ.kind in {tyArray, tyArrayConstr}: first = firstOrd(typ.sons[0])
@ -1293,7 +1293,7 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) =
case op case op
of mOr: genOr(p, n.sons[1], n.sons[2], r) of mOr: genOr(p, n.sons[1], n.sons[2], r)
of mAnd: genAnd(p, n.sons[1], n.sons[2], r) of mAnd: genAnd(p, n.sons[1], n.sons[2], r)
of mAddi..mStrToStr: arith(p, n, r, op) of mAddI..mStrToStr: arith(p, n, r, op)
of mRepr: genRepr(p, n, r) of mRepr: genRepr(p, n, r)
of mSwap: genSwap(p, n) of mSwap: genSwap(p, n)
of mUnaryLt: of mUnaryLt:
@ -1416,7 +1416,7 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) =
for i in countup(1, sonsLen(n) - 1): for i in countup(1, sonsLen(n) - 1):
if i > 0: app(r.res, ", ") if i > 0: app(r.res, ", ")
var it = n.sons[i] var it = n.sons[i]
InternalAssert it.kind == nkExprColonExpr internalAssert it.kind == nkExprColonExpr
gen(p, it.sons[1], a) gen(p, it.sons[1], a)
var f = it.sons[0].sym var f = it.sons[0].sym
if f.loc.r == nil: f.loc.r = mangleName(f) if f.loc.r == nil: f.loc.r = mangleName(f)
@ -1655,7 +1655,7 @@ proc genHeader(): PRope =
"$nvar Globals = this;$n" & "$nvar Globals = this;$n" &
"var framePtr = null;$n" & "var framePtr = null;$n" &
"var excHandler = null;$n", "var excHandler = null;$n",
[toRope(versionAsString)]) [toRope(VersionAsString)])
proc genModule(p: PProc, n: PNode) = proc genModule(p: PProc, n: PNode) =
if optStackTrace in p.options: if optStackTrace in p.options:

View file

@ -226,7 +226,7 @@ proc isInnerProc(s, outerProc: PSym): bool {.inline.} =
#s.typ.callConv == ccClosure #s.typ.callConv == ccClosure
proc addClosureParam(i: PInnerContext, e: PEnv) = proc addClosureParam(i: PInnerContext, e: PEnv) =
var cp = newSym(skParam, getIdent(paramname), i.fn, i.fn.info) var cp = newSym(skParam, getIdent(paramName), i.fn, i.fn.info)
incl(cp.flags, sfFromGeneric) incl(cp.flags, sfFromGeneric)
cp.typ = newType(tyRef, i.fn) cp.typ = newType(tyRef, i.fn)
rawAddSon(cp.typ, e.tup) rawAddSon(cp.typ, e.tup)
@ -679,7 +679,7 @@ proc liftIterator*(iter: PSym, body: PNode): PNode =
c.tup = newType(tyTuple, iter) c.tup = newType(tyTuple, iter)
c.tup.n = newNodeI(nkRecList, iter.info) c.tup.n = newNodeI(nkRecList, iter.info)
var cp = newSym(skParam, getIdent(paramname), iter, iter.info) var cp = newSym(skParam, getIdent(paramName), iter, iter.info)
incl(cp.flags, sfFromGeneric) incl(cp.flags, sfFromGeneric)
cp.typ = newType(tyRef, iter) cp.typ = newType(tyRef, iter)
rawAddSon(cp.typ, c.tup) rawAddSon(cp.typ, c.tup)
@ -758,7 +758,7 @@ proc liftForLoop*(body: PNode): PNode =
... ...
""" """
var L = body.len var L = body.len
InternalAssert body.kind == nkForStmt and body[L-2].kind in nkCallKinds internalAssert body.kind == nkForStmt and body[L-2].kind in nkCallKinds
var call = body[L-2] var call = body[L-2]
result = newNodeI(nkStmtList, body.info) result = newNodeI(nkStmtList, body.info)

View file

@ -581,7 +581,7 @@ proc getCharacter(L: var TLexer, tok: var TToken) =
inc(L.bufpos) # skip ' inc(L.bufpos) # skip '
var c = L.buf[L.bufpos] var c = L.buf[L.bufpos]
case c case c
of '\0'..Pred(' '), '\'': lexMessage(L, errInvalidCharacterConstant) of '\0'..pred(' '), '\'': lexMessage(L, errInvalidCharacterConstant)
of '\\': getEscapedChar(L, tok) of '\\': getEscapedChar(L, tok)
else: else:
tok.literal = $c tok.literal = $c

View file

@ -50,7 +50,7 @@ proc llStreamOpen(data: string): PLLStream =
result.s = data result.s = data
result.kind = llsString result.kind = llsString
proc llStreamOpen(f: var tfile): PLLStream = proc llStreamOpen(f: var TFile): PLLStream =
new(result) new(result)
result.f = f result.f = f
result.kind = llsFile result.kind = llsFile
@ -179,7 +179,7 @@ proc llStreamWriteln(s: PLLStream, data: string) =
llStreamWrite(s, data) llStreamWrite(s, data)
llStreamWrite(s, "\n") llStreamWrite(s, "\n")
proc llStreamWrite(s: PLLStream, data: Char) = proc llStreamWrite(s: PLLStream, data: char) =
var c: char var c: char
case s.kind case s.kind
of llsNone, llsStdIn: of llsNone, llsStdIn:

View file

@ -79,7 +79,7 @@ proc getSysType(kind: TTypeKind): PType =
of tyBool: result = sysTypeFromName("bool") of tyBool: result = sysTypeFromName("bool")
of tyChar: result = sysTypeFromName("char") of tyChar: result = sysTypeFromName("char")
of tyString: result = sysTypeFromName("string") of tyString: result = sysTypeFromName("string")
of tyCstring: result = sysTypeFromName("cstring") of tyCString: result = sysTypeFromName("cstring")
of tyPointer: result = sysTypeFromName("pointer") of tyPointer: result = sysTypeFromName("pointer")
of tyNil: result = newSysType(tyNil, ptrSize) of tyNil: result = newSysType(tyNil, ptrSize)
else: internalError("request for typekind: " & $kind) else: internalError("request for typekind: " & $kind)

View file

@ -39,7 +39,7 @@ proc semanticPasses =
proc commandGenDepend = proc commandGenDepend =
semanticPasses() semanticPasses()
registerPass(genDependPass) registerPass(gendependPass)
registerPass(cleanupPass) registerPass(cleanupPass)
compileProject() compileProject()
generateDot(gProjectFull) generateDot(gProjectFull)
@ -127,7 +127,7 @@ proc commandCompileToJS =
defineSymbol("ecmascript") # For backward compatibility defineSymbol("ecmascript") # For backward compatibility
defineSymbol("js") defineSymbol("js")
semanticPasses() semanticPasses()
registerPass(jsgenPass) registerPass(JSgenPass)
compileProject() compileProject()
proc interactivePasses = proc interactivePasses =
@ -177,7 +177,7 @@ proc commandPretty =
pretty.overwriteFiles() pretty.overwriteFiles()
proc commandScan = proc commandScan =
var f = addFileExt(mainCommandArg(), nimExt) var f = addFileExt(mainCommandArg(), NimExt)
var stream = llStreamOpen(f, fmRead) var stream = llStreamOpen(f, fmRead)
if stream != nil: if stream != nil:
var var
@ -224,7 +224,7 @@ proc wantMainModule =
gProjectName = optMainModule gProjectName = optMainModule
gProjectFull = gProjectPath / gProjectName gProjectFull = gProjectPath / gProjectName
gProjectMainIdx = addFileExt(gProjectFull, nimExt).fileInfoIdx gProjectMainIdx = addFileExt(gProjectFull, NimExt).fileInfoIdx
proc requireMainModuleOption = proc requireMainModuleOption =
if optMainModule.len == 0: if optMainModule.len == 0:
@ -233,7 +233,7 @@ proc requireMainModuleOption =
gProjectName = optMainModule gProjectName = optMainModule
gProjectFull = gProjectPath / gProjectName gProjectFull = gProjectPath / gProjectName
gProjectMainIdx = addFileExt(gProjectFull, nimExt).fileInfoIdx gProjectMainIdx = addFileExt(gProjectFull, NimExt).fileInfoIdx
proc resetMemory = proc resetMemory =
resetCompilationLists() resetCompilationLists()
@ -334,7 +334,7 @@ proc mainCommand* =
of "compiletollvm": of "compiletollvm":
gCmd = cmdCompileToLLVM gCmd = cmdCompileToLLVM
wantMainModule() wantMainModule()
when has_LLVM_Backend: when hasLLVM_Backend:
CommandCompileToLLVM() CommandCompileToLLVM()
else: else:
rawMessage(errInvalidCommandX, command) rawMessage(errInvalidCommandX, command)
@ -386,7 +386,7 @@ proc mainCommand* =
for s in definedSymbolNames(): definedSymbols.elems.add(%s) for s in definedSymbolNames(): definedSymbols.elems.add(%s)
var libpaths = newJArray() var libpaths = newJArray()
for dir in itersearchpath(searchPaths): libpaths.elems.add(%dir) for dir in iterSearchPath(searchPaths): libpaths.elems.add(%dir)
var dumpdata = % [ var dumpdata = % [
(key: "version", val: %VersionAsString), (key: "version", val: %VersionAsString),

View file

@ -41,7 +41,7 @@ template crc(x: PSym): expr =
gMemCacheData[x.position].crc gMemCacheData[x.position].crc
proc crcChanged(fileIdx: int32): bool = proc crcChanged(fileIdx: int32): bool =
InternalAssert fileIdx >= 0 and fileIdx < gMemCacheData.len internalAssert fileIdx >= 0 and fileIdx < gMemCacheData.len
template updateStatus = template updateStatus =
gMemCacheData[fileIdx].crcStatus = if result: crcHasChanged gMemCacheData[fileIdx].crcStatus = if result: crcHasChanged

View file

@ -724,7 +724,7 @@ proc writeContext(lastinfo: TLineInfo) =
var info = lastinfo var info = lastinfo
for i in countup(0, len(msgContext) - 1): for i in countup(0, len(msgContext) - 1):
if msgContext[i] != lastinfo and msgContext[i] != info: if msgContext[i] != lastinfo and msgContext[i] != info:
msgWriteln(posContextFormat % [toMsgFilename(msgContext[i]), msgWriteln(PosContextFormat % [toMsgFilename(msgContext[i]),
coordToStr(msgContext[i].line), coordToStr(msgContext[i].line),
coordToStr(msgContext[i].col), coordToStr(msgContext[i].col),
getMessageStr(errInstantiationFrom, "")]) getMessageStr(errInstantiationFrom, "")])
@ -735,17 +735,17 @@ proc rawMessage*(msg: TMsgKind, args: openArray[string]) =
case msg case msg
of errMin..errMax: of errMin..errMax:
writeContext(unknownLineInfo()) writeContext(unknownLineInfo())
frmt = rawErrorFormat frmt = RawErrorFormat
of warnMin..warnMax: of warnMin..warnMax:
if optWarns notin gOptions: return if optWarns notin gOptions: return
if msg notin gNotes: return if msg notin gNotes: return
writeContext(unknownLineInfo()) writeContext(unknownLineInfo())
frmt = rawWarningFormat frmt = RawWarningFormat
inc(gWarnCounter) inc(gWarnCounter)
of hintMin..hintMax: of hintMin..hintMax:
if optHints notin gOptions: return if optHints notin gOptions: return
if msg notin gNotes: return if msg notin gNotes: return
frmt = rawHintFormat frmt = RawHintFormat
inc(gHintCounter) inc(gHintCounter)
let s = `%`(frmt, `%`(msgKindToString(msg), args)) let s = `%`(frmt, `%`(msgKindToString(msg), args))
msgWriteln(s) msgWriteln(s)
@ -766,7 +766,7 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string,
case msg case msg
of errMin..errMax: of errMin..errMax:
writeContext(info) writeContext(info)
frmt = posErrorFormat frmt = PosErrorFormat
# we try to filter error messages so that not two error message # we try to filter error messages so that not two error message
# in the same file and line are produced: # in the same file and line are produced:
#ignoreMsg = lastError == info and eh != doAbort #ignoreMsg = lastError == info and eh != doAbort
@ -774,11 +774,11 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string,
of warnMin..warnMax: of warnMin..warnMax:
ignoreMsg = optWarns notin gOptions or msg notin gNotes ignoreMsg = optWarns notin gOptions or msg notin gNotes
if not ignoreMsg: writeContext(info) if not ignoreMsg: writeContext(info)
frmt = posWarningFormat frmt = PosWarningFormat
inc(gWarnCounter) inc(gWarnCounter)
of hintMin..hintMax: of hintMin..hintMax:
ignoreMsg = optHints notin gOptions or msg notin gNotes ignoreMsg = optHints notin gOptions or msg notin gNotes
frmt = posHintFormat frmt = PosHintFormat
inc(gHintCounter) inc(gHintCounter)
let s = frmt % [toMsgFilename(info), coordToStr(info.line), let s = frmt % [toMsgFilename(info), coordToStr(info.line),
coordToStr(info.col), getMessageStr(msg, arg)] coordToStr(info.col), getMessageStr(msg, arg)]

View file

@ -81,7 +81,7 @@ proc doElif(L: var TLexer, tok: var TToken) =
proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) =
var nestedIfs = 0 var nestedIfs = 0
while True: while true:
if (tok.ident != nil) and (tok.ident.s == "@"): if (tok.ident != nil) and (tok.ident.s == "@"):
ppGetTok(L, tok) ppGetTok(L, tok)
case whichKeyword(tok.ident) case whichKeyword(tok.ident)

View file

@ -107,7 +107,7 @@ proc fillBuffer(L: var TBaseLexer) =
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]),
oldBufLen * chrSize) div chrSize oldBufLen * chrSize) div chrSize
if charsRead < oldBufLen: if charsRead < oldBufLen:

View file

@ -71,7 +71,7 @@ proc handleCmdLine() =
binPath = options.outFile.prependCurDir binPath = options.outFile.prependCurDir
else: else:
# Figure out ourselves a valid binary name. # Figure out ourselves a valid binary name.
binPath = changeFileExt(gProjectFull, exeExt).prependCurDir binPath = changeFileExt(gProjectFull, ExeExt).prependCurDir
var ex = quoteShell(binPath) var ex = quoteShell(binPath)
execExternalProgram(ex & ' ' & service.arguments) execExternalProgram(ex & ' ' & service.arguments)

View file

@ -98,13 +98,13 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode =
result.typ = settype result.typ = settype
result.info = info result.info = info
e = 0 e = 0
while e < len(s) * elemSize: while e < len(s) * ElemSize:
if bitSetIn(s, e): if bitSetIn(s, e):
a = e a = e
b = e b = e
while true: while true:
inc(b) inc(b)
if (b >= len(s) * elemSize) or not bitSetIn(s, b): break if (b >= len(s) * ElemSize) or not bitSetIn(s, b): break
dec(b) dec(b)
if a == b: if a == b:
addSon(result, newIntTypeNode(nkIntLit, a + first, elemType)) addSon(result, newIntTypeNode(nkIntLit, a + first, elemType))

View file

@ -192,16 +192,16 @@ proc canonicalizePath*(path: string): string =
proc shortenDir*(dir: string): string = proc shortenDir*(dir: string): string =
## returns the interesting part of a dir ## returns the interesting part of a dir
var prefix = getPrefixDir() & dirSep var prefix = getPrefixDir() & DirSep
if startsWith(dir, prefix): if startsWith(dir, prefix):
return substr(dir, len(prefix)) return substr(dir, len(prefix))
prefix = gProjectPath & dirSep prefix = gProjectPath & DirSep
if startsWith(dir, prefix): if startsWith(dir, prefix):
return substr(dir, len(prefix)) return substr(dir, len(prefix))
result = dir result = dir
proc removeTrailingDirSep*(path: string): string = proc removeTrailingDirSep*(path: string): string =
if (len(path) > 0) and (path[len(path) - 1] == dirSep): if (len(path) > 0) and (path[len(path) - 1] == DirSep):
result = substr(path, 0, len(path) - 2) result = substr(path, 0, len(path) - 2)
else: else:
result = path result = path
@ -213,9 +213,9 @@ proc getGeneratedPath: string =
proc getPackageName*(path: string): string = proc getPackageName*(path: string): string =
var q = 1 var q = 1
var b = 0 var b = 0
if path[len(path)-1] in {dirsep, altsep}: q = 2 if path[len(path)-1] in {DirSep, AltSep}: q = 2
for i in countdown(len(path)-q, 0): for i in countdown(len(path)-q, 0):
if path[i] in {dirsep, altsep}: if path[i] in {DirSep, AltSep}:
if b == 0: b = i if b == 0: b = i
else: else:
let x = path.substr(i+1, b-1) let x = path.substr(i+1, b-1)
@ -288,7 +288,7 @@ proc findFile*(f: string): string {.procvar.} =
proc findModule*(modulename, currentModule: string): string = proc findModule*(modulename, currentModule: string): string =
# returns path to module # returns path to module
let m = addFileExt(modulename, nimExt) let m = addFileExt(modulename, NimExt)
let currentPath = currentModule.splitFile.dir let currentPath = currentModule.splitFile.dir
result = currentPath / m result = currentPath / m
if not existsFile(result): if not existsFile(result):

View file

@ -97,14 +97,14 @@ proc compileConstraints(p: PNode, result: var TPatternCode) =
of "nosideeffect": result.add(ppNoSideEffect) of "nosideeffect": result.add(ppNoSideEffect)
else: else:
# check all symkinds: # check all symkinds:
InternalAssert int(high(TSymKind)) < 255 internalAssert int(high(TSymKind)) < 255
for i in low(TSymKind)..high(TSymKind): for i in low(TSymKind)..high(TSymKind):
if cmpIgnoreStyle(($i).substr(2), spec) == 0: if cmpIgnoreStyle(($i).substr(2), spec) == 0:
result.add(ppSymKind) result.add(ppSymKind)
result.add(chr(i.ord)) result.add(chr(i.ord))
return return
# check all nodekinds: # check all nodekinds:
InternalAssert int(high(TNodeKind)) < 255 internalAssert int(high(TNodeKind)) < 255
for i in low(TNodeKind)..high(TNodeKind): for i in low(TNodeKind)..high(TNodeKind):
if cmpIgnoreStyle($i, spec) == 0: if cmpIgnoreStyle($i, spec) == 0:
result.add(ppNodeKind) result.add(ppNodeKind)
@ -124,7 +124,7 @@ proc semNodeKindConstraints*(p: PNode): PNode =
if p.len >= 2: if p.len >= 2:
for i in 1.. <p.len: for i in 1.. <p.len:
compileConstraints(p.sons[i], result.strVal) compileConstraints(p.sons[i], result.strVal)
if result.strVal.len > maxStackSize-1: if result.strVal.len > MaxStackSize-1:
internalError(p.info, "parameter pattern too complex") internalError(p.info, "parameter pattern too complex")
else: else:
patternError(p) patternError(p)
@ -221,7 +221,7 @@ proc isAssignable*(owner: PSym, n: PNode): TAssignableResult =
proc matchNodeKinds*(p, n: PNode): bool = proc matchNodeKinds*(p, n: PNode): bool =
# matches the parameter constraint 'p' against the concrete AST 'n'. # matches the parameter constraint 'p' against the concrete AST 'n'.
# Efficiency matters here. # Efficiency matters here.
var stack {.noinit.}: array[0..maxStackSize, bool] var stack {.noinit.}: array[0..MaxStackSize, bool]
# empty patterns are true: # empty patterns are true:
stack[0] = true stack[0] = true
var sp = 1 var sp = 1

View file

@ -211,7 +211,7 @@ proc getPrecedence(tok: TToken): int =
of '?': result = 2 of '?': result = 2
else: considerAsgn(2) else: considerAsgn(2)
of tkDiv, tkMod, tkShl, tkShr: result = 9 of tkDiv, tkMod, tkShl, tkShr: result = 9
of tkIn, tkNotIn, tkIs, tkIsNot, tkNot, tkOf, tkAs: result = 5 of tkIn, tkNotin, tkIs, tkIsnot, tkNot, tkOf, tkAs: result = 5
of tkDotDot: result = 6 of tkDotDot: result = 6
of tkAnd: result = 4 of tkAnd: result = 4
of tkOr, tkXor: result = 3 of tkOr, tkXor: result = 3
@ -455,7 +455,7 @@ proc simpleExpr(p: var TParser, mode = pmNormal): PNode
proc semiStmtList(p: var TParser, result: PNode) = proc semiStmtList(p: var TParser, result: PNode) =
result.add(complexOrSimpleStmt(p)) result.add(complexOrSimpleStmt(p))
while p.tok.tokType == tkSemicolon: while p.tok.tokType == tkSemiColon:
getTok(p) getTok(p)
optInd(p, result) optInd(p, result)
result.add(complexOrSimpleStmt(p)) result.add(complexOrSimpleStmt(p))
@ -482,7 +482,7 @@ proc parsePar(p: var TParser): PNode =
# XXX 'bind' used to be an expression, so we exclude it here; # XXX 'bind' used to be an expression, so we exclude it here;
# tests/reject/tbind2 fails otherwise. # tests/reject/tbind2 fails otherwise.
semiStmtList(p, result) semiStmtList(p, result)
elif p.tok.tokType == tkSemicolon: elif p.tok.tokType == tkSemiColon:
# '(;' enforces 'stmt' context: # '(;' enforces 'stmt' context:
getTok(p) getTok(p)
optInd(p, result) optInd(p, result)
@ -498,7 +498,7 @@ proc parsePar(p: var TParser): PNode =
asgn.sons[0] = a asgn.sons[0] = a
asgn.sons[1] = b asgn.sons[1] = b
result.add(asgn) result.add(asgn)
elif p.tok.tokType == tkSemicolon: elif p.tok.tokType == tkSemiColon:
# stmt context: # stmt context:
result.add(a) result.add(a)
semiStmtList(p, result) semiStmtList(p, result)
@ -798,7 +798,7 @@ proc parseTuple(p: var TParser, indentAllowed = false): PNode =
while p.tok.tokType in {tkSymbol, tkAccent}: while p.tok.tokType in {tkSymbol, tkAccent}:
var a = parseIdentColonEquals(p, {}) var a = parseIdentColonEquals(p, {})
addSon(result, a) addSon(result, a)
if p.tok.tokType notin {tkComma, tkSemicolon}: break if p.tok.tokType notin {tkComma, tkSemiColon}: break
getTok(p) getTok(p)
skipComment(p, a) skipComment(p, a)
optPar(p) optPar(p)
@ -840,7 +840,7 @@ proc parseParamList(p: var TParser, retColon = true): PNode =
parMessage(p, errTokenExpected, ")") parMessage(p, errTokenExpected, ")")
break break
addSon(result, a) addSon(result, a)
if p.tok.tokType notin {tkComma, tkSemicolon}: break if p.tok.tokType notin {tkComma, tkSemiColon}: break
getTok(p) getTok(p)
skipComment(p, a) skipComment(p, a)
optPar(p) optPar(p)
@ -1378,7 +1378,7 @@ proc parseGenericParamList(p: var TParser): PNode =
while p.tok.tokType in {tkSymbol, tkAccent}: while p.tok.tokType in {tkSymbol, tkAccent}:
var a = parseGenericParam(p) var a = parseGenericParam(p)
addSon(result, a) addSon(result, a)
if p.tok.tokType notin {tkComma, tkSemicolon}: break if p.tok.tokType notin {tkComma, tkSemiColon}: break
getTok(p) getTok(p)
skipComment(p, a) skipComment(p, a)
optPar(p) optPar(p)
@ -1810,7 +1810,7 @@ proc parseStmt(p: var TParser): PNode =
while true: while true:
if p.tok.indent == p.currInd: if p.tok.indent == p.currInd:
nil nil
elif p.tok.tokType == tkSemicolon: elif p.tok.tokType == tkSemiColon:
getTok(p) getTok(p)
if p.tok.indent < 0 or p.tok.indent == p.currInd: discard if p.tok.indent < 0 or p.tok.indent == p.currInd: discard
else: break else: break
@ -1842,7 +1842,7 @@ proc parseStmt(p: var TParser): PNode =
let a = simpleStmt(p) let a = simpleStmt(p)
if a.kind == nkEmpty: parMessage(p, errExprExpected, p.tok) if a.kind == nkEmpty: parMessage(p, errExprExpected, p.tok)
result.add(a) result.add(a)
if p.tok.tokType != tkSemicolon: break if p.tok.tokType != tkSemiColon: break
getTok(p) getTok(p)
proc parseAll(p: var TParser): PNode = proc parseAll(p: var TParser): PNode =
@ -1866,7 +1866,7 @@ proc parseTopLevelStmt(p: var TParser): PNode =
else: parMessage(p, errInvalidIndentation) else: parMessage(p, errInvalidIndentation)
p.firstTok = false p.firstTok = false
case p.tok.tokType case p.tok.tokType
of tkSemicolon: of tkSemiColon:
getTok(p) getTok(p)
if p.tok.indent <= 0: discard if p.tok.indent <= 0: discard
else: parMessage(p, errInvalidIndentation) else: parMessage(p, errInvalidIndentation)

View file

@ -20,49 +20,49 @@ const
const const
procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl, procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
wMagic, wNosideEffect, wSideEffect, wNoreturn, wDynLib, wHeader, wMagic, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
wCompilerProc, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge, wCompilerproc, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge,
wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC, wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC,
wNoStackFrame, wError, wDiscardable, wNoInit, wDestructor, wCodegenDecl, wNoStackFrame, wError, wDiscardable, wNoInit, wDestructor, wCodegenDecl,
wGenSym, wInject, wRaises, wTags, wOperator, wDelegator} wGensym, wInject, wRaises, wTags, wOperator, wDelegator}
converterPragmas* = procPragmas converterPragmas* = procPragmas
methodPragmas* = procPragmas methodPragmas* = procPragmas
templatePragmas* = {wImmediate, wDeprecated, wError, wGenSym, wInject, wDirty, templatePragmas* = {wImmediate, wDeprecated, wError, wGensym, wInject, wDirty,
wDelegator} wDelegator}
macroPragmas* = {FirstCallConv..LastCallConv, wImmediate, wImportc, wExportc, macroPragmas* = {FirstCallConv..LastCallConv, wImmediate, wImportc, wExportc,
wNodecl, wMagic, wNosideEffect, wCompilerProc, wDeprecated, wExtern, wNodecl, wMagic, wNosideeffect, wCompilerproc, wDeprecated, wExtern,
wImportcpp, wImportobjc, wError, wDiscardable, wGenSym, wInject, wDelegator} wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wDelegator}
iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideEffect, wSideEffect, iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideeffect, wSideeffect,
wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern, wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern,
wImportcpp, wImportobjc, wError, wDiscardable, wGenSym, wInject, wRaises, wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises,
wTags, wOperator} wTags, wOperator}
exprPragmas* = {wLine} exprPragmas* = {wLine}
stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks, stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks,
wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints,
wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError, wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError,
wFatal, wDefine, wUndef, wCompile, wLink, wLinkSys, wPure, wPush, wPop, wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop,
wBreakpoint, wWatchpoint, wPassL, wPassC, wDeadCodeElim, wDeprecated, wBreakpoint, wWatchPoint, wPassl, wPassc, wDeadCodeElim, wDeprecated,
wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll, wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll,
wLinearScanEnd, wPatterns, wEffects, wNoForward, wComputedGoto, wLinearScanEnd, wPatterns, wEffects, wNoForward, wComputedGoto,
wInjectStmt} wInjectStmt}
lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl, lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl,
wNosideEffect, wSideEffect, wNoreturn, wDynLib, wHeader, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader,
wDeprecated, wExtern, wThread, wImportcpp, wImportobjc, wNoStackFrame, wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wNoStackFrame,
wRaises, wTags} wRaises, wTags}
typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl, typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl,
wPure, wHeader, wCompilerProc, wFinal, wSize, wExtern, wShallow, wPure, wHeader, wCompilerproc, wFinal, wSize, wExtern, wShallow,
wImportcpp, wImportobjc, wError, wIncompleteStruct, wByCopy, wByRef, wImportCpp, wImportObjC, wError, wIncompleteStruct, wByCopy, wByRef,
wInheritable, wGenSym, wInject, wRequiresInit} wInheritable, wGensym, wInject, wRequiresInit}
fieldPragmas* = {wImportc, wExportc, wDeprecated, wExtern, fieldPragmas* = {wImportc, wExportc, wDeprecated, wExtern,
wImportcpp, wImportobjc, wError} wImportCpp, wImportObjC, wError}
varPragmas* = {wImportc, wExportc, wVolatile, wRegister, wThreadVar, wNodecl, varPragmas* = {wImportc, wExportc, wVolatile, wRegister, wThreadVar, wNodecl,
wMagic, wHeader, wDeprecated, wCompilerProc, wDynLib, wExtern, wMagic, wHeader, wDeprecated, wCompilerproc, wDynlib, wExtern,
wImportcpp, wImportobjc, wError, wNoInit, wCompileTime, wGlobal, wImportCpp, wImportObjC, wError, wNoInit, wCompileTime, wGlobal,
wGenSym, wInject, wCodegenDecl} wGensym, wInject, wCodegenDecl}
constPragmas* = {wImportc, wExportc, wHeader, wDeprecated, wMagic, wNodecl, constPragmas* = {wImportc, wExportc, wHeader, wDeprecated, wMagic, wNodecl,
wExtern, wImportcpp, wImportobjc, wError, wGenSym, wInject} wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject}
letPragmas* = varPragmas letPragmas* = varPragmas
procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideEffect, procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideeffect,
wThread, wRaises, wTags} wThread, wRaises, wTags}
allRoutinePragmas* = procPragmas + iteratorPragmas + lambdaPragmas allRoutinePragmas* = procPragmas + iteratorPragmas + lambdaPragmas
@ -199,7 +199,7 @@ proc processCallConv(c: PContext, n: PNode) =
if (n.kind == nkExprColonExpr) and (n.sons[1].kind == nkIdent): if (n.kind == nkExprColonExpr) and (n.sons[1].kind == nkIdent):
var sw = whichKeyword(n.sons[1].ident) var sw = whichKeyword(n.sons[1].ident)
case sw case sw
of firstCallConv..lastCallConv: of FirstCallConv..LastCallConv:
POptionEntry(c.optionStack.tail).defaultCC = wordToCallConv(sw) POptionEntry(c.optionStack.tail).defaultCC = wordToCallConv(sw)
else: localError(n.info, errCallConvExpected) else: localError(n.info, errCallConvExpected)
else: else:
@ -247,7 +247,7 @@ proc processDynLib(c: PContext, n: PNode, sym: PSym) =
# since we'll be loading the dynlib symbols dynamically, we must use # since we'll be loading the dynlib symbols dynamically, we must use
# a calling convention that doesn't introduce custom name mangling # a calling convention that doesn't introduce custom name mangling
# cdecl is the default - the user can override this explicitly # cdecl is the default - the user can override this explicitly
if sym.kind in RoutineKinds and sym.typ != nil and if sym.kind in routineKinds and sym.typ != nil and
sym.typ.callConv == ccDefault: sym.typ.callConv == ccDefault:
sym.typ.callConv = ccCDecl sym.typ.callConv = ccCDecl
@ -284,27 +284,27 @@ proc processOption(c: PContext, n: PNode): bool =
else: else:
var sw = whichKeyword(n.sons[0].ident) var sw = whichKeyword(n.sons[0].ident)
case sw case sw
of wChecks: onOff(c, n, checksOptions) of wChecks: onOff(c, n, ChecksOptions)
of wObjChecks: onOff(c, n, {optObjCheck}) of wObjChecks: onOff(c, n, {optObjCheck})
of wFieldchecks: onOff(c, n, {optFieldCheck}) of wFieldChecks: onOff(c, n, {optFieldCheck})
of wRangechecks: onOff(c, n, {optRangeCheck}) of wRangechecks: onOff(c, n, {optRangeCheck})
of wBoundchecks: onOff(c, n, {optBoundsCheck}) of wBoundchecks: onOff(c, n, {optBoundsCheck})
of wOverflowchecks: onOff(c, n, {optOverflowCheck}) of wOverflowchecks: onOff(c, n, {optOverflowCheck})
of wNilchecks: onOff(c, n, {optNilCheck}) of wNilchecks: onOff(c, n, {optNilCheck})
of wFloatChecks: onOff(c, n, {optNanCheck, optInfCheck}) of wFloatchecks: onOff(c, n, {optNaNCheck, optInfCheck})
of wNaNchecks: onOff(c, n, {optNanCheck}) of wNanChecks: onOff(c, n, {optNaNCheck})
of wInfChecks: onOff(c, n, {optInfCheck}) of wInfChecks: onOff(c, n, {optInfCheck})
of wAssertions: onOff(c, n, {optAssert}) of wAssertions: onOff(c, n, {optAssert})
of wWarnings: onOff(c, n, {optWarns}) of wWarnings: onOff(c, n, {optWarns})
of wHints: onOff(c, n, {optHints}) of wHints: onOff(c, n, {optHints})
of wCallConv: processCallConv(c, n) of wCallconv: processCallConv(c, n)
of wLinedir: onOff(c, n, {optLineDir}) of wLinedir: onOff(c, n, {optLineDir})
of wStacktrace: onOff(c, n, {optStackTrace}) of wStacktrace: onOff(c, n, {optStackTrace})
of wLinetrace: onOff(c, n, {optLineTrace}) of wLinetrace: onOff(c, n, {optLineTrace})
of wDebugger: onOff(c, n, {optEndb}) of wDebugger: onOff(c, n, {optEndb})
of wProfiler: onOff(c, n, {optProfiler}) of wProfiler: onOff(c, n, {optProfiler})
of wByRef: onOff(c, n, {optByRef}) of wByRef: onOff(c, n, {optByRef})
of wDynLib: processDynLib(c, n, nil) of wDynlib: processDynLib(c, n, nil)
of wOptimization: of wOptimization:
if n.sons[1].kind != nkIdent: if n.sons[1].kind != nkIdent:
invalidPragma(n) invalidPragma(n)
@ -591,23 +591,23 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
noVal(it) noVal(it)
incl(sym.flags, sfNoSideEffect) incl(sym.flags, sfNoSideEffect)
if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect) if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect)
of wSideEffect: of wSideeffect:
noVal(it) noVal(it)
incl(sym.flags, sfSideEffect) incl(sym.flags, sfSideEffect)
of wNoReturn: of wNoreturn:
noVal(it) noVal(it)
incl(sym.flags, sfNoReturn) incl(sym.flags, sfNoReturn)
of wDynLib: of wDynlib:
processDynLib(c, it, sym) processDynLib(c, it, sym)
of wCompilerProc: of wCompilerproc:
noVal(it) # compilerproc may not get a string! noVal(it) # compilerproc may not get a string!
makeExternExport(sym, "$1") makeExternExport(sym, "$1")
incl(sym.flags, sfCompilerProc) incl(sym.flags, sfCompilerProc)
incl(sym.flags, sfUsed) # suppress all those stupid warnings incl(sym.flags, sfUsed) # suppress all those stupid warnings
registerCompilerProc(sym) registerCompilerProc(sym)
of wProcvar: of wProcVar:
noVal(it) noVal(it)
incl(sym.flags, sfProcVar) incl(sym.flags, sfProcvar)
of wDeprecated: of wDeprecated:
noVal(it) noVal(it)
if sym != nil: incl(sym.flags, sfDeprecated) if sym != nil: incl(sym.flags, sfDeprecated)
@ -638,7 +638,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
of wThread: of wThread:
noVal(it) noVal(it)
incl(sym.flags, sfThread) incl(sym.flags, sfThread)
incl(sym.flags, sfProcVar) incl(sym.flags, sfProcvar)
if sym.typ != nil: incl(sym.typ.flags, tfThread) if sym.typ != nil: incl(sym.typ.flags, tfThread)
of wHint: message(it.info, hintUser, expectStrLit(c, it)) of wHint: message(it.info, hintUser, expectStrLit(c, it))
of wWarning: message(it.info, warnUser, expectStrLit(c, it)) of wWarning: message(it.info, warnUser, expectStrLit(c, it))
@ -657,11 +657,11 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
of wUndef: processUndef(c, it) of wUndef: processUndef(c, it)
of wCompile: processCompile(c, it) of wCompile: processCompile(c, it)
of wLink: processCommonLink(c, it, linkNormal) of wLink: processCommonLink(c, it, linkNormal)
of wLinkSys: processCommonLink(c, it, linkSys) of wLinksys: processCommonLink(c, it, linkSys)
of wPassL: extccomp.addLinkOption(expectStrLit(c, it)) of wPassl: extccomp.addLinkOption(expectStrLit(c, it))
of wPassC: extccomp.addCompileOption(expectStrLit(c, it)) of wPassc: extccomp.addCompileOption(expectStrLit(c, it))
of wBreakpoint: pragmaBreakpoint(c, it) of wBreakpoint: pragmaBreakpoint(c, it)
of wWatchpoint: pragmaWatchpoint(c, it) of wWatchPoint: pragmaWatchpoint(c, it)
of wPush: of wPush:
processPush(c, n, i + 1) processPush(c, n, i + 1)
result = true result = true
@ -679,13 +679,13 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks, of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks,
wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints,
wLinedir, wStacktrace, wLinetrace, wOptimization, wLinedir, wStacktrace, wLinetrace, wOptimization,
wCallConv, wCallconv,
wDebugger, wProfiler, wFloatChecks, wNanChecks, wInfChecks, wDebugger, wProfiler, wFloatchecks, wNanChecks, wInfChecks,
wPatterns: wPatterns:
if processOption(c, it): if processOption(c, it):
# calling conventions (boring...): # calling conventions (boring...):
localError(it.info, errOptionExpected) localError(it.info, errOptionExpected)
of firstCallConv..lastCallConv: of FirstCallConv..LastCallConv:
assert(sym != nil) assert(sym != nil)
if sym.typ == nil: invalidPragma(it) if sym.typ == nil: invalidPragma(it)
else: sym.typ.callConv = wordToCallConv(k) else: sym.typ.callConv = wordToCallConv(k)
@ -713,7 +713,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int,
noVal(it) noVal(it)
if sym.kind != skType or sym.typ == nil: invalidPragma(it) if sym.kind != skType or sym.typ == nil: invalidPragma(it)
else: incl(sym.typ.flags, tfByCopy) else: incl(sym.typ.flags, tfByCopy)
of wInject, wGenSym: of wInject, wGensym:
# We check for errors, but do nothing with these pragmas otherwise # We check for errors, but do nothing with these pragmas otherwise
# as they are handled directly in 'evalTemplate'. # as they are handled directly in 'evalTemplate'.
noVal(it) noVal(it)

View file

@ -149,9 +149,8 @@ proc checkDef(c: PGen; n: PNode) =
if {sfImportc, sfExportc} * s.flags == {} or c.checkExtern: if {sfImportc, sfExportc} * s.flags == {} or c.checkExtern:
checkStyle(n.info, s.name.s, s.kind) checkStyle(n.info, s.name.s, s.kind)
proc checkUse*(n: PNode) = proc checkUse*(n: PNode, s: PSym) =
if n.info.fileIndex < 0 or n.kind != nkSym: return if n.info.fileIndex < 0: return
let s = n.sym
# we simply convert it to what it looks like in the definition # we simply convert it to what it looks like in the definition
# for consistency # for consistency
@ -267,7 +266,7 @@ when false:
proc check(c: PGen, n: PNode) = proc check(c: PGen, n: PNode) =
case n.kind case n.kind
of nkSym: checkUse(n) of nkSym: checkUse(n, n.sym)
of nkBlockStmt, nkBlockExpr, nkBlockType: of nkBlockStmt, nkBlockExpr, nkBlockType:
checkDef(c, n[0]) checkDef(c, n[0])
check(c, n.sons[1]) check(c, n.sons[1])

View file

@ -104,16 +104,16 @@ proc optNL(g: var TSrcGen) =
optNL(g, g.indent) optNL(g, g.indent)
proc indentNL(g: var TSrcGen) = proc indentNL(g: var TSrcGen) =
inc(g.indent, indentWidth) inc(g.indent, IndentWidth)
g.pendingNL = g.indent g.pendingNL = g.indent
g.lineLen = g.indent g.lineLen = g.indent
proc dedent(g: var TSrcGen) = proc dedent(g: var TSrcGen) =
dec(g.indent, indentWidth) dec(g.indent, IndentWidth)
assert(g.indent >= 0) assert(g.indent >= 0)
if g.pendingNL > indentWidth: if g.pendingNL > IndentWidth:
dec(g.pendingNL, indentWidth) dec(g.pendingNL, IndentWidth)
dec(g.lineLen, indentWidth) dec(g.lineLen, IndentWidth)
proc put(g: var TSrcGen, kind: TTokType, s: string) = proc put(g: var TSrcGen, kind: TTokType, s: string) =
addPendingNL(g) addPendingNL(g)
@ -269,7 +269,7 @@ proc gcom(g: var TSrcGen, n: PNode) =
if (g.pendingNL < 0) and (len(g.buf) > 0) and if (g.pendingNL < 0) and (len(g.buf) > 0) and
(g.lineLen < LineCommentColumn): (g.lineLen < LineCommentColumn):
var ml = maxLineLength(n.comment) var ml = maxLineLength(n.comment)
if ml + LineCommentColumn <= maxLineLen: if ml + LineCommentColumn <= MaxLineLen:
put(g, tkSpaces, repeatChar(LineCommentColumn - g.lineLen)) put(g, tkSpaces, repeatChar(LineCommentColumn - g.lineLen))
putComment(g, n.comment) #assert(g.comStack[high(g.comStack)] = n); putComment(g, n.comment) #assert(g.comStack[high(g.comStack)] = n);
@ -361,11 +361,11 @@ proc lsons(n: PNode, start: int = 0, theEnd: int = - 1): int =
proc lsub(n: PNode): int = proc lsub(n: PNode): int =
# computes the length of a tree # computes the length of a tree
if isNil(n): return 0 if isNil(n): return 0
if n.comment != nil: return maxLineLen + 1 if n.comment != nil: return MaxLineLen + 1
case n.kind case n.kind
of nkEmpty: result = 0 of nkEmpty: result = 0
of nkTripleStrLit: of nkTripleStrLit:
if containsNL(n.strVal): result = maxLineLen + 1 if containsNL(n.strVal): result = MaxLineLen + 1
else: result = len(atom(n)) else: result = len(atom(n))
of succ(nkEmpty)..pred(nkTripleStrLit), succ(nkTripleStrLit)..nkNilLit: of succ(nkEmpty)..pred(nkTripleStrLit), succ(nkTripleStrLit)..nkNilLit:
result = len(atom(n)) result = len(atom(n))
@ -437,7 +437,7 @@ proc lsub(n: PNode): int =
result = len("enum") result = len("enum")
of nkEnumFieldDef: result = lsons(n) + 3 of nkEnumFieldDef: result = lsons(n) + 3
of nkVarSection, nkLetSection: of nkVarSection, nkLetSection:
if sonsLen(n) > 1: result = maxLineLen + 1 if sonsLen(n) > 1: result = MaxLineLen + 1
else: result = lsons(n) + len("var_") else: result = lsons(n) + len("var_")
of nkReturnStmt: result = lsub(n.sons[0]) + len("return_") of nkReturnStmt: result = lsub(n.sons[0]) + len("return_")
of nkRaiseStmt: result = lsub(n.sons[0]) + len("raise_") of nkRaiseStmt: result = lsub(n.sons[0]) + len("raise_")
@ -458,10 +458,10 @@ proc lsub(n: PNode): int =
if n.sons[0].kind != nkEmpty: result = result + lsub(n.sons[0]) + 2 if n.sons[0].kind != nkEmpty: result = result + lsub(n.sons[0]) + 2
of nkExceptBranch: of nkExceptBranch:
result = lcomma(n, 0, -2) + lsub(lastSon(n)) + len("except_:_") result = lcomma(n, 0, -2) + lsub(lastSon(n)) + len("except_:_")
else: result = maxLineLen + 1 else: result = MaxLineLen + 1
proc fits(g: TSrcGen, x: int): bool = proc fits(g: TSrcGen, x: int): bool =
result = x + g.lineLen <= maxLineLen result = x + g.lineLen <= MaxLineLen
type type
TSubFlag = enum TSubFlag = enum
@ -500,7 +500,7 @@ proc gcommaAux(g: var TSrcGen, n: PNode, ind: int, start: int = 0,
for i in countup(start, sonsLen(n) + theEnd): for i in countup(start, sonsLen(n) + theEnd):
var c = i < sonsLen(n) + theEnd var c = i < sonsLen(n) + theEnd
var sublen = lsub(n.sons[i]) + ord(c) var sublen = lsub(n.sons[i]) + ord(c)
if not fits(g, sublen) and (ind + sublen < maxLineLen): optNL(g, ind) if not fits(g, sublen) and (ind + sublen < MaxLineLen): optNL(g, ind)
let oldLen = g.tokens.len let oldLen = g.tokens.len
gsub(g, n.sons[i]) gsub(g, n.sons[i])
if c: if c:
@ -514,21 +514,21 @@ proc gcomma(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
theEnd: int = - 1) = theEnd: int = - 1) =
var ind: int var ind: int
if rfInConstExpr in c.flags: if rfInConstExpr in c.flags:
ind = g.indent + indentWidth ind = g.indent + IndentWidth
else: else:
ind = g.lineLen ind = g.lineLen
if ind > maxLineLen div 2: ind = g.indent + longIndentWid if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
gcommaAux(g, n, ind, start, theEnd) gcommaAux(g, n, ind, start, theEnd)
proc gcomma(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) = proc gcomma(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
var ind = g.lineLen var ind = g.lineLen
if ind > maxLineLen div 2: ind = g.indent + longIndentWid if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
gcommaAux(g, n, ind, start, theEnd) gcommaAux(g, n, ind, start, theEnd)
proc gsemicolon(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) = proc gsemicolon(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) =
var ind = g.lineLen var ind = g.lineLen
if ind > maxLineLen div 2: ind = g.indent + longIndentWid if ind > MaxLineLen div 2: ind = g.indent + longIndentWid
gcommaAux(g, n, ind, start, theEnd, tkSemicolon) gcommaAux(g, n, ind, start, theEnd, tkSemiColon)
proc gsons(g: var TSrcGen, n: PNode, c: TContext, start: int = 0, proc gsons(g: var TSrcGen, n: PNode, c: TContext, start: int = 0,
theEnd: int = - 1) = theEnd: int = - 1) =
@ -551,7 +551,7 @@ proc longMode(n: PNode, start: int = 0, theEnd: int = - 1): bool =
if not result: if not result:
# check further # check further
for i in countup(start, sonsLen(n) + theEnd): for i in countup(start, sonsLen(n) + theEnd):
if (lsub(n.sons[i]) > maxLineLen): if (lsub(n.sons[i]) > MaxLineLen):
result = true result = true
break break
@ -576,7 +576,7 @@ proc gif(g: var TSrcGen, n: PNode) =
gsub(g, n.sons[0].sons[0]) gsub(g, n.sons[0].sons[0])
initContext(c) initContext(c)
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
if longMode(n) or (lsub(n.sons[0].sons[1]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[0].sons[1]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[0].sons[1], c) gstmts(g, n.sons[0].sons[1], c)
@ -591,7 +591,7 @@ proc gwhile(g: var TSrcGen, n: PNode) =
gsub(g, n.sons[0]) gsub(g, n.sons[0])
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
initContext(c) initContext(c)
if longMode(n) or (lsub(n.sons[1]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[1]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[1], c) gstmts(g, n.sons[1], c)
@ -600,7 +600,7 @@ proc gpattern(g: var TSrcGen, n: PNode) =
var c: TContext var c: TContext
put(g, tkCurlyLe, "{") put(g, tkCurlyLe, "{")
initContext(c) initContext(c)
if longMode(n) or (lsub(n.sons[0]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[0]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[0], c) gstmts(g, n.sons[0], c)
@ -611,7 +611,7 @@ proc gpragmaBlock(g: var TSrcGen, n: PNode) =
gsub(g, n.sons[0]) gsub(g, n.sons[0])
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
initContext(c) initContext(c)
if longMode(n) or (lsub(n.sons[1]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[1]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[1], c) gstmts(g, n.sons[1], c)
@ -621,7 +621,7 @@ proc gtry(g: var TSrcGen, n: PNode) =
put(g, tkTry, "try") put(g, tkTry, "try")
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
initContext(c) initContext(c)
if longMode(n) or (lsub(n.sons[0]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[0]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[0], c) gstmts(g, n.sons[0], c)
@ -634,7 +634,7 @@ proc gfor(g: var TSrcGen, n: PNode) =
initContext(c) initContext(c)
if longMode(n) or if longMode(n) or
(lsub(n.sons[length - 1]) + lsub(n.sons[length - 2]) + 6 + g.lineLen > (lsub(n.sons[length - 1]) + lsub(n.sons[length - 2]) + 6 + g.lineLen >
maxLineLen): MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcomma(g, n, c, 0, - 3) gcomma(g, n, c, 0, - 3)
put(g, tkSpaces, Space) put(g, tkSpaces, Space)
@ -649,7 +649,7 @@ proc gmacro(g: var TSrcGen, n: PNode) =
initContext(c) initContext(c)
gsub(g, n.sons[0]) gsub(g, n.sons[0])
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
if longMode(n) or (lsub(n.sons[1]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[1]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) gcoms(g)
gsons(g, n, c, 1) gsons(g, n, c, 1)
@ -709,7 +709,7 @@ proc gblock(g: var TSrcGen, n: PNode) =
else: else:
put(g, tkBlock, "block") put(g, tkBlock, "block")
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
if longMode(n) or (lsub(n.sons[1]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[1]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) gcoms(g)
# XXX I don't get why this is needed here! gstmts should already handle this! # XXX I don't get why this is needed here! gstmts should already handle this!
@ -722,7 +722,7 @@ proc gstaticStmt(g: var TSrcGen, n: PNode) =
putWithSpace(g, tkStatic, "static") putWithSpace(g, tkStatic, "static")
putWithSpace(g, tkColon, ":") putWithSpace(g, tkColon, ":")
initContext(c) initContext(c)
if longMode(n) or (lsub(n.sons[0]) + g.lineLen > maxLineLen): if longMode(n) or (lsub(n.sons[0]) + g.lineLen > MaxLineLen):
incl(c.flags, rfLongMode) incl(c.flags, rfLongMode)
gcoms(g) # a good place for comments gcoms(g) # a good place for comments
gstmts(g, n.sons[0], c) gstmts(g, n.sons[0], c)
@ -816,7 +816,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) =
put(g, tkParRi, ")") put(g, tkParRi, ")")
of nkStaticExpr: of nkStaticExpr:
put(g, tkStatic, "static") put(g, tkStatic, "static")
put(g, tkSpaces, space) put(g, tkSpaces, Space)
gsub(g, n.sons[0]) gsub(g, n.sons[0])
of nkBracketExpr: of nkBracketExpr:
gsub(g, n.sons[0]) gsub(g, n.sons[0])
@ -833,7 +833,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) =
gcomma(g, n, 1) gcomma(g, n, 1)
of nkCommand: of nkCommand:
gsub(g, n.sons[0]) gsub(g, n.sons[0])
put(g, tkSpaces, space) put(g, tkSpaces, Space)
gcomma(g, n, 1) gcomma(g, n, 1)
of nkExprEqExpr, nkAsgn, nkFastAsgn: of nkExprEqExpr, nkAsgn, nkFastAsgn:
gsub(g, n.sons[0]) gsub(g, n.sons[0])
@ -940,7 +940,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) =
of nkPrefix: of nkPrefix:
gsub(g, n.sons[0]) gsub(g, n.sons[0])
if n.len > 1: if n.len > 1:
put(g, tkSpaces, space) put(g, tkSpaces, Space)
if n.sons[1].kind == nkInfix: if n.sons[1].kind == nkInfix:
put(g, tkParLe, "(") put(g, tkParLe, "(")
gsub(g, n.sons[1]) gsub(g, n.sons[1])

View file

@ -696,7 +696,7 @@ proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType =
# load the type: # load the type:
var oldPos = r.pos var oldPos = r.pos
var d = iiTableGet(r.index.tab, id) var d = iiTableGet(r.index.tab, id)
if d == invalidKey: internalError(info, "rrGetType") if d == InvalidKey: internalError(info, "rrGetType")
r.pos = d + r.dataIdx r.pos = d + r.dataIdx
result = decodeType(r, info) result = decodeType(r, info)
r.pos = oldPos r.pos = oldPos
@ -726,7 +726,7 @@ proc findSomeWhere(id: int) =
var rd = gMods[i].rd var rd = gMods[i].rd
if rd != nil: if rd != nil:
var d = iiTableGet(rd.index.tab, id) var d = iiTableGet(rd.index.tab, id)
if d != invalidKey: if d != InvalidKey:
echo "found id ", id, " in ", gMods[i].filename echo "found id ", id, " in ", gMods[i].filename
proc getReader(moduleId: int): PRodReader = proc getReader(moduleId: int): PRodReader =
@ -744,7 +744,7 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym =
if result == nil: if result == nil:
# load the symbol: # load the symbol:
var d = iiTableGet(r.index.tab, id) var d = iiTableGet(r.index.tab, id)
if d == invalidKey: if d == InvalidKey:
# import from other module: # import from other module:
var moduleID = iiTableGet(r.imports.tab, id) var moduleID = iiTableGet(r.imports.tab, id)
if moduleID < 0: if moduleID < 0:
@ -753,7 +753,7 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym =
internalError(info, "missing from both indexes: +" & x) internalError(info, "missing from both indexes: +" & x)
var rd = getReader(moduleID) var rd = getReader(moduleID)
d = iiTableGet(rd.index.tab, id) d = iiTableGet(rd.index.tab, id)
if d != invalidKey: if d != InvalidKey:
result = decodeSymSafePos(rd, d, info) result = decodeSymSafePos(rd, d, info)
else: else:
var x = "" var x = ""
@ -800,7 +800,7 @@ proc loadMethods(r: PRodReader) =
if r.s[r.pos] == ' ': inc(r.pos) if r.s[r.pos] == ' ': inc(r.pos)
proc getCRC*(fileIdx: int32): TCrc32 = proc getCRC*(fileIdx: int32): TCrc32 =
InternalAssert fileIdx >= 0 and fileIdx < gMods.len internalAssert fileIdx >= 0 and fileIdx < gMods.len
if gMods[fileIdx].crcDone: if gMods[fileIdx].crcDone:
return gMods[fileIdx].crc return gMods[fileIdx].crc
@ -875,7 +875,7 @@ proc rawLoadStub(s: PSym) =
var rd = gMods[s.position].rd var rd = gMods[s.position].rd
var theId = s.id # used for later check var theId = s.id # used for later check
var d = iiTableGet(rd.index.tab, s.id) var d = iiTableGet(rd.index.tab, s.id)
if d == invalidKey: internalError("loadStub: invalid key") if d == InvalidKey: internalError("loadStub: invalid key")
var rs = decodeSymSafePos(rd, d, unknownLineInfo()) var rs = decodeSymSafePos(rd, d, unknownLineInfo())
if rs != s: if rs != s:
#echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2), #echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2),

View file

@ -101,12 +101,12 @@ proc addInclDep(w: PRodWriter, dep: string) =
proc pushType(w: PRodWriter, t: PType) = proc pushType(w: PRodWriter, t: PType) =
# check so that the stack does not grow too large: # check so that the stack does not grow too large:
if iiTableGet(w.index.tab, t.id) == invalidKey: if iiTableGet(w.index.tab, t.id) == InvalidKey:
w.tstack.add(t) w.tstack.add(t)
proc pushSym(w: PRodWriter, s: PSym) = proc pushSym(w: PRodWriter, s: PSym) =
# check so that the stack does not grow too large: # check so that the stack does not grow too large:
if iiTableGet(w.index.tab, s.id) == invalidKey: if iiTableGet(w.index.tab, s.id) == InvalidKey:
w.sstack.add(s) w.sstack.add(s)
proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode,
@ -336,7 +336,7 @@ proc symStack(w: PRodWriter): int =
if sfForward in s.flags: if sfForward in s.flags:
w.sstack[result] = s w.sstack[result] = s
inc result inc result
elif iiTableGet(w.index.tab, s.id) == invalidKey: elif iiTableGet(w.index.tab, s.id) == InvalidKey:
var m = getModule(s) var m = getModule(s)
if m == nil: internalError("symStack: module nil: " & s.name.s) if m == nil: internalError("symStack: module nil: " & s.name.s)
if (m.id == w.module.id) or (sfFromGeneric in s.flags): if (m.id == w.module.id) or (sfFromGeneric in s.flags):
@ -364,7 +364,7 @@ proc symStack(w: PRodWriter): int =
if s.kind == skMethod and sfDispatcher notin s.flags: if s.kind == skMethod and sfDispatcher notin s.flags:
if w.methods.len != 0: add(w.methods, ' ') if w.methods.len != 0: add(w.methods, ' ')
encodeVInt(s.id, w.methods) encodeVInt(s.id, w.methods)
elif iiTableGet(w.imports.tab, s.id) == invalidKey: elif iiTableGet(w.imports.tab, s.id) == InvalidKey:
addToIndex(w.imports, s.id, m.id) addToIndex(w.imports, s.id, m.id)
when debugWrittenIds: when debugWrittenIds:
if not Contains(debugWritten, s.id): if not Contains(debugWritten, s.id):
@ -383,7 +383,7 @@ proc typeStack(w: PRodWriter): int =
if t.kind == tyForward: if t.kind == tyForward:
w.tstack[result] = t w.tstack[result] = t
inc result inc result
elif iiTableGet(w.index.tab, t.id) == invalidKey: elif iiTableGet(w.index.tab, t.id) == InvalidKey:
var L = w.data.len var L = w.data.len
addToIndex(w.index, t.id, L) addToIndex(w.index, t.id, L)
encodeType(w, t, w.data) encodeType(w, t, w.data)

View file

@ -157,7 +157,7 @@ proc toRope(s: string): PRope =
result = nil result = nil
else: else:
result = insertInCache(s) result = insertInCache(s)
assert(RopeInvariant(result)) assert(ropeInvariant(result))
proc ropeSeqInsert(rs: var TRopeSeq, r: PRope, at: Natural) = proc ropeSeqInsert(rs: var TRopeSeq, r: PRope, at: Natural) =
var length = len(rs) var length = len(rs)
@ -280,7 +280,7 @@ proc ropef(frmt: TFormatStr, args: varargs[PRope]): PRope =
else: break else: break
if i - 1 >= start: if i - 1 >= start:
app(result, substr(frmt, start, i - 1)) app(result, substr(frmt, start, i - 1))
assert(RopeInvariant(result)) assert(ropeInvariant(result))
{.push stack_trace: off, line_trace: off.} {.push stack_trace: off, line_trace: off.}
proc `~`*(r: expr[string]): PRope = proc `~`*(r: expr[string]): PRope =
@ -313,7 +313,7 @@ proc ropeEqualsFile(r: PRope, f: string): bool =
result = open(bin, f) result = open(bin, f)
if not result: if not result:
return # not equal if file does not exist return # not equal if file does not exist
var buf = alloc(BufSize) var buf = alloc(bufSize)
result = auxRopeEqualsFile(r, bin, buf) result = auxRopeEqualsFile(r, bin, buf)
if result: if result:
result = readBuffer(bin, buf, bufSize) == 0 # really at the end of file? result = readBuffer(bin, buf, bufSize) == 0 # really at the end of file?
@ -346,7 +346,7 @@ proc newCrcFromRopeAux(r: PRope, startVal: TCrc32): TCrc32 =
inc(i) inc(i)
proc crcFromRope(r: PRope): TCrc32 = proc crcFromRope(r: PRope): TCrc32 =
result = newCrcFromRopeAux(r, initCrc32) result = newCrcFromRopeAux(r, InitCrc32)
proc writeRopeIfNotEqual(r: PRope, filename: string): bool = proc writeRopeIfNotEqual(r: PRope, filename: string): bool =
# returns true if overwritten # returns true if overwritten

View file

@ -134,8 +134,8 @@ proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym =
# like newSymS, but considers gensym'ed symbols # like newSymS, but considers gensym'ed symbols
if n.kind == nkSym: if n.kind == nkSym:
result = n.sym result = n.sym
InternalAssert sfGenSym in result.flags internalAssert sfGenSym in result.flags
InternalAssert result.kind == kind internalAssert result.kind == kind
else: else:
result = newSym(kind, considerAcc(n), getCurrOwner(), n.info) result = newSym(kind, considerAcc(n), getCurrOwner(), n.info)

View file

@ -139,7 +139,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode,
let overloadsState = result.state let overloadsState = result.state
if overloadsState != csMatch: if overloadsState != csMatch:
if nfDelegate in n.flags: if nfDelegate in n.flags:
InternalAssert f.kind == nkIdent internalAssert f.kind == nkIdent
let calleeName = newStrNode(nkStrLit, f.ident.s) let calleeName = newStrNode(nkStrLit, f.ident.s)
calleeName.info = n.info calleeName.info = n.info

View file

@ -198,15 +198,15 @@ proc addToLib(lib: PLib, sym: PSym) =
proc makePtrType(c: PContext, baseType: PType): PType = proc makePtrType(c: PContext, baseType: PType): PType =
result = newTypeS(tyPtr, c) result = newTypeS(tyPtr, c)
addSonSkipIntLit(result, baseType.AssertNotNil) addSonSkipIntLit(result, baseType.assertNotNil)
proc makeVarType(c: PContext, baseType: PType): PType = proc makeVarType(c: PContext, baseType: PType): PType =
result = newTypeS(tyVar, c) result = newTypeS(tyVar, c)
addSonSkipIntLit(result, baseType.AssertNotNil) addSonSkipIntLit(result, baseType.assertNotNil)
proc makeTypeDesc*(c: PContext, typ: PType): PType = proc makeTypeDesc*(c: PContext, typ: PType): PType =
result = newTypeS(tyTypeDesc, c) result = newTypeS(tyTypeDesc, c)
result.addSonSkipIntLit(typ.AssertNotNil) result.addSonSkipIntLit(typ.assertNotNil)
proc makeTypeSymNode*(c: PContext, typ: PType, info: TLineInfo): PNode = proc makeTypeSymNode*(c: PContext, typ: PType, info: TLineInfo): PNode =
let typedesc = makeTypeDesc(c, typ) let typedesc = makeTypeDesc(c, typ)

View file

@ -658,7 +658,7 @@ proc semStaticExpr(c: PContext, n: PNode): PNode =
proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode,
flags: TExprFlags): PNode = flags: TExprFlags): PNode =
if flags*{efInTypeOf, efWantIterator} != {}: if flags*{efInTypeof, efWantIterator} != {}:
# consider: 'for x in pReturningArray()' --> we don't want the restriction # consider: 'for x in pReturningArray()' --> we don't want the restriction
# to 'skIterator' anymore; skIterator is preferred in sigmatch already for # to 'skIterator' anymore; skIterator is preferred in sigmatch already for
# typeof support. # typeof support.
@ -702,7 +702,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode =
semOpAux(c, n) semOpAux(c, n)
var t: PType = nil var t: PType = nil
if n.sons[0].typ != nil: if n.sons[0].typ != nil:
t = skipTypes(n.sons[0].typ, abstractInst-{tyTypedesc}) t = skipTypes(n.sons[0].typ, abstractInst-{tyTypeDesc})
if t != nil and t.kind == tyProc: if t != nil and t.kind == tyProc:
# This is a proc variable, apply normal overload resolution # This is a proc variable, apply normal overload resolution
var m: TCandidate var m: TCandidate
@ -964,10 +964,10 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
if f != nil: if f != nil:
if fieldVisible(c, f): if fieldVisible(c, f):
# is the access to a public field or in the same module or in a friend? # is the access to a public field or in the same module or in a friend?
markUsed(n.sons[1], f)
n.sons[0] = makeDeref(n.sons[0]) n.sons[0] = makeDeref(n.sons[0])
n.sons[1] = newSymNode(f) # we now have the correct field n.sons[1] = newSymNode(f) # we now have the correct field
n.typ = f.typ n.typ = f.typ
markUsed(n, f)
if check == nil: if check == nil:
result = n result = n
else: else:
@ -977,11 +977,11 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode =
elif ty.kind == tyTuple and ty.n != nil: elif ty.kind == tyTuple and ty.n != nil:
f = getSymFromList(ty.n, i) f = getSymFromList(ty.n, i)
if f != nil: if f != nil:
markUsed(n.sons[1], f)
n.sons[0] = makeDeref(n.sons[0]) n.sons[0] = makeDeref(n.sons[0])
n.sons[1] = newSymNode(f) n.sons[1] = newSymNode(f)
n.typ = f.typ n.typ = f.typ
result = n result = n
markUsed(n, f)
proc dotTransformation(c: PContext, n: PNode): PNode = proc dotTransformation(c: PContext, n: PNode): PNode =
if isSymChoice(n.sons[1]): if isSymChoice(n.sons[1]):
@ -1164,7 +1164,7 @@ proc semAsgn(c: PContext, n: PNode): PNode =
n.typ = enforceVoidContext n.typ = enforceVoidContext
if lhs.sym.typ.kind == tyGenericParam: if lhs.sym.typ.kind == tyGenericParam:
if matchTypeClass(lhs.typ, rhs.typ): if matchTypeClass(lhs.typ, rhs.typ):
InternalAssert c.p.resultSym != nil internalAssert c.p.resultSym != nil
lhs.typ = rhs.typ lhs.typ = rhs.typ
c.p.resultSym.typ = rhs.typ c.p.resultSym.typ = rhs.typ
c.p.owner.typ.sons[0] = rhs.typ c.p.owner.typ.sons[0] = rhs.typ
@ -1356,7 +1356,7 @@ proc semUsing(c: PContext, n: PNode): PNode =
of skProcKinds: of skProcKinds:
addDeclAt(c.currentScope, usedSym.sym) addDeclAt(c.currentScope, usedSym.sym)
continue continue
else: nil else: discard
localError(e.info, errUsingNoSymbol, e.renderTree) localError(e.info, errUsingNoSymbol, e.renderTree)
@ -1372,7 +1372,7 @@ proc semExpandToAst(c: PContext, n: PNode): PNode =
macroCall.sons[i] = semExprWithType(c, macroCall[i], {}) macroCall.sons[i] = semExprWithType(c, macroCall[i], {})
# Preserve the magic symbol in order to be handled in evals.nim # Preserve the magic symbol in order to be handled in evals.nim
InternalAssert n.sons[0].sym.magic == mExpandToAst internalAssert n.sons[0].sym.magic == mExpandToAst
n.typ = getSysSym("PNimrodNode").typ # expandedSym.getReturnType n.typ = getSysSym("PNimrodNode").typ # expandedSym.getReturnType
result = n result = n
@ -1409,7 +1409,7 @@ proc processQuotations(n: var PNode, op: string,
processQuotations(n.sons[i], op, quotes, ids) processQuotations(n.sons[i], op, quotes, ids)
proc semQuoteAst(c: PContext, n: PNode): PNode = proc semQuoteAst(c: PContext, n: PNode): PNode =
InternalAssert n.len == 2 or n.len == 3 internalAssert n.len == 2 or n.len == 3
# We transform the do block into a template with a param for # We transform the do block into a template with a param for
# each interpolation. We'll pass this template to getAst. # each interpolation. We'll pass this template to getAst.
var var

View file

@ -132,7 +132,7 @@ proc sideEffectsCheck(c: PContext, s: PSym) =
c.threadEntries.add(s) c.threadEntries.add(s)
proc lateInstantiateGeneric(c: PContext, invocation: PType, info: TLineInfo): PType = proc lateInstantiateGeneric(c: PContext, invocation: PType, info: TLineInfo): PType =
InternalAssert invocation.kind == tyGenericInvokation internalAssert invocation.kind == tyGenericInvokation
let cacheHit = searchInstTypes(invocation) let cacheHit = searchInstTypes(invocation)
if cacheHit != nil: if cacheHit != nil:

View file

@ -26,7 +26,7 @@ proc semInstantiationInfo(c: PContext, n: PNode): PNode =
let useFullPaths = expectIntLit(c, n.sons[2]) let useFullPaths = expectIntLit(c, n.sons[2])
let info = getInfoContext(idx) let info = getInfoContext(idx)
var filename = newNodeIT(nkStrLit, n.info, getSysType(tyString)) var filename = newNodeIT(nkStrLit, n.info, getSysType(tyString))
filename.strVal = if useFullPaths != 0: info.toFullPath else: info.ToFilename filename.strVal = if useFullPaths != 0: info.toFullPath else: info.toFilename
var line = newNodeIT(nkIntLit, n.info, getSysType(tyInt)) var line = newNodeIT(nkIntLit, n.info, getSysType(tyInt))
line.intVal = toLinenumber(info) line.intVal = toLinenumber(info)
result.add(filename) result.add(filename)

View file

@ -305,7 +305,7 @@ proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) =
if n.kind == nkAddr: if n.kind == nkAddr:
# addr(x[]) can't be proven, but addr(x) can: # addr(x[]) can't be proven, but addr(x) can:
if not containsNode(n, {nkDerefExpr, nkHiddenDeref}): return if not containsNode(n, {nkDerefExpr, nkHiddenDeref}): return
elif n.kind == nkSym and n.sym.kind in RoutineKinds: elif n.kind == nkSym and n.sym.kind in routineKinds:
# 'p' is not nil obviously: # 'p' is not nil obviously:
return return
case impliesNotNil(tracked.guards, n) case impliesNotNil(tracked.guards, n)
@ -319,7 +319,7 @@ proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) =
proc trackOperand(tracked: PEffects, n: PNode, paramType: PType) = proc trackOperand(tracked: PEffects, n: PNode, paramType: PType) =
let op = n.typ let op = n.typ
if op != nil and op.kind == tyProc and n.kind != nkNilLit: if op != nil and op.kind == tyProc and n.kind != nkNilLit:
InternalAssert op.n.sons[0].kind == nkEffectList internalAssert op.n.sons[0].kind == nkEffectList
var effectList = op.n.sons[0] var effectList = op.n.sons[0]
let s = n.skipConv let s = n.skipConv
if s.kind == nkSym and s.sym.kind in routineKinds: if s.kind == nkSym and s.sym.kind in routineKinds:
@ -568,13 +568,13 @@ proc checkMethodEffects*(disp, branch: PSym) =
proc setEffectsForProcType*(t: PType, n: PNode) = proc setEffectsForProcType*(t: PType, n: PNode) =
var effects = t.n.sons[0] var effects = t.n.sons[0]
InternalAssert t.kind == tyProc and effects.kind == nkEffectList internalAssert t.kind == tyProc and effects.kind == nkEffectList
let let
raisesSpec = effectSpec(n, wRaises) raisesSpec = effectSpec(n, wRaises)
tagsSpec = effectSpec(n, wTags) tagsSpec = effectSpec(n, wTags)
if not isNil(raisesSpec) or not isNil(tagsSpec): if not isNil(raisesSpec) or not isNil(tagsSpec):
InternalAssert effects.len == 0 internalAssert effects.len == 0
newSeq(effects.sons, effectListLen) newSeq(effects.sons, effectListLen)
if not isNil(raisesSpec): if not isNil(raisesSpec):
effects.sons[exceptionEffects] = raisesSpec effects.sons[exceptionEffects] = raisesSpec
@ -583,7 +583,7 @@ proc setEffectsForProcType*(t: PType, n: PNode) =
proc trackProc*(s: PSym, body: PNode) = proc trackProc*(s: PSym, body: PNode) =
var effects = s.typ.n.sons[0] var effects = s.typ.n.sons[0]
InternalAssert effects.kind == nkEffectList internalAssert effects.kind == nkEffectList
# effects already computed? # effects already computed?
if sfForward in s.flags: return if sfForward in s.flags: return
if effects.len == effectListLen: return if effects.len == effectListLen: return

View file

@ -70,7 +70,7 @@ proc toCover(t: PType): BiggestInt =
proc performProcvarCheck(c: PContext, n: PNode, s: PSym) = proc performProcvarCheck(c: PContext, n: PNode, s: PSym) =
var smoduleId = getModule(s).id var smoduleId = getModule(s).id
if sfProcVar notin s.flags and s.typ.callConv == ccDefault and if sfProcvar notin s.flags and s.typ.callConv == ccDefault and
smoduleId != c.module.id and smoduleId != c.friendModule.id: smoduleId != c.module.id and smoduleId != c.friendModule.id:
localError(n.info, errXCannotBePassedToProcVar, s.name.s) localError(n.info, errXCannotBePassedToProcVar, s.name.s)
@ -788,8 +788,8 @@ proc typeSectionFinalPass(c: PContext, n: PNode) =
# give anonymous object a dummy symbol: # give anonymous object a dummy symbol:
var st = s.typ var st = s.typ
if st.kind == tyGenericBody: st = st.lastSon if st.kind == tyGenericBody: st = st.lastSon
InternalAssert st.kind in {tyPtr, tyRef} internalAssert st.kind in {tyPtr, tyRef}
InternalAssert st.sons[0].sym == nil internalAssert st.sons[0].sym == nil
st.sons[0].sym = newSym(skType, getIdent(s.name.s & ":ObjectType"), st.sons[0].sym = newSym(skType, getIdent(s.name.s & ":ObjectType"),
getCurrOwner(), s.info) getCurrOwner(), s.info)
@ -887,7 +887,7 @@ proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode =
illFormedAst(n) # process parameters: illFormedAst(n) # process parameters:
if n.sons[paramsPos].kind != nkEmpty: if n.sons[paramsPos].kind != nkEmpty:
var gp = newNodeI(nkGenericParams, n.info) var gp = newNodeI(nkGenericParams, n.info)
semParamList(c, n.sons[ParamsPos], gp, s) semParamList(c, n.sons[paramsPos], gp, s)
paramsTypeCheck(c, s.typ) paramsTypeCheck(c, s.typ)
else: else:
s.typ = newTypeS(tyProc, c) s.typ = newTypeS(tyProc, c)
@ -939,7 +939,7 @@ type
stepCompileBody stepCompileBody
proc isForwardDecl(s: PSym): bool = proc isForwardDecl(s: PSym): bool =
InternalAssert s.kind == skProc internalAssert s.kind == skProc
result = s.ast[bodyPos].kind != nkEmpty result = s.ast[bodyPos].kind != nkEmpty
proc semProcAux(c: PContext, n: PNode, kind: TSymKind, proc semProcAux(c: PContext, n: PNode, kind: TSymKind,
@ -982,7 +982,7 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind,
gp = newNodeI(nkGenericParams, n.info) gp = newNodeI(nkGenericParams, n.info)
# process parameters: # process parameters:
if n.sons[paramsPos].kind != nkEmpty: if n.sons[paramsPos].kind != nkEmpty:
semParamList(c, n.sons[ParamsPos], gp, s) semParamList(c, n.sons[paramsPos], gp, s)
if sonsLen(gp) > 0: if sonsLen(gp) > 0:
if n.sons[genericParamsPos].kind == nkEmpty: if n.sons[genericParamsPos].kind == nkEmpty:
# we have a list of implicit type parameters: # we have a list of implicit type parameters:

View file

@ -36,7 +36,7 @@ proc symBinding(n: PNode): TSymBinding =
var key = if it.kind == nkExprColonExpr: it.sons[0] else: it var key = if it.kind == nkExprColonExpr: it.sons[0] else: it
if key.kind == nkIdent: if key.kind == nkIdent:
case whichKeyword(key.ident) case whichKeyword(key.ident)
of wGenSym: return spGenSym of wGensym: return spGenSym
of wInject: return spInject of wInject: return spInject
else: nil else: nil
@ -435,7 +435,7 @@ proc semTemplateDef(c: PContext, n: PNode): PNode =
gp = newNodeI(nkGenericParams, n.info) gp = newNodeI(nkGenericParams, n.info)
# process parameters: # process parameters:
if n.sons[paramsPos].kind != nkEmpty: if n.sons[paramsPos].kind != nkEmpty:
semParamList(c, n.sons[ParamsPos], gp, s) semParamList(c, n.sons[paramsPos], gp, s)
if sonsLen(gp) > 0: if sonsLen(gp) > 0:
if n.sons[genericParamsPos].kind == nkEmpty: if n.sons[genericParamsPos].kind == nkEmpty:
# we have a list of implicit type parameters: # we have a list of implicit type parameters:

View file

@ -50,13 +50,13 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType =
of tyTuple: of tyTuple:
if sonsLen(v) == 2: if sonsLen(v) == 2:
strVal = v.sons[1] # second tuple part is the string value strVal = v.sons[1] # second tuple part is the string value
if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCstring}: if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCString}:
x = getOrdValue(v.sons[0]) # first tuple part is the ordinal x = getOrdValue(v.sons[0]) # first tuple part is the ordinal
else: else:
localError(strVal.info, errStringLiteralExpected) localError(strVal.info, errStringLiteralExpected)
else: else:
localError(v.info, errWrongNumberOfVariables) localError(v.info, errWrongNumberOfVariables)
of tyString, tyCstring: of tyString, tyCString:
strVal = v strVal = v
x = counter x = counter
else: else:
@ -148,7 +148,7 @@ proc semDistinct(c: PContext, n: PNode, prev: PType): PType =
result = newConstraint(c, tyDistinct) result = newConstraint(c, tyDistinct)
proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = proc semRangeAux(c: PContext, n: PNode, prev: PType): PType =
assert IsRange(n) assert isRange(n)
checkSonsLen(n, 3) checkSonsLen(n, 3)
result = newOrPrevType(tyRange, prev, c) result = newOrPrevType(tyRange, prev, c)
result.n = newNodeI(nkRange, n.info) result.n = newNodeI(nkRange, n.info)
@ -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
@ -331,7 +331,7 @@ proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode,
of skVar: pragma(c, result, n.sons[1], varPragmas) of skVar: pragma(c, result, n.sons[1], varPragmas)
of skLet: pragma(c, result, n.sons[1], letPragmas) of skLet: pragma(c, result, n.sons[1], letPragmas)
of skConst: pragma(c, result, n.sons[1], constPragmas) of skConst: pragma(c, result, n.sons[1], constPragmas)
else: nil else: discard
else: else:
result = semIdentVis(c, kind, n, allowed) result = semIdentVis(c, kind, n, allowed)
@ -970,7 +970,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType =
result = newOrPrevType(tyError, prev, c) result = newOrPrevType(tyError, prev, c)
elif s.kind == skParam and s.typ.kind == tyTypeDesc: elif s.kind == skParam and s.typ.kind == tyTypeDesc:
assert s.typ.len > 0 assert s.typ.len > 0
InternalAssert prev == nil internalAssert prev == nil
result = s.typ.sons[0] result = s.typ.sons[0]
elif prev == nil: elif prev == nil:
result = s.typ result = s.typ

View file

@ -33,7 +33,7 @@ proc checkConstructedType*(info: TLineInfo, typ: PType) =
proc searchInstTypes*(key: PType): PType = proc searchInstTypes*(key: PType): PType =
let genericTyp = key.sons[0] let genericTyp = key.sons[0]
InternalAssert genericTyp.kind == tyGenericBody and internalAssert genericTyp.kind == tyGenericBody and
key.sons[0] == genericTyp and key.sons[0] == genericTyp and
genericTyp.sym != nil genericTyp.sym != nil

View file

@ -36,7 +36,7 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) =
parseopt.next(p) parseopt.next(p)
case p.kind case p.kind
of cmdEnd: break of cmdEnd: break
of cmdLongOption, cmdShortOption: of cmdLongoption, cmdShortOption:
# hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off") # hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off")
# we fix this here # we fix this here
var bracketLe = strutils.find(p.key, '[') var bracketLe = strutils.find(p.key, '[')

View file

@ -86,7 +86,7 @@ proc initCandidate*(c: var TCandidate, callee: PSym, binding: PNode,
c.calleeScope = calleeScope c.calleeScope = calleeScope
initIdTable(c.bindings) initIdTable(c.bindings)
c.errors = nil c.errors = nil
if binding != nil and callee.kind in RoutineKinds: if binding != nil and callee.kind in routineKinds:
var typeParams = callee.ast[genericParamsPos] var typeParams = callee.ast[genericParamsPos]
for i in 1..min(sonsLen(typeParams), sonsLen(binding)-1): for i in 1..min(sonsLen(typeParams), sonsLen(binding)-1):
var formalTypeParam = typeParams.sons[i-1].typ var formalTypeParam = typeParams.sons[i-1].typ
@ -716,7 +716,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation =
if f.sons == nil or f.sons.len == 0: if f.sons == nil or f.sons.len == 0:
result = isGeneric result = isGeneric
else: else:
InternalAssert a.sons != nil and a.sons.len > 0 internalAssert a.sons != nil and a.sons.len > 0
c.typedescMatched = true c.typedescMatched = true
result = typeRel(c, f.sons[0], a.sons[0]) result = typeRel(c, f.sons[0], a.sons[0])
else: else:
@ -752,7 +752,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation =
else: else:
result = isNone result = isNone
else: else:
InternalAssert prev.sonsLen == 1 internalAssert prev.sonsLen == 1
let toMatch = if tfUnresolved in f.flags: a let toMatch = if tfUnresolved in f.flags: a
else: a.sons[0] else: a.sons[0]
result = typeRel(c, prev.sons[0], toMatch) result = typeRel(c, prev.sons[0], toMatch)
@ -825,7 +825,7 @@ proc localConvMatch(c: PContext, m: var TCandidate, f, a: PType,
var call = newNodeI(nkCall, arg.info) var call = newNodeI(nkCall, arg.info)
call.add(f.n.copyTree) call.add(f.n.copyTree)
call.add(arg.copyTree) call.add(arg.copyTree)
result = c.semOverloadedCall(c, call, call, RoutineKinds) result = c.semOverloadedCall(c, call, call, routineKinds)
if result != nil: if result != nil:
# resulting type must be consistent with the other arguments: # resulting type must be consistent with the other arguments:
var r = typeRel(m, f.sons[0], result.typ) var r = typeRel(m, f.sons[0], result.typ)
@ -867,7 +867,7 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate,
dummyName = param dummyName = param
dummyType = a dummyType = a
InternalAssert dummyName.kind == nkIdent internalAssert dummyName.kind == nkIdent
var dummyParam = newSym(skType, dummyName.ident, f.sym, f.sym.info) var dummyParam = newSym(skType, dummyName.ident, f.sym, f.sym.info)
dummyParam.typ = dummyType dummyParam.typ = dummyType
addDecl(c, dummyParam) addDecl(c, dummyParam)
@ -904,7 +904,7 @@ proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType,
r = isGeneric r = isGeneric
else: else:
if a.kind == tyExpr: if a.kind == tyExpr:
InternalAssert a.len > 0 internalAssert a.len > 0
r = typeRel(m, f.lastSon, a.lastSon) r = typeRel(m, f.lastSon, a.lastSon)
else: else:
let match = matchTypeClass(m.bindings, fMaybeExpr, a) let match = matchTypeClass(m.bindings, fMaybeExpr, a)
@ -1156,7 +1156,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode,
# unnamed param # unnamed param
if f >= formalLen: if f >= formalLen:
# too many arguments? # too many arguments?
if tfVarArgs in m.callee.flags: if tfVarargs in m.callee.flags:
# is ok... but don't increment any counters... # is ok... but don't increment any counters...
# we have no formal here to snoop at: # we have no formal here to snoop at:
n.sons[a] = prepareOperand(c, n.sons[a]) n.sons[a] = prepareOperand(c, n.sons[a])

View file

@ -203,7 +203,7 @@ const
CallNodes = {nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit} CallNodes = {nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit}
proc findClosestCall(n: PNode): PNode = proc findClosestCall(n: PNode): PNode =
if n.kind in callNodes and msgs.inCheckpoint(n.info) == cpExact: if n.kind in CallNodes and msgs.inCheckpoint(n.info) == cpExact:
result = n result = n
else: else:
for i in 0.. <safeLen(n): for i in 0.. <safeLen(n):
@ -327,7 +327,7 @@ proc markUsed(n: PNode, s: PSym) =
if sfDeprecated in s.flags: message(n.info, warnDeprecated, s.name.s) if sfDeprecated in s.flags: message(n.info, warnDeprecated, s.name.s)
if sfError in s.flags: localError(n.info, errWrongSymbolX, s.name.s) if sfError in s.flags: localError(n.info, errWrongSymbolX, s.name.s)
suggestSym(n, s) suggestSym(n, s)
if gCmd == cmdPretty: checkUse(n) if gCmd == cmdPretty: checkUse(n, s)
proc useSym*(sym: PSym): PNode = proc useSym*(sym: PSym): PNode =
result = newSymNode(sym) result = newSymNode(sym)

View file

@ -83,7 +83,7 @@ proc utf8Bom(s: string): int =
proc containsShebang(s: string, i: int): bool = proc containsShebang(s: string, i: int): bool =
if (s[i] == '#') and (s[i + 1] == '!'): if (s[i] == '#') and (s[i + 1] == '!'):
var j = i + 2 var j = i + 2
while s[j] in WhiteSpace: inc(j) while s[j] in Whitespace: inc(j)
result = s[j] == '/' result = s[j] == '/'
proc parsePipe(filename: string, inputStream: PLLStream): PNode = proc parsePipe(filename: string, inputStream: PLLStream): PNode =
@ -98,7 +98,7 @@ proc parsePipe(filename: string, inputStream: PLLStream): PNode =
i = 0 i = 0
if line[i] == '#' and line[i+1] == '!': if line[i] == '#' and line[i+1] == '!':
inc(i, 2) inc(i, 2)
while line[i] in WhiteSpace: inc(i) while line[i] in Whitespace: inc(i)
var q: TParser var q: TParser
openParser(q, filename, llStreamOpen(substr(line, i))) openParser(q, filename, llStreamOpen(substr(line, i)))
result = parser.parseAll(q) result = parser.parseAll(q)

View file

@ -142,7 +142,7 @@ proc transformVarSection(c: PTransf, v: PNode): PTransNode =
result[i] = PTransNode(it) result[i] = PTransNode(it)
elif it.kind == nkIdentDefs: elif it.kind == nkIdentDefs:
if it.sons[0].kind != nkSym: internalError(it.info, "transformVarSection") if it.sons[0].kind != nkSym: internalError(it.info, "transformVarSection")
InternalAssert(it.len == 3) internalAssert(it.len == 3)
var newVar = copySym(it.sons[0].sym) var newVar = copySym(it.sons[0].sym)
incl(newVar.flags, sfFromGeneric) incl(newVar.flags, sfFromGeneric)
# fixes a strange bug for rodgen: # fixes a strange bug for rodgen:
@ -152,7 +152,7 @@ proc transformVarSection(c: PTransf, v: PNode): PTransNode =
var defs = newTransNode(nkIdentDefs, it.info, 3) var defs = newTransNode(nkIdentDefs, it.info, 3)
if importantComments(): if importantComments():
# keep documentation information: # keep documentation information:
pnode(defs).comment = it.comment PNode(defs).comment = it.comment
defs[0] = newSymNode(newVar).PTransNode defs[0] = newSymNode(newVar).PTransNode
defs[1] = it.sons[1].PTransNode defs[1] = it.sons[1].PTransNode
defs[2] = transform(c, it.sons[2]) defs[2] = transform(c, it.sons[2])
@ -186,7 +186,7 @@ proc transformConstSection(c: PTransf, v: PNode): PTransNode =
var b = newNodeI(nkConstDef, it.info) var b = newNodeI(nkConstDef, it.info)
addSon(b, it[0]) addSon(b, it[0])
addSon(b, ast.emptyNode) # no type description addSon(b, ast.emptyNode) # no type description
addSon(b, transform(c, it[2]).pnode) addSon(b, transform(c, it[2]).PNode)
result[i] = PTransNode(b) result[i] = PTransNode(b)
else: else:
result[i] = PTransNode(it) result[i] = PTransNode(it)
@ -217,7 +217,7 @@ proc transformBlock(c: PTransf, n: PNode): PTransNode =
proc transformBreak(c: PTransf, n: PNode): PTransNode = proc transformBreak(c: PTransf, n: PNode): PTransNode =
if c.inLoop > 0 or n.sons[0].kind != nkEmpty: if c.inLoop > 0 or n.sons[0].kind != nkEmpty:
result = n.ptransNode result = n.PTransNode
else: else:
let labl = c.breakSyms[c.breakSyms.high] let labl = c.breakSyms[c.breakSyms.high]
result = transformSons(c, n) result = transformSons(c, n)
@ -292,11 +292,11 @@ proc transformYield(c: PTransf, n: PNode): PTransNode =
add(result, c.transCon.forLoopBody) add(result, c.transCon.forLoopBody)
else: else:
# we need to introduce new local variables: # we need to introduce new local variables:
add(result, introduceNewLocalVars(c, c.transCon.forLoopBody.pnode)) add(result, introduceNewLocalVars(c, c.transCon.forLoopBody.PNode))
proc transformAddrDeref(c: PTransf, n: PNode, a, b: TNodeKind): PTransNode = proc transformAddrDeref(c: PTransf, n: PNode, a, b: TNodeKind): PTransNode =
result = transformSons(c, n) result = transformSons(c, n)
var n = result.pnode var n = result.PNode
case n.sons[0].kind case n.sons[0].kind
of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64: of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64:
var m = n.sons[0].sons[0] var m = n.sons[0].sons[0]
@ -436,8 +436,8 @@ proc transformFor(c: PTransf, n: PNode): PTransNode =
if call.kind notin nkCallKinds or call.sons[0].kind != nkSym or if call.kind notin nkCallKinds or call.sons[0].kind != nkSym or
call.sons[0].typ.callConv == ccClosure or call.sons[0].typ.callConv == ccClosure or
call.sons[0].sym.kind != skIterator: call.sons[0].sym.kind != skIterator:
n.sons[length-1] = transformLoopBody(c, n.sons[length-1]).pnode n.sons[length-1] = transformLoopBody(c, n.sons[length-1]).PNode
return lambdalifting.liftForLoop(n).ptransNode return lambdalifting.liftForLoop(n).PTransNode
#InternalError(call.info, "transformFor") #InternalError(call.info, "transformFor")
#echo "transforming: ", renderTree(n) #echo "transforming: ", renderTree(n)
@ -446,7 +446,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode =
var v = newNodeI(nkVarSection, n.info) var v = newNodeI(nkVarSection, n.info)
for i in countup(0, length - 3): for i in countup(0, length - 3):
addVar(v, copyTree(n.sons[i])) # declare new vars addVar(v, copyTree(n.sons[i])) # declare new vars
add(result, v.ptransNode) add(result, v.PTransNode)
# Bugfix: inlined locals belong to the invoking routine, not to the invoked # Bugfix: inlined locals belong to the invoking routine, not to the invoked
# iterator! # iterator!
@ -458,7 +458,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode =
# generate access statements for the parameters (unless they are constant) # generate access statements for the parameters (unless they are constant)
pushTransCon(c, newC) pushTransCon(c, newC)
for i in countup(1, sonsLen(call) - 1): for i in countup(1, sonsLen(call) - 1):
var arg = transform(c, call.sons[i]).pnode var arg = transform(c, call.sons[i]).PNode
var formal = skipTypes(iter.typ, abstractInst).n.sons[i].sym var formal = skipTypes(iter.typ, abstractInst).n.sons[i].sym
case putArgInto(arg, formal.typ) case putArgInto(arg, formal.typ)
of paDirectMapping: of paDirectMapping:
@ -467,7 +467,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode =
# generate a temporary and produce an assignment statement: # generate a temporary and produce an assignment statement:
var temp = newTemp(c, formal.typ, formal.info) var temp = newTemp(c, formal.typ, formal.info)
addVar(v, newSymNode(temp)) addVar(v, newSymNode(temp))
add(result, newAsgnStmt(c, newSymNode(temp), arg.ptransNode)) add(result, newAsgnStmt(c, newSymNode(temp), arg.PTransNode))
idNodeTablePut(newC.mapping, formal, newSymNode(temp)) idNodeTablePut(newC.mapping, formal, newSymNode(temp))
of paVarAsgn: of paVarAsgn:
assert(skipTypes(formal.typ, abstractInst).kind == tyVar) assert(skipTypes(formal.typ, abstractInst).kind == tyVar)
@ -500,19 +500,19 @@ proc transformCase(c: PTransf, n: PNode): PTransNode =
var e = transform(c, it) var e = transform(c, it)
case it.kind case it.kind
of nkElifBranch: of nkElifBranch:
if ifs.pnode == nil: if ifs.PNode == nil:
ifs = newTransNode(nkIfStmt, it.info, 0) ifs = newTransNode(nkIfStmt, it.info, 0)
ifs.add(e) ifs.add(e)
of nkElse: of nkElse:
if ifs.pnode == nil: result.add(e) if ifs.PNode == nil: result.add(e)
else: ifs.add(e) else: ifs.add(e)
else: else:
result.add(e) result.add(e)
if ifs.pnode != nil: if ifs.PNode != nil:
var elseBranch = newTransNode(nkElse, n.info, 1) var elseBranch = newTransNode(nkElse, n.info, 1)
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:
@ -523,7 +523,7 @@ proc transformCase(c: PTransf, n: PNode): PTransNode =
proc transformArrayAccess(c: PTransf, n: PNode): PTransNode = proc transformArrayAccess(c: PTransf, n: PNode): PTransNode =
# XXX this is really bad; transf should use a proper AST visitor # XXX this is really bad; transf should use a proper AST visitor
if n.sons[0].kind == nkSym and n.sons[0].sym.kind == skType: if n.sons[0].kind == nkSym and n.sons[0].sym.kind == skType:
result = n.ptransnode result = n.PTransNode
else: else:
result = newTransNode(n) result = newTransNode(n)
for i in 0 .. < n.len: for i in 0 .. < n.len:
@ -563,24 +563,24 @@ proc transformCall(c: PTransf, n: PNode): PTransNode =
add(result, transform(c, n.sons[0])) add(result, transform(c, n.sons[0]))
var j = 1 var j = 1
while j < sonsLen(n): while j < sonsLen(n):
var a = transform(c, n.sons[j]).pnode var a = transform(c, n.sons[j]).PNode
inc(j) inc(j)
if isConstExpr(a): if isConstExpr(a):
while (j < sonsLen(n)): while (j < sonsLen(n)):
let b = transform(c, n.sons[j]).pnode let b = transform(c, n.sons[j]).PNode
if not isConstExpr(b): break if not isConstExpr(b): break
a = evalOp(op.magic, n, a, b, nil) a = evalOp(op.magic, n, a, b, nil)
inc(j) inc(j)
add(result, a.ptransnode) add(result, a.PTransNode)
if len(result) == 2: result = result[1] if len(result) == 2: result = result[1]
else: else:
let s = transformSons(c, n).pnode let s = transformSons(c, n).PNode
# bugfix: check after 'transformSons' if it's still a method call: # bugfix: check after 'transformSons' if it's still a method call:
# use the dispatcher for the call: # use the dispatcher for the call:
if s.sons[0].kind == nkSym and s.sons[0].sym.kind == skMethod: if s.sons[0].kind == nkSym and s.sons[0].sym.kind == skMethod:
result = methodCall(s).ptransNode result = methodCall(s).PTransNode
else: else:
result = s.ptransNode result = s.PTransNode
proc dontInlineConstant(orig, cnst: PNode): bool {.inline.} = proc dontInlineConstant(orig, cnst: PNode): bool {.inline.} =
# symbols that expand to a complex constant (array, etc.) should not be # symbols that expand to a complex constant (array, etc.) should not be
@ -683,7 +683,7 @@ proc transform(c: PTransf, n: PNode): PTransNode =
# completely: # completely:
result = PTransNode(newNode(nkCommentStmt)) result = PTransNode(newNode(nkCommentStmt))
of nkCommentStmt, nkTemplateDef: of nkCommentStmt, nkTemplateDef:
return n.ptransNode return n.PTransNode
of nkConstSection: of nkConstSection:
# do not replace ``const c = 3`` with ``const 3 = 3`` # do not replace ``const c = 3`` with ``const 3 = 3``
return transformConstSection(c, n) return transformConstSection(c, n)
@ -707,7 +707,7 @@ proc transform(c: PTransf, n: PNode): PTransNode =
result = transformSons(c, n) result = transformSons(c, n)
# XXX comment handling really sucks: # XXX comment handling really sucks:
if importantComments(): if importantComments():
pnode(result).comment = n.comment PNode(result).comment = n.comment
else: else:
result = transformSons(c, n) result = transformSons(c, n)
var cnst = getConstExpr(c.module, PNode(result)) var cnst = getConstExpr(c.module, PNode(result))

View file

@ -83,7 +83,7 @@ proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) =
t.data[index].val = val t.data[index].val = val
else: else:
if mustRehash(len(t.data), t.counter): if mustRehash(len(t.data), t.counter):
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != nil: if t.data[i].key != nil:
nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val) nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val)
@ -100,7 +100,7 @@ proc nodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int =
result = t.data[index].val result = t.data[index].val
else: else:
if mustRehash(len(t.data), t.counter): if mustRehash(len(t.data), t.counter):
newSeq(n, len(t.data) * growthFactor) newSeq(n, len(t.data) * GrowthFactor)
for i in countup(0, high(t.data)): for i in countup(0, high(t.data)):
if t.data[i].key != nil: if t.data[i].key != nil:
nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val) nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val)

View file

@ -97,7 +97,7 @@ proc isPureObject(typ: PType): bool =
while t.kind == tyObject and t.sons[0] != nil: t = t.sons[0] while t.kind == tyObject and t.sons[0] != nil: t = t.sons[0]
result = t.sym != nil and sfPure in t.sym.flags result = t.sym != nil and sfPure in t.sym.flags
proc getOrdValue(n: PNode): biggestInt = proc getOrdValue(n: PNode): BiggestInt =
case n.kind case n.kind
of nkCharLit..nkInt64Lit: result = n.intVal of nkCharLit..nkInt64Lit: result = n.intVal
of nkNilLit: result = 0 of nkNilLit: result = 0
@ -526,7 +526,7 @@ proc resultType(t: PType): PType =
proc base(t: PType): PType = proc base(t: PType): PType =
result = t.sons[0] result = t.sons[0]
proc firstOrd(t: PType): biggestInt = proc firstOrd(t: PType): BiggestInt =
case t.kind case t.kind
of tyBool, tyChar, tySequence, tyOpenArray, tyString, tyVarargs, tyProxy: of tyBool, tyChar, tySequence, tyOpenArray, tyString, tyVarargs, tyProxy:
result = 0 result = 0
@ -557,7 +557,7 @@ proc firstOrd(t: PType): biggestInt =
internalError("invalid kind for first(" & $t.kind & ')') internalError("invalid kind for first(" & $t.kind & ')')
result = 0 result = 0
proc lastOrd(t: PType): biggestInt = proc lastOrd(t: PType): BiggestInt =
case t.kind case t.kind
of tyBool: result = 1 of tyBool: result = 1
of tyChar: result = 255 of tyChar: result = 255
@ -591,7 +591,7 @@ proc lastOrd(t: PType): biggestInt =
internalError("invalid kind for last(" & $t.kind & ')') internalError("invalid kind for last(" & $t.kind & ')')
result = 0 result = 0
proc lengthOrd(t: PType): biggestInt = proc lengthOrd(t: PType): BiggestInt =
case t.kind case t.kind
of tyInt64, tyInt32, tyInt: result = lastOrd(t) of tyInt64, tyInt32, tyInt: result = lastOrd(t)
of tyDistinct, tyConst, tyMutable: result = lengthOrd(t.sons[0]) of tyDistinct, tyConst, tyMutable: result = lengthOrd(t.sons[0])
@ -732,7 +732,7 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool =
result = false result = false
template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} =
if tfFromGeneric not_in a.flags + b.flags: if tfFromGeneric notin a.flags + b.flags:
# fast case: id comparison suffices: # fast case: id comparison suffices:
result = a.id == b.id result = a.id == b.id
else: else:
@ -835,7 +835,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool =
result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b) result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b)
of tyObject: of tyObject:
ifFastObjectTypeCheckFailed(a, b): ifFastObjectTypeCheckFailed(a, b):
CycleCheck() cycleCheck()
result = sameObjectStructures(a, b, c) and sameFlags(a, b) result = sameObjectStructures(a, b, c) and sameFlags(a, b)
of tyDistinct: of tyDistinct:
cycleCheck() cycleCheck()
@ -1133,7 +1133,7 @@ proc computeRecSizeAux(n: PNode, a, currOffset: var BiggestInt): BiggestInt =
a = 1 a = 1
result = - 1 result = - 1
proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = proc computeSizeAux(typ: PType, a: var BiggestInt): BiggestInt =
var res, maxAlign, length, currOffset: BiggestInt var res, maxAlign, length, currOffset: BiggestInt
if typ.size == - 2: if typ.size == - 2:
# we are already computing the size of the type # we are already computing the size of the type
@ -1184,7 +1184,7 @@ proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt =
length = lastOrd(typ) # BUGFIX: use lastOrd! length = lastOrd(typ) # BUGFIX: use lastOrd!
if length + 1 < `shl`(1, 8): result = 1 if length + 1 < `shl`(1, 8): result = 1
elif length + 1 < `shl`(1, 16): result = 2 elif length + 1 < `shl`(1, 16): result = 2
elif length + 1 < `shl`(biggestInt(1), 32): result = 4 elif length + 1 < `shl`(BiggestInt(1), 32): result = 4
else: result = 8 else: result = 8
a = result a = result
of tySet: of tySet:
@ -1235,7 +1235,7 @@ proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt =
typ.size = result typ.size = result
typ.align = int(a) typ.align = int(a)
proc computeSize(typ: PType): biggestInt = proc computeSize(typ: PType): BiggestInt =
var a: BiggestInt = 1 var a: BiggestInt = 1
result = computeSizeAux(typ, a) result = computeSizeAux(typ, a)
@ -1244,7 +1244,7 @@ proc getReturnType*(s: PSym): PType =
assert s.kind in {skProc, skTemplate, skMacro, skIterator} assert s.kind in {skProc, skTemplate, skMacro, skIterator}
result = s.typ.sons[0] result = s.typ.sons[0]
proc getSize(typ: PType): biggestInt = proc getSize(typ: PType): BiggestInt =
result = computeSize(typ) result = computeSize(typ)
if result < 0: internalError("getSize: " & $typ.kind) if result < 0: internalError("getSize: " & $typ.kind)
@ -1289,8 +1289,8 @@ proc compatibleEffectsAux(se, re: PNode): bool =
proc compatibleEffects*(formal, actual: PType): bool = proc compatibleEffects*(formal, actual: PType): bool =
# for proc type compatibility checking: # for proc type compatibility checking:
assert formal.kind == tyProc and actual.kind == tyProc assert formal.kind == tyProc and actual.kind == tyProc
InternalAssert formal.n.sons[0].kind == nkEffectList internalAssert formal.n.sons[0].kind == nkEffectList
InternalAssert actual.n.sons[0].kind == nkEffectList internalAssert actual.n.sons[0].kind == nkEffectList
var spec = formal.n.sons[0] var spec = formal.n.sons[0]
if spec.len != 0: if spec.len != 0:
@ -1315,7 +1315,7 @@ proc compatibleEffects*(formal, actual: PType): bool =
result = true result = true
proc isCompileTimeOnly*(t: PType): bool {.inline.} = proc isCompileTimeOnly*(t: PType): bool {.inline.} =
result = t.kind in {tyTypedesc, tyExpr} result = t.kind in {tyTypeDesc, tyExpr}
proc containsCompileTimeOnly*(t: PType): bool = proc containsCompileTimeOnly*(t: PType): bool =
if isCompileTimeOnly(t): return true if isCompileTimeOnly(t): return true

View file

@ -579,7 +579,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode =
of opcMinusSet: of opcMinusSet:
decodeBC(nkCurly) decodeBC(nkCurly)
move(regs[ra].sons, nimsets.diffSets(regs[rb], regs[rc]).sons) move(regs[ra].sons, nimsets.diffSets(regs[rb], regs[rc]).sons)
of opcSymDiffSet: of opcSymdiffSet:
decodeBC(nkCurly) decodeBC(nkCurly)
move(regs[ra].sons, nimsets.symdiffSets(regs[rb], regs[rc]).sons) move(regs[ra].sons, nimsets.symdiffSets(regs[rb], regs[rc]).sons)
of opcConcatStr: of opcConcatStr:
@ -982,7 +982,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode =
of opcNSetType: of opcNSetType:
decodeB(nkMetaNode) decodeB(nkMetaNode)
let b = regs[rb].skipMeta let b = regs[rb].skipMeta
InternalAssert b.kind == nkSym and b.sym.kind == skType internalAssert b.kind == nkSym and b.sym.kind == skType
regs[ra].uast.typ = b.sym.typ regs[ra].uast.typ = b.sym.typ
of opcNSetStrVal: of opcNSetStrVal:
decodeB(nkMetaNode) decodeB(nkMetaNode)

View file

@ -198,7 +198,7 @@ proc refresh*(c: PCtx, module: PSym) =
const const
firstABxInstr* = opcTJmp firstABxInstr* = opcTJmp
largeInstrs* = { # instructions which use 2 int32s instead of 1: largeInstrs* = { # instructions which use 2 int32s instead of 1:
opcSubstr, opcConv, opcCast, opcNewSeq, opcOf} opcSubStr, opcConv, opcCast, opcNewSeq, opcOf}
slotSomeTemp* = slotTempUnknown slotSomeTemp* = slotTempUnknown
relativeJumps* = {opcTJmp, opcFJmp, opcJmp} relativeJumps* = {opcTJmp, opcFJmp, opcJmp}

View file

@ -85,7 +85,7 @@ proc genLabel(c: PCtx): TPosition =
proc jmpBack(c: PCtx, n: PNode, opc: TOpcode, p = TPosition(0)) = proc jmpBack(c: PCtx, n: PNode, opc: TOpcode, p = TPosition(0)) =
let dist = p.int - c.code.len let dist = p.int - c.code.len
InternalAssert(-0x7fff < dist and dist < 0x7fff) internalAssert(-0x7fff < dist and dist < 0x7fff)
gABx(c, n, opc, 0, dist) gABx(c, n, opc, 0, dist)
proc patch(c: PCtx, p: TPosition) = proc patch(c: PCtx, p: TPosition) =
@ -93,7 +93,7 @@ proc patch(c: PCtx, p: TPosition) =
let p = p.int let p = p.int
let diff = c.code.len - p let diff = c.code.len - p
#c.jumpTargets.incl(c.code.len) #c.jumpTargets.incl(c.code.len)
InternalAssert(-0x7fff < diff and diff < 0x7fff) internalAssert(-0x7fff < diff and diff < 0x7fff)
let oldInstr = c.code[p] let oldInstr = c.code[p]
# opcode and regA stay the same: # opcode and regA stay the same:
c.code[p] = ((oldInstr.uint32 and 0xffff'u32).uint32 or c.code[p] = ((oldInstr.uint32 and 0xffff'u32).uint32 or
@ -194,7 +194,7 @@ proc gen(c: PCtx; n: PNode; dest: var TDest)
proc gen(c: PCtx; n: PNode; dest: TRegister) = proc gen(c: PCtx; n: PNode; dest: TRegister) =
var d: TDest = dest var d: TDest = dest
gen(c, n, d) gen(c, n, d)
InternalAssert d == dest internalAssert d == dest
proc gen(c: PCtx; n: PNode) = proc gen(c: PCtx; n: PNode) =
var tmp: TDest = -1 var tmp: TDest = -1
@ -308,7 +308,7 @@ proc genAndOr(c: PCtx; n: PNode; opc: TOpcode; dest: var TDest) =
proc rawGenLiteral(c: PCtx; n: PNode): int = proc rawGenLiteral(c: PCtx; n: PNode): int =
result = c.constants.len result = c.constants.len
c.constants.add n c.constants.add n
InternalAssert result < 0x7fff internalAssert result < 0x7fff
proc sameConstant*(a, b: PNode): bool = proc sameConstant*(a, b: PNode): bool =
result = false result = false
@ -678,8 +678,8 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) =
tmp2 = c.genx(n.sons[2]) tmp2 = c.genx(n.sons[2])
tmp3 = c.getTemp(n.sons[2].typ) tmp3 = c.getTemp(n.sons[2].typ)
c.gABC(n, opcLenStr, tmp3, tmp1) c.gABC(n, opcLenStr, tmp3, tmp1)
c.gABC(n, opcSubstr, dest, tmp1, tmp2) c.gABC(n, opcSubStr, dest, tmp1, tmp2)
c.gABC(n, opcSubstr, tmp3) c.gABC(n, opcSubStr, tmp3)
c.freeTemp(tmp1) c.freeTemp(tmp1)
c.freeTemp(tmp2) c.freeTemp(tmp2)
c.freeTemp(tmp3) c.freeTemp(tmp3)
@ -689,8 +689,8 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) =
tmp1 = c.genx(n.sons[1]) tmp1 = c.genx(n.sons[1])
tmp2 = c.genx(n.sons[2]) tmp2 = c.genx(n.sons[2])
tmp3 = c.genx(n.sons[3]) tmp3 = c.genx(n.sons[3])
c.gABC(n, opcSubstr, dest, tmp1, tmp2) c.gABC(n, opcSubStr, dest, tmp1, tmp2)
c.gABC(n, opcSubstr, tmp3) c.gABC(n, opcSubStr, tmp3)
c.freeTemp(tmp1) c.freeTemp(tmp1)
c.freeTemp(tmp2) c.freeTemp(tmp2)
c.freeTemp(tmp3) c.freeTemp(tmp3)
@ -922,7 +922,7 @@ proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) =
gen(c, ri, tmp) gen(c, ri, tmp)
c.gABx(le, whichAsgnOpc(le, opcWrGlobal), tmp, s.position) c.gABx(le, whichAsgnOpc(le, opcWrGlobal), tmp, s.position)
else: else:
InternalAssert s.position > 0 or (s.position == 0 and internalAssert s.position > 0 or (s.position == 0 and
s.kind in {skParam, skResult}) s.kind in {skParam, skResult})
var dest: TRegister = s.position + ord(s.kind == skParam) var dest: TRegister = s.position + ord(s.kind == skParam)
gen(c, ri, dest) gen(c, ri, dest)
@ -1212,7 +1212,7 @@ proc gen(c: PCtx; n: PNode; dest: var TDest) =
var lit = genLiteral(c, newIntNode(nkIntLit, s.position)) var lit = genLiteral(c, newIntNode(nkIntLit, s.position))
c.gABx(n, opcLdConst, dest, lit) c.gABx(n, opcLdConst, dest, lit)
of skField: of skField:
InternalAssert dest < 0 internalAssert dest < 0
if s.position > high(dest): if s.position > high(dest):
internalError(n.info, internalError(n.info,
"too large offset! cannot generate code for: " & s.name.s) "too large offset! cannot generate code for: " & s.name.s)
@ -1346,7 +1346,7 @@ proc genParams(c: PCtx; params: PNode) =
c.prc.maxSlots = max(params.len, 1) c.prc.maxSlots = max(params.len, 1)
proc finalJumpTarget(c: PCtx; pc, diff: int) = proc finalJumpTarget(c: PCtx; pc, diff: int) =
InternalAssert(-0x7fff < diff and diff < 0x7fff) internalAssert(-0x7fff < diff and diff < 0x7fff)
let oldInstr = c.code[pc] let oldInstr = c.code[pc]
# opcode and regA stay the same: # opcode and regA stay the same:
c.code[pc] = ((oldInstr.uint32 and 0xffff'u32).uint32 or c.code[pc] = ((oldInstr.uint32 and 0xffff'u32).uint32 or

View file

@ -115,7 +115,7 @@ proc findStartNimrod: string =
if existsFile(dir / nimrod): return nimrod if existsFile(dir / nimrod): return nimrod
when defined(Posix): when defined(Posix):
const buildScript = "build.sh" const buildScript = "build.sh"
if ExistsFile(buildScript): if existsFile(buildScript):
if tryExec("./" & buildScript): return "bin" / nimrod if tryExec("./" & buildScript): return "bin" / nimrod
else: else:
const buildScript = "build.bat" const buildScript = "build.bat"
@ -183,7 +183,7 @@ proc cleanAux(dir: string) =
else: nil else: nil
proc removePattern(pattern: string) = proc removePattern(pattern: string) =
for f in WalkFiles(pattern): for f in walkFiles(pattern):
echo "removing: ", f echo "removing: ", f
removeFile(f) removeFile(f)

View file

@ -428,7 +428,7 @@ proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string],
g.kind = gtOperator g.kind = gtOperator
of 'a'..'z', 'A'..'Z', '_', '\x80'..'\xFF': of 'a'..'z', 'A'..'Z', '_', '\x80'..'\xFF':
var id = "" var id = ""
while g.buf[pos] in SymChars: while g.buf[pos] in symChars:
add(id, g.buf[pos]) add(id, g.buf[pos])
inc(pos) inc(pos)
if isKeyword(keywords, id) >= 0: g.kind = gtKeyword if isKeyword(keywords, id) >= 0: g.kind = gtKeyword

View file

@ -58,10 +58,10 @@ const
mwUnsupportedLanguage: "language '$1' not supported" mwUnsupportedLanguage: "language '$1' not supported"
] ]
proc rstnodeToRefname*(n: PRSTNode): string proc rstnodeToRefname*(n: PRstNode): string
proc addNodes*(n: PRSTNode): string proc addNodes*(n: PRstNode): string
proc getFieldValue*(n: PRSTNode, fieldname: string): string proc getFieldValue*(n: PRstNode, fieldname: string): string
proc getArgument*(n: PRSTNode): string proc getArgument*(n: PRstNode): string
# ----------------------------- scanner part -------------------------------- # ----------------------------- scanner part --------------------------------
@ -130,7 +130,7 @@ proc getThing(L: var TLexer, tok: var TToken, s: TCharSet) =
tok.line = L.line tok.line = L.line
tok.col = L.col tok.col = L.col
var pos = L.bufpos var pos = L.bufpos
while True: while true:
add(tok.symbol, L.buf[pos]) add(tok.symbol, L.buf[pos])
inc(pos) inc(pos)
if L.buf[pos] notin s: break if L.buf[pos] notin s: break
@ -143,7 +143,7 @@ proc getAdornment(L: var TLexer, tok: var TToken) =
tok.col = L.col tok.col = L.col
var pos = L.bufpos var pos = L.bufpos
var c = L.buf[pos] var c = L.buf[pos]
while True: while true:
add(tok.symbol, L.buf[pos]) add(tok.symbol, L.buf[pos])
inc(pos) inc(pos)
if L.buf[pos] != c: break if L.buf[pos] != c: break
@ -162,7 +162,7 @@ proc getIndentAux(L: var TLexer, start: int): int =
if L.skipPounds: if L.skipPounds:
if buf[pos] == '#': inc(pos) if buf[pos] == '#': inc(pos)
if buf[pos] == '#': inc(pos) if buf[pos] == '#': inc(pos)
while True: while true:
case buf[pos] case buf[pos]
of ' ', '\x0B', '\x0C': of ' ', '\x0B', '\x0C':
inc(pos) inc(pos)
@ -251,10 +251,10 @@ proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int =
tokens[0].kind = tkIndent tokens[0].kind = tkIndent
type type
TLevelMap = array[Char, int] TLevelMap = array[char, int]
TSubstitution{.final.} = object TSubstitution{.final.} = object
key*: string key*: string
value*: PRSTNode value*: PRstNode
TSharedState {.final.} = object TSharedState {.final.} = object
options: TRstParseOptions # parsing options options: TRstParseOptions # parsing options
@ -351,7 +351,7 @@ proc initParser(p: var TRstParser, sharedState: PSharedState) =
p.line = 1 p.line = 1
p.s = sharedState p.s = sharedState
proc addNodesAux(n: PRSTNode, result: var string) = proc addNodesAux(n: PRstNode, result: var string) =
if n.kind == rnLeaf: if n.kind == rnLeaf:
add(result, n.text) add(result, n.text)
else: else:
@ -361,7 +361,7 @@ proc addNodes(n: PRstNode): string =
result = "" result = ""
addNodesAux(n, result) addNodesAux(n, result)
proc rstnodeToRefnameAux(n: PRSTNode, r: var string, b: var bool) = proc rstnodeToRefnameAux(n: PRstNode, r: var string, b: var bool) =
if n.kind == rnLeaf: if n.kind == rnLeaf:
for i in countup(0, len(n.text) - 1): for i in countup(0, len(n.text) - 1):
case n.text[i] case n.text[i]
@ -391,7 +391,7 @@ proc rstnodeToRefname(n: PRstNode): string =
var b = false var b = false
rstnodeToRefnameAux(n, result, b) rstnodeToRefnameAux(n, result, b)
proc findSub(p: var TRstParser, n: PRSTNode): int = proc findSub(p: var TRstParser, n: PRstNode): int =
var key = addNodes(n) var key = addNodes(n)
# the spec says: if no exact match, try one without case distinction: # the spec says: if no exact match, try one without case distinction:
for i in countup(0, high(p.s.subs)): for i in countup(0, high(p.s.subs)):
@ -402,7 +402,7 @@ proc findSub(p: var TRstParser, n: PRSTNode): int =
return i return i
result = -1 result = -1
proc setSub(p: var TRstParser, key: string, value: PRSTNode) = proc setSub(p: var TRstParser, key: string, value: PRstNode) =
var length = len(p.s.subs) var length = len(p.s.subs)
for i in countup(0, length - 1): for i in countup(0, length - 1):
if key == p.s.subs[i].key: if key == p.s.subs[i].key:
@ -412,7 +412,7 @@ proc setSub(p: var TRstParser, key: string, value: PRSTNode) =
p.s.subs[length].key = key p.s.subs[length].key = key
p.s.subs[length].value = value p.s.subs[length].value = value
proc setRef(p: var TRstParser, key: string, value: PRSTNode) = proc setRef(p: var TRstParser, key: string, value: PRstNode) =
var length = len(p.s.refs) var length = len(p.s.refs)
for i in countup(0, length - 1): for i in countup(0, length - 1):
if key == p.s.refs[i].key: if key == p.s.refs[i].key:
@ -425,15 +425,15 @@ proc setRef(p: var TRstParser, key: string, value: PRSTNode) =
p.s.refs[length].key = key p.s.refs[length].key = key
p.s.refs[length].value = value p.s.refs[length].value = value
proc findRef(p: var TRstParser, key: string): PRSTNode = proc findRef(p: var TRstParser, key: string): PRstNode =
for i in countup(0, high(p.s.refs)): for i in countup(0, high(p.s.refs)):
if key == p.s.refs[i].key: if key == p.s.refs[i].key:
return p.s.refs[i].value return p.s.refs[i].value
proc newLeaf(p: var TRstParser): PRSTNode = proc newLeaf(p: var TRstParser): PRstNode =
result = newRstNode(rnLeaf, p.tok[p.idx].symbol) result = newRstNode(rnLeaf, p.tok[p.idx].symbol)
proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode = proc getReferenceName(p: var TRstParser, endStr: string): PRstNode =
var res = newRstNode(rnInner) var res = newRstNode(rnInner)
while true: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
@ -451,7 +451,7 @@ proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode =
inc(p.idx) inc(p.idx)
result = res result = res
proc untilEol(p: var TRstParser): PRSTNode = proc untilEol(p: var TRstParser): PRstNode =
result = newRstNode(rnInner) result = newRstNode(rnInner)
while not (p.tok[p.idx].kind in {tkIndent, tkEof}): while not (p.tok[p.idx].kind in {tkIndent, tkEof}):
add(result, newLeaf(p)) add(result, newLeaf(p))
@ -550,7 +550,7 @@ proc match(p: TRstParser, start: int, expr: string): bool =
inc(i) inc(i)
result = true result = true
proc fixupEmbeddedRef(n, a, b: PRSTNode) = proc fixupEmbeddedRef(n, a, b: PRstNode) =
var sep = - 1 var sep = - 1
for i in countdown(len(n) - 2, 0): for i in countdown(len(n) - 2, 0):
if n.sons[i].text == "<": if n.sons[i].text == "<":
@ -560,7 +560,7 @@ proc fixupEmbeddedRef(n, a, b: PRSTNode) =
for i in countup(0, sep - incr): add(a, n.sons[i]) for i in countup(0, sep - incr): add(a, n.sons[i])
for i in countup(sep + 1, len(n) - 2): add(b, n.sons[i]) for i in countup(sep + 1, len(n) - 2): add(b, n.sons[i])
proc parsePostfix(p: var TRstParser, n: PRSTNode): PRSTNode = proc parsePostfix(p: var TRstParser, n: PRstNode): PRstNode =
result = n result = n
if isInlineMarkupEnd(p, "_"): if isInlineMarkupEnd(p, "_"):
inc(p.idx) inc(p.idx)
@ -613,7 +613,7 @@ proc matchVerbatim(p: TRstParser, start: int, expr: string): int =
inc result inc result
if j < expr.len: result = 0 if j < expr.len: result = 0
proc parseSmiley(p: var TRstParser): PRSTNode = proc parseSmiley(p: var TRstParser): PRstNode =
if p.tok[p.idx].symbol[0] notin SmileyStartChars: return if p.tok[p.idx].symbol[0] notin SmileyStartChars: return
for key, val in items(Smilies): for key, val in items(Smilies):
let m = matchVerbatim(p, p.idx, key) let m = matchVerbatim(p, p.idx, key)
@ -629,14 +629,14 @@ when false:
'$', '(', ')', '~', '_', '?', '+', '-', '=', '\\', '.', '&', '$', '(', ')', '~', '_', '?', '+', '-', '=', '\\', '.', '&',
'\128'..'\255'} '\128'..'\255'}
proc isURL(p: TRstParser, i: int): bool = proc isUrl(p: TRstParser, i: int): bool =
result = (p.tok[i+1].symbol == ":") and (p.tok[i+2].symbol == "//") and result = (p.tok[i+1].symbol == ":") and (p.tok[i+2].symbol == "//") and
(p.tok[i+3].kind == tkWord) and (p.tok[i+3].kind == tkWord) and
(p.tok[i].symbol in ["http", "https", "ftp", "telnet", "file"]) (p.tok[i].symbol in ["http", "https", "ftp", "telnet", "file"])
proc parseURL(p: var TRstParser, father: PRSTNode) = proc parseUrl(p: var TRstParser, father: PRstNode) =
#if p.tok[p.idx].symbol[strStart] == '<': #if p.tok[p.idx].symbol[strStart] == '<':
if isURL(p, p.idx): if isUrl(p, p.idx):
var n = newRstNode(rnStandaloneHyperlink) var n = newRstNode(rnStandaloneHyperlink)
while true: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
@ -654,7 +654,7 @@ proc parseURL(p: var TRstParser, father: PRSTNode) =
if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n)
add(father, n) add(father, n)
proc parseBackslash(p: var TRstParser, father: PRSTNode) = proc parseBackslash(p: var TRstParser, father: PRstNode) =
assert(p.tok[p.idx].kind == tkPunct) assert(p.tok[p.idx].kind == tkPunct)
if p.tok[p.idx].symbol == "\\\\": if p.tok[p.idx].symbol == "\\\\":
add(father, newRstNode(rnLeaf, "\\")) add(father, newRstNode(rnLeaf, "\\"))
@ -692,7 +692,7 @@ when false:
if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n)
add(father, n) add(father, n)
proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string, proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string,
interpretBackslash: bool) = interpretBackslash: bool) =
let let
line = p.tok[p.idx].line line = p.tok[p.idx].line
@ -723,7 +723,7 @@ proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string,
inc(p.idx) inc(p.idx)
else: rstMessage(p, meExpected, postfix, line, col) else: rstMessage(p, meExpected, postfix, line, col)
proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode = proc parseMarkdownCodeblock(p: var TRstParser): PRstNode =
var args = newRstNode(rnDirArg) var args = newRstNode(rnDirArg)
if p.tok[p.idx].kind == tkWord: if p.tok[p.idx].kind == tkWord:
add(args, newLeaf(p)) add(args, newLeaf(p))
@ -753,7 +753,7 @@ proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode =
add(result, nil) add(result, nil)
add(result, lb) add(result, lb)
proc parseInline(p: var TRstParser, father: PRSTNode) = proc parseInline(p: var TRstParser, father: PRstNode) =
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkPunct: of tkPunct:
if isInlineMarkupStart(p, "***"): if isInlineMarkupStart(p, "***"):
@ -797,7 +797,7 @@ proc parseInline(p: var TRstParser, father: PRSTNode) =
if n != nil: if n != nil:
add(father, n) add(father, n)
return return
parseURL(p, father) parseUrl(p, father)
of tkAdornment, tkOther, tkWhite: of tkAdornment, tkOther, tkWhite:
if roSupportSmilies in p.s.options: if roSupportSmilies in p.s.options:
let n = parseSmiley(p) let n = parseSmiley(p)
@ -828,21 +828,21 @@ proc getDirective(p: var TRstParser): string =
else: else:
result = "" result = ""
proc parseComment(p: var TRstParser): PRSTNode = proc parseComment(p: var TRstParser): PRstNode =
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkIndent, tkEof: of tkIndent, tkEof:
if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent: if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent:
inc(p.idx) # empty comment inc(p.idx) # empty comment
else: else:
var indent = p.tok[p.idx].ival var indent = p.tok[p.idx].ival
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkEof: of tkEof:
break break
of tkIndent: of tkIndent:
if (p.tok[p.idx].ival < indent): break if (p.tok[p.idx].ival < indent): break
else: else:
nil discard
inc(p.idx) inc(p.idx)
else: else:
while p.tok[p.idx].kind notin {tkIndent, tkEof}: inc(p.idx) while p.tok[p.idx].kind notin {tkIndent, tkEof}: inc(p.idx)
@ -863,25 +863,25 @@ proc getDirKind(s: string): TDirKind =
if i >= 0: result = TDirKind(i) if i >= 0: result = TDirKind(i)
else: result = dkNone else: result = dkNone
proc parseLine(p: var TRstParser, father: PRSTNode) = proc parseLine(p: var TRstParser, father: PRstNode) =
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father) of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father)
else: break else: break
proc parseUntilNewline(p: var TRstParser, father: PRSTNode) = proc parseUntilNewline(p: var TRstParser, father: PRstNode) =
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father) of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father)
of tkEof, tkIndent: break of tkEof, tkIndent: break
proc parseSection(p: var TRstParser, result: PRSTNode) proc parseSection(p: var TRstParser, result: PRstNode)
proc parseField(p: var TRstParser): PRSTNode = proc parseField(p: var TRstParser): PRstNode =
result = newRstNode(rnField) result = newRstNode(rnField)
var col = p.tok[p.idx].col var col = p.tok[p.idx].col
var fieldname = newRstNode(rnFieldname) var fieldname = newRstNode(rnFieldName)
parseUntil(p, fieldname, ":", false) parseUntil(p, fieldname, ":", false)
var fieldbody = newRstNode(rnFieldbody) var fieldbody = newRstNode(rnFieldBody)
if p.tok[p.idx].kind != tkIndent: parseLine(p, fieldbody) if p.tok[p.idx].kind != tkIndent: parseLine(p, fieldbody)
if p.tok[p.idx].kind == tkIndent: if p.tok[p.idx].kind == tkIndent:
var indent = p.tok[p.idx].ival var indent = p.tok[p.idx].ival
@ -892,7 +892,7 @@ proc parseField(p: var TRstParser): PRSTNode =
add(result, fieldname) add(result, fieldname)
add(result, fieldbody) add(result, fieldbody)
proc parseFields(p: var TRstParser): PRSTNode = proc parseFields(p: var TRstParser): PRstNode =
result = nil result = nil
var atStart = p.idx == 0 and p.tok[0].symbol == ":" var atStart = p.idx == 0 and p.tok[0].symbol == ":"
if (p.tok[p.idx].kind == tkIndent) and (p.tok[p.idx + 1].symbol == ":") or if (p.tok[p.idx].kind == tkIndent) and (p.tok[p.idx + 1].symbol == ":") or
@ -926,14 +926,14 @@ proc getArgument(n: PRstNode): string =
if n.sons[0] == nil: result = "" if n.sons[0] == nil: result = ""
else: result = addNodes(n.sons[0]) else: result = addNodes(n.sons[0])
proc parseDotDot(p: var TRstParser): PRSTNode proc parseDotDot(p: var TRstParser): PRstNode
proc parseLiteralBlock(p: var TRstParser): PRSTNode = proc parseLiteralBlock(p: var TRstParser): PRstNode =
result = newRstNode(rnLiteralBlock) result = newRstNode(rnLiteralBlock)
var n = newRstNode(rnLeaf, "") var n = newRstNode(rnLeaf, "")
if p.tok[p.idx].kind == tkIndent: if p.tok[p.idx].kind == tkIndent:
var indent = p.tok[p.idx].ival var indent = p.tok[p.idx].ival
inc(p.idx) inc(p.idx)
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkEof: of tkEof:
break break
@ -1032,7 +1032,7 @@ proc whichSection(p: TRstParser): TRstNodeKind =
else: result = rnParagraph else: result = rnParagraph
else: result = rnLeaf else: result = rnLeaf
proc parseLineBlock(p: var TRstParser): PRSTNode = proc parseLineBlock(p: var TRstParser): PRstNode =
result = nil result = nil
if p.tok[p.idx + 1].kind == tkWhite: if p.tok[p.idx + 1].kind == tkWhite:
var col = p.tok[p.idx].col var col = p.tok[p.idx].col
@ -1051,8 +1051,8 @@ proc parseLineBlock(p: var TRstParser): PRSTNode =
break break
popInd(p) popInd(p)
proc parseParagraph(p: var TRstParser, result: PRSTNode) = proc parseParagraph(p: var TRstParser, result: PRstNode) =
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkIndent: of tkIndent:
if p.tok[p.idx + 1].kind == tkIndent: if p.tok[p.idx + 1].kind == tkIndent:
@ -1082,7 +1082,7 @@ proc parseParagraph(p: var TRstParser, result: PRSTNode) =
parseInline(p, result) parseInline(p, result)
else: break else: break
proc parseHeadline(p: var TRstParser): PRSTNode = proc parseHeadline(p: var TRstParser): PRstNode =
result = newRstNode(rnHeadline) result = newRstNode(rnHeadline)
parseUntilNewline(p, result) parseUntilNewline(p, result)
assert(p.tok[p.idx].kind == tkIndent) assert(p.tok[p.idx].kind == tkIndent)
@ -1112,16 +1112,16 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) =
# last column has no limit: # last column has no limit:
cols[L - 1] = 32000 cols[L - 1] = 32000
proc parseDoc(p: var TRstParser): PRSTNode proc parseDoc(p: var TRstParser): PRstNode
proc parseSimpleTable(p: var TRstParser): PRSTNode = proc parseSimpleTable(p: var TRstParser): PRstNode =
var var
cols: TIntSeq cols: TIntSeq
row: seq[string] row: seq[string]
i, last, line: int i, last, line: int
c: char c: char
q: TRstParser q: TRstParser
a, b: PRSTNode a, b: PRstNode
result = newRstNode(rnTable) result = newRstNode(rnTable)
cols = @[] cols = @[]
row = @[] row = @[]
@ -1167,13 +1167,13 @@ proc parseSimpleTable(p: var TRstParser): PRSTNode =
add(a, b) add(a, b)
add(result, a) add(result, a)
proc parseTransition(p: var TRstParser): PRSTNode = proc parseTransition(p: var TRstParser): PRstNode =
result = newRstNode(rnTransition) result = newRstNode(rnTransition)
inc(p.idx) inc(p.idx)
if p.tok[p.idx].kind == tkIndent: inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx)
if p.tok[p.idx].kind == tkIndent: inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx)
proc parseOverline(p: var TRstParser): PRSTNode = proc parseOverline(p: var TRstParser): PRstNode =
var c = p.tok[p.idx].symbol[0] var c = p.tok[p.idx].symbol[0]
inc(p.idx, 2) inc(p.idx, 2)
result = newRstNode(rnOverline) result = newRstNode(rnOverline)
@ -1192,7 +1192,7 @@ proc parseOverline(p: var TRstParser): PRSTNode =
inc(p.idx) # XXX: check? inc(p.idx) # XXX: check?
if p.tok[p.idx].kind == tkIndent: inc(p.idx) if p.tok[p.idx].kind == tkIndent: inc(p.idx)
proc parseBulletList(p: var TRstParser): PRSTNode = proc parseBulletList(p: var TRstParser): PRstNode =
result = nil result = nil
if p.tok[p.idx + 1].kind == tkWhite: if p.tok[p.idx + 1].kind == tkWhite:
var bullet = p.tok[p.idx].symbol var bullet = p.tok[p.idx].symbol
@ -1212,7 +1212,7 @@ proc parseBulletList(p: var TRstParser): PRSTNode =
break break
popInd(p) popInd(p)
proc parseOptionList(p: var TRstParser): PRSTNode = proc parseOptionList(p: var TRstParser): PRstNode =
result = newRstNode(rnOptionList) result = newRstNode(rnOptionList)
while true: while true:
if isOptionList(p): if isOptionList(p):
@ -1241,7 +1241,7 @@ proc parseOptionList(p: var TRstParser): PRSTNode =
else: else:
break break
proc parseDefinitionList(p: var TRstParser): PRSTNode = proc parseDefinitionList(p: var TRstParser): PRstNode =
result = nil result = nil
var j = tokenAfterNewline(p) - 1 var j = tokenAfterNewline(p) - 1
if (j >= 1) and (p.tok[j].kind == tkIndent) and if (j >= 1) and (p.tok[j].kind == tkIndent) and
@ -1272,12 +1272,12 @@ proc parseDefinitionList(p: var TRstParser): PRSTNode =
j = tokenAfterNewline(p) - 1 j = tokenAfterNewline(p) - 1
if j >= 1 and p.tok[j].kind == tkIndent and p.tok[j].ival > col and if j >= 1 and p.tok[j].kind == tkIndent and p.tok[j].ival > col and
p.tok[j-1].symbol != "::" and p.tok[j+1].kind != tkIndent: p.tok[j-1].symbol != "::" and p.tok[j+1].kind != tkIndent:
nil discard
else: else:
break break
if len(result) == 0: result = nil if len(result) == 0: result = nil
proc parseEnumList(p: var TRstParser): PRSTNode = proc parseEnumList(p: var TRstParser): PRstNode =
const const
wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "] wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "]
wildpos: array[0..2, int] = [1, 0, 0] wildpos: array[0..2, int] = [1, 0, 0]
@ -1307,7 +1307,7 @@ proc parseEnumList(p: var TRstParser): PRSTNode =
dec(p.idx, wildpos[w] + 3) dec(p.idx, wildpos[w] + 3)
result = nil result = nil
proc sonKind(father: PRSTNode, i: int): TRstNodeKind = proc sonKind(father: PRstNode, i: int): TRstNodeKind =
result = rnLeaf result = rnLeaf
if i < len(father): result = father.sons[i].kind if i < len(father): result = father.sons[i].kind
@ -1328,14 +1328,14 @@ proc parseSection(p: var TRstParser, result: PRstNode) =
leave = true leave = true
break break
if leave or p.tok[p.idx].kind == tkEof: break if leave or p.tok[p.idx].kind == tkEof: break
var a: PRSTNode = nil var a: PRstNode = nil
var k = whichSection(p) var k = whichSection(p)
case k case k
of rnLiteralBlock: of rnLiteralBlock:
inc(p.idx) # skip '::' inc(p.idx) # skip '::'
a = parseLiteralBlock(p) a = parseLiteralBlock(p)
of rnBulletList: a = parseBulletList(p) of rnBulletList: a = parseBulletList(p)
of rnLineblock: a = parseLineBlock(p) of rnLineBlock: a = parseLineBlock(p)
of rnDirective: a = parseDotDot(p) of rnDirective: a = parseDotDot(p)
of rnEnumList: a = parseEnumList(p) of rnEnumList: a = parseEnumList(p)
of rnLeaf: rstMessage(p, meNewSectionExpected) of rnLeaf: rstMessage(p, meNewSectionExpected)
@ -1359,7 +1359,7 @@ proc parseSection(p: var TRstParser, result: PRstNode) =
if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph: if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph:
result.sons[0].kind = rnInner result.sons[0].kind = rnInner
proc parseSectionWrapper(p: var TRstParser): PRSTNode = proc parseSectionWrapper(p: var TRstParser): PRstNode =
result = newRstNode(rnInner) result = newRstNode(rnInner)
parseSection(p, result) parseSection(p, result)
while (result.kind == rnInner) and (len(result) == 1): while (result.kind == rnInner) and (len(result) == 1):
@ -1385,16 +1385,16 @@ type
TDirFlag = enum TDirFlag = enum
hasArg, hasOptions, argIsFile, argIsWord hasArg, hasOptions, argIsFile, argIsWord
TDirFlags = set[TDirFlag] TDirFlags = set[TDirFlag]
TSectionParser = proc (p: var TRstParser): PRSTNode {.nimcall.} TSectionParser = proc (p: var TRstParser): PRstNode {.nimcall.}
proc parseDirective(p: var TRstParser, flags: TDirFlags): PRSTNode = proc parseDirective(p: var TRstParser, flags: TDirFlags): PRstNode =
result = newRstNode(rnDirective) result = newRstNode(rnDirective)
var args: PRSTNode = nil var args: PRstNode = nil
var options: PRSTNode = nil var options: PRstNode = nil
if hasArg in flags: if hasArg in flags:
args = newRstNode(rnDirArg) args = newRstNode(rnDirArg)
if argIsFile in flags: if argIsFile in flags:
while True: while true:
case p.tok[p.idx].kind case p.tok[p.idx].kind
of tkWord, tkOther, tkPunct, tkAdornment: of tkWord, tkOther, tkPunct, tkAdornment:
add(args, newLeaf(p)) add(args, newLeaf(p))
@ -1420,7 +1420,7 @@ proc indFollows(p: TRstParser): bool =
result = p.tok[p.idx].kind == tkIndent and p.tok[p.idx].ival > currInd(p) result = p.tok[p.idx].kind == tkIndent and p.tok[p.idx].ival > currInd(p)
proc parseDirective(p: var TRstParser, flags: TDirFlags, proc parseDirective(p: var TRstParser, flags: TDirFlags,
contentParser: TSectionParser): PRSTNode = contentParser: TSectionParser): PRstNode =
result = parseDirective(p, flags) result = parseDirective(p, flags)
if not isNil(contentParser) and indFollows(p): if not isNil(contentParser) and indFollows(p):
pushInd(p, p.tok[p.idx].ival) pushInd(p, p.tok[p.idx].ival)
@ -1430,13 +1430,13 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags,
else: else:
add(result, nil) add(result, nil)
proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRSTNode = proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRstNode =
if indFollows(p): if indFollows(p):
pushInd(p, p.tok[p.idx].ival) pushInd(p, p.tok[p.idx].ival)
result = contentParser(p) result = contentParser(p)
popInd(p) popInd(p)
proc dirInclude(p: var TRstParser): PRSTNode = proc dirInclude(p: var TRstParser): PRstNode =
# #
#The following options are recognized: #The following options are recognized:
# #
@ -1474,7 +1474,7 @@ proc dirInclude(p: var TRstParser): PRSTNode =
# InternalError("Too many binary zeros in include file") # InternalError("Too many binary zeros in include file")
result = parseDoc(q) result = parseDoc(q)
proc dirCodeBlock(p: var TRstParser): PRSTNode = proc dirCodeBlock(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasArg, hasOptions}, parseLiteralBlock) result = parseDirective(p, {hasArg, hasOptions}, parseLiteralBlock)
var filename = strip(getFieldValue(result, "file")) var filename = strip(getFieldValue(result, "file"))
if filename != "": if filename != "":
@ -1485,34 +1485,34 @@ proc dirCodeBlock(p: var TRstParser): PRSTNode =
result.sons[2] = n result.sons[2] = n
result.kind = rnCodeBlock result.kind = rnCodeBlock
proc dirContainer(p: var TRstParser): PRSTNode = proc dirContainer(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasArg}, parseSectionWrapper) result = parseDirective(p, {hasArg}, parseSectionWrapper)
assert(result.kind == rnDirective) assert(result.kind == rnDirective)
assert(len(result) == 3) assert(len(result) == 3)
result.kind = rnContainer result.kind = rnContainer
proc dirImage(p: var TRstParser): PRSTNode = proc dirImage(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil) result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil)
result.kind = rnImage result.kind = rnImage
proc dirFigure(p: var TRstParser): PRSTNode = proc dirFigure(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasOptions, hasArg, argIsFile}, result = parseDirective(p, {hasOptions, hasArg, argIsFile},
parseSectionWrapper) parseSectionWrapper)
result.kind = rnFigure result.kind = rnFigure
proc dirTitle(p: var TRstParser): PRSTNode = proc dirTitle(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasArg}, nil) result = parseDirective(p, {hasArg}, nil)
result.kind = rnTitle result.kind = rnTitle
proc dirContents(p: var TRstParser): PRSTNode = proc dirContents(p: var TRstParser): PRstNode =
result = parseDirective(p, {hasArg}, nil) result = parseDirective(p, {hasArg}, nil)
result.kind = rnContents result.kind = rnContents
proc dirIndex(p: var TRstParser): PRSTNode = proc dirIndex(p: var TRstParser): PRstNode =
result = parseDirective(p, {}, parseSectionWrapper) result = parseDirective(p, {}, parseSectionWrapper)
result.kind = rnIndex result.kind = rnIndex
proc dirRawAux(p: var TRstParser, result: var PRSTNode, kind: TRstNodeKind, proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind,
contentParser: TSectionParser) = contentParser: TSectionParser) =
var filename = getFieldValue(result, "file") var filename = getFieldValue(result, "file")
if filename.len > 0: if filename.len > 0:
@ -1527,7 +1527,7 @@ proc dirRawAux(p: var TRstParser, result: var PRSTNode, kind: TRstNodeKind,
result.kind = kind result.kind = kind
add(result, parseDirBody(p, contentParser)) add(result, parseDirBody(p, contentParser))
proc dirRaw(p: var TRstParser): PRSTNode = proc dirRaw(p: var TRstParser): PRstNode =
# #
#The following options are recognized: #The following options are recognized:
# #
@ -1566,7 +1566,7 @@ proc parseDotDot(p: var TRstParser): PRstNode =
result = dirRaw(p) result = dirRaw(p)
else: else:
rstMessage(p, meInvalidDirective, d) rstMessage(p, meInvalidDirective, d)
of dkCodeblock: result = dirCodeBlock(p) of dkCodeBlock: result = dirCodeBlock(p)
of dkIndex: result = dirIndex(p) of dkIndex: result = dirIndex(p)
else: rstMessage(p, meInvalidDirective, d) else: rstMessage(p, meInvalidDirective, d)
popInd(p) popInd(p)
@ -1581,7 +1581,7 @@ proc parseDotDot(p: var TRstParser): PRstNode =
# substitution definitions: # substitution definitions:
inc(p.idx, 2) inc(p.idx, 2)
var a = getReferenceName(p, "|") var a = getReferenceName(p, "|")
var b: PRSTNode var b: PRstNode
if p.tok[p.idx].kind == tkWhite: inc(p.idx) if p.tok[p.idx].kind == tkWhite: inc(p.idx)
if cmpIgnoreStyle(p.tok[p.idx].symbol, "replace") == 0: if cmpIgnoreStyle(p.tok[p.idx].symbol, "replace") == 0:
inc(p.idx) inc(p.idx)
@ -1603,7 +1603,7 @@ proc parseDotDot(p: var TRstParser): PRstNode =
else: else:
result = parseComment(p) result = parseComment(p)
proc resolveSubs(p: var TRstParser, n: PRSTNode): PRSTNode = proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode =
result = n result = n
if n == nil: return if n == nil: return
case n.kind case n.kind
@ -1634,7 +1634,7 @@ proc rstParse*(text, filename: string,
line, column: int, hasToc: var bool, line, column: int, hasToc: var bool,
options: TRstParseOptions, options: TRstParseOptions,
findFile: TFindFileHandler = nil, findFile: TFindFileHandler = nil,
msgHandler: TMsgHandler = nil): PRSTNode = msgHandler: TMsgHandler = nil): PRstNode =
var p: TRstParser var p: TRstParser
initParser(p, newSharedState(options, findFile, msgHandler)) initParser(p, newSharedState(options, findFile, msgHandler))
p.filename = filename p.filename = filename

View file

@ -62,34 +62,34 @@ type
# leaf val # leaf val
PRSTNode* = ref TRSTNode ## an RST node PRstNode* = ref TRstNode ## an RST node
TRstNodeSeq* = seq[PRSTNode] TRstNodeSeq* = seq[PRstNode]
TRSTNode* {.acyclic, final.} = object ## an RST node's description TRstNode* {.acyclic, final.} = object ## an RST node's description
kind*: TRstNodeKind ## the node's kind kind*: TRstNodeKind ## the node's kind
text*: string ## valid for leafs in the AST; and the title of text*: string ## valid for leafs in the AST; and the title of
## the document or the section ## the document or the section
level*: int ## valid for some node kinds level*: int ## valid for some node kinds
sons*: TRstNodeSeq ## the node's sons sons*: TRstNodeSeq ## the node's sons
proc len*(n: PRSTNode): int = proc len*(n: PRstNode): int =
result = len(n.sons) result = len(n.sons)
proc newRstNode*(kind: TRstNodeKind): PRSTNode = proc newRstNode*(kind: TRstNodeKind): PRstNode =
new(result) new(result)
result.sons = @[] result.sons = @[]
result.kind = kind result.kind = kind
proc newRstNode*(kind: TRstNodeKind, s: string): PRSTNode = proc newRstNode*(kind: TRstNodeKind, s: string): PRstNode =
result = newRstNode(kind) result = newRstNode(kind)
result.text = s result.text = s
proc lastSon*(n: PRSTNode): PRSTNode = proc lastSon*(n: PRstNode): PRstNode =
result = n.sons[len(n.sons)-1] result = n.sons[len(n.sons)-1]
proc add*(father, son: PRSTNode) = proc add*(father, son: PRstNode) =
add(father.sons, son) add(father.sons, son)
proc addIfNotNil*(father, son: PRSTNode) = proc addIfNotNil*(father, son: PRstNode) =
if son != nil: add(father, son) if son != nil: add(father, son)
@ -98,9 +98,9 @@ type
indent: int indent: int
verbatim: int verbatim: int
proc renderRstToRst(d: var TRenderContext, n: PRSTNode, result: var string) proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string)
proc renderRstSons(d: var TRenderContext, n: PRSTNode, result: var string) = proc renderRstSons(d: var TRenderContext, n: PRstNode, result: var string) =
for i in countup(0, len(n) - 1): for i in countup(0, len(n) - 1):
renderRstToRst(d, n.sons[i], result) renderRstToRst(d, n.sons[i], result)
@ -281,7 +281,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) =
else: else:
result.add("Error: cannot render: " & $n.kind) result.add("Error: cannot render: " & $n.kind)
proc renderRstToRst*(n: PRSTNode, result: var string) = proc renderRstToRst*(n: PRstNode, result: var string) =
## renders `n` into its string representation and appends to `result`. ## renders `n` into its string representation and appends to `result`.
var d: TRenderContext var d: TRenderContext
renderRstToRst(d, n, result) renderRstToRst(d, n, result)

View file

@ -32,7 +32,7 @@ type
outLatex # output is Latex outLatex # output is Latex
TTocEntry{.final.} = object TTocEntry{.final.} = object
n*: PRSTNode n*: PRstNode
refname*, header*: string refname*, header*: string
TMetaEnum* = enum TMetaEnum* = enum
@ -196,7 +196,7 @@ proc dispA(target: TOutputTarget, dest: var string,
if target != outLatex: addf(dest, xml, args) if target != outLatex: addf(dest, xml, args)
else: addf(dest, tex, args) else: addf(dest, tex, args)
proc renderRstToOut*(d: var TRstGenerator, n: PRSTNode, result: var string) proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string)
## Writes into ``result`` the rst ast ``n`` using the ``d`` configuration. ## Writes into ``result`` the rst ast ``n`` using the ``d`` configuration.
## ##
## Before using this proc you need to initialise a ``TRstGenerator`` with ## Before using this proc you need to initialise a ``TRstGenerator`` with
@ -210,10 +210,10 @@ proc renderRstToOut*(d: var TRstGenerator, n: PRSTNode, result: var string)
## renderRstToOut(gen, rst, generatedHTML) ## renderRstToOut(gen, rst, generatedHTML)
## echo generatedHTML ## echo generatedHTML
proc renderAux(d: PDoc, n: PRSTNode, result: var string) = proc renderAux(d: PDoc, n: PRstNode, result: var string) =
for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result) for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result)
proc renderAux(d: PDoc, n: PRSTNode, frmtA, frmtB: string, result: var string) = proc renderAux(d: PDoc, n: PRstNode, frmtA, frmtB: string, result: var string) =
var tmp = "" var tmp = ""
for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp) for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp)
if d.target != outLatex: if d.target != outLatex:
@ -232,7 +232,7 @@ proc setIndexTerm*(d: var TRstGenerator, id, term: string) =
d.theIndex.add(id) d.theIndex.add(id)
d.theIndex.add("\n") d.theIndex.add("\n")
proc hash(n: PRSTNode): int = proc hash(n: PRstNode): int =
if n.kind == rnLeaf: if n.kind == rnLeaf:
result = hash(n.text) result = hash(n.text)
elif n.len > 0: elif n.len > 0:
@ -241,7 +241,7 @@ proc hash(n: PRSTNode): int =
result = result !& hash(n.sons[i]) result = result !& hash(n.sons[i])
result = !$result result = !$result
proc renderIndexTerm(d: PDoc, n: PRSTNode, result: var string) = proc renderIndexTerm(d: PDoc, n: PRstNode, result: var string) =
let id = rstnodeToRefname(n) & '_' & $abs(hash(n)) let id = rstnodeToRefname(n) & '_' & $abs(hash(n))
var term = "" var term = ""
renderAux(d, n, term) renderAux(d, n, term)
@ -314,7 +314,7 @@ proc mergeIndexes*(dir: string): string =
# ---------------------------------------------------------------------------- # ----------------------------------------------------------------------------
proc renderHeadline(d: PDoc, n: PRSTNode, result: var string) = proc renderHeadline(d: PDoc, n: PRstNode, result: var string) =
var tmp = "" var tmp = ""
for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp)
var refname = rstnodeToRefname(n) var refname = rstnodeToRefname(n)
@ -336,7 +336,7 @@ proc renderHeadline(d: PDoc, n: PRSTNode, result: var string) =
$n.level, refname, tmp, $n.level, refname, tmp,
$chr(n.level - 1 + ord('A'))]) $chr(n.level - 1 + ord('A'))])
proc renderOverline(d: PDoc, n: PRSTNode, result: var string) = proc renderOverline(d: PDoc, n: PRstNode, result: var string) =
if d.meta[metaTitle].len == 0: if d.meta[metaTitle].len == 0:
for i in countup(0, len(n)-1): for i in countup(0, len(n)-1):
renderRstToOut(d, n.sons[i], d.meta[metaTitle]) renderRstToOut(d, n.sons[i], d.meta[metaTitle])
@ -373,7 +373,7 @@ proc renderTocEntries*(d: var TRstGenerator, j: var int, lvl: int, result: var s
else: else:
result.add(tmp) result.add(tmp)
proc renderImage(d: PDoc, n: PRSTNode, result: var string) = proc renderImage(d: PDoc, n: PRstNode, result: var string) =
var options = "" var options = ""
var s = getFieldValue(n, "scale") var s = getFieldValue(n, "scale")
if s != "": dispA(d.target, options, " scale=\"$1\"", " scale=$1", [strip(s)]) if s != "": dispA(d.target, options, " scale=\"$1\"", " scale=$1", [strip(s)])
@ -396,13 +396,13 @@ proc renderImage(d: PDoc, n: PRSTNode, result: var string) =
[getArgument(n), options]) [getArgument(n), options])
if len(n) >= 3: renderRstToOut(d, n.sons[2], result) if len(n) >= 3: renderRstToOut(d, n.sons[2], result)
proc renderSmiley(d: PDoc, n: PRSTNode, result: var string) = proc renderSmiley(d: PDoc, n: PRstNode, result: var string) =
dispA(d.target, result, dispA(d.target, result,
"""<img src="/images/smilies/$1.gif" width="15" """<img src="/images/smilies/$1.gif" width="15"
height="17" hspace="2" vspace="2" />""", height="17" hspace="2" vspace="2" />""",
"\\includegraphics{$1}", [n.text]) "\\includegraphics{$1}", [n.text])
proc renderCodeBlock(d: PDoc, n: PRSTNode, result: var string) = proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) =
if n.sons[2] == nil: return if n.sons[2] == nil: return
var m = n.sons[2].sons[0] var m = n.sons[2].sons[0]
assert m.kind == rnLeaf assert m.kind == rnLeaf
@ -433,7 +433,7 @@ proc renderCodeBlock(d: PDoc, n: PRSTNode, result: var string) =
deinitGeneralTokenizer(g) deinitGeneralTokenizer(g)
dispA(d.target, result, "</pre>", "\n\\end{rstpre}\n") dispA(d.target, result, "</pre>", "\n\\end{rstpre}\n")
proc renderContainer(d: PDoc, n: PRSTNode, result: var string) = proc renderContainer(d: PDoc, n: PRstNode, result: var string) =
var tmp = "" var tmp = ""
renderRstToOut(d, n.sons[2], tmp) renderRstToOut(d, n.sons[2], tmp)
var arg = strip(getArgument(n)) var arg = strip(getArgument(n))
@ -442,11 +442,11 @@ proc renderContainer(d: PDoc, n: PRSTNode, result: var string) =
else: else:
dispA(d.target, result, "<div class=\"$1\">$2</div>", "$2", [arg, tmp]) dispA(d.target, result, "<div class=\"$1\">$2</div>", "$2", [arg, tmp])
proc texColumns(n: PRSTNode): string = proc texColumns(n: PRstNode): string =
result = "" result = ""
for i in countup(1, len(n)): add(result, "|X") for i in countup(1, len(n)): add(result, "|X")
proc renderField(d: PDoc, n: PRSTNode, result: var string) = proc renderField(d: PDoc, n: PRstNode, result: var string) =
var b = false var b = false
if d.target == outLatex: if d.target == outLatex:
var fieldname = addNodes(n.sons[0]) var fieldname = addNodes(n.sons[0])

View file

@ -645,7 +645,7 @@ proc hasKey*(node: PJsonNode, key: string): bool =
## Checks if `key` exists in `node`. ## Checks if `key` exists in `node`.
assert(node.kind == JObject) assert(node.kind == JObject)
for k, item in items(node.fields): for k, item in items(node.fields):
if k == key: return True if k == key: return true
proc existsKey*(node: PJsonNode, key: string): bool {.deprecated.} = node.hasKey(key) proc existsKey*(node: PJsonNode, key: string): bool {.deprecated.} = node.hasKey(key)
## Deprecated for `hasKey` ## Deprecated for `hasKey`
@ -730,8 +730,8 @@ proc escapeJson*(s: string): string =
result.add(toHex(r, 4)) result.add(toHex(r, 4))
result.add("\"") result.add("\"")
proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True, proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = true,
lstArr = False, currIndent = 0) = lstArr = false, currIndent = 0) =
case node.kind case node.kind
of JObject: of JObject:
if currIndent != 0 and not lstArr: result.nl(ml) if currIndent != 0 and not lstArr: result.nl(ml)
@ -747,7 +747,7 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True,
result.indent(newIndent(currIndent, indent, ml)) result.indent(newIndent(currIndent, indent, ml))
result.add(escapeJson(node.fields[i].key)) result.add(escapeJson(node.fields[i].key))
result.add(": ") result.add(": ")
toPretty(result, node.fields[i].val, indent, ml, False, toPretty(result, node.fields[i].val, indent, ml, false,
newIndent(currIndent, indent, ml)) newIndent(currIndent, indent, ml))
result.nl(ml) result.nl(ml)
result.indent(currIndent) # indent the same as { result.indent(currIndent) # indent the same as {
@ -776,7 +776,7 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True,
result.add(", ") result.add(", ")
result.nl(ml) # New Line result.nl(ml) # New Line
toPretty(result, node.elems[i], indent, ml, toPretty(result, node.elems[i], indent, ml,
True, newIndent(currIndent, indent, ml)) true, newIndent(currIndent, indent, ml))
result.nl(ml) result.nl(ml)
result.indent(currIndent) result.indent(currIndent)
result.add("]") result.add("]")
@ -794,7 +794,7 @@ proc pretty*(node: PJsonNode, indent = 2): string =
proc `$`*(node: PJsonNode): string = proc `$`*(node: PJsonNode): string =
## Converts `node` to its JSON Representation on one line. ## Converts `node` to its JSON Representation on one line.
result = "" result = ""
toPretty(result, node, 1, False) toPretty(result, node, 1, false)
iterator items*(node: PJsonNode): PJsonNode = iterator items*(node: PJsonNode): PJsonNode =
## Iterator for the items of `node`. `node` has to be a JArray. ## Iterator for the items of `node`. `node` has to be a JArray.

View file

@ -102,7 +102,7 @@ proc fillBuffer(L: var TBaseLexer) =
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]),
oldBufLen * chrSize) div chrSize oldBufLen * chrSize) div chrSize
if charsRead < oldBufLen: if charsRead < oldBufLen:

View file

@ -95,8 +95,8 @@ elif defined(macos):
const const
CurDir* = ':' CurDir* = ':'
ParDir* = "::" ParDir* = "::"
Dirsep* = ':' DirSep* = ':'
Altsep* = Dirsep AltSep* = Dirsep
PathSep* = ',' PathSep* = ','
FileSystemCaseSensitive* = false FileSystemCaseSensitive* = false
ExeExt* = "" ExeExt* = ""
@ -123,10 +123,10 @@ elif defined(macos):
# grandparent etc. # grandparent etc.
elif doslike: elif doslike:
const const
Curdir* = '.' CurDir* = '.'
Pardir* = ".." ParDir* = ".."
Dirsep* = '\\' # seperator within paths DirSep* = '\\' # seperator within paths
Altsep* = '/' AltSep* = '/'
PathSep* = ';' # seperator between paths PathSep* = ';' # seperator between paths
FileSystemCaseSensitive* = false FileSystemCaseSensitive* = false
ExeExt* = "exe" ExeExt* = "exe"
@ -134,19 +134,19 @@ elif doslike:
DynlibFormat* = "$1.dll" DynlibFormat* = "$1.dll"
elif defined(PalmOS) or defined(MorphOS): elif defined(PalmOS) or defined(MorphOS):
const const
Dirsep* = '/' DirSep* = '/'
Altsep* = Dirsep AltSep* = Dirsep
PathSep* = ';' PathSep* = ';'
Pardir* = ".." ParDir* = ".."
FileSystemCaseSensitive* = false FileSystemCaseSensitive* = false
ExeExt* = "" ExeExt* = ""
ScriptExt* = "" ScriptExt* = ""
DynlibFormat* = "$1.prc" DynlibFormat* = "$1.prc"
elif defined(RISCOS): elif defined(RISCOS):
const const
Dirsep* = '.' DirSep* = '.'
Altsep* = '.' AltSep* = '.'
Pardir* = ".." # is this correct? ParDir* = ".." # is this correct?
PathSep* = ',' PathSep* = ','
FileSystemCaseSensitive* = true FileSystemCaseSensitive* = true
ExeExt* = "" ExeExt* = ""
@ -154,10 +154,10 @@ elif defined(RISCOS):
DynlibFormat* = "lib$1.so" DynlibFormat* = "lib$1.so"
else: # UNIX-like operating system else: # UNIX-like operating system
const const
Curdir* = '.' CurDir* = '.'
Pardir* = ".." ParDir* = ".."
Dirsep* = '/' DirSep* = '/'
Altsep* = Dirsep AltSep* = Dirsep
PathSep* = ':' PathSep* = ':'
FileSystemCaseSensitive* = true FileSystemCaseSensitive* = true
ExeExt* = "" ExeExt* = ""
@ -308,7 +308,7 @@ proc unixToNativePath*(path: string): string {.
start = 1 start = 1
elif path[0] == '.' and path[1] == '/': elif path[0] == '.' and path[1] == '/':
# current directory # current directory
result = $Curdir result = $CurDir
start = 2 start = 2
else: else:
result = "" result = ""
@ -538,7 +538,7 @@ proc splitPath*(path: string): tuple[head, tail: string] {.
## splitPath("") -> ("", "") ## splitPath("") -> ("", "")
var sepPos = -1 var sepPos = -1
for i in countdown(len(path)-1, 0): for i in countdown(len(path)-1, 0):
if path[i] in {Dirsep, Altsep}: if path[i] in {DirSep, AltSep}:
sepPos = i sepPos = i
break break
if sepPos >= 0: if sepPos >= 0:
@ -550,9 +550,9 @@ proc splitPath*(path: string): tuple[head, tail: string] {.
proc parentDirPos(path: string): int = proc parentDirPos(path: string): int =
var q = 1 var q = 1
if path[len(path)-1] in {Dirsep, Altsep}: q = 2 if path[len(path)-1] in {DirSep, AltSep}: q = 2
for i in countdown(len(path)-q, 0): for i in countdown(len(path)-q, 0):
if path[i] in {Dirsep, Altsep}: return i if path[i] in {DirSep, AltSep}: return i
result = -1 result = -1
proc parentDir*(path: string): string {. proc parentDir*(path: string): string {.
@ -593,8 +593,8 @@ iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string =
else: else:
for i in countup(0, path.len - 2): # ignore the last / for i in countup(0, path.len - 2): # ignore the last /
# deal with non-normalized paths such as /foo//bar//baz # deal with non-normalized paths such as /foo//bar//baz
if path[i] in {Dirsep, Altsep} and if path[i] in {DirSep, AltSep} and
(i == 0 or path[i-1] notin {Dirsep, Altsep}): (i == 0 or path[i-1] notin {DirSep, AltSep}):
yield path.substr(0, i) yield path.substr(0, i)
if inclusive: yield path if inclusive: yield path
@ -619,7 +619,7 @@ proc searchExtPos(s: string): int =
if s[i] == ExtSep: if s[i] == ExtSep:
result = i result = i
break break
elif s[i] in {Dirsep, Altsep}: elif s[i] in {DirSep, AltSep}:
break # do not skip over path break # do not skip over path
proc splitFile*(path: string): tuple[dir, name, ext: string] {. proc splitFile*(path: string): tuple[dir, name, ext: string] {.
@ -639,7 +639,7 @@ proc splitFile*(path: string): tuple[dir, name, ext: string] {.
## If `path` has no extension, `ext` is the empty string. ## If `path` has no extension, `ext` is the empty string.
## If `path` has no directory component, `dir` is the empty string. ## If `path` has no directory component, `dir` is the empty string.
## If `path` has no filename component, `name` and `ext` are empty strings. ## If `path` has no filename component, `name` and `ext` are empty strings.
if path.len == 0 or path[path.len-1] in {DirSep, Altsep}: if path.len == 0 or path[path.len-1] in {DirSep, AltSep}:
result = (path, "", "") result = (path, "", "")
else: else:
var sepPos = -1 var sepPos = -1
@ -647,8 +647,8 @@ proc splitFile*(path: string): tuple[dir, name, ext: string] {.
for i in countdown(len(path)-1, 0): for i in countdown(len(path)-1, 0):
if path[i] == ExtSep: if path[i] == ExtSep:
if dotPos == path.len and i > 0 and if dotPos == path.len and i > 0 and
path[i-1] notin {Dirsep, Altsep}: dotPos = i path[i-1] notin {DirSep, AltSep}: dotPos = i
elif path[i] in {Dirsep, Altsep}: elif path[i] in {DirSep, AltSep}:
sepPos = i sepPos = i
break break
result.dir = substr(path, 0, sepPos-1) result.dir = substr(path, 0, sepPos-1)
@ -659,7 +659,7 @@ proc extractFilename*(path: string): string {.
noSideEffect, rtl, extern: "nos$1".} = noSideEffect, rtl, extern: "nos$1".} =
## Extracts the filename of a given `path`. This is the same as ## Extracts the filename of a given `path`. This is the same as
## ``name & ext`` from ``splitFile(path)``. ## ``name & ext`` from ``splitFile(path)``.
if path.len == 0 or path[path.len-1] in {DirSep, Altsep}: if path.len == 0 or path[path.len-1] in {DirSep, AltSep}:
result = "" result = ""
else: else:
result = splitPath(path).tail result = splitPath(path).tail
@ -814,11 +814,11 @@ proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1",
if not open(b, path2): if not open(b, path2):
close(a) close(a)
return false return false
var bufA = alloc(bufsize) var bufA = alloc(bufSize)
var bufB = alloc(bufsize) var bufB = alloc(bufSize)
while true: while true:
var readA = readBuffer(a, bufA, bufsize) var readA = readBuffer(a, bufA, bufSize)
var readB = readBuffer(b, bufB, bufsize) var readB = readBuffer(b, bufB, bufSize)
if readA != readB: if readA != readB:
result = false result = false
break break
@ -1159,7 +1159,7 @@ iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} =
while true: while true:
if not skipFindData(f): if not skipFindData(f):
yield splitFile(pattern).dir / extractFilename(getFilename(f)) yield splitFile(pattern).dir / extractFilename(getFilename(f))
if findnextFile(res, f) == 0'i32: break if findNextFile(res, f) == 0'i32: break
findClose(res) findClose(res)
else: # here we use glob else: # here we use glob
var var
@ -1214,7 +1214,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
if (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32: if (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32:
k = pcDir k = pcDir
yield (k, dir / extractFilename(getFilename(f))) yield (k, dir / extractFilename(getFilename(f)))
if findnextFile(h, f) == 0'i32: break if findNextFile(h, f) == 0'i32: break
findClose(h) findClose(h)
else: else:
var d = openDir(dir) var d = openDir(dir)
@ -1308,7 +1308,7 @@ proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
when defined(doslike): when defined(doslike):
omitNext = isAbsolute(dir) omitNext = isAbsolute(dir)
for i in 1.. dir.len-1: for i in 1.. dir.len-1:
if dir[i] in {Dirsep, Altsep}: if dir[i] in {DirSep, AltSep}:
if omitNext: if omitNext:
omitNext = false omitNext = false
else: else:

View file

@ -396,7 +396,7 @@ when defined(Windows) and not defined(useNimRtl):
proc startProcess(command: string, proc startProcess(command: string,
workingDir: string = "", workingDir: string = "",
args: openarray[string] = [], args: openArray[string] = [],
env: PStringTable = nil, env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut}): PProcess = options: set[TProcessOption] = {poStdErrToStdOut}): PProcess =
var var

View file

@ -105,7 +105,7 @@ proc next*(p: var TOptParser) {.
of '-': of '-':
inc(i) inc(i)
if p.cmd[i] == '-': if p.cmd[i] == '-':
p.kind = cmdLongOption p.kind = cmdLongoption
inc(i) inc(i)
i = parseWord(p.cmd, i, p.key.string, {'\0', ' ', '\x09', ':', '='}) i = parseWord(p.cmd, i, p.key.string, {'\0', ' ', '\x09', ':', '='})
while p.cmd[i] in {'\x09', ' '}: inc(i) while p.cmd[i] in {'\x09', ' '}: inc(i)

View file

@ -26,7 +26,7 @@
{.deadCodeElim: on.} {.deadCodeElim: on.}
when hostos == "solaris": when hostOS == "solaris":
{.passl: "-lsocket -lnsl".} {.passl: "-lsocket -lnsl".}
import os, parseutils import os, parseutils
@ -467,7 +467,7 @@ template acceptAddrPlain(noClientRet, successRet: expr,
sslImplementation: stmt): stmt {.immediate.} = sslImplementation: stmt): stmt {.immediate.} =
assert(client != nil) assert(client != nil)
var sockAddress: Tsockaddr_in var sockAddress: Tsockaddr_in
var addrLen = sizeof(sockAddress).Tsocklen var addrLen = sizeof(sockAddress).TSockLen
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)), var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
addr(addrLen)) addr(addrLen))
@ -1258,10 +1258,10 @@ proc recvLine*(socket: TSocket, line: var TaintedString, timeout = -1): bool {.
if n > 0 and c == '\L': if n > 0 and c == '\L':
discard recv(socket, addr(c), 1) discard recv(socket, addr(c), 1)
elif n <= 0: return false elif n <= 0: return false
addNlIfEmpty() addNLIfEmpty()
return true return true
elif c == '\L': elif c == '\L':
addNlIfEmpty() addNLIfEmpty()
return true return true
add(line.string, c) add(line.string, c)
@ -1299,10 +1299,10 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {.
if n > 0 and c == '\L': if n > 0 and c == '\L':
discard recv(socket, addr(c), 1) discard recv(socket, addr(c), 1)
elif n <= 0: osError(osLastError()) elif n <= 0: osError(osLastError())
addNlIfEmpty() addNLIfEmpty()
return return
elif c == '\L': elif c == '\L':
addNlIfEmpty() addNLIfEmpty()
return return
add(line.string, c) add(line.string, c)
@ -1457,7 +1457,7 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
let err = osLastError() let err = osLastError()
when defined(windows): when defined(windows):
if err.int32 == WSAEWOULDBLOCK: if err.int32 == WSAEWOULDBLOCK:
return False return false
else: osError(err) else: osError(err)
else: else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
@ -1469,7 +1469,7 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
# increase capacity: # increase capacity:
setLen(s.string, s.string.len + bufSize) setLen(s.string, s.string.len + bufSize)
inc(pos, bytesRead) inc(pos, bytesRead)
result = True result = true
proc recvFrom*(socket: TSocket, data: var string, length: int, proc recvFrom*(socket: TSocket, data: var string, length: int,
address: var string, port: var TPort, flags = 0'i32): int {. address: var string, port: var TPort, flags = 0'i32): int {.
@ -1510,7 +1510,7 @@ proc recvFromAsync*(socket: TSocket, data: var string, length: int,
let err = osLastError() let err = osLastError()
when defined(windows): when defined(windows):
if err.int32 == WSAEWOULDBLOCK: if err.int32 == WSAEWOULDBLOCK:
return False return false
else: osError(err) else: osError(err)
else: else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
@ -1710,6 +1710,6 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking
when defined(Windows): when defined(Windows):
var wsa: TWSAData var wsa: TWSAData
if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError()) if wsaStartup(0x0101'i16, addr wsa) != 0: osError(osLastError())

View file

@ -214,7 +214,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string =
while last < len(s): while last < len(s):
while s[last] in seps: inc(last) while s[last] in seps: inc(last)
var first = last var first = last
while last < len(s) and s[last] not_in seps: inc(last) # BUGFIX! while last < len(s) and s[last] notin seps: inc(last) # BUGFIX!
if first <= last-1: if first <= last-1:
yield substr(s, first, last-1) yield substr(s, first, last-1)

View file

@ -1115,10 +1115,10 @@ proc toLower*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into lower case. This works for any Unicode character. ## Converts `c` into lower case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`. ## If possible, prefer `toLower` over `toUpper`.
var c = IRune(c) var c = IRune(c)
var p = binarySearch(c, tolowerRanges, len(toLowerRanges) div 3, 3) var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]: if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return TRune(c + tolowerRanges[p+2] - 500) return TRune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2) p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]: if p >= 0 and c == tolowerSinglets[p]:
return TRune(c + tolowerSinglets[p+1] - 500) return TRune(c + tolowerSinglets[p+1] - 500)
return TRune(c) return TRune(c)
@ -1127,10 +1127,10 @@ proc toUpper*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into upper case. This works for any Unicode character. ## Converts `c` into upper case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`. ## If possible, prefer `toLower` over `toUpper`.
var c = IRune(c) var c = IRune(c)
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3) var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]: if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return TRune(c + toupperRanges[p+2] - 500) return TRune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2) p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]: if p >= 0 and c == toupperSinglets[p]:
return TRune(c + toupperSinglets[p+1] - 500) return TRune(c + toupperSinglets[p+1] - 500)
return TRune(c) return TRune(c)
@ -1147,10 +1147,10 @@ proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## If possible, prefer `isLower` over `isUpper`. ## If possible, prefer `isLower` over `isUpper`.
var c = IRune(c) var c = IRune(c)
# Note: toUpperRanges is correct here! # Note: toUpperRanges is correct here!
var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3) var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]: if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
return true return true
p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2) p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]: if p >= 0 and c == toupperSinglets[p]:
return true return true
@ -1159,10 +1159,10 @@ proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
## If possible, prefer `isLower` over `isUpper`. ## If possible, prefer `isLower` over `isUpper`.
var c = IRune(c) var c = IRune(c)
# Note: toLowerRanges is correct here! # Note: toLowerRanges is correct here!
var p = binarySearch(c, toLowerRanges, len(toLowerRanges) div 3, 3) var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]: if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
return true return true
p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2) p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]: if p >= 0 and c == tolowerSinglets[p]:
return true return true

View file

@ -1145,7 +1145,7 @@ when not defined(nimrodVM):
## otherwise. Like any procedure dealing with raw memory this is ## otherwise. Like any procedure dealing with raw memory this is
## *unsafe*. ## *unsafe*.
when hostOs != "standalone": when hostOS != "standalone":
proc alloc*(size: int): pointer {.noconv, rtl, tags: [].} proc alloc*(size: int): pointer {.noconv, rtl, tags: [].}
## allocates a new memory block with at least ``size`` bytes. The ## allocates a new memory block with at least ``size`` bytes. The
## block has to be freed with ``realloc(block, 0)`` or ## block has to be freed with ``realloc(block, 0)`` or

View file

@ -144,7 +144,7 @@ proc objectInitAux(dest: pointer, n: ptr TNimNode) =
var d = cast[TAddress](dest) var d = cast[TAddress](dest)
case n.kind case n.kind
of nkNone: sysAssert(false, "objectInitAux") of nkNone: sysAssert(false, "objectInitAux")
of nkSLot: objectInit(cast[pointer](d +% n.offset), n.typ) of nkSlot: objectInit(cast[pointer](d +% n.offset), n.typ)
of nkList: of nkList:
for i in 0..n.len-1: for i in 0..n.len-1:
objectInitAux(dest, n.sons[i]) objectInitAux(dest, n.sons[i])

View file

@ -10,7 +10,7 @@
# Implementation of some runtime checks. # Implementation of some runtime checks.
proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} = proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} =
when hostOs == "standalone": when hostOS == "standalone":
sysFatal(EOutOfRange, "value out of range") sysFatal(EOutOfRange, "value out of range")
else: else:
sysFatal(EOutOfRange, "value out of range: ", $val) sysFatal(EOutOfRange, "value out of range: ", $val)

View file

@ -573,7 +573,7 @@ proc scan(s: PCell) =
proc collectWhite(s: PCell) = proc collectWhite(s: PCell) =
if s.color == rcWhite and s notin gch.cycleRoots: if s.color == rcWhite and s notin gch.cycleRoots:
s.setcolor(rcBlack) s.setColor(rcBlack)
forAllChildren(s, waCollectWhite) forAllChildren(s, waCollectWhite)
freeCyclicCell(gch, s) freeCyclicCell(gch, s)
@ -891,7 +891,7 @@ proc collectZCT(gch: var TGcHeap): bool =
const workPackage = 100 const workPackage = 100
var L = addr(gch.zct.len) var L = addr(gch.zct.len)
when withRealtime: when withRealTime:
var steps = workPackage var steps = workPackage
var t0: TTicks var t0: TTicks
if gch.maxPause > 0: t0 = getticks() if gch.maxPause > 0: t0 = getticks()
@ -904,7 +904,7 @@ proc collectZCT(gch: var TGcHeap): bool =
c.refcount = c.refcount and not ZctFlag c.refcount = c.refcount and not ZctFlag
gch.zct.d[0] = gch.zct.d[L[] - 1] gch.zct.d[0] = gch.zct.d[L[] - 1]
dec(L[]) dec(L[])
when withRealtime: dec steps when withRealTime: dec steps
if c.refcount <% rcIncrement: if c.refcount <% rcIncrement:
# It may have a RC > 0, if it is in the hardware stack or # It may have a RC > 0, if it is in the hardware stack or
# it has not been removed yet from the ZCT. This is because # it has not been removed yet from the ZCT. This is because
@ -927,7 +927,7 @@ proc collectZCT(gch: var TGcHeap): bool =
else: else:
sysAssert(c.typ != nil, "collectZCT 2") sysAssert(c.typ != nil, "collectZCT 2")
zeroMem(c, sizeof(TCell)) zeroMem(c, sizeof(TCell))
when withRealtime: when withRealTime:
if steps == 0: if steps == 0:
steps = workPackage steps = workPackage
if gch.maxPause > 0: if gch.maxPause > 0:
@ -952,7 +952,7 @@ proc unmarkStackAndRegisters(gch: var TGcHeap) =
gch.decStack.len = 0 gch.decStack.len = 0
proc collectCTBody(gch: var TGcHeap) = proc collectCTBody(gch: var TGcHeap) =
when withRealtime: when withRealTime:
let t0 = getticks() let t0 = getticks()
sysAssert(allocInv(gch.region), "collectCT: begin") sysAssert(allocInv(gch.region), "collectCT: begin")
@ -975,7 +975,7 @@ proc collectCTBody(gch: var TGcHeap) =
unmarkStackAndRegisters(gch) unmarkStackAndRegisters(gch)
sysAssert(allocInv(gch.region), "collectCT: end") sysAssert(allocInv(gch.region), "collectCT: end")
when withRealtime: when withRealTime:
let duration = getticks() - t0 let duration = getticks() - t0
gch.stat.maxPause = max(gch.stat.maxPause, duration) gch.stat.maxPause = max(gch.stat.maxPause, duration)
when defined(reportMissedDeadlines): when defined(reportMissedDeadlines):
@ -997,7 +997,7 @@ proc collectCT(gch: var TGcHeap) =
markForDebug(gch) markForDebug(gch)
collectCTBody(gch) collectCTBody(gch)
when withRealtime: when withRealTime:
proc toNano(x: int): TNanos {.inline.} = proc toNano(x: int): TNanos {.inline.} =
result = x * 1000 result = x * 1000

View file

@ -95,7 +95,7 @@ proc write(f: TFile, i: int) =
fprintf(f, "%ld", i) fprintf(f, "%ld", i)
proc write(f: TFile, i: BiggestInt) = proc write(f: TFile, i: BiggestInt) =
when sizeof(Biggestint) == 8: when sizeof(BiggestInt) == 8:
fprintf(f, "%lld", i) fprintf(f, "%lld", i)
else: else:
fprintf(f, "%ld", i) fprintf(f, "%ld", i)
@ -235,17 +235,17 @@ proc fwrite(buf: pointer, size, n: int, f: TFile): int {.
proc readBuffer(f: TFile, buffer: pointer, len: int): int = proc readBuffer(f: TFile, buffer: pointer, len: int): int =
result = fread(buffer, 1, len, f) result = fread(buffer, 1, len, f)
proc readBytes(f: TFile, a: var openarray[int8], start, len: int): int = proc readBytes(f: TFile, a: var openArray[int8], start, len: int): int =
result = readBuffer(f, addr(a[start]), len) result = readBuffer(f, addr(a[start]), len)
proc readChars(f: TFile, a: var openarray[char], start, len: int): int = proc readChars(f: TFile, a: var openArray[char], start, len: int): int =
result = readBuffer(f, addr(a[start]), len) result = readBuffer(f, addr(a[start]), len)
{.push stackTrace:off, profiler:off.} {.push stackTrace:off, profiler:off.}
proc writeBytes(f: TFile, a: openarray[int8], start, len: int): int = proc writeBytes(f: TFile, a: openArray[int8], start, len: int): int =
var x = cast[ptr array[0..1000_000_000, int8]](a) var x = cast[ptr array[0..1000_000_000, int8]](a)
result = writeBuffer(f, addr(x[start]), len) result = writeBuffer(f, addr(x[start]), len)
proc writeChars(f: TFile, a: openarray[char], start, len: int): int = proc writeChars(f: TFile, a: openArray[char], start, len: int): int =
var x = cast[ptr array[0..1000_000_000, int8]](a) var x = cast[ptr array[0..1000_000_000, int8]](a)
result = writeBuffer(f, addr(x[start]), len) result = writeBuffer(f, addr(x[start]), len)
proc writeBuffer(f: TFile, buffer: pointer, len: int): int = proc writeBuffer(f: TFile, buffer: pointer, len: int): int =

View file

@ -92,7 +92,7 @@ const
DETACHED_PROCESS* = 8'i32 DETACHED_PROCESS* = 8'i32
SW_SHOWNORMAL* = 1'i32 SW_SHOWNORMAL* = 1'i32
INVALID_HANDLE_VALUE* = THANDLE(-1) INVALID_HANDLE_VALUE* = THandle(-1)
CREATE_UNICODE_ENVIRONMENT* = 1024'i32 CREATE_UNICODE_ENVIRONMENT* = 1024'i32
@ -418,7 +418,7 @@ type
ai_addr*: ptr TSockAddr ## Socket address of socket. ai_addr*: ptr TSockAddr ## Socket address of socket.
ai_next*: ptr TAddrInfo ## Pointer to next in list. ai_next*: ptr TAddrInfo ## Pointer to next in list.
Tsocklen* = cuint TSockLen* = cuint
var var
SOMAXCONN* {.importc, header: "Winsock2.h".}: cint SOMAXCONN* {.importc, header: "Winsock2.h".}: cint
@ -457,20 +457,20 @@ proc socket*(af, typ, protocol: cint): TSocketHandle {.
proc closesocket*(s: TSocketHandle): cint {. proc closesocket*(s: TSocketHandle): cint {.
stdcall, importc: "closesocket", dynlib: ws2dll.} stdcall, importc: "closesocket", dynlib: ws2dll.}
proc accept*(s: TSocketHandle, a: ptr TSockAddr, addrlen: ptr Tsocklen): TSocketHandle {. proc accept*(s: TSocketHandle, a: ptr TSockAddr, addrlen: ptr TSockLen): TSocketHandle {.
stdcall, importc: "accept", dynlib: ws2dll.} stdcall, importc: "accept", dynlib: ws2dll.}
proc bindSocket*(s: TSocketHandle, name: ptr TSockAddr, namelen: Tsocklen): cint {. proc bindSocket*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
stdcall, importc: "bind", dynlib: ws2dll.} stdcall, importc: "bind", dynlib: ws2dll.}
proc connect*(s: TSocketHandle, name: ptr TSockAddr, namelen: Tsocklen): cint {. proc connect*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
stdcall, importc: "connect", dynlib: ws2dll.} stdcall, importc: "connect", dynlib: ws2dll.}
proc getsockname*(s: TSocketHandle, name: ptr TSockAddr, proc getsockname*(s: TSocketHandle, name: ptr TSockAddr,
namelen: ptr Tsocklen): cint {. namelen: ptr TSockLen): cint {.
stdcall, importc: "getsockname", dynlib: ws2dll.} stdcall, importc: "getsockname", dynlib: ws2dll.}
proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer,
optlen: ptr Tsocklen): cint {. optlen: ptr TSockLen): cint {.
stdcall, importc: "getsockopt", dynlib: ws2dll.} stdcall, importc: "getsockopt", dynlib: ws2dll.}
proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer,
optlen: Tsocklen): cint {. optlen: TSockLen): cint {.
stdcall, importc: "setsockopt", dynlib: ws2dll.} stdcall, importc: "setsockopt", dynlib: ws2dll.}
proc listen*(s: TSocketHandle, backlog: cint): cint {. proc listen*(s: TSocketHandle, backlog: cint): cint {.
@ -478,7 +478,7 @@ proc listen*(s: TSocketHandle, backlog: cint): cint {.
proc recv*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {. proc recv*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "recv", dynlib: ws2dll.} stdcall, importc: "recv", dynlib: ws2dll.}
proc recvfrom*(s: TSocketHandle, buf: cstring, len, flags: cint, proc recvfrom*(s: TSocketHandle, buf: cstring, len, flags: cint,
fromm: ptr TSockAddr, fromlen: ptr Tsocklen): cint {. fromm: ptr TSockAddr, fromlen: ptr TSockLen): cint {.
stdcall, importc: "recvfrom", dynlib: ws2dll.} stdcall, importc: "recvfrom", dynlib: ws2dll.}
proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet, proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet,
timeout: ptr TTimeval): cint {. timeout: ptr TTimeval): cint {.
@ -486,15 +486,15 @@ proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet,
proc send*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {. proc send*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "send", dynlib: ws2dll.} stdcall, importc: "send", dynlib: ws2dll.}
proc sendto*(s: TSocketHandle, buf: pointer, len, flags: cint, proc sendto*(s: TSocketHandle, buf: pointer, len, flags: cint,
to: ptr TSockAddr, tolen: Tsocklen): cint {. to: ptr TSockAddr, tolen: TSockLen): cint {.
stdcall, importc: "sendto", dynlib: ws2dll.} stdcall, importc: "sendto", dynlib: ws2dll.}
proc shutdown*(s: TSocketHandle, how: cint): cint {. proc shutdown*(s: TSocketHandle, how: cint): cint {.
stdcall, importc: "shutdown", dynlib: ws2dll.} stdcall, importc: "shutdown", dynlib: ws2dll.}
proc getnameinfo*(a1: ptr TSockAddr, a2: Tsocklen, proc getnameinfo*(a1: ptr TSockAddr, a2: TSockLen,
a3: cstring, a4: Tsocklen, a5: cstring, a3: cstring, a4: TSockLen, a5: cstring,
a6: Tsocklen, a7: cint): cint {. a6: TSockLen, a7: cint): cint {.
stdcall, importc: "getnameinfo", dynlib: ws2dll.} stdcall, importc: "getnameinfo", dynlib: ws2dll.}
proc inet_addr*(cp: cstring): int32 {. proc inet_addr*(cp: cstring): int32 {.
@ -514,7 +514,7 @@ proc FD_SET*(Socket: TSocketHandle, FDSet: var TFdSet) =
proc FD_ZERO*(FDSet: var TFdSet) = proc FD_ZERO*(FDSet: var TFdSet) =
FDSet.fd_count = 0 FDSet.fd_count = 0
proc WSAStartup*(wVersionRequired: int16, WSData: ptr TWSAData): cint {. proc wsaStartup*(wVersionRequired: int16, WSData: ptr TWSAData): cint {.
stdcall, importc: "WSAStartup", dynlib: ws2dll.} stdcall, importc: "WSAStartup", dynlib: ws2dll.}
proc getaddrinfo*(nodename, servname: cstring, hints: ptr TAddrInfo, proc getaddrinfo*(nodename, servname: cstring, hints: ptr TAddrInfo,