From 9035d15ed22de1f80486d94ec63e720a4d04cbc0 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 25 Nov 2013 13:04:11 +0100 Subject: next steps for FFI support --- compiler/commands.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/commands.nim b/compiler/commands.nim index d3266930b..a02728dac 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -398,13 +398,13 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = if pass in {passCmd2, passPP}: extccomp.addLinkOption(arg) of "cincludes": expectArg(switch, arg, pass, info) - if pass in {passCmd2, passPP}: cIncludes.add arg + if pass in {passCmd2, passPP}: cIncludes.add arg.processPath of "clibdir": expectArg(switch, arg, pass, info) - if pass in {passCmd2, passPP}: cLibs.add arg + if pass in {passCmd2, passPP}: cLibs.add arg.processPath of "clib": expectArg(switch, arg, pass, info) - if pass in {passCmd2, passPP}: cLinkedLibs.add arg + if pass in {passCmd2, passPP}: cLinkedLibs.add arg.processPath of "header": headerFile = arg incl(gGlobalOptions, optGenIndex) -- cgit 1.4.1-2-gfad0 From 2df9b442c646e06cc577a723dc2592275bf9b6f5 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 27 Dec 2013 15:48:53 +0100 Subject: case consistency part 1 --- compiler/astalgo.nim | 177 ++++++++++++++++++------------------ compiler/bitsets.nim | 40 ++++----- compiler/ccgexprs.nim | 4 +- compiler/ccgmerge.nim | 3 +- compiler/ccgstmts.nim | 32 +++---- compiler/ccgthreadvars.nim | 4 +- compiler/ccgtypes.nim | 6 +- compiler/ccgutils.nim | 36 ++++---- compiler/cgen.nim | 8 +- compiler/cgmeth.nim | 6 +- compiler/commands.nim | 82 ++++++++--------- compiler/condsyms.nim | 64 ++++++------- compiler/docgen.nim | 20 ++--- compiler/extccomp.nim | 18 ++-- compiler/idents.nim | 2 +- compiler/idgen.nim | 6 +- compiler/lexer.nim | 8 +- compiler/lists.nim | 22 ++--- compiler/llstream.nim | 75 ++++++++-------- compiler/lookups.nim | 86 +++++++++--------- compiler/magicsys.nim | 17 ++-- compiler/main.nim | 32 +++---- compiler/modules.nim | 2 +- compiler/msgs.nim | 52 +++++------ compiler/nimconf.nim | 2 +- compiler/nimlexbase.nim | 15 ++-- compiler/nimrod.nim | 10 +-- compiler/nimsets.nim | 8 +- compiler/options.nim | 2 +- compiler/parser.nim | 32 +++---- compiler/pbraces.nim | 2 +- compiler/platform.nim | 12 +-- compiler/pragmas.nim | 32 +++---- compiler/pretty.nim | 166 ++++++++++++++++++++++++++++++---- compiler/procfind.nim | 10 +-- compiler/renderer.nim | 8 +- compiler/rodread.nim | 34 +++---- compiler/rodutils.nim | 4 +- compiler/ropes.nim | 26 +++--- compiler/sem.nim | 2 +- compiler/semcall.nim | 24 ++--- compiler/semdata.nim | 32 +++---- compiler/semdestruct.nim | 6 +- compiler/semexprs.nim | 20 ++--- compiler/semgnrc.nim | 2 +- compiler/seminst.nim | 8 +- compiler/semstmts.nim | 10 +-- compiler/semtempl.nim | 4 +- compiler/semtypes.nim | 2 +- compiler/semtypinst.nim | 21 +++-- compiler/service.nim | 2 +- compiler/sigmatch.nim | 12 +-- compiler/suggest.nim | 4 +- compiler/syntaxes.nim | 30 +++---- compiler/transf.nim | 2 +- compiler/trees.nim | 36 ++++---- compiler/treetab.nim | 30 +++---- compiler/types.nim | 81 ++++++++--------- compiler/vm.nim | 2 +- compiler/vmgen.nim | 2 +- doc/manual.txt | 2 + lib/impure/rdstdin.nim | 8 +- lib/packages/docutils/rstast.nim | 4 +- lib/packages/docutils/rstgen.nim | 6 +- lib/pure/collections/intsets.nim | 8 +- lib/pure/collections/lists.nim | 8 +- lib/pure/collections/tables.nim | 72 +++++++-------- lib/pure/lexbase.nim | 18 ++-- lib/pure/os.nim | 190 +++++++++++++++++++-------------------- lib/pure/osproc.nim | 16 ++-- lib/pure/parseutils.nim | 4 +- lib/pure/sockets.nim | 24 ++--- lib/pure/strtabs.nim | 8 +- lib/pure/strutils.nim | 18 ++-- lib/pure/times.nim | 10 +-- lib/pure/unicode.nim | 4 +- lib/system.nim | 20 ++--- lib/system/alloc.nim | 45 +++++----- lib/system/assign.nim | 4 +- lib/system/atomics.nim | 122 ++++++++++++------------- lib/system/avltree.nim | 10 +-- lib/system/cellsets.nim | 50 +++++------ lib/system/dyncalls.nim | 13 +-- lib/system/gc.nim | 4 +- lib/system/repr.nim | 2 +- lib/system/syslocks.nim | 54 +++++------ lib/windows/winlean.nim | 184 +++++++++++++++++++------------------ todo.txt | 5 +- 88 files changed, 1266 insertions(+), 1144 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 4f869cfca..b04cff598 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -24,35 +24,35 @@ proc symToYaml*(n: PSym, indent: int = 0, maxRecDepth: int = - 1): PRope proc lineInfoToStr*(info: TLineInfo): PRope # ----------------------- node sets: --------------------------------------- -proc ObjectSetContains*(t: TObjectSet, obj: PObject): bool +proc objectSetContains*(t: TObjectSet, obj: PObject): bool # returns true whether n is in t -proc ObjectSetIncl*(t: var TObjectSet, obj: PObject) +proc objectSetIncl*(t: var TObjectSet, obj: PObject) # include an element n in the table t -proc ObjectSetContainsOrIncl*(t: var TObjectSet, obj: PObject): bool +proc objectSetContainsOrIncl*(t: var TObjectSet, obj: PObject): bool # more are not needed ... # ----------------------- (key, val)-Hashtables ---------------------------- -proc TablePut*(t: var TTable, key, val: PObject) -proc TableGet*(t: TTable, key: PObject): PObject +proc tablePut*(t: var TTable, key, val: PObject) +proc tableGet*(t: TTable, key: PObject): PObject type TCmpProc* = proc (key, closure: PObject): bool {.nimcall.} # true if found -proc TableSearch*(t: TTable, key, closure: PObject, +proc tableSearch*(t: TTable, key, closure: PObject, comparator: TCmpProc): PObject # return val as soon as comparator returns true; if this never happens, # nil is returned # ----------------------- str table ----------------------------------------- -proc StrTableContains*(t: TStrTable, n: PSym): bool -proc StrTableAdd*(t: var TStrTable, n: PSym) -proc StrTableGet*(t: TStrTable, name: PIdent): PSym +proc strTableContains*(t: TStrTable, n: PSym): bool +proc strTableAdd*(t: var TStrTable, n: PSym) +proc strTableGet*(t: TStrTable, name: PIdent): PSym type TTabIter*{.final.} = object # consider all fields here private h*: THash # current hash -proc InitTabIter*(ti: var TTabIter, tab: TStrTable): PSym -proc NextIter*(ti: var TTabIter, tab: TStrTable): PSym +proc initTabIter*(ti: var TTabIter, tab: TStrTable): PSym +proc nextIter*(ti: var TTabIter, tab: TStrTable): PSym # usage: # var # i: TTabIter @@ -69,8 +69,8 @@ type name*: PIdent -proc InitIdentIter*(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym -proc NextIdentIter*(ti: var TIdentIter, tab: TStrTable): PSym +proc initIdentIter*(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym +proc nextIdentIter*(ti: var TIdentIter, tab: TStrTable): PSym # these are for debugging only: They are not really deprecated, but I want # the warning so that release versions do not contain debugging statements: @@ -79,15 +79,14 @@ proc debug*(n: PType) {.deprecated.} proc debug*(n: PNode) {.deprecated.} # --------------------------- ident tables ---------------------------------- -proc IdTableGet*(t: TIdTable, key: PIdObj): PObject -proc IdTableGet*(t: TIdTable, key: int): PObject -proc IdTablePut*(t: var TIdTable, key: PIdObj, val: PObject) -proc IdTableHasObjectAsKey*(t: TIdTable, key: PIdObj): bool +proc idTableGet*(t: TIdTable, key: PIdObj): PObject +proc idTableGet*(t: TIdTable, key: int): PObject +proc idTablePut*(t: var TIdTable, key: PIdObj, val: PObject) +proc idTableHasObjectAsKey*(t: TIdTable, key: PIdObj): bool # checks if `t` contains the `key` (compared by the pointer value, not only # `key`'s id) -proc IdNodeTableGet*(t: TIdNodeTable, key: PIdObj): PNode -proc IdNodeTablePut*(t: var TIdNodeTable, key: PIdObj, val: PNode) -proc writeIdNodeTable*(t: TIdNodeTable) +proc idNodeTableGet*(t: TIdNodeTable, key: PIdObj): PNode +proc idNodeTablePut*(t: var TIdNodeTable, key: PIdObj, val: PNode) # --------------------------------------------------------------------------- @@ -111,9 +110,9 @@ type data*: TIIPairSeq -proc initIITable*(x: var TIITable) -proc IITableGet*(t: TIITable, key: int): int -proc IITablePut*(t: var TIITable, key, val: int) +proc initIiTable*(x: var TIITable) +proc iiTableGet*(t: TIITable, key: int): int +proc iiTablePut*(t: var TIITable, key, val: int) # implementation @@ -129,7 +128,7 @@ proc skipConvTakeType*(n: PNode): PNode = result = n.skipConv result.typ = n.typ -proc SameValue*(a, b: PNode): bool = +proc sameValue*(a, b: PNode): bool = result = false case a.kind of nkCharLit..nkInt64Lit: @@ -141,7 +140,7 @@ proc SameValue*(a, b: PNode): bool = else: # don't raise an internal error for 'nimrod check': #InternalError(a.info, "SameValue") - nil + discard proc leValue*(a, b: PNode): bool = # a <= b? @@ -156,7 +155,7 @@ proc leValue*(a, b: PNode): bool = else: # don't raise an internal error for 'nimrod check': #InternalError(a.info, "leValue") - nil + discard proc lookupInRecord(n: PNode, field: PIdent): PSym = result = nil @@ -182,14 +181,14 @@ proc lookupInRecord(n: PNode, field: PIdent): PSym = proc getModule(s: PSym): PSym = result = s assert((result.kind == skModule) or (result.owner != result)) - while (result != nil) and (result.kind != skModule): result = result.owner + while result != nil and result.kind != skModule: result = result.owner proc getSymFromList(list: PNode, ident: PIdent, start: int = 0): PSym = for i in countup(start, sonsLen(list) - 1): if list.sons[i].kind == nkSym: result = list.sons[i].sym if result.name.id == ident.id: return - else: InternalError(list.info, "getSymFromList") + else: internalError(list.info, "getSymFromList") result = nil proc hashNode(p: PObject): THash = @@ -501,7 +500,7 @@ proc objectSetContainsOrIncl(t: var TObjectSet, obj: PObject): bool = inc(t.counter) result = false -proc TableRawGet(t: TTable, key: PObject): int = +proc tableRawGet(t: TTable, key: PObject): int = var h: THash = hashNode(key) and high(t.data) # start with real hash value while t.data[h].key != nil: if t.data[h].key == key: @@ -509,7 +508,7 @@ proc TableRawGet(t: TTable, key: PObject): int = h = nextTry(h, high(t.data)) result = -1 -proc TableSearch(t: TTable, key, closure: PObject, +proc tableSearch(t: TTable, key, closure: PObject, comparator: TCmpProc): PObject = var h: THash = hashNode(key) and high(t.data) # start with real hash value while t.data[h].key != nil: @@ -520,13 +519,13 @@ proc TableSearch(t: TTable, key, closure: PObject, h = nextTry(h, high(t.data)) result = nil -proc TableGet(t: TTable, key: PObject): PObject = - var index = TableRawGet(t, key) +proc tableGet(t: TTable, key: PObject): PObject = + var index = tableRawGet(t, key) if index >= 0: result = t.data[index].val else: result = nil -proc TableRawInsert(data: var TPairSeq, key, val: PObject) = - var h: THash = HashNode(key) and high(data) +proc tableRawInsert(data: var TPairSeq, key, val: PObject) = + var h: THash = hashNode(key) and high(data) while data[h].key != nil: assert(data[h].key != key) h = nextTry(h, high(data)) @@ -534,23 +533,23 @@ proc TableRawInsert(data: var TPairSeq, key, val: PObject) = data[h].key = key data[h].val = val -proc TableEnlarge(t: var TTable) = +proc tableEnlarge(t: var TTable) = var n: TPairSeq newSeq(n, len(t.data) * growthFactor) 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) -proc TablePut(t: var TTable, key, val: PObject) = +proc tablePut(t: var TTable, key, val: PObject) = var index = TableRawGet(t, key) if index >= 0: t.data[index].val = val else: - if mustRehash(len(t.data), t.counter): TableEnlarge(t) - TableRawInsert(t.data, key, val) + if mustRehash(len(t.data), t.counter): tableEnlarge(t) + tableRawInsert(t.data, key, val) inc(t.counter) -proc StrTableContains(t: TStrTable, n: PSym): bool = +proc strTableContains(t: TStrTable, n: PSym): bool = var h: THash = n.name.h and high(t.data) # start with real hash value while t.data[h] != nil: if (t.data[h] == n): @@ -558,7 +557,7 @@ proc StrTableContains(t: TStrTable, n: PSym): bool = h = nextTry(h, high(t.data)) result = false -proc StrTableRawInsert(data: var TSymSeq, n: PSym) = +proc strTableRawInsert(data: var TSymSeq, n: PSym) = var h: THash = n.name.h and high(data) while data[h] != nil: if data[h] == n: @@ -569,7 +568,7 @@ proc StrTableRawInsert(data: var TSymSeq, n: PSym) = assert(data[h] == nil) data[h] = n -proc SymTabReplaceRaw(data: var TSymSeq, prevSym: PSym, newSym: PSym) = +proc symTabReplaceRaw(data: var TSymSeq, prevSym: PSym, newSym: PSym) = assert prevSym.name.h == newSym.name.h var h: THash = prevSym.name.h and high(data) while data[h] != nil: @@ -579,22 +578,22 @@ proc SymTabReplaceRaw(data: var TSymSeq, prevSym: PSym, newSym: PSym) = h = nextTry(h, high(data)) assert false -proc SymTabReplace*(t: var TStrTable, prevSym: PSym, newSym: PSym) = - SymTabReplaceRaw(t.data, prevSym, newSym) +proc symTabReplace*(t: var TStrTable, prevSym: PSym, newSym: PSym) = + symTabReplaceRaw(t.data, prevSym, newSym) -proc StrTableEnlarge(t: var TStrTable) = +proc strTableEnlarge(t: var TStrTable) = var n: TSymSeq newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): if t.data[i] != nil: StrTableRawInsert(n, t.data[i]) swap(t.data, n) -proc StrTableAdd(t: var TStrTable, n: PSym) = +proc strTableAdd(t: var TStrTable, n: PSym) = if mustRehash(len(t.data), t.counter): StrTableEnlarge(t) StrTableRawInsert(t.data, n) inc(t.counter) -proc StrTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = +proc strTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = # returns true if n is already in the string table: # It is essential that `n` is written nevertheless! # This way the newest redefinition is picked by the semantic analyses! @@ -616,7 +615,7 @@ proc StrTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = inc(t.counter) result = false -proc StrTableGet(t: TStrTable, name: PIdent): PSym = +proc strTableGet(t: TStrTable, name: PIdent): PSym = var h: THash = name.h and high(t.data) while true: result = t.data[h] @@ -624,13 +623,13 @@ proc StrTableGet(t: TStrTable, name: PIdent): PSym = if result.name.id == name.id: break h = nextTry(h, high(t.data)) -proc InitIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym = +proc initIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym = ti.h = s.h ti.name = s if tab.Counter == 0: result = nil else: result = NextIdentIter(ti, tab) -proc NextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = +proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = var h, start: THash h = ti.h and high(tab.data) start = h @@ -644,7 +643,7 @@ proc NextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = result = tab.data[h] ti.h = nextTry(h, high(tab.data)) -proc NextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, +proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, excluding: TIntSet): PSym = var h: THash = ti.h and high(tab.data) var start = h @@ -660,33 +659,33 @@ proc NextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, ti.h = nextTry(h, high(tab.data)) if result != nil and Contains(excluding, result.id): result = nil -proc FirstIdentExcluding*(ti: var TIdentIter, tab: TStrTable, s: PIdent, +proc firstIdentExcluding*(ti: var TIdentIter, tab: TStrTable, s: PIdent, excluding: TIntSet): PSym = ti.h = s.h ti.name = s if tab.Counter == 0: result = nil else: result = NextIdentExcluding(ti, tab, excluding) -proc InitTabIter(ti: var TTabIter, tab: TStrTable): PSym = +proc initTabIter(ti: var TTabIter, tab: TStrTable): PSym = ti.h = 0 # we start by zero ... if tab.counter == 0: result = nil # FIX 1: removed endless loop else: result = NextIter(ti, tab) -proc NextIter(ti: var TTabIter, tab: TStrTable): PSym = +proc nextIter(ti: var TTabIter, tab: TStrTable): PSym = result = nil while (ti.h <= high(tab.data)): result = tab.data[ti.h] - Inc(ti.h) # ... and increment by one always + inc(ti.h) # ... and increment by one always if result != nil: break iterator items*(tab: TStrTable): PSym = var it: TTabIter - var s = InitTabIter(it, tab) + var s = initTabIter(it, tab) while s != nil: yield s - s = NextIter(it, tab) + s = nextIter(it, tab) proc hasEmptySlot(data: TIdPairSeq): bool = for h in countup(0, high(data)): @@ -694,7 +693,7 @@ proc hasEmptySlot(data: TIdPairSeq): bool = return true result = false -proc IdTableRawGet(t: TIdTable, key: int): int = +proc idTableRawGet(t: TIdTable, key: int): int = var h: THash h = key and high(t.data) # start with real hash value while t.data[h].key != nil: @@ -703,18 +702,18 @@ proc IdTableRawGet(t: TIdTable, key: int): int = h = nextTry(h, high(t.data)) result = - 1 -proc IdTableHasObjectAsKey(t: TIdTable, key: PIdObj): bool = - var index = IdTableRawGet(t, key.id) +proc idTableHasObjectAsKey(t: TIdTable, key: PIdObj): bool = + var index = idTableRawGet(t, key.id) if index >= 0: result = t.data[index].key == key else: result = false -proc IdTableGet(t: TIdTable, key: PIdObj): PObject = - var index = IdTableRawGet(t, key.id) +proc idTableGet(t: TIdTable, key: PIdObj): PObject = + var index = idTableRawGet(t, key.id) if index >= 0: result = t.data[index].val else: result = nil -proc IdTableGet(t: TIdTable, key: int): PObject = - var index = IdTableRawGet(t, key) +proc idTableGet(t: TIdTable, key: int): PObject = + var index = idTableRawGet(t, key) if index >= 0: result = t.data[index].val else: result = nil @@ -723,7 +722,7 @@ iterator pairs*(t: TIdTable): tuple[key: int, value: PObject] = if t.data[i].key != nil: yield (t.data[i].key.id, t.data[i].val) -proc IdTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) = +proc idTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) = var h: THash h = key.id and high(data) while data[h].key != nil: @@ -733,7 +732,7 @@ proc IdTableRawInsert(data: var TIdPairSeq, key: PIdObj, val: PObject) = data[h].key = key data[h].val = val -proc IdTablePut(t: var TIdTable, key: PIdObj, val: PObject) = +proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) = var index: int n: TIdPairSeq @@ -752,14 +751,11 @@ proc IdTablePut(t: var TIdTable, key: PIdObj, val: PObject) = IdTableRawInsert(t.data, key, val) inc(t.counter) -iterator IdTablePairs*(t: TIdTable): tuple[key: PIdObj, val: PObject] = +iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: PObject] = for i in 0 .. high(t.data): if not isNil(t.data[i].key): yield (t.data[i].key, t.data[i].val) -proc writeIdNodeTable(t: TIdNodeTable) = - nil - -proc IdNodeTableRawGet(t: TIdNodeTable, key: PIdObj): int = +proc idNodeTableRawGet(t: TIdNodeTable, key: PIdObj): int = var h: THash h = key.id and high(t.data) # start with real hash value while t.data[h].key != nil: @@ -768,17 +764,17 @@ proc IdNodeTableRawGet(t: TIdNodeTable, key: PIdObj): int = h = nextTry(h, high(t.data)) result = - 1 -proc IdNodeTableGet(t: TIdNodeTable, key: PIdObj): PNode = +proc idNodeTableGet(t: TIdNodeTable, key: PIdObj): PNode = var index: int - index = IdNodeTableRawGet(t, key) + index = idNodeTableRawGet(t, key) if index >= 0: result = t.data[index].val else: result = nil -proc IdNodeTableGetLazy*(t: TIdNodeTable, key: PIdObj): PNode = +proc idNodeTableGetLazy*(t: TIdNodeTable, key: PIdObj): PNode = if not isNil(t.data): - result = IdNodeTableGet(t, key) + result = idNodeTableGet(t, key) -proc IdNodeTableRawInsert(data: var TIdNodePairSeq, key: PIdObj, val: PNode) = +proc idNodeTableRawInsert(data: var TIdNodePairSeq, key: PIdObj, val: PNode) = var h: THash h = key.id and high(data) while data[h].key != nil: @@ -788,7 +784,7 @@ proc IdNodeTableRawInsert(data: var TIdNodePairSeq, key: PIdObj, val: PNode) = data[h].key = key data[h].val = val -proc IdNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) = +proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) = var index = IdNodeTableRawGet(t, key) if index >= 0: assert(t.data[index].key != nil) @@ -799,14 +795,14 @@ proc IdNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) = newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): 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) swap(t.data, n) - IdNodeTableRawInsert(t.data, key, val) + idNodeTableRawInsert(t.data, key, val) inc(t.counter) -proc IdNodeTablePutLazy*(t: var TIdNodeTable, key: PIdObj, val: PNode) = +proc idNodeTablePutLazy*(t: var TIdNodeTable, key: PIdObj, val: PNode) = if isNil(t.data): initIdNodeTable(t) - IdNodeTablePut(t, key, val) + idNodeTablePut(t, key, val) iterator pairs*(t: TIdNodeTable): tuple[key: PIdObj, val: PNode] = for i in 0 .. high(t.data): @@ -817,21 +813,20 @@ proc initIITable(x: var TIITable) = newSeq(x.data, startSize) 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 h = key and high(t.data) # start with real hash value while t.data[h].key != InvalidKey: - if (t.data[h].key == key): - return h + if t.data[h].key == key: return h h = nextTry(h, high(t.data)) - result = - 1 + result = -1 -proc IITableGet(t: TIITable, key: int): int = - var index = IITableRawGet(t, key) +proc iiTableGet(t: TIITable, key: int): int = + var index = iiTableRawGet(t, key) if index >= 0: result = t.data[index].val else: result = InvalidKey -proc IITableRawInsert(data: var TIIPairSeq, key, val: int) = +proc iiTableRawInsert(data: var TIIPairSeq, key, val: int) = var h: THash h = key and high(data) while data[h].key != InvalidKey: @@ -841,7 +836,7 @@ proc IITableRawInsert(data: var TIIPairSeq, key, val: int) = data[h].key = key data[h].val = val -proc IITablePut(t: var TIITable, key, val: int) = +proc iiTablePut(t: var TIITable, key, val: int) = var index = IITableRawGet(t, key) if index >= 0: assert(t.data[index].key != InvalidKey) @@ -853,7 +848,7 @@ proc IITablePut(t: var TIITable, key, val: int) = for i in countup(0, high(n)): n[i].key = InvalidKey for i in countup(0, high(t.data)): if t.data[i].key != InvalidKey: - IITableRawInsert(n, t.data[i].key, t.data[i].val) + iiTableRawInsert(n, t.data[i].key, t.data[i].val) swap(t.data, n) - IITableRawInsert(t.data, key, val) + iiTableRawInsert(t.data, key, val) inc(t.counter) diff --git a/compiler/bitsets.nim b/compiler/bitsets.nim index dfb23b06d..740bdd5ef 100644 --- a/compiler/bitsets.nim +++ b/compiler/bitsets.nim @@ -18,53 +18,53 @@ type const ElemSize* = sizeof(int8) * 8 -proc BitSetInit*(b: var TBitSet, length: int) -proc BitSetUnion*(x: var TBitSet, y: TBitSet) -proc BitSetDiff*(x: var TBitSet, y: TBitSet) -proc BitSetSymDiff*(x: var TBitSet, y: TBitSet) -proc BitSetIntersect*(x: var TBitSet, y: TBitSet) -proc BitSetIncl*(x: var TBitSet, elem: BiggestInt) -proc BitSetExcl*(x: var TBitSet, elem: BiggestInt) -proc BitSetIn*(x: TBitSet, e: BiggestInt): bool -proc BitSetEquals*(x, y: TBitSet): bool -proc BitSetContains*(x, y: TBitSet): bool +proc bitSetInit*(b: var TBitSet, length: int) +proc bitSetUnion*(x: var TBitSet, y: TBitSet) +proc bitSetDiff*(x: var TBitSet, y: TBitSet) +proc bitSetSymDiff*(x: var TBitSet, y: TBitSet) +proc bitSetIntersect*(x: var TBitSet, y: TBitSet) +proc bitSetIncl*(x: var TBitSet, elem: BiggestInt) +proc bitSetExcl*(x: var TBitSet, elem: BiggestInt) +proc bitSetIn*(x: TBitSet, e: BiggestInt): bool +proc bitSetEquals*(x, y: TBitSet): bool +proc bitSetContains*(x, y: TBitSet): bool # implementation -proc BitSetIn(x: TBitSet, e: BiggestInt): bool = +proc bitSetIn(x: TBitSet, e: BiggestInt): bool = result = (x[int(e div ElemSize)] and toU8(int(1 shl (e mod ElemSize)))) != toU8(0) -proc BitSetIncl(x: var TBitSet, elem: BiggestInt) = +proc bitSetIncl(x: var TBitSet, elem: BiggestInt) = assert(elem >= 0) x[int(elem div ElemSize)] = x[int(elem div ElemSize)] or toU8(int(1 shl (elem mod ElemSize))) -proc BitSetExcl(x: var TBitSet, elem: BiggestInt) = +proc bitSetExcl(x: var TBitSet, elem: BiggestInt) = x[int(elem div ElemSize)] = x[int(elem div ElemSize)] and not toU8(int(1 shl (elem mod ElemSize))) -proc BitSetInit(b: var TBitSet, length: int) = +proc bitSetInit(b: var TBitSet, length: int) = newSeq(b, length) -proc BitSetUnion(x: var TBitSet, y: TBitSet) = +proc bitSetUnion(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] or y[i] -proc BitSetDiff(x: var TBitSet, y: TBitSet) = +proc bitSetDiff(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] and not y[i] -proc BitSetSymDiff(x: var TBitSet, y: TBitSet) = +proc bitSetSymDiff(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] xor y[i] -proc BitSetIntersect(x: var TBitSet, y: TBitSet) = +proc bitSetIntersect(x: var TBitSet, y: TBitSet) = for i in countup(0, high(x)): x[i] = x[i] and y[i] -proc BitSetEquals(x, y: TBitSet): bool = +proc bitSetEquals(x, y: TBitSet): bool = for i in countup(0, high(x)): if x[i] != y[i]: return false result = true -proc BitSetContains(x, y: TBitSet): bool = +proc bitSetContains(x, y: TBitSet): bool = for i in countup(0, high(x)): if (x[i] and not y[i]) != int8(0): return false diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 873c61ed4..a9097a264 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -1669,14 +1669,14 @@ proc genTupleConstr(p: BProc, n: PNode, d: var TLoc) = [rdLoc(d), mangleRecFieldName(t.n.sons[i].sym, t)]) expr(p, it, rec) -proc IsConstClosure(n: PNode): bool {.inline.} = +proc isConstClosure(n: PNode): bool {.inline.} = result = n.sons[0].kind == nkSym and isRoutine(n.sons[0].sym) and n.sons[1].kind == nkNilLit proc genClosure(p: BProc, n: PNode, d: var TLoc) = assert n.kind == nkClosure - if IsConstClosure(n): + if isConstClosure(n): inc(p.labels) var tmp = con("LOC", toRope(p.labels)) appf(p.module.s[cfsData], "NIM_CONST $1 $2 = $3;$n", diff --git a/compiler/ccgmerge.nim b/compiler/ccgmerge.nim index c6c294b97..de207c532 100644 --- a/compiler/ccgmerge.nim +++ b/compiler/ccgmerge.nim @@ -208,7 +208,7 @@ proc readKey(L: var TBaseLexer, result: var string) = if buf[pos] != ':': internalError("ccgmerge: ':' expected") L.bufpos = pos + 1 # skip ':' -proc NewFakeType(id: int): PType = +proc newFakeType(id: int): PType = new(result) result.id = id @@ -323,4 +323,3 @@ proc mergeFiles*(cfilename: string, m: BModule) = m.s[i] = con(old.f[i], m.s[i]) for i in low(TCProcSection)..high(TCProcSection): m.initProc.s(i) = con(old.p[i], m.initProc.s(i)) - diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index d9e6d83d0..9b56556fc 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -232,11 +232,11 @@ proc genIf(p: BProc, n: PNode, d: var TLoc) = # Lend: var a: TLoc - Lelse: TLabel + lelse: TLabel if not isEmptyType(n.typ) and d.k == locNone: getTemp(p, n.typ, d) genLineDir(p, n) - let Lend = getLabel(p) + let lend = getLabel(p) for i in countup(0, sonsLen(n) - 1): let it = n.sons[i] if it.len == 2: @@ -251,14 +251,14 @@ proc genIf(p: BProc, n: PNode, d: var TLoc) = expr(p, it.sons[1], d) endBlock(p) if sonsLen(n) > 1: - lineFF(p, cpsStmts, "goto $1;$n", "br label %$1$n", [Lend]) + lineFF(p, cpsStmts, "goto $1;$n", "br label %$1$n", [lend]) fixLabel(p, Lelse) elif it.len == 1: startBlock(p) expr(p, it.sons[0], d) endBlock(p) else: internalError(n.info, "genIf()") - if sonsLen(n) > 1: fixLabel(p, Lend) + if sonsLen(n) > 1: fixLabel(p, lend) proc blockLeaveActions(p: BProc, howMany: int) = var L = p.nestedTryStmts.len @@ -367,7 +367,7 @@ proc genWhileStmt(p: BProc, t: PNode) = # significantly worse code var a: TLoc - Labl: TLabel + labl: TLabel assert(sonsLen(t) == 2) inc(p.withinLoop) genLineDir(p, t) @@ -499,16 +499,16 @@ proc genCaseGenericBranch(p: BProc, b: PNode, e: TLoc, proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc, labId, until: int): TLabel = - var Lend = getLabel(p) + var lend = getLabel(p) for i in 1..until: lineF(p, cpsStmts, "LA$1: ;$n", [toRope(labId + i)]) if t.sons[i].kind == nkOfBranch: var length = sonsLen(t.sons[i]) exprBlock(p, t.sons[i].sons[length - 1], d) - lineF(p, cpsStmts, "goto $1;$n", [Lend]) + lineF(p, cpsStmts, "goto $1;$n", [lend]) else: exprBlock(p, t.sons[i].sons[0], d) - result = Lend + result = lend proc genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc, rangeFormat, eqFormat: TFormatStr, @@ -535,8 +535,8 @@ proc genCaseGeneric(p: BProc, t: PNode, d: var TLoc, rangeFormat, eqFormat: TFormatStr) = var a: TLoc initLocExpr(p, t.sons[0], a) - var Lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, sonsLen(t)-1, a) - fixLabel(p, Lend) + var lend = genIfForCaseUntil(p, t, d, rangeFormat, eqFormat, sonsLen(t)-1, a) + fixLabel(p, lend) proc genCaseStringBranch(p: BProc, b: PNode, e: TLoc, labl: TLabel, branches: var openArray[PRope]) = @@ -580,8 +580,8 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) = if t.sons[sonsLen(t)-1].kind != nkOfBranch: lineF(p, cpsStmts, "goto LA$1;$n", [toRope(p.labels)]) # third pass: generate statements - var Lend = genCaseSecondPass(p, t, d, labId, sonsLen(t)-1) - fixLabel(p, Lend) + var lend = genCaseSecondPass(p, t, d, labId, sonsLen(t)-1) + fixLabel(p, lend) else: genCaseGeneric(p, t, d, "", "if (#eqStrings($1, $2)) goto $3;$n") @@ -592,7 +592,7 @@ proc branchHasTooBigRange(b: PNode): bool = b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit: return true -proc IfSwitchSplitPoint(p: BProc, n: PNode): int = +proc ifSwitchSplitPoint(p: BProc, n: PNode): int = for i in 1..n.len-1: var branch = n[i] var stmtBlock = lastSon(branch) @@ -625,7 +625,7 @@ proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) = # generate if part (might be empty): var a: TLoc initLocExpr(p, n.sons[0], a) - var Lend = if splitPoint > 0: genIfForCaseUntil(p, n, d, + var lend = if splitPoint > 0: genIfForCaseUntil(p, n, d, rangeFormat = "if ($1 >= $2 && $1 <= $3) goto $4;$n", eqFormat = "if ($1 == $2) goto $3;$n", splitPoint, a) else: nil @@ -647,7 +647,7 @@ proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) = if (hasAssume in CC[ccompiler].props) and not hasDefault: lineF(p, cpsStmts, "default: __assume(0);$n") lineF(p, cpsStmts, "}$n") - if Lend != nil: fixLabel(p, Lend) + if lend != nil: fixLabel(p, lend) proc genCase(p: BProc, t: PNode, d: var TLoc) = genLineDir(p, t) @@ -928,7 +928,7 @@ proc genPragma(p: BProc, n: PNode) = p.module.injectStmt = p.s(cpsStmts) else: discard -proc FieldDiscriminantCheckNeeded(p: BProc, asgn: PNode): bool = +proc fieldDiscriminantCheckNeeded(p: BProc, asgn: PNode): bool = if optFieldCheck in p.options: var le = asgn.sons[0] if le.kind == nkCheckedFieldExpr: diff --git a/compiler/ccgthreadvars.nim b/compiler/ccgthreadvars.nim index d312ea027..ee01972fc 100644 --- a/compiler/ccgthreadvars.nim +++ b/compiler/ccgthreadvars.nim @@ -17,7 +17,7 @@ proc emulatedThreadVars(): bool = proc accessThreadLocalVar(p: BProc, s: PSym) = if emulatedThreadVars() and not p.ThreadVarAccessed: - p.ThreadVarAccessed = true + p.threadVarAccessed = true p.module.usesThreadVars = true appf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV;$n") app(p.procSec(cpsInit), @@ -55,7 +55,7 @@ proc generateThreadLocalStorage(m: BModule) = for t in items(nimtvDeps): discard getTypeDesc(m, t) appf(m.s[cfsSeqTypes], "typedef struct {$1} NimThreadVars;$n", [nimtv]) -proc GenerateThreadVarsSize(m: BModule) = +proc generateThreadVarsSize(m: BModule) = if nimtv != nil: app(m.s[cfsProcs], "NI NimThreadVarsSize(){return (NI)sizeof(NimThreadVars);}" & tnl) diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index 4548ac641..66441af5e 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -229,11 +229,11 @@ const "stdcall $1", "ccc $1", "safecall $1", "syscall $1", "$1 alwaysinline", "$1 noinline", "fastcc $1", "ccc $1", "$1"] -proc CacheGetType(tab: TIdTable, key: PType): PRope = +proc cacheGetType(tab: TIdTable, key: PType): PRope = # returns nil if we need to declare this type # since types are now unique via the ``GetUniqueType`` mechanism, this slow # linear search is not necessary anymore: - result = PRope(IdTableGet(tab, key)) + result = PRope(idTableGet(tab, key)) proc getTempName(): PRope = result = rfmt(nil, "TMP$1", toRope(backendId())) @@ -952,4 +952,4 @@ proc genTypeInfo(m: BModule, t: PType): PRope = result = con("(&".toRope, result, ")".toRope) proc genTypeSection(m: BModule, n: PNode) = - nil + discard diff --git a/compiler/ccgutils.nim b/compiler/ccgutils.nim index 310f7204a..accb7a261 100644 --- a/compiler/ccgutils.nim +++ b/compiler/ccgutils.nim @@ -22,7 +22,7 @@ proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode = of nkPragma: for i in 0 .. < n.len: if whichPragma(n[i]) == w: return n[i] - else: nil + else: discard proc stmtsContainPragma*(n: PNode, w: TSpecialWord): bool = result = getPragmaStmt(n, w) != nil @@ -70,7 +70,7 @@ when false: for i in countup(low(TTypeKind), high(TTypeKind)): echo i, " ", gTypeTable[i].counter -proc GetUniqueType*(key: PType): PType = +proc getUniqueType*(key: PType): PType = # this is a hotspot in the compiler! if key == nil: return var k = key.kind @@ -87,11 +87,11 @@ proc GetUniqueType*(key: PType): PType = gCanonicalTypes[k] = key result = key of tyTypeDesc, tyTypeClasses: - InternalError("value expected, but got a type") + internalError("value expected, but got a type") of tyGenericParam: - InternalError("GetUniqueType") + internalError("GetUniqueType") of tyGenericInst, tyDistinct, tyOrdinal, tyMutable, tyConst, tyIter: - result = GetUniqueType(lastSon(key)) + result = getUniqueType(lastSon(key)) of tyArrayConstr, tyGenericInvokation, tyGenericBody, tyOpenArray, tyArray, tySet, tyRange, tyTuple, tyPtr, tyRef, tySequence, tyForward, tyVarargs, tyProxy, tyVar: @@ -102,33 +102,33 @@ proc GetUniqueType*(key: PType): PType = # we have to do a slow linear search because types may need # to be compared by their structure: - if IdTableHasObjectAsKey(gTypeTable[k], key): return key + if idTableHasObjectAsKey(gTypeTable[k], key): return key for h in countup(0, high(gTypeTable[k].data)): var t = PType(gTypeTable[k].data[h].key) if t != nil and sameBackendType(t, key): return t - IdTablePut(gTypeTable[k], key, key) + idTablePut(gTypeTable[k], key, key) result = key of tyObject: if tfFromGeneric notin key.flags: # fast case; lookup per id suffices: - result = PType(IdTableGet(gTypeTable[k], key)) + result = PType(idTableGet(gTypeTable[k], key)) if result == nil: - IdTablePut(gTypeTable[k], key, key) + idTablePut(gTypeTable[k], key, key) result = key else: # ugly slow case: need to compare by structure - if IdTableHasObjectAsKey(gTypeTable[k], key): return key + if idTableHasObjectAsKey(gTypeTable[k], key): return key for h in countup(0, high(gTypeTable[k].data)): var t = PType(gTypeTable[k].data[h].key) if t != nil and sameType(t, key): return t - IdTablePut(gTypeTable[k], key, key) + idTablePut(gTypeTable[k], key, key) result = key of tyEnum: - result = PType(IdTableGet(gTypeTable[k], key)) + result = PType(idTableGet(gTypeTable[k], key)) if result == nil: - IdTablePut(gTypeTable[k], key, key) + idTablePut(gTypeTable[k], key, key) result = key of tyProc: # tyVar is not 100% correct, but would speeds things up a little: @@ -136,17 +136,17 @@ proc GetUniqueType*(key: PType): PType = result = key else: # ugh, we need the canon here: - if IdTableHasObjectAsKey(gTypeTable[k], key): return key + if idTableHasObjectAsKey(gTypeTable[k], key): return key for h in countup(0, high(gTypeTable[k].data)): var t = PType(gTypeTable[k].data[h].key) if t != nil and sameBackendType(t, key): return t - IdTablePut(gTypeTable[k], key, key) + idTablePut(gTypeTable[k], key, key) result = key -proc TableGetType*(tab: TIdTable, key: PType): PObject = +proc tableGetType*(tab: TIdTable, key: PType): PObject = # returns nil if we need to declare this type - result = IdTableGet(tab, key) + result = idTableGet(tab, key) if (result == nil) and (tab.counter > 0): # we have to do a slow linear search because types may need # to be compared by their structure: @@ -178,4 +178,4 @@ proc makeLLVMString*(s: string): PRope = add(res, "\\00\"") app(result, toRope(res)) -InitTypeTables() +initTypeTables() diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 6ccef5fde..ad1dfa89e 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -513,7 +513,7 @@ proc assignLocalVar(p: BProc, s: PSym) = include ccgthreadvars -proc VarInDynamicLib(m: BModule, sym: PSym) +proc varInDynamicLib(m: BModule, sym: PSym) proc mangleDynLibProc(sym: PSym): PRope proc assignGlobalVar(p: BProc, s: PSym) = @@ -641,7 +641,7 @@ proc mangleDynLibProc(sym: PSym): PRope = else: result = ropef("Dl_$1", [toRope(sym.id)]) -proc SymInDynamicLib(m: BModule, sym: PSym) = +proc symInDynamicLib(m: BModule, sym: PSym) = var lib = sym.annex let isCall = isGetProcAddr(lib) var extname = sym.loc.r @@ -682,7 +682,7 @@ proc SymInDynamicLib(m: BModule, sym: PSym) = "$1 = linkonce global $2 zeroinitializer$n", [sym.loc.r, getTypeDesc(m, sym.loc.t)]) -proc VarInDynamicLib(m: BModule, sym: PSym) = +proc varInDynamicLib(m: BModule, sym: PSym) = var lib = sym.annex var extname = sym.loc.r loadDynamicLib(m, lib) @@ -697,7 +697,7 @@ proc VarInDynamicLib(m: BModule, sym: PSym) = appf(m.s[cfsVars], "$2* $1;$n", [sym.loc.r, getTypeDesc(m, sym.loc.t)]) -proc SymInDynamicLibPartial(m: BModule, sym: PSym) = +proc symInDynamicLibPartial(m: BModule, sym: PSym) = sym.loc.r = mangleDynLibProc(sym) sym.typ.sym = nil # generate a new name diff --git a/compiler/cgmeth.nim b/compiler/cgmeth.nim index 33bb94b38..3467fea7e 100644 --- a/compiler/cgmeth.nim +++ b/compiler/cgmeth.nim @@ -126,14 +126,14 @@ proc cmpSignatures(a, b: PSym, relevantCols: TIntSet): int = proc sortBucket(a: var TSymSeq, relevantCols: TIntSet) = # we use shellsort here; fast and simple - var N = len(a) + var n = len(a) var h = 1 while true: h = 3 * h + 1 - if h > N: break + if h > n: break while true: h = h div 3 - for i in countup(h, N - 1): + for i in countup(h, n - 1): var v = a[i] var j = i while cmpSignatures(a[j - h], v, relevantCols) >= 0: diff --git a/compiler/commands.nim b/compiler/commands.nim index a02728dac..e67b0d422 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -21,7 +21,7 @@ type passCmd2, # second pass over the command line passPP # preprocessor called ProcessCommand() -proc ProcessCommand*(switch: string, pass: TCmdLinePass) +proc processCommand*(switch: string, pass: TCmdLinePass) proc processSwitch*(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) # implementation @@ -38,21 +38,21 @@ proc getCommandLineDesc(): string = result = (HelpMessage % [VersionAsString, platform.os[platform.hostOS].name, cpu[platform.hostCPU].name]) & Usage -proc HelpOnError(pass: TCmdLinePass) = +proc helpOnError(pass: TCmdLinePass) = if pass == passCmd1: - MsgWriteln(getCommandLineDesc()) + msgWriteln(getCommandLineDesc()) quit(0) proc writeAdvancedUsage(pass: TCmdLinePass) = if pass == passCmd1: - MsgWriteln(`%`(HelpMessage, [VersionAsString, + msgWriteln(`%`(HelpMessage, [VersionAsString, platform.os[platform.hostOS].name, cpu[platform.hostCPU].name]) & AdvancedUsage) quit(0) proc writeVersionInfo(pass: TCmdLinePass) = if pass == passCmd1: - MsgWriteln(`%`(HelpMessage, [VersionAsString, + msgWriteln(`%`(HelpMessage, [VersionAsString, platform.os[platform.hostOS].name, cpu[platform.hostCPU].name])) quit(0) @@ -62,16 +62,16 @@ var proc writeCommandLineUsage() = if not helpWritten: - MsgWriteln(getCommandLineDesc()) + msgWriteln(getCommandLineDesc()) helpWritten = true proc addPrefix(switch: string): string = if len(switch) == 1: result = "-" & switch else: result = "--" & switch -proc InvalidCmdLineOption(pass: TCmdLinePass, switch: string, info: TLineInfo) = - if switch == " ": LocalError(info, errInvalidCmdLineOption, "-") - else: LocalError(info, errInvalidCmdLineOption, addPrefix(switch)) +proc invalidCmdLineOption(pass: TCmdLinePass, switch: string, info: TLineInfo) = + if switch == " ": localError(info, errInvalidCmdLineOption, "-") + else: localError(info, errInvalidCmdLineOption, addPrefix(switch)) proc splitSwitch(switch: string, cmd, arg: var string, pass: TCmdLinePass, info: TLineInfo) = @@ -86,29 +86,29 @@ proc splitSwitch(switch: string, cmd, arg: var string, pass: TCmdLinePass, inc(i) if i >= len(switch): arg = "" elif switch[i] in {':', '=', '['}: arg = substr(switch, i + 1) - else: InvalidCmdLineOption(pass, switch, info) + else: invalidCmdLineOption(pass, switch, info) -proc ProcessOnOffSwitch(op: TOptions, arg: string, pass: TCmdlinePass, +proc processOnOffSwitch(op: TOptions, arg: string, pass: TCmdlinePass, info: TLineInfo) = case whichKeyword(arg) of wOn: gOptions = gOptions + op of wOff: gOptions = gOptions - op - else: LocalError(info, errOnOrOffExpectedButXFound, arg) + else: localError(info, errOnOrOffExpectedButXFound, arg) -proc ProcessOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdlinePass, +proc processOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdlinePass, info: TLineInfo) = case whichKeyword(arg) of wOn: gGlobalOptions = gGlobalOptions + op of wOff: gGlobalOptions = gGlobalOptions - op - else: LocalError(info, errOnOrOffExpectedButXFound, arg) + else: localError(info, errOnOrOffExpectedButXFound, arg) -proc ExpectArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = - if arg == "": LocalError(info, errCmdLineArgExpected, addPrefix(switch)) +proc expectArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = + if arg == "": localError(info, errCmdLineArgExpected, addPrefix(switch)) -proc ExpectNoArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = - if arg != "": LocalError(info, errCmdLineNoArgExpected, addPrefix(switch)) +proc expectNoArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = + if arg != "": localError(info, errCmdLineNoArgExpected, addPrefix(switch)) -proc ProcessSpecificNote(arg: string, state: TSpecialWord, pass: TCmdlinePass, +proc processSpecificNote(arg: string, state: TSpecialWord, pass: TCmdlinePass, info: TLineInfo) = var id = "" # arg = "X]:on|off" var i = 0 @@ -117,21 +117,21 @@ proc ProcessSpecificNote(arg: string, state: TSpecialWord, pass: TCmdlinePass, add(id, arg[i]) inc(i) if i < len(arg) and (arg[i] == ']'): inc(i) - else: InvalidCmdLineOption(pass, arg, info) + else: invalidCmdLineOption(pass, arg, info) if i < len(arg) and (arg[i] in {':', '='}): inc(i) - else: InvalidCmdLineOption(pass, arg, info) + else: invalidCmdLineOption(pass, arg, info) if state == wHint: var x = findStr(msgs.HintsToStr, id) if x >= 0: n = TNoteKind(x + ord(hintMin)) - else: InvalidCmdLineOption(pass, arg, info) + else: invalidCmdLineOption(pass, arg, info) else: var x = findStr(msgs.WarningsToStr, id) if x >= 0: n = TNoteKind(x + ord(warnMin)) - else: InvalidCmdLineOption(pass, arg, info) + else: invalidCmdLineOption(pass, arg, info) case whichKeyword(substr(arg, i)) of wOn: incl(gNotes, n) of wOff: excl(gNotes, n) - else: LocalError(info, errOnOrOffExpectedButXFound, arg) + else: localError(info, errOnOrOffExpectedButXFound, arg) proc processCompile(filename: string) = var found = findFile(filename) @@ -150,14 +150,14 @@ proc testCompileOptionArg*(switch, arg: string, info: TLineInfo): bool = of "markandsweep": result = gSelectedGC == gcMarkAndSweep of "generational": result = gSelectedGC == gcGenerational of "none": result = gSelectedGC == gcNone - else: LocalError(info, errNoneBoehmRefcExpectedButXFound, arg) + else: localError(info, errNoneBoehmRefcExpectedButXFound, arg) of "opt": case arg.normalize of "speed": result = contains(gOptions, optOptimizeSpeed) of "size": result = contains(gOptions, optOptimizeSize) of "none": result = gOptions * {optOptimizeSpeed, optOptimizeSize} == {} - else: LocalError(info, errNoneSpeedOrSizeExpectedButXFound, arg) - else: InvalidCmdLineOption(passCmd1, switch, info) + else: localError(info, errNoneSpeedOrSizeExpectedButXFound, arg) + else: invalidCmdLineOption(passCmd1, switch, info) proc testCompileOption*(switch: string, info: TLineInfo): bool = case switch.normalize @@ -194,7 +194,7 @@ proc testCompileOption*(switch: string, info: TLineInfo): bool = of "tlsemulation": result = contains(gGlobalOptions, optTlsEmulation) of "implicitstatic": result = contains(gOptions, optImplicitStatic) of "patterns": result = contains(gOptions, optPatterns) - else: InvalidCmdLineOption(passCmd1, switch, info) + else: invalidCmdLineOption(passCmd1, switch, info) proc processPath(path: string, notRelativeToProj = false): string = let p = if notRelativeToProj or os.isAbsolute(path) or @@ -202,20 +202,20 @@ proc processPath(path: string, notRelativeToProj = false): string = path else: options.gProjectPath / path - result = UnixToNativePath(p % ["nimrod", getPrefixDir(), "lib", libpath, + result = unixToNativePath(p % ["nimrod", getPrefixDir(), "lib", libpath, "home", removeTrailingDirSep(os.getHomeDir()), "projectname", options.gProjectName, "projectpath", options.gProjectPath]) proc trackDirty(arg: string, info: TLineInfo) = var a = arg.split(',') - if a.len != 4: LocalError(info, errTokenExpected, + if a.len != 4: localError(info, errTokenExpected, "DIRTY_BUFFER,ORIGINAL_FILE,LINE,COLUMN") var line, column: int if parseUtils.parseInt(a[2], line) <= 0: - LocalError(info, errInvalidNumber, a[1]) + localError(info, errInvalidNumber, a[1]) if parseUtils.parseInt(a[3], column) <= 0: - LocalError(info, errInvalidNumber, a[2]) + localError(info, errInvalidNumber, a[2]) gDirtyBufferIdx = a[0].fileInfoIdx gDirtyOriginalIdx = a[1].fileInfoIdx @@ -225,12 +225,12 @@ proc trackDirty(arg: string, info: TLineInfo) = proc track(arg: string, info: TLineInfo) = var a = arg.split(',') - if a.len != 3: LocalError(info, errTokenExpected, "FILE,LINE,COLUMN") + if a.len != 3: localError(info, errTokenExpected, "FILE,LINE,COLUMN") var line, column: int if parseUtils.parseInt(a[1], line) <= 0: - LocalError(info, errInvalidNumber, a[1]) + localError(info, errInvalidNumber, a[1]) if parseUtils.parseInt(a[2], column) <= 0: - LocalError(info, errInvalidNumber, a[2]) + localError(info, errInvalidNumber, a[2]) optTrackPos = newLineInfo(a[0], line, column) msgs.addCheckpoint(optTrackPos) @@ -305,7 +305,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = case arg.normalize of "boehm": gSelectedGC = gcBoehm - DefineSymbol("boehmgc") + defineSymbol("boehmgc") of "refc": gSelectedGC = gcRefc of "v2": @@ -319,8 +319,8 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = of "none": gSelectedGC = gcNone defineSymbol("nogc") - else: LocalError(info, errNoneBoehmRefcExpectedButXFound, arg) - of "warnings", "w": ProcessOnOffSwitch({optWarns}, arg, pass, info) + else: localError(info, errNoneBoehmRefcExpectedButXFound, arg) + of "warnings", "w": processOnOffSwitch({optWarns}, arg, pass, info) of "warning": ProcessSpecificNote(arg, wWarning, pass, info) of "hint": ProcessSpecificNote(arg, wHint, pass, info) of "hints": ProcessOnOffSwitch({optHints}, arg, pass, info) @@ -517,13 +517,13 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = case arg of "partial": idents.firstCharIsCS = true of "none": idents.firstCharIsCS = false - else: LocalError(info, errGenerated, + else: localError(info, errGenerated, "'partial' or 'none' expected, but found " & arg) else: if strutils.find(switch, '.') >= 0: options.setConfigVar(switch, arg) - else: InvalidCmdLineOption(pass, switch, info) + else: invalidCmdLineOption(pass, switch, info) -proc ProcessCommand(switch: string, pass: TCmdLinePass) = +proc processCommand(switch: string, pass: TCmdLinePass) = var cmd, arg: string splitSwitch(switch, cmd, arg, pass, gCmdLineInfo) processSwitch(cmd, arg, pass, gCmdLineInfo) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index 21095072b..71dce9529 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -16,10 +16,10 @@ import # to be style insensitive. Otherwise hell would break lose. var gSymbols: PStringTable -proc DefineSymbol*(symbol: string) = +proc defineSymbol*(symbol: string) = gSymbols[symbol] = "true" -proc UndefSymbol*(symbol: string) = +proc undefSymbol*(symbol: string) = gSymbols[symbol] = "false" proc isDefined*(symbol: string): bool = @@ -37,52 +37,52 @@ proc countDefinedSymbols*(): int = for key, val in pairs(gSymbols): if val == "true": inc(result) -proc InitDefines*() = +proc initDefines*() = gSymbols = newStringTable(modeStyleInsensitive) - DefineSymbol("nimrod") # 'nimrod' is always defined + defineSymbol("nimrod") # 'nimrod' is always defined # for bootstrapping purposes and old code: - DefineSymbol("nimhygiene") - DefineSymbol("niminheritable") - DefineSymbol("nimmixin") - DefineSymbol("nimeffects") - DefineSymbol("nimbabel") - DefineSymbol("nimcomputedgoto") + defineSymbol("nimhygiene") + defineSymbol("niminheritable") + defineSymbol("nimmixin") + defineSymbol("nimeffects") + defineSymbol("nimbabel") + defineSymbol("nimcomputedgoto") # add platform specific symbols: case targetCPU - of cpuI386: DefineSymbol("x86") - of cpuIa64: DefineSymbol("itanium") - of cpuAmd64: DefineSymbol("x8664") + of cpuI386: defineSymbol("x86") + of cpuIa64: defineSymbol("itanium") + of cpuAmd64: defineSymbol("x8664") else: discard case targetOS of osDOS: - DefineSymbol("msdos") + defineSymbol("msdos") of osWindows: - DefineSymbol("mswindows") - DefineSymbol("win32") + defineSymbol("mswindows") + defineSymbol("win32") of osLinux, osMorphOS, osSkyOS, osIrix, osPalmOS, osQNX, osAtari, osAix, osHaiku: # these are all 'unix-like' - DefineSymbol("unix") - DefineSymbol("posix") + defineSymbol("unix") + defineSymbol("posix") of osSolaris: - DefineSymbol("sunos") - DefineSymbol("unix") - DefineSymbol("posix") + defineSymbol("sunos") + defineSymbol("unix") + defineSymbol("posix") of osNetBSD, osFreeBSD, osOpenBSD: - DefineSymbol("unix") - DefineSymbol("bsd") - DefineSymbol("posix") + defineSymbol("unix") + defineSymbol("bsd") + defineSymbol("posix") of osMacOS: - DefineSymbol("macintosh") + defineSymbol("macintosh") of osMacOSX: - DefineSymbol("macintosh") - DefineSymbol("unix") + defineSymbol("macintosh") + defineSymbol("unix") DefineSymbol("posix") else: discard - DefineSymbol("cpu" & $cpu[targetCPU].bit) - DefineSymbol(normalize(endianToStr[cpu[targetCPU].endian])) - DefineSymbol(cpu[targetCPU].name) - DefineSymbol(platform.os[targetOS].name) + defineSymbol("cpu" & $cpu[targetCPU].bit) + defineSymbol(normalize(endianToStr[cpu[targetCPU].endian])) + defineSymbol(cpu[targetCPU].name) + defineSymbol(platform.os[targetOS].name) if platform.OS[targetOS].props.contains(ospLacksThreadVars): - DefineSymbol("emulatedthreadvars") + defineSymbol("emulatedthreadvars") diff --git a/compiler/docgen.nim b/compiler/docgen.nim index d44018a2b..018dcd270 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -313,7 +313,7 @@ proc generateDoc*(d: PDoc, n: PNode) = of nkImportStmt: for i in 0 .. sonsLen(n)-1: traceDeps(d, n.sons[i]) of nkFromStmt, nkImportExceptStmt: traceDeps(d, n.sons[0]) - else: nil + else: discard proc generateJson(d: PDoc, n: PNode, jArray: PJsonNode = nil): PJsonNode = case n.kind @@ -355,7 +355,7 @@ proc generateJson(d: PDoc, n: PNode, jArray: PJsonNode = nil): PJsonNode = # generate documentation for the first branch only: if not checkForFalse(n.sons[0].sons[0]) and jArray != nil: discard generateJson(d, lastSon(n.sons[0]), jArray) - else: nil + else: discard proc genSection(d: PDoc, kind: TSymKind) = const sectionNames: array[skModule..skTemplate, string] = [ @@ -417,7 +417,7 @@ proc writeOutput*(d: PDoc, filename, outExt: string, useWarning = false) = else: writeRope(content, getOutFile(filename, outExt), useWarning) -proc CommandDoc*() = +proc commandDoc*() = var ast = parseFile(gProjectMainIdx) if ast == nil: return var d = newDocumentor(gProjectFull, options.gConfigVars) @@ -426,7 +426,7 @@ proc CommandDoc*() = writeOutput(d, gProjectFull, HtmlExt) generateIndex(d) -proc CommandRstAux(filename, outExt: string) = +proc commandRstAux(filename, outExt: string) = var filen = addFileExt(filename, "txt") var d = newDocumentor(filen, options.gConfigVars) var rst = parseRst(readFile(filen), filen, 0, 1, d.hasToc, @@ -439,14 +439,14 @@ proc CommandRstAux(filename, outExt: string) = writeOutput(d, filename, outExt) generateIndex(d) -proc CommandRst2Html*() = - CommandRstAux(gProjectFull, HtmlExt) +proc commandRst2Html*() = + commandRstAux(gProjectFull, HtmlExt) -proc CommandRst2TeX*() = +proc commandRst2TeX*() = splitter = "\\-" - CommandRstAux(gProjectFull, TexExt) + commandRstAux(gProjectFull, TexExt) -proc CommandJSON*() = +proc commandJSON*() = var ast = parseFile(gProjectMainIdx) if ast == nil: return var d = newDocumentor(gProjectFull, options.gConfigVars) @@ -460,7 +460,7 @@ proc CommandJSON*() = echo getOutFile(gProjectFull, JsonExt) writeRope(content, getOutFile(gProjectFull, JsonExt), useWarning = false) -proc CommandBuildIndex*() = +proc commandBuildIndex*() = var content = mergeIndexes(gProjectFull).toRope let code = ropeFormatNamedVars(getConfigVar("doc.file"), ["title", diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index d3b3cee75..629cf95eb 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -324,7 +324,7 @@ var compileOptions: string = "" ccompilerpath: string = "" -proc NameToCC*(name: string): TSystemCC = +proc nameToCC*(name: string): TSystemCC = for i in countup(succ(ccNone), high(TSystemCC)): if cmpIgnoreStyle(name, CC[i].name) == 0: return i @@ -405,7 +405,7 @@ proc execExternalProgram*(cmd: string) = proc generateScript(projectFile: string, script: PRope) = let (dir, name, ext) = splitFile(projectFile) - WriteRope(script, dir / addFileExt("compile_" & name, + writeRope(script, dir / addFileExt("compile_" & name, platform.os[targetOS].scriptExt)) proc getOptSpeed(c: TSystemCC): string = @@ -439,7 +439,7 @@ var fileCounter: int proc add(s: var string, many: openarray[string]) = s.add many.join -proc CFileSpecificOptions(cfilename: string): string = +proc cFileSpecificOptions(cfilename: string): string = result = compileOptions var trunk = splitFile(cfilename).name if optCDebug in gGlobalOptions: @@ -541,7 +541,7 @@ proc addExternalFileToCompile*(filename: string) = if optForceFullMake in gGlobalOptions or externalFileChanged(filename): appendStr(externalToCompile, filename) -proc CompileCFile(list: TLinkedList, script: var PRope, cmds: var TStringSeq, +proc compileCFile(list: TLinkedList, script: var PRope, cmds: var TStringSeq, isExternal: bool) = var it = PStrEntry(list.head) while it != nil: @@ -554,7 +554,7 @@ proc CompileCFile(list: TLinkedList, script: var PRope, cmds: var TStringSeq, app(script, tnl) it = PStrEntry(it.next) -proc CallCCompiler*(projectfile: string) = +proc callCCompiler*(projectfile: string) = var linkCmd, buildgui, builddll: string if gGlobalOptions * {optCompileOnly, optGenScript} == {optCompileOnly}: @@ -564,8 +564,8 @@ proc CallCCompiler*(projectfile: string) = var c = ccompiler var script: PRope = nil var cmds: TStringSeq = @[] - CompileCFile(toCompile, script, cmds, false) - CompileCFile(externalToCompile, script, cmds, true) + compileCFile(toCompile, script, cmds, false) + compileCFile(externalToCompile, script, cmds, true) if optCompileOnly notin gGlobalOptions: if gNumberOfProcessors == 0: gNumberOfProcessors = countProcessors() var res = 0 @@ -640,7 +640,7 @@ proc CallCCompiler*(projectfile: string) = proc genMappingFiles(list: TLinkedList): PRope = var it = PStrEntry(list.head) while it != nil: - appf(result, "--file:r\"$1\"$N", [toRope(AddFileExt(it.data, cExt))]) + appf(result, "--file:r\"$1\"$N", [toRope(addFileExt(it.data, cExt))]) it = PStrEntry(it.next) proc writeMapping*(gSymbolMapping: PRope) = @@ -658,5 +658,5 @@ proc writeMapping*(gSymbolMapping: PRope) = app(code, strutils.escape(libpath)) appf(code, "\n[Symbols]$n$1", [gSymbolMapping]) - WriteRope(code, joinPath(gProjectPath, "mapping.txt")) + writeRope(code, joinPath(gProjectPath, "mapping.txt")) diff --git a/compiler/idents.nim b/compiler/idents.nim index 1e6f9d2fd..ec903826a 100644 --- a/compiler/idents.nim +++ b/compiler/idents.nim @@ -102,7 +102,7 @@ proc getIdent*(identifier: string): PIdent = proc getIdent*(identifier: string, h: THash): PIdent = result = getIdent(cstring(identifier), len(identifier), h) -proc IdentEq*(id: PIdent, name: string): bool = +proc identEq*(id: PIdent, name: string): bool = result = id.id == getIdent(name).id var idAnon* = getIdent":anonymous" diff --git a/compiler/idgen.nim b/compiler/idgen.nim index fbf450c90..f47e2e3b6 100644 --- a/compiler/idgen.nim +++ b/compiler/idgen.nim @@ -23,8 +23,8 @@ when debugIds: proc registerID*(id: PIdObj) = when debugIDs: - if id.id == -1 or ContainsOrIncl(usedIds, id.id): - InternalError("ID already used: " & $id.id) + if id.id == -1 or containsOrIncl(usedIds, id.id): + internalError("ID already used: " & $id.id) proc getID*(): int {.inline.} = result = gFrontEndId @@ -37,7 +37,7 @@ proc backendId*(): int {.inline.} = proc setId*(id: int) {.inline.} = gFrontEndId = max(gFrontEndId, id + 1) -proc IDsynchronizationPoint*(idRange: int) = +proc idSynchronizationPoint*(idRange: int) = gFrontEndId = (gFrontEndId div IdRange + 1) * IdRange + 1 proc toGid(f: string): string = diff --git a/compiler/lexer.nim b/compiler/lexer.nim index eb9287dfe..7410f7ec5 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -132,7 +132,7 @@ proc getLineInfo*(L: TLexer, tok: TToken): TLineInfo {.inline.} = newLineInfo(L.fileIdx, tok.line, tok.col) proc closeLexer*(lex: var TLexer) -proc PrintTok*(tok: TToken) +proc printTok*(tok: TToken) proc tokToStr*(tok: TToken): string proc openLexer*(lex: var TLexer, filename: string, inputstream: PLLStream) = @@ -172,7 +172,7 @@ proc prettyTok*(tok: TToken): string = if IsKeyword(tok.tokType): result = "keyword " & tok.ident.s else: result = tokToStr(tok) -proc PrintTok*(tok: TToken) = +proc printTok*(tok: TToken) = write(stdout, TokTypeToStr[tok.tokType]) write(stdout, " ") writeln(stdout, tokToStr(tok)) @@ -246,7 +246,7 @@ proc isFloatLiteral(s: string): bool = return true result = false -proc GetNumber(L: var TLexer): TToken = +proc getNumber(L: var TLexer): TToken = var pos, endpos: int xi: biggestInt @@ -499,7 +499,7 @@ proc newString(s: cstring, len: int): string = for i in 0 .. 0: setlen(s.s, len(s.s) + bufLen) @@ -203,10 +203,9 @@ proc LLStreamWrite(s: PLLStream, buf: pointer, buflen: int) = of llsFile: discard writeBuffer(s.f, buf, bufLen) -proc LLStreamReadAll(s: PLLStream): string = +proc llStreamReadAll(s: PLLStream): string = const bufSize = 2048 - var bytes, i: int case s.kind of llsNone, llsStdIn: result = "" @@ -216,8 +215,8 @@ proc LLStreamReadAll(s: PLLStream): string = s.rd = len(s.s) of llsFile: result = newString(bufSize) - bytes = readBuffer(s.f, addr(result[0]), bufSize) - i = bytes + var bytes = readBuffer(s.f, addr(result[0]), bufSize) + var i = bytes while bytes == bufSize: setlen(result, i + bufSize) bytes = readBuffer(s.f, addr(result[i + 0]), bufSize) diff --git a/compiler/lookups.nim b/compiler/lookups.nim index 642243468..951998d15 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -21,7 +21,7 @@ proc considerAcc*(n: PNode): PIdent = of nkSym: result = n.sym.name of nkAccQuoted: case n.len - of 0: GlobalError(n.info, errIdentifierExpected, renderTree(n)) + of 0: globalError(n.info, errIdentifierExpected, renderTree(n)) of 1: result = considerAcc(n.sons[0]) else: var id = "" @@ -30,16 +30,16 @@ proc considerAcc*(n: PNode): PIdent = case x.kind of nkIdent: id.add(x.ident.s) of nkSym: id.add(x.sym.name.s) - else: GlobalError(n.info, errIdentifierExpected, renderTree(n)) + else: globalError(n.info, errIdentifierExpected, renderTree(n)) result = getIdent(id) else: - GlobalError(n.info, errIdentifierExpected, renderTree(n)) + globalError(n.info, errIdentifierExpected, renderTree(n)) template addSym*(scope: PScope, s: PSym) = - StrTableAdd(scope.symbols, s) + strTableAdd(scope.symbols, s) proc addUniqueSym*(scope: PScope, s: PSym): TResult = - if StrTableIncl(scope.symbols, s): + if strTableIncl(scope.symbols, s): result = Failure else: result = Success @@ -64,17 +64,17 @@ iterator walkScopes*(scope: PScope): PScope = current = current.parent proc localSearchInScope*(c: PContext, s: PIdent): PSym = - result = StrTableGet(c.currentScope.symbols, s) + result = strTableGet(c.currentScope.symbols, s) proc searchInScopes*(c: PContext, s: PIdent): PSym = for scope in walkScopes(c.currentScope): - result = StrTableGet(scope.symbols, s) + result = strTableGet(scope.symbols, s) if result != nil: return result = nil proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym = for scope in walkScopes(c.currentScope): - result = StrTableGet(scope.symbols, s) + result = strTableGet(scope.symbols, s) if result != nil and result.kind in filter: return result = nil @@ -114,22 +114,22 @@ proc getSymRepr*(s: PSym): string = proc ensureNoMissingOrUnusedSymbols(scope: PScope) = # check if all symbols have been used and defined: var it: TTabIter - var s = InitTabIter(it, scope.symbols) + var s = initTabIter(it, scope.symbols) var missingImpls = 0 while s != nil: if sfForward in s.flags: # too many 'implementation of X' errors are annoying # and slow 'suggest' down: if missingImpls == 0: - LocalError(s.info, errImplOfXexpected, getSymRepr(s)) + localError(s.info, errImplOfXexpected, getSymRepr(s)) inc missingImpls elif {sfUsed, sfExported} * s.flags == {} and optHints in s.options: # BUGFIX: check options in s! if s.kind notin {skForVar, skParam, skMethod, skUnknown, skGenericParam}: - Message(s.info, hintXDeclaredButNotUsed, getSymRepr(s)) - s = NextIter(it, scope.symbols) + message(s.info, hintXDeclaredButNotUsed, getSymRepr(s)) + s = nextIter(it, scope.symbols) -proc WrongRedefinition*(info: TLineInfo, s: string) = +proc wrongRedefinition*(info: TLineInfo, s: string) = if gCmd != cmdInteractive: localError(info, errAttemptToRedefine, s) @@ -144,7 +144,7 @@ proc addDeclAt*(scope: PScope, sym: PSym) = if scope.addUniqueSym(sym) == Failure: WrongRedefinition(sym.info, sym.Name.s) -proc AddInterfaceDeclAux(c: PContext, sym: PSym) = +proc addInterfaceDeclAux(c: PContext, sym: PSym) = if sfExported in sym.flags: # add to interface: if c.module != nil: StrTableAdd(c.module.tab, sym) @@ -152,27 +152,27 @@ proc AddInterfaceDeclAux(c: PContext, sym: PSym) = proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) = addDeclAt(scope, sym) - AddInterfaceDeclAux(c, sym) + addInterfaceDeclAux(c, sym) proc addOverloadableSymAt*(scope: PScope, fn: PSym) = if fn.kind notin OverloadableSyms: - InternalError(fn.info, "addOverloadableSymAt") + internalError(fn.info, "addOverloadableSymAt") return var check = StrTableGet(scope.symbols, fn.name) if check != nil and check.Kind notin OverloadableSyms: - WrongRedefinition(fn.info, fn.Name.s) + wrongRedefinition(fn.info, fn.Name.s) else: scope.addSym(fn) proc addInterfaceDecl*(c: PContext, sym: PSym) = # it adds the symbol to the interface if appropriate addDecl(c, sym) - AddInterfaceDeclAux(c, sym) + addInterfaceDeclAux(c, sym) proc addInterfaceOverloadableSymAt*(c: PContext, scope: PScope, sym: PSym) = # it adds the symbol to the interface if appropriate addOverloadableSymAt(scope, sym) - AddInterfaceDeclAux(c, sym) + addInterfaceDeclAux(c, sym) proc lookUp*(c: PContext, n: PNode): PSym = # Looks up a symbol. Generates an error in case of nil. @@ -180,7 +180,7 @@ proc lookUp*(c: PContext, n: PNode): PSym = of nkIdent: result = searchInScopes(c, n.ident) if result == nil: - LocalError(n.info, errUndeclaredIdentifier, n.ident.s) + localError(n.info, errUndeclaredIdentifier, n.ident.s) result = errorSym(c, n) of nkSym: result = n.sym @@ -188,34 +188,34 @@ proc lookUp*(c: PContext, n: PNode): PSym = var ident = considerAcc(n) result = searchInScopes(c, ident) if result == nil: - LocalError(n.info, errUndeclaredIdentifier, ident.s) + localError(n.info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n) else: - InternalError(n.info, "lookUp") + internalError(n.info, "lookUp") return - if Contains(c.AmbiguousSymbols, result.id): - LocalError(n.info, errUseQualifier, result.name.s) + if contains(c.AmbiguousSymbols, result.id): + localError(n.info, errUseQualifier, result.name.s) if result.kind == skStub: loadStub(result) type TLookupFlag* = enum checkAmbiguity, checkUndeclared -proc QualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = +proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = case n.kind of nkIdent, nkAccQuoted: var ident = considerAcc(n) result = searchInScopes(c, ident) if result == nil and checkUndeclared in flags: - LocalError(n.info, errUndeclaredIdentifier, ident.s) + localError(n.info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n) elif checkAmbiguity in flags and result != nil and - Contains(c.AmbiguousSymbols, result.id): - LocalError(n.info, errUseQualifier, ident.s) + contains(c.AmbiguousSymbols, result.id): + localError(n.info, errUseQualifier, ident.s) of nkSym: result = n.sym - if checkAmbiguity in flags and Contains(c.AmbiguousSymbols, result.id): - LocalError(n.info, errUseQualifier, n.sym.name.s) + if checkAmbiguity in flags and contains(c.AmbiguousSymbols, result.id): + localError(n.info, errUseQualifier, n.sym.name.s) of nkDotExpr: result = nil var m = qualifiedLookUp(c, n.sons[0], flags*{checkUndeclared}) @@ -227,31 +227,31 @@ proc QualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = ident = considerAcc(n.sons[1]) if ident != nil: if m == c.module: - result = StrTableGet(c.topLevelScope.symbols, ident) + result = strTableGet(c.topLevelScope.symbols, ident) else: - result = StrTableGet(m.tab, ident) + result = strTableGet(m.tab, ident) if result == nil and checkUndeclared in flags: - LocalError(n.sons[1].info, errUndeclaredIdentifier, ident.s) + localError(n.sons[1].info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n.sons[1]) elif n.sons[1].kind == nkSym: result = n.sons[1].sym elif checkUndeclared in flags and n.sons[1].kind notin {nkOpenSymChoice, nkClosedSymChoice}: - LocalError(n.sons[1].info, errIdentifierExpected, + localError(n.sons[1].info, errIdentifierExpected, renderTree(n.sons[1])) result = errorSym(c, n.sons[1]) else: result = nil if result != nil and result.kind == skStub: loadStub(result) -proc InitOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = +proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = case n.kind of nkIdent, nkAccQuoted: var ident = considerAcc(n) o.scope = c.currentScope o.mode = oimNoQualifier while true: - result = InitIdentIter(o.it, o.scope.symbols, ident) + result = initIdentIter(o.it, o.scope.symbols, ident) if result != nil: break else: @@ -272,12 +272,12 @@ proc InitOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = if ident != nil: if o.m == c.module: # a module may access its private members: - result = InitIdentIter(o.it, c.topLevelScope.symbols, ident) + result = initIdentIter(o.it, c.topLevelScope.symbols, ident) o.mode = oimSelfModule else: result = InitIdentIter(o.it, o.m.tab, ident) else: - LocalError(n.sons[1].info, errIdentifierExpected, + localError(n.sons[1].info, errIdentifierExpected, renderTree(n.sons[1])) result = errorSym(c, n.sons[1]) of nkClosedSymChoice, nkOpenSymChoice: @@ -285,7 +285,7 @@ proc InitOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = result = n.sons[0].sym o.symChoiceIndex = 1 o.inSymChoice = initIntSet() - Incl(o.inSymChoice, result.id) + incl(o.inSymChoice, result.id) else: nil if result != nil and result.kind == skStub: loadStub(result) @@ -306,7 +306,7 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = while result == nil: o.scope = o.scope.parent if o.scope == nil: break - result = InitIdentIter(o.it, o.scope.symbols, o.it.name) + result = initIdentIter(o.it, o.scope.symbols, o.it.name) # BUGFIX: o.it.name <-> n.ident else: result = nil @@ -323,19 +323,19 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = # try 'local' symbols too for Koenig's lookup: o.mode = oimSymChoiceLocalLookup o.scope = c.currentScope - result = FirstIdentExcluding(o.it, o.scope.symbols, + result = firstIdentExcluding(o.it, o.scope.symbols, n.sons[0].sym.name, o.inSymChoice) while result == nil: o.scope = o.scope.parent if o.scope == nil: break - result = FirstIdentExcluding(o.it, o.scope.symbols, + result = firstIdentExcluding(o.it, o.scope.symbols, n.sons[0].sym.name, o.inSymChoice) of oimSymChoiceLocalLookup: result = nextIdentExcluding(o.it, o.scope.symbols, o.inSymChoice) while result == nil: o.scope = o.scope.parent if o.scope == nil: break - result = FirstIdentExcluding(o.it, o.scope.symbols, + result = firstIdentExcluding(o.it, o.scope.symbols, n.sons[0].sym.name, o.inSymChoice) if result != nil and result.kind == skStub: loadStub(result) diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index 0c0b87222..066ccc6cd 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -12,14 +12,14 @@ import ast, astalgo, hashes, msgs, platform, nversion, times, idents, rodread -var SystemModule*: PSym +var systemModule*: PSym proc registerSysType*(t: PType) # magic symbols in the system module: proc getSysType*(kind: TTypeKind): PType proc getCompilerProc*(name: string): PSym proc registerCompilerProc*(s: PSym) -proc FinishSystem*(tab: TStrTable) +proc finishSystem*(tab: TStrTable) proc getSysSym*(name: string): PSym # implementation @@ -126,7 +126,7 @@ proc skipIntLit*(t: PType): PType {.inline.} = return getSysType(t.kind) result = t -proc AddSonSkipIntLit*(father, son: PType) = +proc addSonSkipIntLit*(father, son: PType) = if isNil(father.sons): father.sons = @[] let s = son.skipIntLit add(father.sons, s) @@ -158,13 +158,13 @@ proc setIntLitType*(result: PNode) = result.typ = getSysType(tyInt32) else: result.typ = getSysType(tyInt64) - else: InternalError(result.info, "invalid int size") + else: internalError(result.info, "invalid int size") proc getCompilerProc(name: string): PSym = var ident = getIdent(name, hashIgnoreStyle(name)) - result = StrTableGet(compilerprocs, ident) + result = strTableGet(compilerprocs, ident) if result == nil: - result = StrTableGet(rodCompilerProcs, ident) + result = strTableGet(rodCompilerProcs, ident) if result != nil: strTableAdd(compilerprocs, result) if result.kind == skStub: loadStub(result) @@ -172,7 +172,6 @@ proc getCompilerProc(name: string): PSym = proc registerCompilerProc(s: PSym) = strTableAdd(compilerprocs, s) -proc FinishSystem(tab: TStrTable) = nil - -initStrTable(compilerprocs) +proc finishSystem(tab: TStrTable) = discard +initStrTable(compilerprocs) diff --git a/compiler/main.nim b/compiler/main.nim index b91b596b0..3f8b6aeba 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -21,9 +21,9 @@ import from magicsys import SystemModule, resetSysTypes const - has_LLVM_Backend = false + hasLLVM_Backend = false -when has_LLVM_Backend: +when hasLLVM_Backend: import llvmgen proc rodPass = @@ -37,7 +37,7 @@ proc semanticPasses = registerPass verbosePass registerPass semPass -proc CommandGenDepend = +proc commandGenDepend = semanticPasses() registerPass(genDependPass) registerPass(cleanupPass) @@ -46,13 +46,13 @@ proc CommandGenDepend = execExternalProgram("dot -Tpng -o" & changeFileExt(gProjectFull, "png") & ' ' & changeFileExt(gProjectFull, "dot")) -proc CommandCheck = +proc commandCheck = msgs.gErrorMax = high(int) # do not stop after first error semanticPasses() # use an empty backend for semantic checking only rodPass() compileProject() -proc CommandDoc2 = +proc commandDoc2 = msgs.gErrorMax = high(int) # do not stop after first error semanticPasses() registerPass(docgen2Pass) @@ -60,7 +60,7 @@ proc CommandDoc2 = compileProject() finishDoc2Pass(gProjectName) -proc CommandCompileToC = +proc commandCompileToC = semanticPasses() registerPass(cgenPass) rodPass() @@ -111,15 +111,15 @@ proc CommandCompileToC = ccgutils.resetCaches() GC_fullCollect() -when has_LLVM_Backend: - proc CommandCompileToLLVM = +when hasLLVM_Backend: + proc commandCompileToLLVM = semanticPasses() registerPass(llvmgen.llvmgenPass()) rodPass() #registerPass(cleanupPass()) compileProject() -proc CommandCompileToJS = +proc commandCompileToJS = #incl(gGlobalOptions, optSafeCode) setTarget(osJS, cpuJS) #initDefines() @@ -130,7 +130,7 @@ proc CommandCompileToJS = registerPass(jsgenPass) compileProject() -proc InteractivePasses = +proc interactivePasses = #incl(gGlobalOptions, optSafeCode) #setTarget(osNimrodVM, cpuNimrodVM) initDefines() @@ -140,7 +140,7 @@ proc InteractivePasses = registerPass(semPass) registerPass(evalPass) -proc CommandInteractive = +proc commandInteractive = msgs.gErrorMax = high(int) # do not stop after first error InteractivePasses() compileSystemModule() @@ -163,20 +163,20 @@ proc commandEval(exp: string) = var echoExp = "echo \"eval\\t\", " & "repr(" & exp & ")" evalNim(echoExp.parseString, makeStdinModule()) -proc CommandPrettyOld = +proc commandPrettyOld = var projectFile = addFileExt(mainCommandArg(), NimExt) var module = parseFile(projectFile.fileInfoIdx) if module != nil: renderModule(module, getOutFile(mainCommandArg(), "pretty." & NimExt)) -proc CommandPretty = +proc commandPretty = msgs.gErrorMax = high(int) # do not stop after first error semanticPasses() registerPass(prettyPass) compileProject() pretty.overwriteFiles() -proc CommandScan = +proc commandScan = var f = addFileExt(mainCommandArg(), nimExt) var stream = LLStreamOpen(f, fmRead) if stream != nil: @@ -193,7 +193,7 @@ proc CommandScan = else: rawMessage(errCannotOpenFile, f) -proc CommandSuggest = +proc commandSuggest = if isServing: # XXX: hacky work-around ahead # Currently, it's possible to issue a idetools command, before @@ -286,7 +286,7 @@ const SimiluateCaasMemReset = false PrintRopeCacheStats = false -proc MainCommand* = +proc mainCommand* = when SimiluateCaasMemReset: gGlobalOptions.incl(optCaasEnabled) diff --git a/compiler/modules.nim b/compiler/modules.nim index ef6af3d69..15af40363 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -184,7 +184,7 @@ proc compileSystemModule* = SystemFileIdx = fileInfoIdx(options.libpath/"system.nim") discard CompileModule(SystemFileIdx, {sfSystemModule}) -proc CompileProject*(projectFile = gProjectMainIdx) = +proc compileProject*(projectFile = gProjectMainIdx) = let systemFileIdx = fileInfoIdx(options.libpath / "system.nim") if projectFile == SystemFileIdx: discard CompileModule(projectFile, {sfMainModule, sfSystemModule}) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 2a7d54d4e..44139b576 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -453,7 +453,7 @@ const var filenameToIndexTbl = initTable[string, int32]() fileInfos*: seq[TFileInfo] = @[] - SystemFileIdx*: int32 + systemFileIdx*: int32 proc toCChar*(c: Char): string = case c @@ -545,7 +545,7 @@ var when useCaas: var stdoutSocket*: TSocket -proc UnknownLineInfo*(): TLineInfo = +proc unknownLineInfo*(): TLineInfo = result.line = int16(-1) result.col = int16(-1) result.fileIndex = -1 @@ -560,7 +560,7 @@ var proc clearBufferedMsgs* = bufferedMsgs = nil -proc SuggestWriteln*(s: string) = +proc suggestWriteln*(s: string) = if eStdOut in errorOutputs: when useCaas: if isNil(stdoutSocket): Writeln(stdout, s) @@ -573,7 +573,7 @@ proc SuggestWriteln*(s: string) = if eInMemory in errorOutputs: bufferedMsgs.safeAdd(s) -proc SuggestQuit*() = +proc suggestQuit*() = if not isServing: quit(0) elif isWorkingWithDirtyBuffer: @@ -656,11 +656,11 @@ proc addCheckpoint*(info: TLineInfo) = proc addCheckpoint*(filename: string, line: int) = addCheckpoint(newLineInfo(filename, line, - 1)) -proc OutWriteln*(s: string) = +proc outWriteln*(s: string) = ## Writes to stdout. Always. if eStdOut in errorOutputs: Writeln(stdout, s) -proc MsgWriteln*(s: string) = +proc msgWriteln*(s: string) = ## Writes to stdout. If --stdout option is given, writes to stderr instead. if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return @@ -675,7 +675,7 @@ proc coordToStr(coord: int): string = if coord == -1: result = "???" else: result = $coord -proc MsgKindToString*(kind: TMsgKind): string = +proc msgKindToString*(kind: TMsgKind): string = # later versions may provide translated error messages result = msgKindToStr[kind] @@ -724,7 +724,7 @@ proc writeContext(lastinfo: TLineInfo) = var info = lastInfo for i in countup(0, len(msgContext) - 1): 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].col), getMessageStr(errInstantiationFrom, "")]) @@ -748,7 +748,7 @@ proc rawMessage*(msg: TMsgKind, args: openarray[string]) = frmt = rawHintFormat inc(gHintCounter) let s = `%`(frmt, `%`(msgKindToString(msg), args)) - MsgWriteln(s) + msgWriteln(s) handleError(msg, doAbort, s) proc rawMessage*(msg: TMsgKind, arg: string) = @@ -756,8 +756,8 @@ proc rawMessage*(msg: TMsgKind, arg: string) = proc writeSurroundingSrc(info: TLineInfo) = const indent = " " - MsgWriteln(indent & info.sourceLine.ropeToStr) - MsgWriteln(indent & repeatChar(info.col, ' ') & '^') + msgWriteln(indent & info.sourceLine.ropeToStr) + msgWriteln(indent & repeatChar(info.col, ' ') & '^') proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, eh: TErrorHandling) = @@ -783,45 +783,45 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, let s = frmt % [toMsgFilename(info), coordToStr(info.line), coordToStr(info.col), getMessageStr(msg, arg)] if not ignoreMsg: - MsgWriteln(s) + msgWriteln(s) if optPrintSurroundingSrc and msg in errMin..errMax: info.writeSurroundingSrc handleError(msg, eh, s) -proc Fatal*(info: TLineInfo, msg: TMsgKind, arg = "") = +proc fatal*(info: TLineInfo, msg: TMsgKind, arg = "") = liMessage(info, msg, arg, doAbort) -proc GlobalError*(info: TLineInfo, msg: TMsgKind, arg = "") = +proc globalError*(info: TLineInfo, msg: TMsgKind, arg = "") = liMessage(info, msg, arg, doRaise) -proc GlobalError*(info: TLineInfo, arg: string) = +proc globalError*(info: TLineInfo, arg: string) = liMessage(info, errGenerated, arg, doRaise) -proc LocalError*(info: TLineInfo, msg: TMsgKind, arg = "") = +proc localError*(info: TLineInfo, msg: TMsgKind, arg = "") = liMessage(info, msg, arg, doNothing) -proc LocalError*(info: TLineInfo, arg: string) = +proc localError*(info: TLineInfo, arg: string) = liMessage(info, errGenerated, arg, doNothing) -proc Message*(info: TLineInfo, msg: TMsgKind, arg = "") = +proc message*(info: TLineInfo, msg: TMsgKind, arg = "") = liMessage(info, msg, arg, doNothing) -proc InternalError*(info: TLineInfo, errMsg: string) = +proc internalError*(info: TLineInfo, errMsg: string) = if gCmd == cmdIdeTools: return writeContext(info) liMessage(info, errInternal, errMsg, doAbort) -proc InternalError*(errMsg: string) = +proc internalError*(errMsg: string) = if gCmd == cmdIdeTools: return writeContext(UnknownLineInfo()) rawMessage(errInternal, errMsg) -template AssertNotNil*(e: expr): expr = - if e == nil: InternalError($InstantiationInfo()) +template assertNotNil*(e: expr): expr = + if e == nil: internalError($instantiationInfo()) e -template InternalAssert*(e: bool): stmt = - if not e: InternalError($InstantiationInfo()) +template internalAssert*(e: bool): stmt = + if not e: internalError($instantiationInfo()) proc addSourceLine*(fileIdx: int32, line: string) = fileInfos[fileIdx].lines.add line.toRope @@ -835,14 +835,14 @@ proc sourceLine*(i: TLineInfo): PRope = addSourceLine i.fileIndex, line.string except EIO: discard - InternalAssert i.fileIndex < fileInfos.len + internalAssert i.fileIndex < fileInfos.len # can happen if the error points to EOF: if i.line > fileInfos[i.fileIndex].lines.len: return nil result = fileInfos[i.fileIndex].lines[i.line-1] proc quotedFilename*(i: TLineInfo): PRope = - InternalAssert i.fileIndex >= 0 + internalAssert i.fileIndex >= 0 result = fileInfos[i.fileIndex].quotedName ropes.ErrorHandler = proc (err: TRopesError, msg: string, useWarning: bool) = diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index 7ec566a01..ae6487744 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -219,7 +219,7 @@ proc getSystemConfigPath(filename: string): string = if not existsFile(result): result = joinPath([p, "etc", filename]) if not existsFile(result): result = "/etc/" & filename -proc LoadConfigs*(cfg: string) = +proc loadConfigs*(cfg: string) = # set default value (can be overwritten): if libpath == "": # choose default libpath: diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim index 6d45a825a..2e4f8dec7 100644 --- a/compiler/nimlexbase.nim +++ b/compiler/nimlexbase.nim @@ -54,11 +54,11 @@ proc openBaseLexer*(L: var TBaseLexer, inputstream: PLLStream, proc closeBaseLexer*(L: var TBaseLexer) proc getCurrentLine*(L: TBaseLexer, marker: bool = true): string proc getColNumber*(L: TBaseLexer, pos: int): int -proc HandleCR*(L: var TBaseLexer, pos: int): int +proc handleCR*(L: var TBaseLexer, pos: int): int # Call this if you scanned over CR in the buffer; it returns the # position to continue the scanning from. `pos` must be the position # of the CR. -proc HandleLF*(L: var TBaseLexer, pos: int): int +proc handleLF*(L: var TBaseLexer, pos: int): int # Call this if you scanned over LF in the buffer; it returns the the # position to continue the scanning from. `pos` must be the position # of the LF. @@ -71,7 +71,7 @@ proc closeBaseLexer(L: var TBaseLexer) = dealloc(L.buf) LLStreamClose(L.stream) -proc FillBuffer(L: var TBaseLexer) = +proc fillBuffer(L: var TBaseLexer) = var charsRead, toCopy, s: int # all are in characters, # not bytes (in case this @@ -126,20 +126,20 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int = result = 0 L.lineStart = result -proc HandleCR(L: var TBaseLexer, pos: int): int = +proc handleCR(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == CR) inc(L.linenumber) result = fillBaseLexer(L, pos) if L.buf[result] == LF: result = fillBaseLexer(L, result) -proc HandleLF(L: var TBaseLexer, pos: int): int = +proc handleLF(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == LF) inc(L.linenumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; -proc skip_UTF_8_BOM(L: var TBaseLexer) = - if (L.buf[0] == '\xEF') and (L.buf[1] == '\xBB') and (L.buf[2] == '\xBF'): +proc skipUTF8BOM(L: var TBaseLexer) = + if L.buf[0] == '\xEF' and L.buf[1] == '\xBB' and L.buf[2] == '\xBF': inc(L.bufpos, 3) inc(L.lineStart, 3) @@ -167,4 +167,3 @@ proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = result.add("\n") if marker: result.add(RepeatChar(getColNumber(L, L.bufpos)) & '^' & "\n") - diff --git a/compiler/nimrod.nim b/compiler/nimrod.nim index 2bc94e3f8..33c899647 100644 --- a/compiler/nimrod.nim +++ b/compiler/nimrod.nim @@ -31,7 +31,7 @@ proc prependCurDir(f: string): string = else: result = f -proc HandleCmdLine() = +proc handleCmdLine() = if paramCount() == 0: writeCommandLineUsage() else: @@ -47,12 +47,12 @@ proc HandleCmdLine() = gProjectName = p.name else: gProjectPath = getCurrentDir() - LoadConfigs(DefaultConfig) # load all config files + loadConfigs(DefaultConfig) # load all config files # now process command line arguments again, because some options in the # command line can overwite the config file's settings extccomp.initVars() - ProcessCmdLine(passCmd2, "") - MainCommand() + processCmdLine(passCmd2, "") + mainCommand() if gVerbosity >= 2: echo(GC_getStatistics()) #echo(GC_getStatistics()) if msgs.gErrorCounter == 0: @@ -84,5 +84,5 @@ when compileOption("gc", "v2") or compileOption("gc", "refc"): condsyms.InitDefines() when not defined(selftest): - HandleCmdLine() + handleCmdLine() quit(int8(msgs.gErrorCounter > 0)) diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index 34f79e14b..8c2fc42d3 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -18,7 +18,7 @@ proc overlap*(a, b: PNode): bool proc inSet*(s: PNode, elem: PNode): bool proc someInSet*(s: PNode, a, b: PNode): bool proc emptyRange*(a, b: PNode): bool -proc SetHasRange*(s: PNode): bool +proc setHasRange*(s: PNode): bool # returns true if set contains a range (needed by the code generator) # these are used for constant folding: proc unionSets*(a, b: PNode): PNode @@ -87,7 +87,7 @@ proc toBitSet(s: PNode, b: var TBitSet) = else: BitSetIncl(b, getOrdValue(s.sons[i]) - first) -proc ToTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = +proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = var a, b, e, first: BiggestInt # a, b are interval borders elemType: PType @@ -158,9 +158,9 @@ proc cardSet(s: PNode): BiggestInt = else: Inc(result) -proc SetHasRange(s: PNode): bool = +proc setHasRange(s: PNode): bool = if s.kind != nkCurly: - InternalError(s.info, "SetHasRange") + internalError(s.info, "SetHasRange") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: diff --git a/compiler/options.nim b/compiler/options.nim index d4122c7b2..d792b487e 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -277,7 +277,7 @@ proc rawFindFile2(f: string): string = it = PStrEntry(it.Next) result = "" -proc FindFile*(f: string): string {.procvar.} = +proc findFile*(f: string): string {.procvar.} = result = f.rawFindFile if result.len == 0: result = f.toLower.rawFindFile diff --git a/compiler/parser.nim b/compiler/parser.nim index fd51b04ec..652883360 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -35,7 +35,7 @@ type lex*: TLexer # the lexer that is used for parsing tok*: TToken # the current token -proc ParseAll*(p: var TParser): PNode +proc parseAll*(p: var TParser): PNode proc openParser*(p: var TParser, filename: string, inputstream: PLLStream) proc closeParser*(p: var TParser) proc parseTopLevelStmt*(p: var TParser): PNode @@ -59,9 +59,9 @@ proc newFloatNodeP*(kind: TNodeKind, floatVal: BiggestFloat, p: TParser): PNode proc newStrNodeP*(kind: TNodeKind, strVal: string, p: TParser): PNode proc newIdentNodeP*(ident: PIdent, p: TParser): PNode proc expectIdentOrKeyw*(p: TParser) -proc ExpectIdent*(p: TParser) +proc expectIdent*(p: TParser) proc parLineInfo*(p: TParser): TLineInfo -proc Eat*(p: var TParser, TokType: TTokType) +proc eat*(p: var TParser, TokType: TTokType) proc skipInd*(p: var TParser) proc optPar*(p: var TParser) proc optInd*(p: var TParser, n: PNode) @@ -75,17 +75,17 @@ proc parseCase(p: var TParser): PNode proc getTok(p: var TParser) = rawGetTok(p.lex, p.tok) -proc OpenParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream) = +proc openParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream) = initToken(p.tok) - OpenLexer(p.lex, fileIdx, inputstream) + openLexer(p.lex, fileIdx, inputstream) getTok(p) # read the first token p.firstTok = true -proc OpenParser*(p: var TParser, filename: string, inputStream: PLLStream) = +proc openParser*(p: var TParser, filename: string, inputStream: PLLStream) = openParser(p, filename.fileInfoIdx, inputStream) -proc CloseParser(p: var TParser) = - CloseLexer(p.lex) +proc closeParser(p: var TParser) = + closeLexer(p.lex) proc parMessage(p: TParser, msg: TMsgKind, arg: string = "") = lexMessage(p.lex, msg, arg) @@ -135,11 +135,11 @@ proc expectIdentOrKeyw(p: TParser) = if p.tok.tokType != tkSymbol and not isKeyword(p.tok.tokType): lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok)) -proc ExpectIdent(p: TParser) = +proc expectIdent(p: TParser) = if p.tok.tokType != tkSymbol: lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok)) -proc Eat(p: var TParser, TokType: TTokType) = +proc eat(p: var TParser, TokType: TTokType) = if p.tok.TokType == TokType: getTok(p) else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType]) @@ -185,10 +185,10 @@ proc relevantOprChar(ident: PIdent): char {.inline.} = if result == '\\' and L > 1: result = ident.s[1] -proc IsSigilLike(tok: TToken): bool {.inline.} = +proc isSigilLike(tok: TToken): bool {.inline.} = result = tok.tokType == tkOpr and relevantOprChar(tok.ident) == '@' -proc IsLeftAssociative(tok: TToken): bool {.inline.} = +proc isLeftAssociative(tok: TToken): bool {.inline.} = result = tok.tokType != tkOpr or relevantOprChar(tok.ident) != '^' proc getPrecedence(tok: TToken): int = @@ -427,7 +427,7 @@ proc parseCast(p: var TParser): PNode = proc setBaseFlags(n: PNode, base: TNumericalBase) = case base - of base10: nil + of base10: discard of base2: incl(n.flags, nfBase2) of base8: incl(n.flags, nfBase8) of base16: incl(n.flags, nfBase16) @@ -1862,7 +1862,7 @@ proc parseTopLevelStmt(p: var TParser): PNode = result = ast.emptyNode while true: if p.tok.indent != 0: - if p.firstTok and p.tok.indent < 0: nil + if p.firstTok and p.tok.indent < 0: discard else: parMessage(p, errInvalidIndentation) p.firstTok = false case p.tok.tokType @@ -1881,7 +1881,7 @@ proc parseString(s: string, filename: string = "", line: int = 0): PNode = stream.lineOffset = line var parser: TParser - OpenParser(parser, filename, stream) + openParser(parser, filename, stream) result = parser.parseAll - CloseParser(parser) + closeParser(parser) diff --git a/compiler/pbraces.nim b/compiler/pbraces.nim index a944fe0ab..ce6e0d9a9 100644 --- a/compiler/pbraces.nim +++ b/compiler/pbraces.nim @@ -10,7 +10,7 @@ import llstream, lexer, parser, idents, strutils, ast, msgs -proc ParseAll*(p: var TParser): PNode = +proc parseAll*(p: var TParser): PNode = result = nil proc parseTopLevelStmt*(p: var TParser): PNode = diff --git a/compiler/platform.nim b/compiler/platform.nim index 59091b690..5245cba6a 100644 --- a/compiler/platform.nim +++ b/compiler/platform.nim @@ -185,13 +185,13 @@ var targetCPU*, hostCPU*: TSystemCPU targetOS*, hostOS*: TSystemOS -proc NameToOS*(name: string): TSystemOS -proc NameToCPU*(name: string): TSystemCPU +proc nameToOS*(name: string): TSystemOS +proc nameToCPU*(name: string): TSystemCPU var - IntSize*: int + intSize*: int floatSize*: int - PtrSize*: int + ptrSize*: int tnl*: string # target newline proc setTarget*(o: TSystemOS, c: TSystemCPU) = @@ -205,13 +205,13 @@ proc setTarget*(o: TSystemOS, c: TSystemCPU) = ptrSize = cpu[c].bit div 8 tnl = os[o].newLine -proc NameToOS(name: string): TSystemOS = +proc nameToOS(name: string): TSystemOS = for i in countup(succ(osNone), high(TSystemOS)): if cmpIgnoreStyle(name, OS[i].name) == 0: return i result = osNone -proc NameToCPU(name: string): TSystemCPU = +proc nameToCPU(name: string): TSystemCPU = for i in countup(succ(cpuNone), high(TSystemCPU)): if cmpIgnoreStyle(name, CPU[i].name) == 0: return i diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index 6f1e7af25..41898caed 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -92,12 +92,12 @@ proc setExternName(s: PSym, extname: string) = # note that '{.importc.}' is transformed into '{.importc: "$1".}' s.loc.flags.incl(lfFullExternalName) -proc MakeExternImport(s: PSym, extname: string) = +proc makeExternImport(s: PSym, extname: string) = setExternName(s, extname) incl(s.flags, sfImportc) excl(s.flags, sfForward) -proc MakeExternExport(s: PSym, extname: string) = +proc makeExternExport(s: PSym, extname: string) = setExternName(s, extname) incl(s.flags, sfExportc) @@ -133,7 +133,7 @@ proc getStrLitNode(c: PContext, n: PNode): PNode = case n.sons[1].kind of nkStrLit, nkRStrLit, nkTripleStrLit: result = n.sons[1] else: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) # error correction: result = newEmptyStrNode(n) @@ -142,12 +142,12 @@ proc expectStrLit(c: PContext, n: PNode): string = proc expectIntLit(c: PContext, n: PNode): int = if n.kind != nkExprColonExpr: - LocalError(n.info, errIntLiteralExpected) + localError(n.info, errIntLiteralExpected) else: n.sons[1] = c.semConstExpr(c, n.sons[1]) case n.sons[1].kind of nkIntLit..nkInt64Lit: result = int(n.sons[1].intVal) - else: LocalError(n.info, errIntLiteralExpected) + else: localError(n.info, errIntLiteralExpected) proc getOptionalStr(c: PContext, n: PNode, defaultStr: string): string = if n.kind == nkExprColonExpr: result = expectStrLit(c, n) @@ -160,7 +160,7 @@ proc processMagic(c: PContext, n: PNode, s: PSym) = #if sfSystemModule notin c.module.flags: # liMessage(n.info, errMagicOnlyInSystem) if n.kind != nkExprColonExpr: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) return var v: string if n.sons[1].kind == nkIdent: v = n.sons[1].ident.s @@ -176,15 +176,15 @@ proc wordToCallConv(sw: TSpecialWord): TCallingConvention = # the same result = TCallingConvention(ord(ccDefault) + ord(sw) - ord(wNimcall)) -proc IsTurnedOn(c: PContext, n: PNode): bool = +proc isTurnedOn(c: PContext, n: PNode): bool = if n.kind == nkExprColonExpr: let x = c.semConstBoolExpr(c, n.sons[1]) n.sons[1] = x if x.kind == nkIntLit: return x.intVal != 0 - LocalError(n.info, errOnOrOffExpected) + localError(n.info, errOnOrOffExpected) proc onOff(c: PContext, n: PNode, op: TOptions) = - if IsTurnedOn(c, n): gOptions = gOptions + op + if isTurnedOn(c, n): gOptions = gOptions + op else: gOptions = gOptions - op proc pragmaDeadCodeElim(c: PContext, n: PNode) = @@ -387,16 +387,16 @@ proc processCommonLink(c: PContext, n: PNode, feature: TLinkFeature) = extccomp.addFileToLink(libpath / completeCFilePath(found, false)) else: internalError(n.info, "processCommonLink") -proc PragmaBreakpoint(c: PContext, n: PNode) = +proc pragmaBreakpoint(c: PContext, n: PNode) = discard getOptionalStr(c, n, "") -proc PragmaCheckpoint(c: PContext, n: PNode) = +proc pragmaCheckpoint(c: PContext, n: PNode) = # checkpoints can be used to debug the compiler; they are not documented var info = n.info inc(info.line) # next line is affected! msgs.addCheckpoint(info) -proc PragmaWatchpoint(c: PContext, n: PNode) = +proc pragmaWatchpoint(c: PContext, n: PNode) = if n.kind == nkExprColonExpr: n.sons[1] = c.semExpr(c, n.sons[1]) else: @@ -431,14 +431,14 @@ proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode = a = c + 1 else: illFormedAst(n) -proc PragmaEmit(c: PContext, n: PNode) = +proc pragmaEmit(c: PContext, n: PNode) = discard getStrLitNode(c, n) n.sons[1] = semAsmOrEmit(c, n, '`') proc noVal(n: PNode) = if n.kind == nkExprColonExpr: invalidPragma(n) -proc PragmaUnroll(c: PContext, n: PNode) = +proc pragmaUnroll(c: PContext, n: PNode) = if c.p.nestedLoopCounter <= 0: invalidPragma(n) elif n.kind == nkExprColonExpr: @@ -448,7 +448,7 @@ proc PragmaUnroll(c: PContext, n: PNode) = else: invalidPragma(n) -proc PragmaLine(c: PContext, n: PNode) = +proc pragmaLine(c: PContext, n: PNode) = if n.kind == nkExprColonExpr: n.sons[1] = c.semConstExpr(c, n.sons[1]) let a = n.sons[1] @@ -465,7 +465,7 @@ proc PragmaLine(c: PContext, n: PNode) = n.info.fileIndex = msgs.fileInfoIdx(x.strVal) n.info.line = int16(y.intVal) else: - LocalError(n.info, errXExpected, "tuple") + localError(n.info, errXExpected, "tuple") else: # sensible default: n.info = getInfoContext(-1) diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 5036a16a3..2955193d0 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -12,7 +12,7 @@ import strutils, os, options, ast, astalgo, msgs, ropes, idents, passes, - intsets, strtabs + intsets, strtabs, semdata const removeTP = false # when true, "nimrod pretty" converts TTyp to Typ. @@ -50,7 +50,7 @@ proc overwriteFiles*() = try: var f = open(newFile, fmWrite) for line in gSourceFiles[i].lines: - f.writeln(line) + f.writeln(line.strip(leading = false, trailing = true)) f.close except EIO: rawMessage(errCannotOpenFile, newFile) @@ -60,18 +60,25 @@ proc `=~`(s: string, a: openArray[string]): bool = if s.startsWith(x): return true proc beautifyName(s: string, k: TSymKind): string = + # minimal set of rules here for transition: + # GC_ is allowed + + let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'}) + if allUpper and k in {skConst, skEnumField, skType}: return s result = newStringOfCap(s.len) var i = 0 case k of skType, skGenericParam: - # skip leading 'T' + # Types should start with a capital unless builtins like 'int' etc.: when removeTP: if s[0] == 'T' and s[1] in {'A'..'Z'}: i = 1 if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string", "char", "byte", "bool", "openArray", "seq", "array", "void", "pointer", "float", "csize", "cdouble", "cchar", "cschar", - "cshort", "cu"]: + "cshort", "cu", "nil", "expr", "stmt", "typedesc", "auto", "any", + "range", "openarray", "varargs", "set", "cfloat" + ]: result.add s[i] else: result.add toUpper(s[i]) @@ -81,13 +88,19 @@ proc beautifyName(s: string, k: TSymKind): string = else: # as a special rule, don't transform 'L' to 'l' if s.len == 1 and s[0] == 'L': result.add 'L' + elif '_' in s: result.add(s[i]) else: result.add toLower(s[0]) inc i - let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'}) while i < s.len: if s[i] == '_': - inc i - result.add toUpper(s[i]) + if i > 0 and s[i-1] in {'A'..'Z'}: + # don't skip '_' as it's essential for e.g. 'GC_disable' + result.add('_') + inc i + result.add s[i] + else: + inc i + result.add toUpper(s[i]) elif allUpper: result.add toLower(s[i]) else: @@ -97,7 +110,7 @@ proc beautifyName(s: string, k: TSymKind): string = proc checkStyle*(info: TLineInfo, s: string, k: TSymKind) = let beau = beautifyName(s, k) if s != beau: - Message(info, errGenerated, + message(info, errGenerated, "name does not adhere to naming convention; should be: " & beau) const @@ -119,11 +132,88 @@ proc differ(line: string, a, b: int, x: string): bool = var cannotRename = initIntSet() -proc processSym(c: PPassContext, n: PNode): PNode = - result = n - var g = PGen(c) - case n.kind - of nkSym: +proc checkDef(c: PGen; n: PNode) = + if n.kind != nkSym: return + let s = n.sym + + # operators stay as they are: + if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return + if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return + + checkStyle(n.info, s.name.s, s.kind) + +proc checkUse(c: PGen; n: PNode) = + if n.info.fileIndex < 0: return + let s = n.sym + # we simply convert it to what it looks like in the definition + # for consistency + + # operators stay as they are: + if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return + if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return + let newName = s.name.s + + loadFile(n.info) + + let line = gSourceFiles[n.info.fileIndex].lines[n.info.line-1] + var first = min(n.info.col.int, line.len) + if first < 0: return + #inc first, skipIgnoreCase(line, "proc ", first) + while first > 0 and line[first-1] in Letters: dec first + if first < 0: return + if line[first] == '`': inc first + + let last = first+identLen(line, first)-1 + if differ(line, first, last, newName): + # last-first+1 != newName.len or + var x = line.subStr(0, first-1) & newName & line.substr(last+1) + when removeTP: + # the WinAPI module is full of 'TX = X' which after the substitution + # becomes 'X = X'. We remove those lines: + if x.match(peg"\s* {\ident} \s* '=' \s* y$1 ('#' .*)?"): + x = "" + + system.shallowCopy(gSourceFiles[n.info.fileIndex].lines[n.info.line-1], x) + gSourceFiles[n.info.fileIndex].dirty = true + + +when false: + proc beautifyName(s: string, k: TSymKind): string = + let allUpper = allCharsInSet(s, {'A'..'Z', '0'..'9', '_'}) + result = newStringOfCap(s.len) + var i = 0 + case k + of skType, skGenericParam: + # skip leading 'T' + when removeTP: + if s[0] == 'T' and s[1] in {'A'..'Z'}: + i = 1 + if s =~ ["int", "uint", "cint", "cuint", "clong", "cstring", "string", + "char", "byte", "bool", "openArray", "seq", "array", "void", + "pointer", "float", "csize", "cdouble", "cchar", "cschar", + "cshort", "cu"]: + result.add s[i] + else: + result.add toUpper(s[i]) + of skConst, skEnumField: + # for 'const' we keep how it's spelt; either upper case or lower case: + result.add s[0] + else: + # as a special rule, don't transform 'L' to 'l' + if s.len == 1 and s[0] == 'L': result.add 'L' + else: result.add toLower(s[0]) + inc i + while i < s.len: + if s[i] == '_': + inc i + result.add toUpper(s[i]) + elif allUpper: + result.add toLower(s[i]) + else: + result.add s[i] + inc i + + proc checkUse(c: PGen; n: PNode) = if n.info.fileIndex < 0: return let s = n.sym # operators stay as they are: @@ -138,10 +228,11 @@ proc processSym(c: PPassContext, n: PNode): PNode = loadFile(n.info) let line = gSourceFiles[n.info.fileIndex].lines[n.info.line-1] - var first = n.info.col.int + var first = min(n.info.col.int, line.len) if first < 0: return #inc first, skipIgnoreCase(line, "proc ", first) while first > 0 and line[first-1] in Letters: dec first + if first < 0: return if line[first] == '`': inc first if {sfImportc, sfExportc} * s.flags != {}: @@ -149,8 +240,8 @@ proc processSym(c: PPassContext, n: PNode): PNode = # name: if newName != s.name.s and newName != s.loc.r.ropeToStr and lfFullExternalName notin s.loc.flags: - Message(n.info, errGenerated, - "cannot rename $# to $# due to external name" % [s.name.s, newName]) + #Message(n.info, errGenerated, + # "cannot rename $# to $# due to external name" % [s.name.s, newName]) cannotRename.incl(s.id) return let last = first+identLen(line, first)-1 @@ -165,9 +256,48 @@ proc processSym(c: PPassContext, n: PNode): PNode = system.shallowCopy(gSourceFiles[n.info.fileIndex].lines[n.info.line-1], x) gSourceFiles[n.info.fileIndex].dirty = true + +proc check(c: PGen, n: PNode) = + case n.kind + of nkSym: checkUse(c, n) + of nkBlockStmt, nkBlockExpr, nkBlockType: + if n.sons[0].kind != nkEmpty: checkDef(c, n[0]) + check(c, n.sons[1]) + of nkForStmt, nkParForStmt: + let L = n.len + for i in countup(0, L-3): + checkDef(c, n[i]) + check(c, n[L-2]) + check(c, n[L-1]) + of nkProcDef, nkLambdaKinds, nkMethodDef, nkIteratorDef, nkTemplateDef, + nkMacroDef, nkConverterDef: + checkDef(c, n[namePos]) + for i in namePos+1 .. = 0) if g.pendingNL > indentWidth: - Dec(g.pendingNL, indentWidth) - Dec(g.lineLen, indentWidth) + dec(g.pendingNL, indentWidth) + dec(g.lineLen, indentWidth) proc put(g: var TSrcGen, kind: TTokType, s: string) = addPendingNL(g) diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 6e6b83260..9f69f022a 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -184,7 +184,7 @@ proc skipNode(r: PRodReader) = if par == 0: break dec par of '(': inc par - else: nil + else: discard inc pos r.pos = pos+1 # skip ')' @@ -248,7 +248,7 @@ proc decodeNodeLazyBody(r: PRodReader, fInfo: TLineInfo, if r.s[r.pos] == ')': inc(r.pos) else: internalError(result.info, "decodeNode: ')' missing") else: - InternalError(fInfo, "decodeNode: '(' missing " & $r.pos) + internalError(fInfo, "decodeNode: '(' missing " & $r.pos) proc decodeNode(r: PRodReader, fInfo: TLineInfo): PNode = result = decodeNodeLazyBody(r, fInfo, nil) @@ -286,7 +286,7 @@ proc decodeLoc(r: PRodReader, loc: var TLoc, info: TLineInfo) = else: loc.a = 0 if r.s[r.pos] == '>': inc(r.pos) - else: InternalError(info, "decodeLoc " & r.s[r.pos]) + else: internalError(info, "decodeLoc " & r.s[r.pos]) proc decodeType(r: PRodReader, info: TLineInfo): PType = result = nil @@ -303,9 +303,9 @@ proc decodeType(r: PRodReader, info: TLineInfo): PType = setId(result.id) if debugIds: registerID(result) else: - InternalError(info, "decodeType: no id") + internalError(info, "decodeType: no id") # here this also avoids endless recursion for recursive type - IdTablePut(gTypeTable, result, result) + idTablePut(gTypeTable, result, result) if r.s[r.pos] == '(': result.n = decodeNode(r, UnknownLineInfo()) if r.s[r.pos] == '$': inc(r.pos) @@ -370,7 +370,7 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = id = decodeVInt(r.s, r.pos) setId(id) else: - InternalError(info, "decodeSym: no id") + internalError(info, "decodeSym: no id") if r.s[r.pos] == '&': inc(r.pos) ident = getIdent(decodeStr(r.s, r.pos)) @@ -384,7 +384,7 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = IdTablePut(r.syms, result, result) if debugIds: registerID(result) elif result.id != id: - InternalError(info, "decodeSym: wrong id") + internalError(info, "decodeSym: wrong id") elif result.kind != skStub and not r.inViewMode: # we already loaded the symbol return @@ -455,7 +455,7 @@ proc skipSection(r: PRodReader) = elif c > 0: dec(c) of '\0': break # end of file - else: nil + else: discard inc(r.pos) else: InternalError("skipSection " & $r.line) @@ -799,7 +799,7 @@ proc loadMethods(r: PRodReader) = r.methods.add(rrGetSym(r, d, UnknownLineInfo())) 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 if gMods[fileIdx].crcDone: @@ -818,14 +818,14 @@ proc checkDep(fileIdx: int32): TReasonForRecompile = # reason has already been computed for this module: return gMods[fileIdx].reason let filename = fileIdx.toFilename - var crc = GetCRC(fileIdx) + var crc = getCRC(fileIdx) gMods[fileIdx].reason = rrNone # we need to set it here to avoid cycles result = rrNone var r: PRodReader = nil var rodfile = toGeneratedFile(filename.withPackageName, RodExt) r = newRodReader(rodfile, crc, fileIdx) if r == nil: - result = (if ExistsFile(rodfile): rrRodInvalid else: rrRodDoesNotExist) + result = (if existsFile(rodfile): rrRodInvalid else: rrRodDoesNotExist) else: processRodFile(r, crc) result = r.reason @@ -880,12 +880,12 @@ proc rawLoadStub(s: PSym) = if rs != s: #echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2), # "\ns: ", toHex(cast[int](s.position), int.sizeof * 2) - InternalError(rs.info, "loadStub: wrong symbol") + internalError(rs.info, "loadStub: wrong symbol") elif rs.id != theId: - InternalError(rs.info, "loadStub: wrong ID") + internalError(rs.info, "loadStub: wrong ID") #MessageOut('loaded stub: ' + s.name.s); -proc LoadStub*(s: PSym) = +proc loadStub*(s: PSym) = ## loads the stub symbol `s`. # deactivate the GC here because we do a deep recursion and generate no @@ -912,8 +912,8 @@ proc getBody*(s: PSym): PNode = s.ast.sons[bodyPos] = result s.offset = 0 -InitIdTable(gTypeTable) -InitStrTable(rodCompilerProcs) +initIdTable(gTypeTable) +initStrTable(rodCompilerProcs) # viewer: proc writeNode(f: TFile; n: PNode) = @@ -1166,7 +1166,7 @@ proc viewFile(rodfile: string) = if r.s[r.pos] == ')': inc r.pos outf.write(")\n") else: - InternalError("invalid section: '" & section & + internalError("invalid section: '" & section & "' at " & $r.line & " in " & r.filename) skipSection(r) if r.s[r.pos] == '\x0A': diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 0ee3b1ec4..4527f77da 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -12,7 +12,7 @@ import strutils proc c_sprintf(buf, frmt: cstring) {.importc: "sprintf", nodecl, varargs.} -proc ToStrMaxPrecision*(f: BiggestFloat): string = +proc toStrMaxPrecision*(f: BiggestFloat): string = if f != f: result = "NAN" elif f == 0.0: @@ -36,7 +36,7 @@ proc hexChar(c: char, xi: var int) = of '0'..'9': xi = (xi shl 4) or (ord(c) - ord('0')) of 'a'..'f': xi = (xi shl 4) or (ord(c) - ord('a') + 10) of 'A'..'F': xi = (xi shl 4) or (ord(c) - ord('A') + 10) - else: nil + else: discard proc decodeStr*(s: cstring, pos: var int): string = var i = pos diff --git a/compiler/ropes.nim b/compiler/ropes.nim index 707c29123..4f8553375 100644 --- a/compiler/ropes.nim +++ b/compiler/ropes.nim @@ -91,13 +91,13 @@ proc writeRopeIfNotEqual*(r: PRope, filename: string): bool proc ropeToStr*(p: PRope): string proc ropef*(frmt: TFormatStr, args: varargs[PRope]): PRope proc appf*(c: var PRope, frmt: TFormatStr, args: varargs[PRope]) -proc RopeEqualsFile*(r: PRope, f: string): bool +proc ropeEqualsFile*(r: PRope, f: string): bool # returns true if the rope r is the same as the contents of file f -proc RopeInvariant*(r: PRope): bool +proc ropeInvariant*(r: PRope): bool # exported for debugging # implementation -var ErrorHandler*: proc(err: TRopesError, msg: string, useWarning = false) +var errorHandler*: proc(err: TRopesError, msg: string, useWarning = false) # avoid dependency on msgs.nim proc ropeLen(a: PRope): int = @@ -126,7 +126,7 @@ proc resetRopeCache* = for i in low(cache)..high(cache): cache[i] = nil -proc RopeInvariant(r: PRope): bool = +proc ropeInvariant(r: PRope): bool = if r == nil: result = true else: @@ -159,7 +159,7 @@ proc toRope(s: string): PRope = result = insertInCache(s) 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) if at > length: setlen(rs, at + 1) @@ -177,8 +177,8 @@ proc newRecRopeToStr(result: var string, resultLen: var int, r: PRope) = add(stack, it.right) it = it.left assert(it.data != nil) - CopyMem(addr(result[resultLen]), addr(it.data[0]), it.length) - Inc(resultLen, it.length) + copyMem(addr(result[resultLen]), addr(it.data[0]), it.length) + inc(resultLen, it.length) assert(resultLen <= len(result)) proc ropeToStr(p: PRope): string = @@ -227,13 +227,13 @@ proc writeRope*(f: TFile, c: PRope) = assert(it.data != nil) write(f, it.data) -proc WriteRope*(head: PRope, filename: string, useWarning = false) = +proc writeRope*(head: PRope, filename: string, useWarning = false) = var f: tfile if open(f, filename, fmWrite): if head != nil: WriteRope(f, head) close(f) else: - ErrorHandler(rCannotOpenFile, filename, useWarning) + errorHandler(rCannotOpenFile, filename, useWarning) var rnl* = tnl.newRope @@ -263,7 +263,7 @@ proc ropef(frmt: TFormatStr, args: varargs[PRope]): PRope = if (i > length + 0 - 1) or not (frmt[i] in {'0'..'9'}): break num = j if j > high(args) + 1: - ErrorHandler(rInvalidFormatStr, $(j)) + errorHandler(rInvalidFormatStr, $(j)) else: app(result, args[j - 1]) of 'n': @@ -273,7 +273,7 @@ proc ropef(frmt: TFormatStr, args: varargs[PRope]): PRope = app(result, rnl) inc(i) else: - ErrorHandler(rInvalidFormatStr, $(frmt[i])) + errorHandler(rInvalidFormatStr, $(frmt[i])) var start = i while i < length: if frmt[i] != '$': inc(i) @@ -308,8 +308,8 @@ proc auxRopeEqualsFile(r: PRope, bin: var tfile, buf: Pointer): bool = result = auxRopeEqualsFile(r.left, bin, buf) if result: result = auxRopeEqualsFile(r.right, bin, buf) -proc RopeEqualsFile(r: PRope, f: string): bool = - var bin: tfile +proc ropeEqualsFile(r: PRope, f: string): bool = + var bin: TFile result = open(bin, f) if not result: return # not equal if file does not exist diff --git a/compiler/sem.nim b/compiler/sem.nim index d0fc5bfe1..ee1019aa8 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -66,7 +66,7 @@ proc fitNode(c: PContext, formal: PType, arg: PNode): PNode = result = copyTree(arg) result.typ = formal -var CommonTypeBegin = PType(kind: tyExpr) +var commonTypeBegin = PType(kind: tyExpr) proc commonType*(x, y: PType): PType = # new type relation that is used for array constructors, diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 9e9614796..8fe81c4c6 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -19,7 +19,7 @@ proc sameMethodDispatcher(a, b: PSym): bool = if aa.sym == bb.sym: result = true else: - nil + discard # generics have no dispatcher yet, so we need to compare the method # names; however, the names are equal anyway because otherwise we # wouldn't even consider them to be overloaded. But even this does @@ -74,13 +74,13 @@ proc pickBestCandidate(c: PContext, headSymbol: PNode, else: nil sym = nextOverloadIter(o, c, headSymbol) -proc NotFoundError*(c: PContext, n: PNode, errors: seq[string]) = +proc notFoundError*(c: PContext, n: PNode, errors: seq[string]) = # Gives a detailed error message; this is separated from semOverloadedCall, # as semOverlodedCall is already pretty slow (and we need this information # only in case of an error). - if c.InCompilesContext > 0: + if c.inCompilesContext > 0: # fail fast: - GlobalError(n.info, errTypeMismatch, "") + globalError(n.info, errTypeMismatch, "") var result = msgKindToString(errTypeMismatch) add(result, describeArgs(c, n, 1 + ord(nfDelegate in n.flags))) add(result, ')') @@ -93,7 +93,7 @@ proc NotFoundError*(c: PContext, n: PNode, errors: seq[string]) = if candidates != "": add(result, "\n" & msgKindToString(errButExpected) & "\n" & candidates) - LocalError(n.Info, errGenerated, result) + localError(n.Info, errGenerated, result) proc gatherUsedSyms(c: PContext, usedSyms: var seq[PNode]) = for scope in walkScopes(c.currentScope): @@ -164,12 +164,12 @@ proc resolveOverloads(c: PContext, n, orig: PNode, if alt.state == csMatch and cmpCandidates(result, alt) == 0 and not sameMethodDispatcher(result.calleeSym, alt.calleeSym): - InternalAssert result.state == csMatch + internalAssert result.state == csMatch #writeMatches(result) #writeMatches(alt) if c.inCompilesContext > 0: # quick error message for performance of 'compiles' built-in: - GlobalError(n.Info, errGenerated, "ambiguous call") + globalError(n.Info, errGenerated, "ambiguous call") elif gErrorCounter == 0: # don't cascade errors var args = "(" @@ -178,7 +178,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode, add(args, typeToString(n.sons[i].typ)) add(args, ")") - LocalError(n.Info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [ + localError(n.Info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [ getProcHeader(result.calleeSym), getProcHeader(alt.calleeSym), args]) @@ -197,14 +197,14 @@ proc instGenericConvertersSons*(c: PContext, n: PNode, x: TCandidate) = for i in 1 .. 0 if we are in a user-defined type class - InGenericContext*: int # > 0 if we are in a generic type - InUnrolledContext*: int # > 0 if we are unrolling a loop - InCompilesContext*: int # > 0 if we are in a ``compiles`` magic - InGenericInst*: int # > 0 if we are instantiating a generic + inTypeClass*: int # > 0 if we are in a user-defined type class + inGenericContext*: int # > 0 if we are in a generic type + inUnrolledContext*: int # > 0 if we are unrolling a loop + inCompilesContext*: int # > 0 if we are in a ``compiles`` magic + inGenericInst*: int # > 0 if we are instantiating a generic converters*: TSymSeq # sequence of converters patterns*: TSymSeq # sequence of pattern matchers optionStack*: TLinkedList @@ -83,7 +83,7 @@ type includedFiles*: TIntSet # used to detect recursive include files userPragmas*: TStrTable evalContext*: PEvalContext - UnknownIdents*: TIntSet # ids of all unknown identifiers to prevent + unknownIdents*: TIntSet # ids of all unknown identifiers to prevent # naming it multiple times generics*: seq[TInstantiationPair] # pending list of instantiated generics to compile lastGenericIdx*: int # used for the generics stack @@ -114,8 +114,8 @@ proc scopeDepth*(c: PContext): int {.inline.} = # owner handling: proc getCurrOwner*(): PSym -proc PushOwner*(owner: PSym) -proc PopOwner*() +proc pushOwner*(owner: PSym) +proc popOwner*() # implementation var gOwners*: seq[PSym] = @[] @@ -128,13 +128,13 @@ proc getCurrOwner(): PSym = # BUGFIX: global array is needed! result = gOwners[high(gOwners)] -proc PushOwner(owner: PSym) = +proc pushOwner(owner: PSym) = add(gOwners, owner) -proc PopOwner() = +proc popOwner() = var length = len(gOwners) if length > 0: setlen(gOwners, length - 1) - else: InternalError("popOwner") + else: internalError("popOwner") proc lastOptionEntry(c: PContext): POptionEntry = result = POptionEntry(c.optionStack.tail) @@ -249,7 +249,7 @@ proc markIndirect*(c: PContext, s: PSym) {.inline.} = # XXX add to 'c' for global analysis proc illFormedAst*(n: PNode) = - GlobalError(n.info, errIllFormedAstX, renderTree(n, {renderNoComments})) + globalError(n.info, errIllFormedAstX, renderTree(n, {renderNoComments})) proc checkSonsLen*(n: PNode, length: int) = if sonsLen(n) != length: illFormedAst(n) diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index 797d8895e..47d783818 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -15,9 +15,9 @@ # generation (needed for recursive types) # 2) DestructorIsTrivial: completed the analysis before and determined # that the type has a trivial destructor -var AnalyzingDestructor, DestructorIsTrivial: PSym -new(AnalyzingDestructor) -new(DestructorIsTrivial) +var analyzingDestructor, destructorIsTrivial: PSym +new(analyzingDestructor) +new(destructorIsTrivial) var destructorName = getIdent"destroy_" diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index c45b83095..5f41a8dd9 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1176,7 +1176,7 @@ proc semAsgn(c: PContext, n: PNode): PNode = asgnToResultVar(c, n, n.sons[0], n.sons[1]) result = n -proc SemReturn(c: PContext, n: PNode): PNode = +proc semReturn(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1) if c.p.owner.kind in {skConverter, skMethod, skProc, skMacro} or @@ -1223,7 +1223,7 @@ proc semProcBody(c: PContext, n: PNode): PNode = discardCheck(c, result) closeScope(c) -proc SemYieldVarResult(c: PContext, n: PNode, restype: PType) = +proc semYieldVarResult(c: PContext, n: PNode, restype: PType) = var t = skipTypes(restype, {tyGenericInst}) case t.kind of tyVar: @@ -1242,7 +1242,7 @@ proc SemYieldVarResult(c: PContext, n: PNode, restype: PType) = localError(n.sons[0].info, errXExpected, "tuple constructor") else: nil -proc SemYield(c: PContext, n: PNode): PNode = +proc semYield(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1) if c.p.owner == nil or c.p.owner.kind != skIterator: @@ -1267,30 +1267,30 @@ proc lookUpForDefined(c: PContext, i: PIdent, onlyCurrentScope: bool): PSym = else: result = searchInScopes(c, i) # no need for stub loading -proc LookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym = +proc lookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym = case n.kind of nkIdent: - result = LookupForDefined(c, n.ident, onlyCurrentScope) + result = lookupForDefined(c, n.ident, onlyCurrentScope) of nkDotExpr: result = nil if onlyCurrentScope: return checkSonsLen(n, 2) - var m = LookupForDefined(c, n.sons[0], onlyCurrentScope) + var m = lookupForDefined(c, n.sons[0], onlyCurrentScope) if (m != nil) and (m.kind == skModule): if (n.sons[1].kind == nkIdent): var ident = n.sons[1].ident if m == c.module: - result = StrTableGet(c.topLevelScope.symbols, ident) + result = strTableGet(c.topLevelScope.symbols, ident) else: - result = StrTableGet(m.tab, ident) + result = strTableGet(m.tab, ident) else: - LocalError(n.sons[1].info, errIdentifierExpected, "") + localError(n.sons[1].info, errIdentifierExpected, "") of nkAccQuoted: result = lookupForDefined(c, considerAcc(n), onlyCurrentScope) of nkSym: result = n.sym else: - LocalError(n.info, errIdentifierExpected, renderTree(n)) + localError(n.info, errIdentifierExpected, renderTree(n)) result = nil proc semDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PNode = diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index d626d2eb2..760fd303f 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -73,7 +73,7 @@ proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym): PNode = result = n else: result = newSymNode(s, n.info) -proc Lookup(c: PContext, n: PNode, flags: TSemGenericFlags, +proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var TIntSet): PNode = result = n let ident = considerAcc(n) diff --git a/compiler/seminst.nim b/compiler/seminst.nim index d7d64fd54..5a4b83240 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -50,7 +50,7 @@ proc sameInstantiation(a, b: TInstantiation): bool = flags = {TypeDescExactMatch}): return result = true -proc GenericCacheGet(genericSym: Psym, entry: TInstantiation): PSym = +proc genericCacheGet(genericSym: Psym, entry: TInstantiation): PSym = if genericSym.procInstCache != nil: for inst in genericSym.procInstCache: if sameInstantiation(entry, inst[]): @@ -257,7 +257,7 @@ proc fixupProcType(c: PContext, genericType: PType, result.sons[i] = fixupProcType(c, result.sons[i], inst) result = instGenericContainer(c, getInfoContext(-1), result) - else: nil + else: discard proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, info: TLineInfo): PSym = @@ -290,7 +290,7 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, instantiateGenericParamList(c, n.sons[genericParamsPos], pt, entry[]) result.typ = fixupProcType(c, fn.typ, entry[]) n.sons[genericParamsPos] = ast.emptyNode - var oldPrc = GenericCacheGet(fn, entry[]) + var oldPrc = genericCacheGet(fn, entry[]) if oldPrc == nil: fn.procInstCache.safeAdd(entry) c.generics.add(makeInstPair(fn, entry)) @@ -311,5 +311,3 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, c.friendModule = oldFriend dec(c.InstCounter) if result.kind == skMethod: finishMethod(c, result) - - diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 6f0cc3c8b..832e4e962 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -10,7 +10,7 @@ ## this module does the semantic checking of statements # included from sem.nim -var EnforceVoidContext = PType(kind: tyStmt) +var enforceVoidContext = PType(kind: tyStmt) proc semCommand(c: PContext, n: PNode): PNode = result = semExprNoType(c, n) @@ -117,7 +117,7 @@ const nkElse, nkStmtListExpr, nkTryStmt, nkFinally, nkExceptBranch, nkElifBranch, nkElifExpr, nkElseExpr, nkBlockStmt, nkBlockExpr} -proc ImplicitlyDiscardable(n: PNode): bool = +proc implicitlyDiscardable(n: PNode): bool = var n = n while n.kind in skipForDiscardable: n = n.lastSon result = isCallExpr(n) and n.sons[0].kind == nkSym and @@ -197,7 +197,7 @@ proc semCase(c: PContext, n: PNode): PNode = of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32: chckCovered = true of tyFloat..tyFloat128, tyString, tyError: - nil + discard else: LocalError(n.info, errSelectorMustBeOfCertainTypes) return @@ -501,7 +501,7 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = father.add(SemStmt(c.c, body)) dec c.c.InUnrolledContext closeScope(c.c) - of nkNilLit: nil + of nkNilLit: discard of nkRecCase: let L = forLoop.len let call = forLoop.sons[L-2] @@ -793,7 +793,7 @@ proc typeSectionFinalPass(c: PContext, n: PNode) = st.sons[0].sym = newSym(skType, getIdent(s.name.s & ":ObjectType"), getCurrOwner(), s.info) -proc SemTypeSection(c: PContext, n: PNode): PNode = +proc semTypeSection(c: PContext, n: PNode): PNode = typeSectionLeftSidePass(c, n) typeSectionRightSidePass(c, n) typeSectionFinalPass(c, n) diff --git a/compiler/semtempl.nim b/compiler/semtempl.nim index 0c7c2eff4..4f94cd1f6 100644 --- a/compiler/semtempl.nim +++ b/compiler/semtempl.nim @@ -380,7 +380,7 @@ proc semTemplBodyDirty(c: var TemplCtx, n: PNode): PNode = of nkBindStmt: result = semBindStmt(c.c, n, c.toBind) of nkEmpty, nkSym..nkNilLit: - nil + discard else: # dotExpr is ambiguous: note that we explicitely allow 'x.TemplateParam', # so we use the generic code for nkDotExpr too @@ -503,7 +503,7 @@ proc semPatternBody(c: var TemplCtx, n: PNode): PNode = elif templToExpand(s): result = semPatternBody(c, semTemplateExpr(c.c, n, s, false)) else: - nil + discard # we keep the ident unbound for matching instantiated symbols and # more flexibility diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 6c9c476d9..1f995f5e7 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -356,7 +356,7 @@ proc semBranchRange(c: PContext, t, a, b: PNode, covered: var biggestInt): PNode if emptyRange(ac, bc): LocalError(b.info, errRangeIsEmpty) else: covered = covered + getOrdValue(bc) - getOrdValue(ac) + 1 -proc SemCaseBranchRange(c: PContext, t, b: PNode, +proc semCaseBranchRange(c: PContext, t, b: PNode, covered: var biggestInt): PNode = checkSonsLen(b, 3) result = semBranchRange(c, t, b.sons[1], b.sons[2], covered) diff --git a/compiler/semtypinst.nim b/compiler/semtypinst.nim index 61c31a4fe..c872c39f3 100644 --- a/compiler/semtypinst.nim +++ b/compiler/semtypinst.nim @@ -68,9 +68,9 @@ type symMap*: TIdTable # map PSym to PSym info*: TLineInfo -proc ReplaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType -proc ReplaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym -proc ReplaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode +proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType +proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym +proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode = result = copyNode(n) @@ -81,13 +81,13 @@ proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode = if i == 0: result.add(n[i]) else: result.add(prepareNode(cl, n[i])) -proc ReplaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = +proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = if n == nil: return result = copyNode(n) result.typ = ReplaceTypeVarsT(cl, n.typ) case n.kind of nkNone..pred(nkSym), succ(nkSym)..nkNilLit: - nil + discard of nkSym: result.sym = ReplaceTypeVarsS(cl, n.sym) of nkRecWhen: @@ -118,7 +118,7 @@ proc ReplaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = for i in countup(0, length - 1): result.sons[i] = ReplaceTypeVarsN(cl, n.sons[i]) -proc ReplaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym = +proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym = if s == nil: return nil result = PSym(idTableGet(cl.symMap, s)) if result == nil: @@ -192,11 +192,11 @@ proc handleGenericInvokation(cl: var TReplTypeVars, t: PType): PType = rawAddSon(result, newbody) checkPartialConstructedType(cl.info, newbody) -proc ReplaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = +proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = result = t if t == nil: return case t.kind - of tyTypeClass: nil + of tyTypeClass: discard of tyGenericParam: result = lookupTypeVar(cl, t) if result.kind == tyGenericInvokation: @@ -235,11 +235,10 @@ proc ReplaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = proc generateTypeInstance*(p: PContext, pt: TIdTable, arg: PNode, t: PType): PType = var cl: TReplTypeVars - InitIdTable(cl.symMap) + initIdTable(cl.symMap) copyIdTable(cl.typeMap, pt) cl.info = arg.info cl.c = p pushInfoContext(arg.info) - result = ReplaceTypeVarsT(cl, t) + result = replaceTypeVarsT(cl, t) popInfoContext() - diff --git a/compiler/service.nim b/compiler/service.nim index 1de83af7c..1cae72f2a 100644 --- a/compiler/service.nim +++ b/compiler/service.nim @@ -29,7 +29,7 @@ var # the arguments to be passed to the program that # should be run -proc ProcessCmdLine*(pass: TCmdLinePass, cmd: string) = +proc processCmdLine*(pass: TCmdLinePass, cmd: string) = var p = parseopt.initOptParser(cmd) var argsCount = 0 while true: diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index cacf4782e..7ccb1bdc1 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -887,7 +887,7 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate, result = arg put(m.bindings, f, a) -proc ParamTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, +proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, argSemantized, argOrig: PNode): PNode = var r: TTypeRelation @@ -1003,7 +1003,7 @@ proc ParamTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, else: result = userConvMatch(c, m, base(f), a, arg) -proc ParamTypesMatch*(c: PContext, m: var TCandidate, f, a: PType, +proc paramTypesMatch*(c: PContext, m: var TCandidate, f, a: PType, arg, argOrig: PNode): PNode = if arg == nil or arg.kind notin nkSymChoices: result = ParamTypesMatchAux(c, m, f, a, arg, argOrig) @@ -1184,14 +1184,14 @@ proc matchesAux(c: PContext, n, nOrig: PNode, InternalError(n.sons[a].info, "matches") return formal = m.callee.n.sons[f].sym - if ContainsOrIncl(marker, formal.position): + if containsOrIncl(marker, formal.position): # already in namedParams: - LocalError(n.sons[a].info, errCannotBindXTwice, formal.name.s) + localError(n.sons[a].info, errCannotBindXTwice, formal.name.s) m.state = csNoMatch return m.baseTypeMatch = false n.sons[a] = prepareOperand(c, formal.typ, n.sons[a]) - var arg = ParamTypesMatch(c, m, formal.typ, n.sons[a].typ, + var arg = paramTypesMatch(c, m, formal.typ, n.sons[a].typ, n.sons[a], nOrig.sons[a]) if arg == nil: m.state = csNoMatch @@ -1228,7 +1228,7 @@ proc matches*(c: PContext, n, nOrig: PNode, m: var TCandidate) = var f = 1 while f < sonsLen(m.callee.n): var formal = m.callee.n.sons[f].sym - if not ContainsOrIncl(marker, formal.position): + if not containsOrIncl(marker, formal.position): if formal.ast == nil: if formal.typ.kind == tyVarargs: var container = newNodeIT(nkBracket, n.info, arrayConstr(c, n.info)) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 76a6c21d9..4f3172814 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -28,7 +28,7 @@ proc origModuleName(m: PSym): string = else: m.name.s -proc SymToStr(s: PSym, isLocal: bool, section: string, li: TLineInfo): string = +proc symToStr(s: PSym, isLocal: bool, section: string, li: TLineInfo): string = result = section result.add(sep) result.add($s.kind) @@ -55,7 +55,7 @@ proc SymToStr(s: PSym, isLocal: bool, section: string, li: TLineInfo): string = when not defined(noDocgen): result.add(s.extractDocComment.escape) -proc SymToStr(s: PSym, isLocal: bool, section: string): string = +proc symToStr(s: PSym, isLocal: bool, section: string): string = result = SymToStr(s, isLocal, section, s.info) proc filterSym(s: PSym): bool {.inline.} = diff --git a/compiler/syntaxes.nim b/compiler/syntaxes.nim index 3965cb3fe..6970f0c44 100644 --- a/compiler/syntaxes.nim +++ b/compiler/syntaxes.nim @@ -40,7 +40,7 @@ proc parseTopLevelStmt*(p: var TParsers): PNode # implementation -proc ParseFile(fileIdx: int32): PNode = +proc parseFile(fileIdx: int32): PNode = var p: TParsers f: tfile @@ -74,7 +74,7 @@ proc parseTopLevelStmt(p: var TParsers): PNode = result = ast.emptyNode #skinEndX: result := pendx.parseTopLevelStmt(p.parser); -proc UTF8_BOM(s: string): int = +proc utf8Bom(s: string): int = if (s[0] == '\xEF') and (s[1] == '\xBB') and (s[2] == '\xBF'): result = 3 else: @@ -92,7 +92,7 @@ proc parsePipe(filename: string, inputStream: PLLStream): PNode = if s != nil: var line = newStringOfCap(80) discard LLStreamReadLine(s, line) - var i = UTF8_Bom(line) + var i = utf8Bom(line) if containsShebang(line, i): discard LLStreamReadLine(s, line) i = 0 @@ -100,20 +100,20 @@ proc parsePipe(filename: string, inputStream: PLLStream): PNode = inc(i, 2) while line[i] in WhiteSpace: inc(i) var q: TParser - OpenParser(q, filename, LLStreamOpen(substr(line, i))) + openParser(q, filename, LLStreamOpen(substr(line, i))) result = parser.parseAll(q) - CloseParser(q) + closeParser(q) LLStreamClose(s) proc getFilter(ident: PIdent): TFilterKind = for i in countup(low(TFilterKind), high(TFilterKind)): - if IdentEq(ident, filterNames[i]): + if identEq(ident, filterNames[i]): return i result = filtNone proc getParser(ident: PIdent): TParserKind = for i in countup(low(TParserKind), high(TParserKind)): - if IdentEq(ident, parserNames[i]): + if identEq(ident, parserNames[i]): return i rawMessage(errInvalidDirectiveX, ident.s) @@ -142,23 +142,23 @@ proc applyFilter(p: var TParsers, n: PNode, filename: string, if f != filtNone: if gVerbosity >= 2: rawMessage(hintCodeBegin, []) - MsgWriteln(result.s) + msgWriteln(result.s) rawMessage(hintCodeEnd, []) proc evalPipe(p: var TParsers, n: PNode, filename: string, start: PLLStream): PLLStream = result = start if n.kind == nkEmpty: return - if (n.kind == nkInfix) and (n.sons[0].kind == nkIdent) and - IdentEq(n.sons[0].ident, "|"): - for i in countup(1, 2): - if n.sons[i].kind == nkInfix: + if n.kind == nkInfix and n.sons[0].kind == nkIdent and + identEq(n.sons[0].ident, "|"): + for i in countup(1, 2): + if n.sons[i].kind == nkInfix: result = evalPipe(p, n.sons[i], filename, result) - else: + else: result = applyFilter(p, n.sons[i], filename, result) - elif n.kind == nkStmtList: + elif n.kind == nkStmtList: result = evalPipe(p, n.sons[0], filename, result) - else: + else: result = applyFilter(p, n, filename, result) proc openParsers(p: var TParsers, fileIdx: int32, inputstream: PLLStream) = diff --git a/compiler/transf.nim b/compiler/transf.nim index 77642a3b8..d6f54eddb 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -719,7 +719,7 @@ proc processTransf(c: PTransf, n: PNode, owner: PSym): PNode = # Note: For interactive mode we cannot call 'passes.skipCodegen' and skip # this step! We have to rely that the semantic pass transforms too errornous # nodes into an empty node. - if passes.skipCodegen(n) or c.fromCache or nfTransf in n.flags: return n + if c.fromCache or nfTransf in n.flags: return n pushTransCon(c, newTransCon(owner)) result = PNode(transform(c, n)) popTransCon(c) diff --git a/compiler/trees.nim b/compiler/trees.nim index ab5c97a19..ea2f8fbf1 100644 --- a/compiler/trees.nim +++ b/compiler/trees.nim @@ -36,7 +36,7 @@ proc cyclicTree*(n: PNode): bool = var s = newNodeI(nkEmpty, n.info) result = cyclicTreeAux(n, s) -proc ExprStructuralEquivalent*(a, b: PNode): bool = +proc exprStructuralEquivalent*(a, b: PNode): bool = result = false if a == b: result = true @@ -53,17 +53,17 @@ proc ExprStructuralEquivalent*(a, b: PNode): bool = else: if sonsLen(a) == sonsLen(b): for i in countup(0, sonsLen(a) - 1): - if not ExprStructuralEquivalent(a.sons[i], b.sons[i]): return + if not exprStructuralEquivalent(a.sons[i], b.sons[i]): return result = true -proc sameTree*(a, b: PNode): bool = +proc sameTree*(a, b: PNode): bool = result = false - if a == b: + if a == b: result = true - elif (a != nil) and (b != nil) and (a.kind == b.kind): - if a.flags != b.flags: return - if a.info.line != b.info.line: return - if a.info.col != b.info.col: + elif a != nil and b != nil and a.kind == b.kind: + if a.flags != b.flags: return + if a.info.line != b.info.line: return + if a.info.col != b.info.col: return #if a.info.fileIndex <> b.info.fileIndex then exit; case a.kind of nkSym: @@ -74,7 +74,7 @@ proc sameTree*(a, b: PNode): bool = of nkFloatLit..nkFloat64Lit: result = a.floatVal == b.floatVal of nkStrLit..nkTripleStrLit: result = a.strVal == b.strVal of nkEmpty, nkNilLit, nkType: result = true - else: + else: if sonsLen(a) == sonsLen(b): for i in countup(0, sonsLen(a) - 1): if not sameTree(a.sons[i], b.sons[i]): return @@ -84,13 +84,13 @@ proc getProcSym*(call: PNode): PSym = result = call.sons[0].sym proc getOpSym*(op: PNode): PSym = - if not (op.kind in {nkCall, nkHiddenCallConv, nkCommand, nkCallStrLit}): + if op.kind notin {nkCall, nkHiddenCallConv, nkCommand, nkCallStrLit}: result = nil - else: - if (sonsLen(op) <= 0): InternalError(op.info, "getOpSym") + else: + if sonsLen(op) <= 0: internalError(op.info, "getOpSym") elif op.sons[0].Kind == nkSym: result = op.sons[0].sym else: result = nil - + proc getMagic*(op: PNode): TMagic = case op.kind of nkCallKinds: @@ -99,7 +99,7 @@ proc getMagic*(op: PNode): TMagic = else: result = mNone else: result = mNone -proc TreeToSym*(t: PNode): PSym = +proc treeToSym*(t: PNode): PSym = result = t.sym proc isConstExpr*(n: PNode): bool = @@ -118,7 +118,7 @@ proc isDeepConstExpr*(n: PNode): bool = for i in 0 .. = 0: result = t.data[index].val else: result = low(int) -proc NodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, +proc nodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, val: int) = var h: THash = k and high(data) while data[h].key != nil: h = nextTry(h, high(data)) @@ -74,7 +74,7 @@ proc NodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, data[h].key = key data[h].val = val -proc NodeTablePut*(t: var TNodeTable, key: PNode, val: int) = +proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = var n: TNodePairSeq var k: THash = hashTree(key) var index = NodeTableRawGet(t, k, key) @@ -86,15 +86,15 @@ proc NodeTablePut*(t: var TNodeTable, key: PNode, val: int) = newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): 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) swap(t.data, n) - NodeTableRawInsert(t.data, k, key, val) + nodeTableRawInsert(t.data, k, key, val) inc(t.counter) -proc NodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = +proc nodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = var n: TNodePairSeq var k: THash = hashTree(key) - var index = NodeTableRawGet(t, k, key) + var index = nodeTableRawGet(t, k, key) if index >= 0: assert(t.data[index].key != nil) result = t.data[index].val @@ -103,8 +103,8 @@ proc NodeTableTestOrSet*(t: var TNodeTable, key: PNode, val: int): int = newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): 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) swap(t.data, n) - NodeTableRawInsert(t.data, k, key, val) + nodeTableRawInsert(t.data, k, key, val) result = val inc(t.counter) diff --git a/compiler/types.nim b/compiler/types.nim index 7e07a0667..be948246c 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -19,7 +19,7 @@ type TPreferedDesc* = enum preferName, preferDesc, preferExported -proc TypeToString*(typ: PType, prefer: TPreferedDesc = preferName): string +proc typeToString*(typ: PType, prefer: TPreferedDesc = preferName): string proc getProcHeader*(sym: PSym): string proc base*(t: PType): PType # ------------------- type iterator: ---------------------------------------- @@ -28,7 +28,7 @@ type TTypeMutator* = proc (t: PType, closure: PObject): PType {.nimcall.} # copy t and mutate it TTypePredicate* = proc (t: PType): bool {.nimcall.} -proc IterOverType*(t: PType, iter: TTypeIter, closure: PObject): bool +proc iterOverType*(t: PType, iter: TTypeIter, closure: PObject): bool # Returns result of `iter`. proc mutateType*(t: PType, iter: TTypeMutator, closure: PObject): PType # Returns result of `iter`. @@ -74,7 +74,7 @@ proc getOrdValue*(n: PNode): biggestInt proc computeSize*(typ: PType): biggestInt proc getSize*(typ: PType): biggestInt proc isPureObject*(typ: PType): bool -proc InvalidGenericInst*(f: PType): bool +proc invalidGenericInst*(f: PType): bool # for debugging type TTypeFieldResult* = enum @@ -89,8 +89,8 @@ proc analyseObjectWithTypeField*(t: PType): TTypeFieldResult proc typeAllowed*(t: PType, kind: TSymKind): bool # implementation -proc InvalidGenericInst(f: PType): bool = - result = (f.kind == tyGenericInst) and (lastSon(f) == nil) +proc invalidGenericInst(f: PType): bool = + result = f.kind == tyGenericInst and lastSon(f) == nil proc isPureObject(typ: PType): bool = var t = typ @@ -132,7 +132,7 @@ proc getProcHeader(sym: PSym): string = add(result, typeToString(p.sym.typ)) if i != sonsLen(n)-1: add(result, ", ") else: - InternalError("getProcHeader") + internalError("getProcHeader") add(result, ')') if n.sons[0].typ != nil: result.add(": " & typeToString(n.sons[0].typ)) @@ -194,7 +194,7 @@ proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, if result: return if t.n != nil: result = iterOverNode(marker, t.n, iter, closure) -proc IterOverType(t: PType, iter: TTypeIter, closure: PObject): bool = +proc iterOverType(t: PType, iter: TTypeIter, closure: PObject): bool = var marker = InitIntSet() result = iterOverTypeAux(marker, t, iter, closure) @@ -242,7 +242,7 @@ proc searchTypeForAux(t: PType, predicate: TTypePredicate, result = searchTypeForAux(t.sons[i], predicate, marker) if result: return else: - nil + discard proc searchTypeFor(t: PType, predicate: TTypePredicate): bool = var marker = InitIntSet() @@ -284,7 +284,7 @@ proc analyseObjectWithTypeFieldAux(t: PType, if res != frNone: return frEmbedded else: - nil + discard proc analyseObjectWithTypeField(t: PType): TTypeFieldResult = var marker = InitIntSet() @@ -322,7 +322,7 @@ proc canFormAcycleNode(marker: var TIntSet, n: PNode, startId: int): bool = if not result: case n.kind of nkNone..nkNilLit: - nil + discard else: for i in countup(0, sonsLen(n) - 1): result = canFormAcycleNode(marker, n.sons[i], startId) @@ -367,6 +367,7 @@ proc mutateNode(marker: var TIntSet, n: PNode, iter: TTypeMutator, case n.kind of nkNone..nkNilLit: # a leaf + discard else: for i in countup(0, sonsLen(n) - 1): addSon(result, mutateNode(marker, n.sons[i], iter, closure)) @@ -422,7 +423,7 @@ proc constraintsToStr(t: PType): string = if i > 0: result.add(sep) result.add(t.sons[i].consToStr) -proc TypeToString(typ: PType, prefer: TPreferedDesc = preferName): string = +proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string = var t = typ result = "" if t == nil: return @@ -553,7 +554,7 @@ proc firstOrd(t: PType): biggestInt = of tyGenericInst, tyDistinct, tyConst, tyMutable, tyTypeDesc: result = firstOrd(lastSon(t)) else: - InternalError("invalid kind for first(" & $t.kind & ')') + internalError("invalid kind for first(" & $t.kind & ')') result = 0 proc lastOrd(t: PType): biggestInt = @@ -587,7 +588,7 @@ proc lastOrd(t: PType): biggestInt = result = lastOrd(lastSon(t)) of tyProxy: result = 0 else: - InternalError("invalid kind for last(" & $t.kind & ')') + internalError("invalid kind for last(" & $t.kind & ')') result = 0 proc lengthOrd(t: PType): biggestInt = @@ -621,7 +622,7 @@ type proc initSameTypeClosure: TSameTypeClosure = # we do the initialization lazily for performance (avoids memory allocations) - nil + discard proc containsOrIncl(c: var TSameTypeClosure, a, b: PType): bool = result = not IsNil(c.s) and c.s.contains((a.id, b.id)) @@ -629,15 +630,15 @@ proc containsOrIncl(c: var TSameTypeClosure, a, b: PType): bool = if IsNil(c.s): c.s = @[] c.s.add((a.id, b.id)) -proc SameTypeAux(x, y: PType, c: var TSameTypeClosure): bool -proc SameTypeOrNilAux(a, b: PType, c: var TSameTypeClosure): bool = +proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool +proc sameTypeOrNilAux(a, b: PType, c: var TSameTypeClosure): bool = if a == b: result = true else: if a == nil or b == nil: result = false else: result = SameTypeAux(a, b, c) -proc SameTypeOrNil*(a, b: PType, flags: TTypeCmpFlags = {}): bool = +proc sameTypeOrNil*(a, b: PType, flags: TTypeCmpFlags = {}): bool = if a == b: result = true else: @@ -676,7 +677,7 @@ proc equalParams(a, b: PNode): TParamsEquality = of paramsNotEqual: return paramsNotEqual of paramsEqual: - nil + discard of paramsIncompatible: result = paramsIncompatible if (m.name.id != n.name.id): @@ -730,7 +731,7 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = else: result = false -template IfFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = +template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = if tfFromGeneric notin a.flags + b.flags: # fast case: id comparison suffices: result = a.id == b.id @@ -751,7 +752,7 @@ template IfFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = proc sameObjectTypes*(a, b: PType): bool = # specialized for efficiency (sigmatch uses it) - IfFastObjectTypeCheckFailed(a, b): + ifFastObjectTypeCheckFailed(a, b): var c = initSameTypeClosure() result = sameTypeAux(a, b, c) @@ -761,7 +762,7 @@ proc sameDistinctTypes*(a, b: PType): bool {.inline.} = proc sameEnumTypes*(a, b: PType): bool {.inline.} = result = a.id == b.id -proc SameObjectTree(a, b: PNode, c: var TSameTypeClosure): bool = +proc sameObjectTree(a, b: PNode, c: var TSameTypeClosure): bool = if a == b: result = true elif (a != nil) and (b != nil) and (a.kind == b.kind): @@ -778,26 +779,26 @@ proc SameObjectTree(a, b: PNode, c: var TSameTypeClosure): bool = else: if sonsLen(a) == sonsLen(b): for i in countup(0, sonsLen(a) - 1): - if not SameObjectTree(a.sons[i], b.sons[i], c): return + if not sameObjectTree(a.sons[i], b.sons[i], c): return result = true proc sameObjectStructures(a, b: PType, c: var TSameTypeClosure): bool = # check base types: if sonsLen(a) != sonsLen(b): return for i in countup(0, sonsLen(a) - 1): - if not SameTypeOrNilAux(a.sons[i], b.sons[i], c): return - if not SameObjectTree(a.n, b.n, c): return + if not sameTypeOrNilAux(a.sons[i], b.sons[i], c): return + if not sameObjectTree(a.n, b.n, c): return result = true proc sameChildrenAux(a, b: PType, c: var TSameTypeClosure): bool = if sonsLen(a) != sonsLen(b): return false result = true for i in countup(0, sonsLen(a) - 1): - result = SameTypeOrNilAux(a.sons[i], b.sons[i], c) + result = sameTypeOrNilAux(a.sons[i], b.sons[i], c) if not result: return -proc SameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = - template CycleCheck() = +proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = + template cycleCheck() = # believe it or not, the direct check for ``containsOrIncl(c, a, b)`` # increases bootstrapping time from 2.4s to 3.3s on my laptop! So we cheat # again: Since the recursion check is only to not get caught in an endless @@ -831,16 +832,16 @@ proc SameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = tyInt..tyBigNum, tyStmt: result = sameFlags(a, b) of tyExpr: - result = ExprStructuralEquivalent(a.n, b.n) and sameFlags(a, b) + result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b) of tyObject: - IfFastObjectTypeCheckFailed(a, b): + ifFastObjectTypeCheckFailed(a, b): CycleCheck() result = sameObjectStructures(a, b, c) and sameFlags(a, b) of tyDistinct: - CycleCheck() + cycleCheck() if c.cmp == dcEq: if sameFlags(a, b): - IfFastObjectTypeCheckFailed(a, b): + ifFastObjectTypeCheckFailed(a, b): result = sameTypeAux(a.sons[0], b.sons[0], c) else: result = sameTypeAux(a.sons[0], b.sons[0], c) and sameFlags(a, b) @@ -848,14 +849,14 @@ proc SameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = # XXX generic enums do not make much sense, but require structural checking result = a.id == b.id and sameFlags(a, b) of tyTuple: - CycleCheck() + cycleCheck() result = sameTuple(a, b, c) and sameFlags(a, b) of tyGenericInst: result = sameTypeAux(lastSon(a), lastSon(b), c) of tyTypeDesc: if c.cmp == dcEqIgnoreDistinct: result = false elif TypeDescExactMatch in c.flags: - CycleCheck() + cycleCheck() result = sameChildrenAux(x, y, c) and sameFlags(a, b) else: result = sameFlags(a, b) @@ -863,15 +864,15 @@ proc SameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = tyOpenArray, tySet, tyRef, tyPtr, tyVar, tyArrayConstr, tyArray, tyProc, tyConst, tyMutable, tyVarargs, tyIter, tyOrdinal, tyTypeClasses: - CycleCheck() + cycleCheck() result = sameChildrenAux(a, b, c) and sameFlags(a, b) - if result and (a.kind == tyProc): + if result and a.kind == tyProc: result = a.callConv == b.callConv of tyRange: - CycleCheck() - result = SameTypeOrNilAux(a.sons[0], b.sons[0], c) and - SameValue(a.n.sons[0], b.n.sons[0]) and - SameValue(a.n.sons[1], b.n.sons[1]) + cycleCheck() + result = sameTypeOrNilAux(a.sons[0], b.sons[0], c) and + sameValue(a.n.sons[0], b.n.sons[0]) and + sameValue(a.n.sons[1], b.n.sons[1]) of tyNone: result = false proc sameType*(x, y: PType): bool = @@ -954,7 +955,7 @@ proc typeAllowedNode(marker: var TIntSet, n: PNode, kind: TSymKind, if result: case n.kind of nkNone..nkNilLit: - nil + discard else: for i in countup(0, sonsLen(n) - 1): result = typeAllowedNode(marker, n.sons[i], kind, flags) diff --git a/compiler/vm.nim b/compiler/vm.nim index 709baf7b2..a89ad74bd 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -109,7 +109,7 @@ template decodeBx(k: expr) {.immediate, dirty.} = let rbx = instr.regBx - wordExcess ensureKind(k) -template move(a, b: expr) = system.shallowCopy(a, b) +template move(a, b: expr) {.immediate, dirty.} = system.shallowCopy(a, b) # XXX fix minor 'shallowCopy' overloading bug in compiler proc moveConst(x, y: PNode) = diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index ab120f008..d9cbb1514 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1295,7 +1295,7 @@ proc gen(c: PCtx; n: PNode; dest: var TDest) = else: dest = tmp0 of nkEmpty, nkCommentStmt, nkTypeSection, nkConstSection, nkPragma, - nkTemplateDef, nkIncludeStmt, nkImportStmt: + nkTemplateDef, nkIncludeStmt, nkImportStmt, nkFromStmt: unused(n, dest) of nkStringToCString, nkCStringToString: gen(c, n.sons[0], dest) diff --git a/doc/manual.txt b/doc/manual.txt index fd3db1b0d..5024fffec 100644 --- a/doc/manual.txt +++ b/doc/manual.txt @@ -4574,6 +4574,8 @@ the support of destructors. delegator pragma ---------------- +**Note**: The design of the delegator feature is subject to change. + The delegator pragma can be used to intercept and rewrite proc call and field access attempts referring to previously undeclared symbol names. It can be used to provide a fluent interface to objects lying outside the static confines of diff --git a/lib/impure/rdstdin.nim b/lib/impure/rdstdin.nim index cf076e929..c32a59b24 100644 --- a/lib/impure/rdstdin.nim +++ b/lib/impure/rdstdin.nim @@ -14,13 +14,13 @@ ## wanted functionality. when defined(Windows): - proc ReadLineFromStdin*(prompt: string): TaintedString {. + proc readLineFromStdin*(prompt: string): TaintedString {. tags: [FReadIO, FWriteIO].} = ## Reads a line from stdin. stdout.write(prompt) result = readLine(stdin) - proc ReadLineFromStdin*(prompt: string, line: var TaintedString): bool {. + proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {. tags: [FReadIO, FWriteIO].} = ## Reads a `line` from stdin. `line` must not be ## ``nil``! May throw an IO exception. @@ -34,7 +34,7 @@ when defined(Windows): else: import readline, history - proc ReadLineFromStdin*(prompt: string): TaintedString {. + proc readLineFromStdin*(prompt: string): TaintedString {. tags: [FReadIO, FWriteIO].} = var buffer = readline.readLine(prompt) if isNil(buffer): quit(0) @@ -43,7 +43,7 @@ else: add_history(buffer) readline.free(buffer) - proc ReadLineFromStdin*(prompt: string, line: var TaintedString): bool {. + proc readLineFromStdin*(prompt: string, line: var TaintedString): bool {. tags: [FReadIO, FWriteIO].} = var buffer = readline.readLine(prompt) if isNil(buffer): quit(0) diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim index 3d191dacb..c2ff53b58 100644 --- a/lib/packages/docutils/rstast.nim +++ b/lib/packages/docutils/rstast.nim @@ -120,11 +120,11 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = let oldLen = result.len renderRstSons(d, n, result) - let HeadlineLen = result.len - oldLen + let headlineLen = result.len - oldLen result.add("\n") result.add(ind) - result.add repeatChar(HeadlineLen, lvlToChar[n.level]) + result.add repeatChar(headlineLen, lvlToChar[n.level]) of rnOverline: result.add("\n") result.add(ind) diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index 09c6ba8b8..157e04d5b 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -263,14 +263,14 @@ proc `<-`(a: var TIndexEntry, b: TIndexEntry) = proc sortIndex(a: var openArray[TIndexEntry]) = # we use shellsort here; fast and simple - let N = len(a) + let n = len(a) var h = 1 while true: h = 3 * h + 1 - if h > N: break + if h > n: break while true: h = h div 3 - for i in countup(h, N - 1): + for i in countup(h, n - 1): var v: TIndexEntry v <- a[i] var j = i diff --git a/lib/pure/collections/intsets.nim b/lib/pure/collections/intsets.nim index 2a8d7eec2..367caf2e7 100644 --- a/lib/pure/collections/intsets.nim +++ b/lib/pure/collections/intsets.nim @@ -50,7 +50,7 @@ proc mustRehash(length, counter: int): bool {.inline.} = proc nextTry(h, maxHash: THash): THash {.inline.} = result = ((5 * h) + 1) and maxHash -proc IntSetGet(t: TIntSet, key: int): PTrunk = +proc intSetGet(t: TIntSet, key: int): PTrunk = var h = key and t.max while t.data[h] != nil: if t.data[h].key == key: @@ -58,7 +58,7 @@ proc IntSetGet(t: TIntSet, key: int): PTrunk = h = nextTry(h, t.max) result = nil -proc IntSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) = +proc intSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) = var h = desc.key and t.max while data[h] != nil: assert(data[h] != desc) @@ -66,7 +66,7 @@ proc IntSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) = assert(data[h] == nil) data[h] = desc -proc IntSetEnlarge(t: var TIntSet) = +proc intSetEnlarge(t: var TIntSet) = var n: TTrunkSeq var oldMax = t.max t.max = ((t.max + 1) * 2) - 1 @@ -75,7 +75,7 @@ proc IntSetEnlarge(t: var TIntSet) = if t.data[i] != nil: IntSetRawInsert(t, n, t.data[i]) swap(t.data, n) -proc IntSetPut(t: var TIntSet, key: int): PTrunk = +proc intSetPut(t: var TIntSet, key: int): PTrunk = var h = key and t.max while t.data[h] != nil: if t.data[h].key == key: diff --git a/lib/pure/collections/lists.nim b/lib/pure/collections/lists.nim index ad8eca6a9..b8f8d20b5 100644 --- a/lib/pure/collections/lists.nim +++ b/lib/pure/collections/lists.nim @@ -41,19 +41,19 @@ type proc initSinglyLinkedList*[T](): TSinglyLinkedList[T] = ## creates a new singly linked list that is empty. - nil + discard proc initDoublyLinkedList*[T](): TDoublyLinkedList[T] = ## creates a new doubly linked list that is empty. - nil + discard proc initSinglyLinkedRing*[T](): TSinglyLinkedRing[T] = ## creates a new singly linked ring that is empty. - nil + discard proc initDoublyLinkedRing*[T](): TDoublyLinkedRing[T] = ## creates a new doubly linked ring that is empty. - nil + discard proc newDoublyLinkedNode*[T](value: T): PDoublyLinkedNode[T] = ## creates a new doubly linked node with the given `value`. diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index 02d099c1f..ef3a529a1 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -85,7 +85,7 @@ template rawInsertImpl() {.dirty.} = data[h].val = val data[h].slot = seFilled -proc RawGet[A, B](t: TTable[A, B], key: A): int = +proc rawGet[A, B](t: TTable[A, B], key: A): int = rawGetImpl() proc `[]`*[A, B](t: TTable[A, B], key: A): B = @@ -93,13 +93,13 @@ proc `[]`*[A, B](t: TTable[A, B], key: A): B = ## default empty value for the type `B` is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val proc mget*[A, B](t: var TTable[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key not found: " & $key) @@ -107,39 +107,39 @@ proc hasKey*[A, B](t: TTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 -proc RawInsert[A, B](t: var TTable[A, B], data: var TKeyValuePairSeq[A, B], +proc rawInsert[A, B](t: var TTable[A, B], data: var TKeyValuePairSeq[A, B], key: A, val: B) = rawInsertImpl() -proc Enlarge[A, B](t: var TTable[A, B]) = +proc enlarge[A, B](t: var TTable[A, B]) = var n: TKeyValuePairSeq[A, B] newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): - if t.data[i].slot == seFilled: RawInsert(t, n, t.data[i].key, t.data[i].val) + if t.data[i].slot == seFilled: rawInsert(t, n, t.data[i].key, t.data[i].val) swap(t.data, n) -template AddImpl() {.dirty.} = - if mustRehash(len(t.data), t.counter): Enlarge(t) - RawInsert(t, t.data, key, val) +template addImpl() {.dirty.} = + if mustRehash(len(t.data), t.counter): enlarge(t) + rawInsert(t, t.data, key, val) inc(t.counter) -template PutImpl() {.dirty.} = - var index = RawGet(t, key) +template putImpl() {.dirty.} = + var index = rawGet(t, key) if index >= 0: t.data[index].val = val else: - AddImpl() + addImpl() when false: # not yet used: - template HasKeyOrPutImpl() {.dirty.} = - var index = RawGet(t, key) + template hasKeyOrPutImpl() {.dirty.} = + var index = rawGet(t, key) if index >= 0: t.data[index].val = val result = true else: - if mustRehash(len(t.data), t.counter): Enlarge(t) - RawInsert(t, t.data, key, val) + if mustRehash(len(t.data), t.counter): enlarge(t) + rawInsert(t, t.data, key, val) inc(t.counter) result = false @@ -149,11 +149,11 @@ proc `[]=`*[A, B](t: var TTable[A, B], key: A, val: B) = proc add*[A, B](t: var TTable[A, B], key: A, val: B) = ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. - AddImpl() + addImpl() proc del*[A, B](t: var TTable[A, B], key: A) = ## deletes `key` from hash table `t`. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: t.data[index].slot = seDeleted dec(t.counter) @@ -240,7 +240,7 @@ iterator mvalues*[A, B](t: var TOrderedTable[A, B]): var B = forAllOrderedPairs: yield t.data[h].val -proc RawGet[A, B](t: TOrderedTable[A, B], key: A): int = +proc rawGet[A, B](t: TOrderedTable[A, B], key: A): int = rawGetImpl() proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B = @@ -248,13 +248,13 @@ proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B = ## default empty value for the type `B` is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val proc mget*[A, B](t: var TOrderedTable[A, B], key: A): var B = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key not found: " & $key) @@ -262,7 +262,7 @@ proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 -proc RawInsert[A, B](t: var TOrderedTable[A, B], +proc rawInsert[A, B](t: var TOrderedTable[A, B], data: var TOrderedKeyValuePairSeq[A, B], key: A, val: B) = rawInsertImpl() @@ -271,7 +271,7 @@ proc RawInsert[A, B](t: var TOrderedTable[A, B], if t.last >= 0: data[t.last].next = h t.last = h -proc Enlarge[A, B](t: var TOrderedTable[A, B]) = +proc enlarge[A, B](t: var TOrderedTable[A, B]) = var n: TOrderedKeyValuePairSeq[A, B] newSeq(n, len(t.data) * growthFactor) var h = t.first @@ -280,7 +280,7 @@ proc Enlarge[A, B](t: var TOrderedTable[A, B]) = while h >= 0: var nxt = t.data[h].next if t.data[h].slot == seFilled: - RawInsert(t, n, t.data[h].key, t.data[h].val) + rawInsert(t, n, t.data[h].key, t.data[h].val) h = nxt swap(t.data, n) @@ -290,7 +290,7 @@ proc `[]=`*[A, B](t: var TOrderedTable[A, B], key: A, val: B) = proc add*[A, B](t: var TOrderedTable[A, B], key: A, val: B) = ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. - AddImpl() + addImpl() proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] = ## creates a new ordered hash table that is empty. @@ -398,7 +398,7 @@ iterator mvalues*[A](t: TCountTable[A]): var int = for h in 0..high(t.data): if t.data[h].val != 0: yield t.data[h].val -proc RawGet[A](t: TCountTable[A], key: A): int = +proc rawGet[A](t: TCountTable[A], key: A): int = var h: THash = hash(key) and high(t.data) # start with real hash value while t.data[h].val != 0: if t.data[h].key == key: return h @@ -409,13 +409,13 @@ proc `[]`*[A](t: TCountTable[A], key: A): int = ## retrieves the value at ``t[key]``. If `key` is not in `t`, ## 0 is returned. One can check with ``hasKey`` whether the key ## exists. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val proc mget*[A](t: var TCountTable[A], key: A): var int = ## retrieves the value at ``t[key]``. The value can be modified. ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key not found: " & $key) @@ -423,24 +423,24 @@ proc hasKey*[A](t: TCountTable[A], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 -proc RawInsert[A](t: TCountTable[A], data: var seq[tuple[key: A, val: int]], +proc rawInsert[A](t: TCountTable[A], data: var seq[tuple[key: A, val: int]], key: A, val: int) = var h: THash = hash(key) and high(data) while data[h].val != 0: h = nextTry(h, high(data)) data[h].key = key data[h].val = val -proc Enlarge[A](t: var TCountTable[A]) = +proc enlarge[A](t: var TCountTable[A]) = var n: seq[tuple[key: A, val: int]] newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): - if t.data[i].val != 0: RawInsert(t, n, t.data[i].key, t.data[i].val) + if t.data[i].val != 0: rawInsert(t, n, t.data[i].key, t.data[i].val) swap(t.data, n) proc `[]=`*[A](t: var TCountTable[A], key: A, val: int) = ## puts a (key, value)-pair into `t`. `val` has to be positive. assert val > 0 - PutImpl() + putImpl() proc initCountTable*[A](initialSize=64): TCountTable[A] = ## creates a new count table that is empty. @@ -467,11 +467,11 @@ proc inc*[A](t: var TCountTable[A], key: A, val = 1) = if index >= 0: inc(t.data[index].val, val) else: - if mustRehash(len(t.data), t.counter): Enlarge(t) - RawInsert(t, t.data, key, val) + if mustRehash(len(t.data), t.counter): enlarge(t) + rawInsert(t, t.data, key, val) inc(t.counter) -proc Smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] = +proc smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] = ## returns the largest (key,val)-pair. Efficiency: O(n) assert t.len > 0 var minIdx = 0 @@ -480,7 +480,7 @@ proc Smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] = result.key = t.data[minIdx].key result.val = t.data[minIdx].val -proc Largest*[A](t: TCountTable[A]): tuple[key: A, val: int] = +proc largest*[A](t: TCountTable[A]): tuple[key: A, val: int] = ## returns the (key,val)-pair with the largest `val`. Efficiency: O(n) assert t.len > 0 var maxIdx = 0 diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 2756290d8..3b3e3810b 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -48,11 +48,11 @@ proc getCurrentLine*(L: TBaseLexer, marker: bool = true): string proc getColNumber*(L: TBaseLexer, pos: int): int ## retrieves the current column. -proc HandleCR*(L: var TBaseLexer, pos: int): int +proc handleCR*(L: var TBaseLexer, pos: int): int ## Call this if you scanned over '\c' in the buffer; it returns the the ## position to continue the scanning from. `pos` must be the position ## of the '\c'. -proc HandleLF*(L: var TBaseLexer, pos: int): int +proc handleLF*(L: var TBaseLexer, pos: int): int ## Call this if you scanned over '\L' in the buffer; it returns the the ## position to continue the scanning from. `pos` must be the position ## of the '\L'. @@ -66,7 +66,7 @@ proc close(L: var TBaseLexer) = dealloc(L.buf) close(L.input) -proc FillBuffer(L: var TBaseLexer) = +proc fillBuffer(L: var TBaseLexer) = var charsRead, toCopy, s: int # all are in characters, # not bytes (in case this @@ -78,7 +78,7 @@ proc FillBuffer(L: var TBaseLexer) = toCopy = L.BufLen - L.sentinel - 1 assert(toCopy >= 0) if toCopy > 0: - MoveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) + moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) # "moveMem" handles overlapping regions charsRead = readData(L.input, addr(L.buf[toCopy]), (L.sentinel + 1) * chrSize) div chrSize @@ -103,7 +103,7 @@ proc FillBuffer(L: var TBaseLexer) = L.bufLen = L.BufLen * 2 L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) 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 if charsRead < oldBufLen: L.buf[oldBufLen + charsRead] = EndOfFile @@ -121,19 +121,19 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int = result = 0 L.lineStart = result -proc HandleCR(L: var TBaseLexer, pos: int): int = +proc handleCR(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == '\c') inc(L.linenumber) result = fillBaseLexer(L, pos) if L.buf[result] == '\L': result = fillBaseLexer(L, result) -proc HandleLF(L: var TBaseLexer, pos: int): int = +proc handleLF(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == '\L') inc(L.linenumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; -proc skip_UTF_8_BOM(L: var TBaseLexer) = +proc skipUtf8Bom(L: var TBaseLexer) = if (L.buf[0] == '\xEF') and (L.buf[1] == '\xBB') and (L.buf[2] == '\xBF'): inc(L.bufpos, 3) inc(L.lineStart, 3) @@ -149,7 +149,7 @@ proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) = L.lineStart = 0 L.linenumber = 1 # lines start at 1 fillBuffer(L) - skip_UTF_8_BOM(L) + skipUtf8Bom(L) proc getColNumber(L: TBaseLexer, pos: int): int = result = abs(pos - L.lineStart) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 2e15587f4..f5b9ced4c 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -93,11 +93,11 @@ when defined(Nimdoc): # only for proper documentation: elif defined(macos): const - curdir* = ':' - pardir* = "::" - dirsep* = ':' - altsep* = dirsep - pathsep* = ',' + CurDir* = ':' + ParDir* = "::" + Dirsep* = ':' + Altsep* = dirsep + Pathsep* = ',' FileSystemCaseSensitive* = false ExeExt* = "" ScriptExt* = "" @@ -123,42 +123,42 @@ elif defined(macos): # grandparent etc. elif doslike: const - curdir* = '.' - pardir* = ".." - dirsep* = '\\' # seperator within paths - altsep* = '/' - pathSep* = ';' # seperator between paths + Curdir* = '.' + Pardir* = ".." + Dirsep* = '\\' # seperator within paths + Altsep* = '/' + PathSep* = ';' # seperator between paths FileSystemCaseSensitive* = false ExeExt* = "exe" ScriptExt* = "bat" DynlibFormat* = "$1.dll" elif defined(PalmOS) or defined(MorphOS): const - dirsep* = '/' - altsep* = dirsep + Dirsep* = '/' + Altsep* = dirsep PathSep* = ';' - pardir* = ".." + Pardir* = ".." FileSystemCaseSensitive* = false ExeExt* = "" ScriptExt* = "" DynlibFormat* = "$1.prc" elif defined(RISCOS): const - dirsep* = '.' - altsep* = '.' - pardir* = ".." # is this correct? - pathSep* = ',' + Dirsep* = '.' + Altsep* = '.' + Pardir* = ".." # is this correct? + PathSep* = ',' FileSystemCaseSensitive* = true ExeExt* = "" ScriptExt* = "" DynlibFormat* = "lib$1.so" else: # UNIX-like operating system const - curdir* = '.' - pardir* = ".." - dirsep* = '/' - altsep* = dirsep - pathSep* = ':' + Curdir* = '.' + Pardir* = ".." + Dirsep* = '/' + Altsep* = dirsep + PathSep* = ':' FileSystemCaseSensitive* = true ExeExt* = "" ScriptExt* = "" @@ -186,20 +186,20 @@ proc OSErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} = result = "" when defined(Windows): - var err = GetLastError() + var err = getLastError() if err != 0'i32: when useWinUnicode: var msgbuf: widecstring - if FormatMessageW(0x00000100 or 0x00001000 or 0x00000200, + if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, err, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf - if msgbuf != nil: LocalFree(cast[pointer](msgbuf)) + if msgbuf != nil: localFree(cast[pointer](msgbuf)) else: var msgbuf: cstring - if FormatMessageA(0x00000100 or 0x00001000 or 0x00000200, + if formatMessageA(0x00000100 or 0x00001000 or 0x00000200, nil, err, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf - if msgbuf != nil: LocalFree(msgbuf) + if msgbuf != nil: localFree(msgbuf) if errno != 0'i32: result = $os.strerror(errno) @@ -238,16 +238,16 @@ proc OSErrorMsg*(errorCode: TOSErrorCode): string = if errorCode != TOSErrorCode(0'i32): when useWinUnicode: var msgbuf: widecstring - if FormatMessageW(0x00000100 or 0x00001000 or 0x00000200, + if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf - if msgbuf != nil: LocalFree(cast[pointer](msgbuf)) + if msgbuf != nil: localFree(cast[pointer](msgbuf)) else: var msgbuf: cstring - if FormatMessageA(0x00000100 or 0x00001000 or 0x00000200, + if formatMessageA(0x00000100 or 0x00001000 or 0x00000200, nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf - if msgbuf != nil: LocalFree(msgbuf) + if msgbuf != nil: localFree(msgbuf) else: if errorCode != TOSErrorCode(0'i32): result = $os.strerror(errorCode.int32) @@ -287,7 +287,7 @@ proc OSLastError*(): TOSErrorCode = result = TOSErrorCode(errno) {.pop.} -proc UnixToNativePath*(path: string): string {. +proc unixToNativePath*(path: string): string {. noSideEffect, rtl, extern: "nos$1".} = ## Converts an UNIX-like path to a native one. ## @@ -340,16 +340,16 @@ when defined(windows): template wrapBinary(varname, winApiProc, arg, arg2: expr) {.immediate.} = var varname = winApiProc(newWideCString(arg), arg2) - proc FindFirstFile(a: string, b: var TWIN32_FIND_DATA): THandle = - result = FindFirstFileW(newWideCString(a), b) - template FindNextFile(a, b: expr): expr = FindNextFileW(a, b) + proc findFirstFile(a: string, b: var TWIN32_FIND_DATA): THandle = + result = findFirstFileW(newWideCString(a), b) + template findNextFile(a, b: expr): expr = findNextFileW(a, b) template getCommandLine(): expr = getCommandLineW() template getFilename(f: expr): expr = $cast[WideCString](addr(f.cFilename[0])) else: - template FindFirstFile(a, b: expr): expr = FindFirstFileA(a, b) - template FindNextFile(a, b: expr): expr = FindNextFileA(a, b) + template findFirstFile(a, b: expr): expr = findFirstFileA(a, b) + template findNextFile(a, b: expr): expr = findNextFileA(a, b) template getCommandLine(): expr = getCommandLineA() template getFilename(f: expr): expr = $f.cFilename @@ -364,9 +364,9 @@ proc existsFile*(filename: string): bool {.rtl, extern: "nos$1", ## Returns true if the file exists, false otherwise. when defined(windows): when useWinUnicode: - wrapUnary(a, GetFileAttributesW, filename) + wrapUnary(a, getFileAttributesW, filename) else: - var a = GetFileAttributesA(filename) + var a = getFileAttributesA(filename) if a != -1'i32: result = (a and FILE_ATTRIBUTE_DIRECTORY) == 0'i32 else: @@ -378,9 +378,9 @@ proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [FReadDir].} = ## is returned. when defined(windows): when useWinUnicode: - wrapUnary(a, GetFileAttributesW, dir) + wrapUnary(a, getFileAttributesW, dir) else: - var a = GetFileAttributesA(dir) + var a = getFileAttributesA(dir) if a != -1'i32: result = (a and FILE_ATTRIBUTE_DIRECTORY) != 0'i32 else: @@ -395,7 +395,7 @@ proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} = return res.st_mtime else: var f: TWIN32_Find_Data - var h = findfirstFile(file, f) + var h = findFirstFile(file, f) if h == -1'i32: OSError(OSLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime)) findclose(h) @@ -408,7 +408,7 @@ proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} = return res.st_atime else: var f: TWIN32_Find_Data - var h = findfirstFile(file, f) + var h = findFirstFile(file, f) if h == -1'i32: OSError(OSLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime)) findclose(h) @@ -421,7 +421,7 @@ proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} = return res.st_ctime else: var f: TWIN32_Find_Data - var h = findfirstFile(file, f) + var h = findFirstFile(file, f) if h == -1'i32: OSError(OSLastError()) result = winTimeToUnixTime(rdFileTime(f.ftCreationTime)) findclose(h) @@ -437,12 +437,12 @@ proc getCurrentDir*(): string {.rtl, extern: "nos$1", tags: [].} = when defined(windows): when useWinUnicode: var res = newWideCString("", bufsize) - var L = GetCurrentDirectoryW(bufsize, res) + var L = getCurrentDirectoryW(bufsize, res) if L == 0'i32: OSError(OSLastError()) result = res$L else: result = newString(bufsize) - var L = GetCurrentDirectoryA(bufsize, result) + var L = getCurrentDirectoryA(bufsize, result) if L == 0'i32: OSError(OSLastError()) setLen(result, L) else: @@ -457,10 +457,10 @@ proc setCurrentDir*(newDir: string) {.inline, tags: [].} = ## `newDir` cannot been set. when defined(Windows): when useWinUnicode: - if SetCurrentDirectoryW(newWideCString(newDir)) == 0'i32: + if setCurrentDirectoryW(newWideCString(newDir)) == 0'i32: OSError(OSLastError()) else: - if SetCurrentDirectoryA(newDir) == 0'i32: OSError(OSLastError()) + if setCurrentDirectoryA(newDir) == 0'i32: OSError(OSLastError()) else: if chdir(newDir) != 0'i32: OSError(OSLastError()) @@ -512,7 +512,7 @@ proc joinPath*(parts: varargs[string]): string {.noSideEffect, result = joinPath(result, parts[i]) proc `/` * (head, tail: string): string {.noSideEffect.} = - ## The same as ``JoinPath(head, tail)`` + ## The same as ``joinPath(head, tail)`` ## ## Here are some examples for Unix: ## @@ -526,7 +526,7 @@ proc `/` * (head, tail: string): string {.noSideEffect.} = proc splitPath*(path: string): tuple[head, tail: string] {. noSideEffect, rtl, extern: "nos$1".} = ## Splits a directory into (head, tail), so that - ## ``JoinPath(head, tail) == path``. + ## ``joinPath(head, tail) == path``. ## ## Examples: ## @@ -672,14 +672,14 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1", when useWinUnicode: var unused: widecstring var res = newWideCString("", bufsize div 2) - var L = GetFullPathNameW(newWideCString(filename), bufsize, res, unused) + var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused) if L <= 0'i32 or L >= bufsize: OSError(OSLastError()) result = res$L else: var unused: cstring result = newString(bufsize) - var L = GetFullPathNameA(filename, bufsize, result, unused) + var L = getFullPathNameA(filename, bufsize, result, unused) if L <= 0'i32 or L >= bufsize: OSError(OSLastError()) setLen(result, L) else: @@ -758,29 +758,29 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", when useWinUnicode: var p1 = newWideCString(path1) var p2 = newWideCString(path2) - template OpenHandle(path: expr): expr = - CreateFileW(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or + template openHandle(path: expr): expr = + createFileW(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0) - var f1 = OpenHandle(p1) - var f2 = OpenHandle(p2) + var f1 = openHandle(p1) + var f2 = openHandle(p2) else: - template OpenHandle(path: expr): expr = - CreateFileA(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or + template openHandle(path: expr): expr = + createFileA(path, 0'i32, FILE_SHARE_DELETE or FILE_SHARE_READ or FILE_SHARE_WRITE, nil, OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS or FILE_ATTRIBUTE_NORMAL, 0) - var f1 = OpenHandle(path1) - var f2 = OpenHandle(path2) + var f1 = openHandle(path1) + var f2 = openHandle(path2) var lastErr: TOSErrorCode if f1 != INVALID_HANDLE_VALUE and f2 != INVALID_HANDLE_VALUE: var fi1, fi2: TBY_HANDLE_FILE_INFORMATION - if GetFileInformationByHandle(f1, addr(fi1)) != 0 and - GetFileInformationByHandle(f2, addr(fi2)) != 0: + if getFileInformationByHandle(f1, addr(fi1)) != 0 and + getFileInformationByHandle(f2, addr(fi2)) != 0: result = fi1.dwVolumeSerialNumber == fi2.dwVolumeSerialNumber and fi1.nFileIndexHigh == fi2.nFileIndexHigh and fi1.nFileIndexLow == fi2.nFileIndexLow @@ -791,8 +791,8 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1", lastErr = OSLastError() success = false - discard CloseHandle(f1) - discard CloseHandle(f2) + discard closeHandle(f1) + discard closeHandle(f2) if not success: OSError(lastErr) else: @@ -867,9 +867,9 @@ proc getFilePermissions*(filename: string): set[TFilePermission] {. if (a.st_mode and S_IXOTH) != 0'i32: result.incl(fpOthersExec) else: when useWinUnicode: - wrapUnary(res, GetFileAttributesW, filename) + wrapUnary(res, getFileAttributesW, filename) else: - var res = GetFileAttributesA(filename) + var res = getFileAttributesA(filename) if res == -1'i32: OSError(OSLastError()) if (res and FILE_ATTRIBUTE_READONLY) != 0'i32: result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead, @@ -899,18 +899,18 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {. if chmod(filename, p) != 0: OSError(OSLastError()) else: when useWinUnicode: - wrapUnary(res, GetFileAttributesW, filename) + wrapUnary(res, getFileAttributesW, filename) else: - var res = GetFileAttributesA(filename) + var res = getFileAttributesA(filename) if res == -1'i32: OSError(OSLastError()) if fpUserWrite in permissions: res = res and not FILE_ATTRIBUTE_READONLY else: res = res or FILE_ATTRIBUTE_READONLY when useWinUnicode: - wrapBinary(res2, SetFileAttributesW, filename, res) + wrapBinary(res2, setFileAttributesW, filename, res) else: - var res2 = SetFileAttributesA(filename, res) + var res2 = setFileAttributesA(filename, res) if res2 == - 1'i32: OSError(OSLastError()) proc copyFile*(source, dest: string) {.rtl, extern: "nos$1", @@ -928,9 +928,9 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1", when useWinUnicode: let s = newWideCString(source) let d = newWideCString(dest) - if CopyFileW(s, d, 0'i32) == 0'i32: OSError(OSLastError()) + if copyFileW(s, d, 0'i32) == 0'i32: OSError(OSLastError()) else: - if CopyFileA(source, dest, 0'i32) == 0'i32: OSError(OSLastError()) + if copyFileA(source, dest, 0'i32) == 0'i32: OSError(OSLastError()) else: # generic version of copyFile which works for any platform: const bufSize = 8000 # better for memory manager @@ -940,7 +940,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1", close(s) OSError(OSLastError()) var buf = alloc(bufsize) - while True: + while true: var bytesread = readBuffer(s, buf, bufsize) if bytesread > 0: var byteswritten = writeBuffer(d, buf, bytesread) @@ -968,13 +968,13 @@ when not defined(ENOENT) and not defined(Windows): when defined(Windows): when useWinUnicode: - template DeleteFile(file: expr): expr {.immediate.} = DeleteFileW(file) - template SetFileAttributes(file, attrs: expr): expr {.immediate.} = - SetFileAttributesW(file, attrs) + template deleteFile(file: expr): expr {.immediate.} = deleteFileW(file) + template setFileAttributes(file, attrs: expr): expr {.immediate.} = + setFileAttributesW(file, attrs) else: - template DeleteFile(file: expr): expr {.immediate.} = DeleteFileA(file) - template SetFileAttributes(file, attrs: expr): expr {.immediate.} = - SetFileAttributesA(file, attrs) + template deleteFile(file: expr): expr {.immediate.} = deleteFileA(file) + template setFileAttributes(file, attrs: expr): expr {.immediate.} = + setFileAttributesA(file, attrs) proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} = ## Removes the `file`. If this fails, `EOS` is raised. This does not fail @@ -985,11 +985,11 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} = let f = newWideCString(file) else: let f = file - if DeleteFile(f) == 0: - if GetLastError() == ERROR_ACCESS_DENIED: - if SetFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0: + if deleteFile(f) == 0: + if getLastError() == ERROR_ACCESS_DENIED: + if setFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0: OSError(OSLastError()) - if DeleteFile(f) == 0: + if deleteFile(f) == 0: OSError(OSLastError()) else: if cremove(file) != 0'i32 and errno != ENOENT: @@ -1076,7 +1076,7 @@ else: when useNSGetEnviron: var gEnv = NSGetEnviron()[] var i = 0 - while True: + while true: if gEnv[i] == nil: break add environment, $gEnv[i] inc(i) @@ -1130,9 +1130,9 @@ proc putEnv*(key, val: string) {.tags: [FWriteEnv].} = when useWinUnicode: var k = newWideCString(key) var v = newWideCString(val) - if SetEnvironmentVariableW(k, v) == 0'i32: OSError(OSLastError()) + if setEnvironmentVariableW(k, v) == 0'i32: OSError(OSLastError()) else: - if SetEnvironmentVariableA(key, val) == 0'i32: OSError(OSLastError()) + if setEnvironmentVariableA(key, val) == 0'i32: OSError(OSLastError()) iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [FReadEnv].} = ## Iterate over all `environments variables`:idx:. In the first component @@ -1259,9 +1259,9 @@ iterator walkDirRec*(dir: string, filter={pcFile, pcDir}): string {. proc rawRemoveDir(dir: string) = when defined(windows): when useWinUnicode: - wrapUnary(res, RemoveDirectoryW, dir) + wrapUnary(res, removeDirectoryW, dir) else: - var res = RemoveDirectoryA(dir) + var res = removeDirectoryA(dir) let lastError = OSLastError() if res == 0'i32 and lastError.int32 != 3'i32 and lastError.int32 != 18'i32 and lastError.int32 != 2'i32: @@ -1291,10 +1291,10 @@ proc rawCreateDir(dir: string) = OSError(OSLastError()) else: when useWinUnicode: - wrapUnary(res, CreateDirectoryW, dir) + wrapUnary(res, createDirectoryW, dir) else: - var res = CreateDirectoryA(dir) - if res == 0'i32 and GetLastError() != 183'i32: + var res = createDirectoryA(dir) + if res == 0'i32 and getLastError() != 183'i32: OSError(OSLastError()) proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} = @@ -1584,8 +1584,8 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} = if len(result) > 0 and result[0] != DirSep: # not an absolute path? # iterate over any path in the $PATH environment variable for p in split(string(getEnv("PATH")), {PathSep}): - var x = JoinPath(p, result) - if ExistsFile(x): return x + var x = joinPath(p, result) + if existsFile(x): return x proc getApplicationFilename*(): string {.rtl, extern: "nos$1", deprecated.} = ## Returns the filename of the application's executable. @@ -1636,11 +1636,11 @@ proc findExe*(exe: string): string {.tags: [FReadDir, FReadEnv].} = ## Returns "" if the `exe` cannot be found. On DOS-like platforms, `exe` ## is added an ``.exe`` file extension if it has no extension. result = addFileExt(exe, os.exeExt) - if ExistsFile(result): return + if existsFile(result): return var path = string(os.getEnv("PATH")) for candidate in split(path, pathSep): var x = candidate / result - if ExistsFile(x): return x + if existsFile(x): return x result = "" proc expandTilde*(path: string): string = diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 61b940ce8..605ca0f12 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -383,16 +383,16 @@ when defined(Windows) and not defined(useNimRtl): # O_WRONLY {.importc: "_O_WRONLY", header: "".}: int # O_RDONLY {.importc: "_O_RDONLY", header: "".}: int - proc CreatePipeHandles(Rdhandle, WrHandle: var THandle) = + proc createPipeHandles(Rdhandle, WrHandle: var THandle) = var piInheritablePipe: TSecurityAttributes - piInheritablePipe.nlength = SizeOF(TSecurityAttributes).cint + piInheritablePipe.nlength = SizeOf(TSecurityAttributes).cint piInheritablePipe.lpSecurityDescriptor = nil piInheritablePipe.Binherithandle = 1 - if CreatePipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32: + if createPipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32: OSError(OSLastError()) proc fileClose(h: THandle) {.inline.} = - if h > 4: discard CloseHandle(h) + if h > 4: discard closeHandle(h) proc startProcess(command: string, workingDir: string = "", @@ -400,8 +400,8 @@ when defined(Windows) and not defined(useNimRtl): env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess = var - SI: TStartupInfo - ProcInfo: TProcessInformation + si: TStartupInfo + procInfo: TProcessInformation success: int hi, ho, he: THandle new(result) @@ -511,8 +511,8 @@ when defined(Windows) and not defined(useNimRtl): proc execCmd(command: string): int = var - SI: TStartupInfo - ProcInfo: TProcessInformation + si: TStartupInfo + procInfo: TProcessInformation process: THandle L: int32 SI.cb = SizeOf(SI).cint diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim index c11265bfd..bccb274d6 100644 --- a/lib/pure/parseutils.nim +++ b/lib/pure/parseutils.nim @@ -51,7 +51,7 @@ proc parseHex*(s: string, number: var int, start = 0): int {. elif s[i] == '#': inc(i) while true: case s[i] - of '_': nil + of '_': discard of '0'..'9': number = number shl 4 or (ord(s[i]) - ord('0')) foundDigit = true @@ -74,7 +74,7 @@ proc parseOct*(s: string, number: var int, start = 0): int {. if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) while true: case s[i] - of '_': nil + of '_': discard of '0'..'7': number = number shl 3 or (ord(s[i]) - ord('0')) foundDigit = true diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 66bb1e6a9..f5351c41c 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -132,17 +132,17 @@ type ETimeout* = object of ESynch let - InvalidSocket*: TSocket = nil ## invalid socket + invalidSocket*: TSocket = nil ## invalid socket when defined(windows): let - OSInvalidSocket = winlean.INVALID_SOCKET + osInvalidSocket = winlean.INVALID_SOCKET else: let - OSInvalidSocket = posix.INVALID_SOCKET + osInvalidSocket = posix.INVALID_SOCKET proc newTSocket(fd: TSocketHandle, isBuff: bool): TSocket = - if fd == OSInvalidSocket: + if fd == osInvalidSocket: return nil new(result) result.fd = fd @@ -187,14 +187,14 @@ proc htons*(x: int16): int16 = result = sockets.ntohs(x) when defined(Posix): - proc ToInt(domain: TDomain): cint = + proc toInt(domain: TDomain): cint = case domain of AF_UNIX: result = posix.AF_UNIX of AF_INET: result = posix.AF_INET of AF_INET6: result = posix.AF_INET6 else: nil - proc ToInt(typ: TType): cint = + proc toInt(typ: TType): cint = case typ of SOCK_STREAM: result = posix.SOCK_STREAM of SOCK_DGRAM: result = posix.SOCK_DGRAM @@ -202,7 +202,7 @@ when defined(Posix): of SOCK_RAW: result = posix.SOCK_RAW else: nil - proc ToInt(p: TProtocol): cint = + proc toInt(p: TProtocol): cint = case p of IPPROTO_TCP: result = posix.IPPROTO_TCP of IPPROTO_UDP: result = posix.IPPROTO_UDP @@ -216,10 +216,10 @@ else: proc toInt(domain: TDomain): cint = result = toU16(ord(domain)) - proc ToInt(typ: TType): cint = + proc toInt(typ: TType): cint = result = cint(ord(typ)) - proc ToInt(p: TProtocol): cint = + proc toInt(p: TProtocol): cint = result = cint(ord(p)) proc socket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM, @@ -333,7 +333,7 @@ when defined(ssl): if SSLSetFd(socket.sslHandle, socket.fd) != 1: SSLError() -proc SocketError*(socket: TSocket, err: int = -1, async = false) = +proc socketError*(socket: TSocket, err: int = -1, async = false) = ## Raises proper errors based on return values of ``recv`` functions. ## ## If ``async`` is ``True`` no error will be thrown in the case when the @@ -471,7 +471,7 @@ template acceptAddrPlain(noClientRet, successRet: expr, var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen)) - if sock == OSInvalidSocket: + if sock == osInvalidSocket: let err = OSLastError() when defined(windows): if err.int32 == WSAEINPROGRESS: @@ -1661,7 +1661,7 @@ when defined(Windows): proc setBlocking(s: TSocket, blocking: bool) = when defined(Windows): var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking - if ioctlsocket(TSocketHandle(s.fd), FIONBIO, addr(mode)) == -1: + if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1: OSError(OSLastError()) else: # BSD sockets var x: int = fcntl(s.fd, F_GETFL, 0) diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index 77b463fc0..d8bc94176 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -88,7 +88,7 @@ proc mustRehash(length, counter: int): bool = proc nextTry(h, maxHash: THash): THash {.inline.} = result = ((5 * h) + 1) and maxHash -proc RawGet(t: PStringTable, key: string): int = +proc rawGet(t: PStringTable, key: string): int = var h: THash = myhash(t, key) and high(t.data) # start with real hash value while not isNil(t.data[h].key): if mycmp(t, t.data[h].key, key): @@ -116,14 +116,14 @@ proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 -proc RawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) = +proc rawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) = var h: THash = myhash(t, key) and high(data) while not isNil(data[h].key): h = nextTry(h, high(data)) data[h].key = key data[h].val = val -proc Enlarge(t: PStringTable) = +proc enlarge(t: PStringTable) = var n: TKeyValuePairSeq newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): @@ -140,7 +140,7 @@ proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} = RawInsert(t, t.data, key, val) inc(t.counter) -proc RaiseFormatException(s: string) = +proc raiseFormatException(s: string) = var e: ref EInvalidValue new(e) e.msg = "format string: key not found: " & s diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index e290226d2..388a76e71 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -128,7 +128,7 @@ proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, ## | > 0 iff a > b var i = 0 var j = 0 - while True: + while true: while a[i] == '_': inc(i) while b[j] == '_': inc(j) # BUGFIX: typo var aa = toLower(a[i]) @@ -344,7 +344,7 @@ proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect, if x < 0: result = '-' & result -proc ParseInt*(s: string): int {.noSideEffect, procvar, +proc parseInt*(s: string): int {.noSideEffect, procvar, rtl, extern: "nsuParseInt".} = ## Parses a decimal integer value contained in `s`. If `s` is not ## a valid integer, `EInvalidValue` is raised. @@ -352,7 +352,7 @@ proc ParseInt*(s: string): int {.noSideEffect, procvar, if L != s.len or L == 0: raise newException(EInvalidValue, "invalid integer: " & s) -proc ParseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar, +proc parseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar, rtl, extern: "nsuParseBiggestInt".} = ## Parses a decimal integer value contained in `s`. If `s` is not ## a valid integer, `EInvalidValue` is raised. @@ -360,7 +360,7 @@ proc ParseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar, if L != s.len or L == 0: raise newException(EInvalidValue, "invalid integer: " & s) -proc ParseFloat*(s: string): float {.noSideEffect, procvar, +proc parseFloat*(s: string): float {.noSideEffect, procvar, rtl, extern: "nsuParseFloat".} = ## Parses a decimal floating point value contained in `s`. If `s` is not ## a valid floating point number, `EInvalidValue` is raised. ``NAN``, @@ -369,7 +369,7 @@ proc ParseFloat*(s: string): float {.noSideEffect, procvar, if L != s.len or L == 0: raise newException(EInvalidValue, "invalid float: " & s) -proc ParseHexInt*(s: string): int {.noSideEffect, procvar, +proc parseHexInt*(s: string): int {.noSideEffect, procvar, rtl, extern: "nsuParseHexInt".} = ## Parses a hexadecimal integer value contained in `s`. If `s` is not ## a valid integer, `EInvalidValue` is raised. `s` can have one of the @@ -455,7 +455,7 @@ proc align*(s: string, count: int, padding = ' '): string {. ## assert align("1232", 6, '#') == "##1232" if s.len < count: result = newString(count) - var spaces = count - s.len + let spaces = count - s.len for i in 0..spaces-1: result[i] = padding for i in spaces..count-1: result[i] = s[i-spaces] else: @@ -649,7 +649,7 @@ proc join*(a: openArray[string]): string {. result = "" type - TSkipTable = array[Char, int] + TSkipTable = array[char, int] proc preprocessSub(sub: string, a: var TSkipTable) = var m = len(sub) @@ -795,7 +795,7 @@ proc delete*(s: var string, first, last: int) {.noSideEffect, inc(j) setlen(s, newLen) -proc ParseOctInt*(s: string): int {.noSideEffect, +proc parseOctInt*(s: string): int {.noSideEffect, rtl, extern: "nsuParseOctInt".} = ## Parses an octal integer value contained in `s`. If `s` is not ## a valid integer, `EInvalidValue` is raised. `s` can have one of the @@ -896,7 +896,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, raise newException(EInvalidValue, "String does not start with a prefix of: " & prefix) i.inc() - while True: + while true: if i == s.len-suffix.len: break case s[i] of '\\': diff --git a/lib/pure/times.nim b/lib/pure/times.nim index e967ef683..a37091c52 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -146,7 +146,7 @@ proc getGMTime*(t: TTime): TTimeInfo {.tags: [FTime], raises: [].} ## converts the calendar time `t` to broken-down time representation, ## expressed in Coordinated Universal Time (UTC). -proc TimeInfoToTime*(timeInfo: TTimeInfo): TTime {.tags: [].} +proc timeInfoToTime*(timeInfo: TTimeInfo): TTime {.tags: [].} ## converts a broken-down time structure to ## calendar time representation. The function ignores the specified ## contents of the structure members `weekday` and `yearday` and recomputes @@ -297,7 +297,7 @@ when not defined(JS): when not defined(JS): # C wrapper: type - structTM {.importc: "struct tm", final.} = object + StructTM {.importc: "struct tm", final.} = object second {.importc: "tm_sec".}, minute {.importc: "tm_min".}, hour {.importc: "tm_hour".}, @@ -308,7 +308,7 @@ when not defined(JS): yearday {.importc: "tm_yday".}, isdst {.importc: "tm_isdst".}: cint - PTimeInfo = ptr structTM + PTimeInfo = ptr StructTM PTime = ptr TTime TClock {.importc: "clock_t".} = distinct int @@ -401,7 +401,7 @@ when not defined(JS): # copying is needed anyway to provide reentrancity; thus # the conversion is not expensive - proc TimeInfoToTime(timeInfo: TTimeInfo): TTime = + proc timeInfoToTime(timeInfo: TTimeInfo): TTime = var cTimeInfo = timeInfo # for C++ we have to make a copy, # because the header of mktime is broken in my version of libc return mktime(timeInfoToTM(cTimeInfo)) @@ -498,7 +498,7 @@ elif defined(JS): result.weekday = weekDays[t.getUTCDay()] result.yearday = 0 - proc TimeInfoToTime*(timeInfo: TTimeInfo): TTime = + proc timeInfoToTime*(timeInfo: TTimeInfo): TTime = result = internGetTime() result.setSeconds(timeInfo.second) result.setMinutes(timeInfo.minute) diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index 4aacb2f71..1cf2816b4 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -14,8 +14,8 @@ include "system/inclrtl" type - irune = int # underlying type of TRune - TRune* = distinct irune ## type that can hold any Unicode character + IRune = int # underlying type of TRune + TRune* = distinct IRune ## type that can hold any Unicode character TRune16* = distinct int16 ## 16 bit Unicode character proc `<=%`*(a, b: TRune): bool = return int(a) <=% int(b) diff --git a/lib/system.nim b/lib/system.nim index 14be9cc21..726230613 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1963,20 +1963,20 @@ when not defined(JS): #and not defined(NimrodVM): ## Template which expands to either stdout or stderr depending on ## `useStdoutAsStdmsg` compile-time switch. - proc Open*(f: var TFile, filename: string, + proc open*(f: var TFile, filename: string, mode: TFileMode = fmRead, bufSize: int = -1): Bool {.tags: [].} ## Opens a file named `filename` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. ## This throws no exception if the file could not be opened. - proc Open*(f: var TFile, filehandle: TFileHandle, + proc open*(f: var TFile, filehandle: TFileHandle, mode: TFileMode = fmRead): Bool {.tags: [].} ## Creates a ``TFile`` from a `filehandle` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. - proc Open*(filename: string, + proc open*(filename: string, mode: TFileMode = fmRead, bufSize: int = -1): TFile = ## Opens a file named `filename` with given `mode`. ## @@ -1993,16 +1993,16 @@ when not defined(JS): #and not defined(NimrodVM): ## ## Default mode is readonly. Returns true iff the file could be reopened. - proc Close*(f: TFile) {.importc: "fclose", header: "", tags: [].} + proc close*(f: TFile) {.importc: "fclose", header: "", tags: [].} ## Closes the file. - proc EndOfFile*(f: TFile): Bool {.tags: [].} + proc endOfFile*(f: TFile): Bool {.tags: [].} ## Returns true iff `f` is at the end. proc readChar*(f: TFile): char {. importc: "fgetc", header: "", tags: [FReadIO].} ## Reads a single character from the stream `f`. - proc FlushFile*(f: TFile) {. + proc flushFile*(f: TFile) {. importc: "fflush", header: "", tags: [FWriteIO].} ## Flushes `f`'s buffer. @@ -2051,13 +2051,13 @@ when not defined(JS): #and not defined(NimrodVM): proc getFileSize*(f: TFile): int64 {.tags: [FReadIO].} ## retrieves the file size (in bytes) of `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 {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than ## `len` (if not as many bytes are remaining), but not greater. - proc ReadChars*(f: TFile, a: var openarray[char], start, len: int): int {. + proc readChars*(f: TFile, a: var openarray[char], start, len: int): int {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than @@ -2655,7 +2655,7 @@ proc compiles*(x: expr): bool {.magic: "Compiles", noSideEffect.} = ## .. code-block:: Nimrod ## when not compiles(3 + 4): ## echo "'+' for integers is available" - nil + discard when defined(initDebugger): initDebugger() @@ -2680,4 +2680,4 @@ proc locals*(): TObject {.magic: "Locals", noSideEffect.} = ## on any debug or runtime information. Note that in constrast to what ## the official signature says, the return type is not ``TObject`` but a ## tuple of a structure that depends on the current scope. - nil + discard diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index 17258cf68..e0f29a961 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -59,15 +59,16 @@ elif defined(windows): MEM_DECOMMIT = 0x4000 MEM_RELEASE = 0x8000 - proc VirtualAlloc(lpAddress: pointer, dwSize: int, flAllocationType, + proc virtualAlloc(lpAddress: pointer, dwSize: int, flAllocationType, flProtect: int32): pointer {. - header: "", stdcall.} + header: "", stdcall, importc: "VirtualAlloc".} - proc VirtualFree(lpAddress: pointer, dwSize: int, - dwFreeType: int32) {.header: "", stdcall.} + proc virtualFree(lpAddress: pointer, dwSize: int, + dwFreeType: int32) {.header: "", stdcall, + importc: "VirtualFree".} proc osAllocPages(size: int): pointer {.inline.} = - result = VirtualAlloc(nil, size, MEM_RESERVE or MEM_COMMIT, + result = virtualAlloc(nil, size, MEM_RESERVE or MEM_COMMIT, PAGE_READWRITE) if result == nil: raiseOutOfMem() @@ -78,7 +79,7 @@ elif defined(windows): # Windows :-(. We have to live with MEM_DECOMMIT instead. # Well that used to be the case but MEM_DECOMMIT fragments the address # space heavily, so we now treat Windows as a strange unmap target. - when reallyOsDealloc: VirtualFree(p, 0, MEM_RELEASE) + when reallyOsDealloc: virtualFree(p, 0, MEM_RELEASE) #VirtualFree(p, size, MEM_DECOMMIT) else: @@ -251,14 +252,14 @@ proc llDeallocAll(a: var TMemRegion) = osDeallocPages(it, PageSize) it = next -proc IntSetGet(t: TIntSet, key: int): PTrunk = +proc intSetGet(t: TIntSet, key: int): PTrunk = var it = t.data[key and high(t.data)] while it != nil: if it.key == key: return it it = it.next result = nil -proc IntSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = +proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = result = IntSetGet(t, key) if result == nil: result = cast[PTrunk](llAlloc(a, sizeof(result[]))) @@ -266,7 +267,7 @@ proc IntSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = t.data[key and high(t.data)] = result result.key = key -proc Contains(s: TIntSet, key: int): bool = +proc contains(s: TIntSet, key: int): bool = var t = IntSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask @@ -274,12 +275,12 @@ proc Contains(s: TIntSet, key: int): bool = else: result = false -proc Incl(a: var TMemRegion, s: var TIntSet, key: int) = +proc incl(a: var TMemRegion, s: var TIntSet, key: int) = var t = IntSetPut(a, s, key shr TrunkShift) var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) -proc Excl(s: var TIntSet, key: int) = +proc excl(s: var TIntSet, key: int) = var t = IntSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask @@ -387,7 +388,7 @@ proc freeOsChunks(a: var TMemRegion, p: pointer, size: int) = #c_fprintf(c_stdout, "[Alloc] back to OS: %ld\n", size) proc isAccessible(a: TMemRegion, p: pointer): bool {.inline.} = - result = Contains(a.chunkStarts, pageIndex(p)) + result = contains(a.chunkStarts, pageIndex(p)) proc contains[T](list, x: T): bool = var it = list @@ -403,7 +404,7 @@ proc writeFreeList(a: TMemRegion) = it, it.next, it.prev) it = it.next -proc ListAdd[T](head: var T, c: T) {.inline.} = +proc listAdd[T](head: var T, c: T) {.inline.} = sysAssert(c notin head, "listAdd 1") sysAssert c.prev == nil, "listAdd 2" sysAssert c.next == nil, "listAdd 3" @@ -413,7 +414,7 @@ proc ListAdd[T](head: var T, c: T) {.inline.} = head.prev = c head = c -proc ListRemove[T](head: var T, c: T) {.inline.} = +proc listRemove[T](head: var T, c: T) {.inline.} = sysAssert(c in head, "listRemove") if c == head: head = c.next @@ -759,7 +760,7 @@ proc getOccupiedMem(a: TMemRegion): int {.inline.} = # ---------------------- thread memory region ------------------------------- -template InstantiateForRegion(allocator: expr) = +template instantiateForRegion(allocator: expr) = when defined(fulldebug): proc interiorAllocatedPtr*(p: pointer): pointer = result = interiorAllocatedPtr(allocator, p) @@ -801,13 +802,13 @@ template InstantiateForRegion(allocator: expr) = when hasThreadSupport: var sharedHeap: TMemRegion var heapLock: TSysLock - InitSysLock(HeapLock) + initSysLock(HeapLock) proc allocShared(size: int): pointer = when hasThreadSupport: - AcquireSys(HeapLock) + acquireSys(HeapLock) result = alloc(sharedHeap, size) - ReleaseSys(HeapLock) + releaseSys(HeapLock) else: result = alloc(size) @@ -817,17 +818,17 @@ template InstantiateForRegion(allocator: expr) = proc deallocShared(p: pointer) = when hasThreadSupport: - AcquireSys(HeapLock) + acquireSys(HeapLock) dealloc(sharedHeap, p) - ReleaseSys(HeapLock) + releaseSys(HeapLock) else: dealloc(p) proc reallocShared(p: pointer, newsize: int): pointer = when hasThreadSupport: - AcquireSys(HeapLock) + acquireSys(HeapLock) result = realloc(sharedHeap, p, newsize) - ReleaseSys(HeapLock) + releaseSys(HeapLock) else: result = realloc(p, newsize) diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 3b43abcd1..525822620 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -168,12 +168,12 @@ proc objectInit(dest: Pointer, typ: PNimType) = of tyArray, tyArrayConstr: for i in 0..(typ.size div typ.base.size)-1: objectInit(cast[pointer](d +% i * typ.base.size), typ.base) - else: nil # nothing to do + else: discard # nothing to do # ---------------------- assign zero ----------------------------------------- when not defined(nimmixin): - proc destroy(x: int) = nil + proc destroy(x: int) = discard proc nimDestroyRange*[T](r: T) = # internal proc used for destroying sequences and arrays for i in countup(0, r.len - 1): destroy(r[i]) diff --git a/lib/system/atomics.nim b/lib/system/atomics.nim index 36185e0a8..68ee74e84 100644 --- a/lib/system/atomics.nim +++ b/lib/system/atomics.nim @@ -7,62 +7,60 @@ # distribution, for details about the copyright. # -# Atomic operations for Nimrod. +## Atomic operations for Nimrod. -when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: - +when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: type AtomMemModel* = enum - ATOMIC_RELAXED, - ## No barriers or synchronization. - ATOMIC_CONSUME, - ## Data dependency only for both barrier and synchronization with another thread. - ATOMIC_ACQUIRE, - ## Barrier to hoisting of code and synchronizes with release (or stronger) - ## semantic stores from another thread. - ATOMIC_RELEASE, - ## Barrier to sinking of code and synchronizes with acquire (or stronger) - ## semantic loads from another thread. - ATOMIC_ACQ_REL, - ## Full barrier in both directions and synchronizes with acquire loads - ## and release stores in another thread. - ATOMIC_SEQ_CST - ## Full barrier in both directions and synchronizes with acquire loads - ## and release stores in all threads. + ATOMIC_RELAXED, ## No barriers or synchronization. + ATOMIC_CONSUME, ## Data dependency only for both barrier and + ## synchronization with another thread. + ATOMIC_ACQUIRE, ## Barrier to hoisting of code and synchronizes with + ## release (or stronger) + ## semantic stores from another thread. + ATOMIC_RELEASE, ## Barrier to sinking of code and synchronizes with + ## acquire (or stronger) + ## semantic loads from another thread. + ATOMIC_ACQ_REL, ## Full barrier in both directions and synchronizes + ## with acquire loads + ## and release stores in another thread. + ATOMIC_SEQ_CST ## Full barrier in both directions and synchronizes + ## with acquire loads + ## and release stores in all threads. TAtomType* = TNumber|pointer|ptr|char - ## Type Class representing valid types for use with atomic procs + ## Type Class representing valid types for use with atomic procs - proc atomic_load_n*[T: TAtomType](p: ptr T, mem: AtomMemModel): T {. + proc atomicLoadN*[T: TAtomType](p: ptr T, mem: AtomMemModel): T {. importc: "__atomic_load_n", nodecl.} ## This proc implements an atomic load operation. It returns the contents at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_CONSUME. - proc atomic_load*[T: TAtomType](p: ptr T, ret: ptr T, mem: AtomMemModel) {. + proc atomicLoad*[T: TAtomType](p: ptr T, ret: ptr T, mem: AtomMemModel) {. importc: "__atomic_load", nodecl.} ## This is the generic version of an atomic load. It returns the contents at p in ret. - proc atomic_store_n*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel) {. + proc atomicStoreN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel) {. importc: "__atomic_store_n", nodecl.} ## This proc implements an atomic store operation. It writes val at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, and ATOMIC_RELEASE. - proc atomic_store*[T: TAtomType](p: ptr T, val: ptr T, mem: AtomMemModel) {. + proc atomicStore*[T: TAtomType](p: ptr T, val: ptr T, mem: AtomMemModel) {. importc: "__atomic_store", nodecl.} ## This is the generic version of an atomic store. It stores the value of val at p - proc atomic_exchange_n*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicExchangeN*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_exchange_n", nodecl.} ## This proc implements an atomic exchange operation. It writes val at p, ## and returns the previous contents at p. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_ACQUIRE, ATOMIC_RELEASE, ATOMIC_ACQ_REL - proc atomic_exchange*[T: TAtomType](p: ptr T, val: ptr T, ret: ptr T, mem: AtomMemModel) {. + proc atomicExchange*[T: TAtomType](p: ptr T, val: ptr T, ret: ptr T, mem: AtomMemModel) {. importc: "__atomic_exchange", nodecl.} ## This is the generic version of an atomic exchange. It stores the contents at val at p. ## The original value at p is copied into ret. - proc atomic_compare_exchange_n*[T: TAtomType](p: ptr T, expected: ptr T, desired: T, + proc atomicCompareExchangeN*[T: TAtomType](p: ptr T, expected: ptr T, desired: T, weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange_n ", nodecl.} ## This proc implements an atomic compare and exchange operation. This compares the @@ -78,7 +76,7 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: ## cannot be __ATOMIC_RELEASE nor __ATOMIC_ACQ_REL. It also cannot be a stronger model ## than that specified by success_memmodel. - proc atomic_compare_exchange*[T: TAtomType](p: ptr T, expected: ptr T, desired: ptr T, + proc atomicCompareExchange*[T: TAtomType](p: ptr T, expected: ptr T, desired: ptr T, weak: bool, success_memmodel: AtomMemModel, failure_memmodel: AtomMemModel): bool {. importc: "__atomic_compare_exchange_n ", nodecl.} ## This proc implements the generic version of atomic_compare_exchange. @@ -86,58 +84,58 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: ## value is also a pointer. ## Perform the operation return the new value, all memory models are valid - proc atomic_add_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicAddFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_add_fetch", nodecl.} - proc atomic_sub_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicSubFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_sub_fetch", nodecl.} - proc atomic_or_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicOrFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_or_fetch ", nodecl.} - proc atomic_and_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicAndFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_and_fetch", nodecl.} - proc atomic_xor_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicXorFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_xor_fetch", nodecl.} - proc atomic_nand_fetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicNandFetch*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_nand_fetch ", nodecl.} ## Perform the operation return the old value, all memory models are valid - proc atomic_fetch_add*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. - importc: "__atomic_fetch_add ", nodecl.} - proc atomic_fetch_sub*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. - importc: "__atomic_fetch_sub ", nodecl.} - proc atomic_fetch_or*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. - importc: "__atomic_fetch_or ", nodecl.} - proc atomic_fetch_and*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. - importc: "__atomic_fetch_and ", nodecl.} - proc atomic_fetch_xor*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. - importc: "__atomic_fetch_xor ", nodecl.} - proc atomic_fetch_nand*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + proc atomicFetchAdd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + importc: "__atomic_fetch_add", nodecl.} + proc atomicFetchSub*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + importc: "__atomic_fetch_sub", nodecl.} + proc atomicFetchOr*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + importc: "__atomic_fetch_or", nodecl.} + proc atomicFetchAnd*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + importc: "__atomic_fetch_and", nodecl.} + proc atomicFetchXor*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. + importc: "__atomic_fetch_xor", nodecl.} + proc atomicFetchAand*[T: TAtomType](p: ptr T, val: T, mem: AtomMemModel): T {. importc: "__atomic_fetch_nand", nodecl.} - proc atomic_test_and_set*(p: pointer, mem: AtomMemModel): bool {. - importc: "__atomic_test_and_set ", nodecl.} + proc atomicTestAndSet*(p: pointer, mem: AtomMemModel): bool {. + importc: "__atomic_test_and_set", nodecl.} ## This built-in function performs an atomic test-and-set operation on the byte at p. ## The byte is set to some implementation defined nonzero “set” value and the return ## value is true if and only if the previous contents were “set”. ## All memory models are valid. - proc atomic_clear*(p: pointer, mem: AtomMemModel) {. + proc atomicClear*(p: pointer, mem: AtomMemModel) {. importc: "__atomic_clear", nodecl.} ## This built-in function performs an atomic clear operation at p. ## After the operation, at p contains 0. ## ATOMIC_RELAXED, ATOMIC_SEQ_CST, ATOMIC_RELEASE - proc atomic_thread_fence*(mem: AtomMemModel) {. - importc: "__atomic_thread_fence ", nodecl.} + proc atomicThreadFence*(mem: AtomMemModel) {. + importc: "__atomic_thread_fence", nodecl.} ## This built-in function acts as a synchronization fence between threads based ## on the specified memory model. All memory orders are valid. - proc atomic_signal_fence*(mem: AtomMemModel) {. - importc: "__atomic_signal_fence ", nodecl.} + proc atomicSignalFence*(mem: AtomMemModel) {. + importc: "__atomic_signal_fence", nodecl.} ## This built-in function acts as a synchronization fence between a thread and ## signal handlers based in the same thread. All memory orders are valid. - proc atomic_always_lock_free*(size: int, p: pointer): bool {. - importc: "__atomic_always_lock_free ", nodecl.} + proc atomicAlwaysLockFree*(size: int, p: pointer): bool {. + importc: "__atomic_always_lock_free", nodecl.} ## This built-in function returns true if objects of size bytes always generate ## lock free atomic instructions for the target architecture. size must resolve ## to a compile-time constant and the result also resolves to a compile-time constant. @@ -145,8 +143,8 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: ## A value of 0 indicates typical alignment should be used. The compiler may also ## ignore this parameter. - proc atomic_is_lock_free*(size: int, p: pointer): bool {. - importc: "__atomic_is_lock_free ", nodecl.} + proc atomicIsLockFree*(size: int, p: pointer): bool {. + importc: "__atomic_is_lock_free", nodecl.} ## This built-in function returns true if objects of size bytes always generate ## lock free atomic instructions for the target architecture. If it is not known ## to be lock free a call is made to a runtime routine named __atomic_is_lock_free. @@ -154,19 +152,14 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: ## A value of 0 indicates typical alignment should be used. The compiler may also ## ignore this parameter. - - elif defined(vcc) and hasThreadSupport: - proc add_and_fetch*(p: ptr int, val: int): int {. + proc addAndFetch*(p: ptr int, val: int): int {. importc: "NimXadd", nodecl.} else: - proc add_and_fetch*(p: ptr int, val: int): int {.inline.} = + proc addAndFetch*(p: ptr int, val: int): int {.inline.} = inc(p[], val) result = p[] - - - # atomic compare and swap (CAS) funcitons to implement lock-free algorithms #if defined(windows) and not defined(gcc) and hasThreadSupport: @@ -210,6 +203,3 @@ proc atomicDec*(memLoc: var int, x: int = 1): int = else: dec(memLoc, x) result = memLoc - - - diff --git a/lib/system/avltree.nim b/lib/system/avltree.nim index 6a268b453..fc965d6aa 100644 --- a/lib/system/avltree.nim +++ b/lib/system/avltree.nim @@ -9,30 +9,30 @@ # not really an AVL tree anymore, but still balanced ... -template IsBottom(n: PAvlNode): bool = n == bottom +template isBottom(n: PAvlNode): bool = n == bottom proc lowGauge(n: PAvlNode): int = var it = n - while not IsBottom(it): + while not isBottom(it): result = it.key it = it.link[0] proc highGauge(n: PAvlNode): int = result = -1 var it = n - while not IsBottom(it): + while not isBottom(it): result = it.upperBound it = it.link[1] proc find(root: PAvlNode, key: int): PAvlNode = var it = root - while not IsBottom(it): + while not isBottom(it): if it.key == key: return it it = it.link[ord(it.key <% key)] proc inRange(root: PAvlNode, key: int): PAvlNode = var it = root - while not IsBottom(it): + while not isBottom(it): if it.key <=% key and key <% it.upperBound: return it it = it.link[ord(it.key <% key)] diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 7ad814da4..85a24e856 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -43,15 +43,15 @@ type proc contains(s: TCellSeq, c: PCell): bool {.inline.} = for i in 0 .. s.len-1: - if s.d[i] == c: return True - return False + if s.d[i] == c: return true + return false proc add(s: var TCellSeq, c: PCell) {.inline.} = if s.len >= s.cap: s.cap = s.cap * 3 div 2 - var d = cast[PCellArray](Alloc(s.cap * sizeof(PCell))) + var d = cast[PCellArray](alloc(s.cap * sizeof(PCell))) copyMem(d, s.d, s.len * sizeof(PCell)) - Dealloc(s.d) + dealloc(s.d) s.d = d # XXX: realloc? s.d[s.len] = c @@ -60,10 +60,10 @@ proc add(s: var TCellSeq, c: PCell) {.inline.} = proc init(s: var TCellSeq, cap: int = 1024) = s.len = 0 s.cap = cap - s.d = cast[PCellArray](Alloc0(cap * sizeof(PCell))) + s.d = cast[PCellArray](alloc0(cap * sizeof(PCell))) proc deinit(s: var TCellSeq) = - Dealloc(s.d) + dealloc(s.d) s.d = nil s.len = 0 s.cap = 0 @@ -73,20 +73,20 @@ proc deinit(s: var TCellSeq) = const InitCellSetSize = 1024 # must be a power of two! -proc Init(s: var TCellSet) = - s.data = cast[PPageDescArray](Alloc0(InitCellSetSize * sizeof(PPageDesc))) +proc init(s: var TCellSet) = + s.data = cast[PPageDescArray](alloc0(InitCellSetSize * sizeof(PPageDesc))) s.max = InitCellSetSize-1 s.counter = 0 s.head = nil -proc Deinit(s: var TCellSet) = +proc deinit(s: var TCellSet) = var it = s.head while it != nil: var n = it.next - Dealloc(it) + dealloc(it) it = n s.head = nil # play it safe here - Dealloc(s.data) + dealloc(s.data) s.data = nil s.counter = 0 @@ -96,14 +96,14 @@ proc nextTry(h, maxHash: int): int {.inline.} = # generates each int in range(maxHash) exactly once (see any text on # random-number generation for proof). -proc CellSetGet(t: TCellSet, key: TAddress): PPageDesc = +proc cellSetGet(t: TCellSet, key: TAddress): PPageDesc = var h = cast[int](key) and t.max while t.data[h] != nil: if t.data[h].key == key: return t.data[h] h = nextTry(h, t.max) return nil -proc CellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) = +proc cellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) = var h = cast[int](desc.key) and t.max while data[h] != nil: sysAssert(data[h] != desc, "CellSetRawInsert 1") @@ -111,17 +111,17 @@ proc CellSetRawInsert(t: TCellSet, data: PPageDescArray, desc: PPageDesc) = sysAssert(data[h] == nil, "CellSetRawInsert 2") data[h] = desc -proc CellSetEnlarge(t: var TCellSet) = +proc cellSetEnlarge(t: var TCellSet) = var oldMax = t.max t.max = ((t.max+1)*2)-1 - var n = cast[PPageDescArray](Alloc0((t.max + 1) * sizeof(PPageDesc))) + var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc))) for i in 0 .. oldmax: if t.data[i] != nil: - CellSetRawInsert(t, n, t.data[i]) - Dealloc(t.data) + cellSetRawInsert(t, n, t.data[i]) + dealloc(t.data) t.data = n -proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc = +proc cellSetPut(t: var TCellSet, key: TAddress): PPageDesc = var h = cast[int](key) and t.max while true: var x = t.data[h] @@ -130,13 +130,13 @@ proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc = h = nextTry(h, t.max) if ((t.max+1)*2 < t.counter*3) or ((t.max+1)-t.counter < 4): - CellSetEnlarge(t) + cellSetEnlarge(t) inc(t.counter) h = cast[int](key) and t.max while t.data[h] != nil: h = nextTry(h, t.max) sysAssert(t.data[h] == nil, "CellSetPut") # the new page descriptor goes into result - result = cast[PPageDesc](Alloc0(sizeof(TPageDesc))) + result = cast[PPageDesc](alloc0(sizeof(TPageDesc))) result.next = t.head result.key = key t.head = result @@ -146,7 +146,7 @@ proc CellSetPut(t: var TCellSet, key: TAddress): PPageDesc = proc contains(s: TCellSet, cell: PCell): bool = var u = cast[TAddress](cell) - var t = CellSetGet(s, u shr PageShift) + var t = cellSetGet(s, u shr PageShift) if t != nil: u = (u %% PageSize) /% MemAlign result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0 @@ -155,13 +155,13 @@ proc contains(s: TCellSet, cell: PCell): bool = proc incl(s: var TCellSet, cell: PCell) {.noinline.} = var u = cast[TAddress](cell) - var t = CellSetPut(s, u shr PageShift) + var t = cellSetPut(s, u shr PageShift) u = (u %% PageSize) /% MemAlign t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) proc excl(s: var TCellSet, cell: PCell) = var u = cast[TAddress](cell) - var t = CellSetGet(s, u shr PageShift) + var t = cellSetGet(s, u shr PageShift) if t != nil: u = (u %% PageSize) /% MemAlign t.bits[u shr IntShift] = (t.bits[u shr IntShift] and @@ -169,7 +169,7 @@ proc excl(s: var TCellSet, cell: PCell) = proc containsOrIncl(s: var TCellSet, cell: PCell): bool = var u = cast[TAddress](cell) - var t = CellSetGet(s, u shr PageShift) + var t = cellSetGet(s, u shr PageShift) if t != nil: u = (u %% PageSize) /% MemAlign result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0 @@ -177,7 +177,7 @@ proc containsOrIncl(s: var TCellSet, cell: PCell): bool = t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) else: - Incl(s, cell) + incl(s, cell) result = false iterator elements(t: TCellSet): PCell {.inline.} = diff --git a/lib/system/dyncalls.nim b/lib/system/dyncalls.nim index 6a80369b9..65f8cbb09 100644 --- a/lib/system/dyncalls.nim +++ b/lib/system/dyncalls.nim @@ -28,7 +28,7 @@ proc nimLoadLibraryError(path: string) = stdout.rawWrite("\n") quit(1) -proc ProcAddrError(name: cstring) {.noinline.} = +proc procAddrError(name: cstring) {.noinline.} = # carefully written to avoid memory allocation: stdout.rawWrite("could not import: ") stdout.write(name) @@ -83,21 +83,22 @@ elif defined(windows) or defined(dos): type THINSTANCE {.importc: "HINSTANCE".} = pointer - proc FreeLibrary(lib: THINSTANCE) {.importc, header: "", stdcall.} + proc freeLibrary(lib: THINSTANCE) {. + importc: "FreeLibrary", header: "", stdcall.} proc winLoadLibrary(path: cstring): THINSTANCE {. importc: "LoadLibraryA", header: "", stdcall.} - proc GetProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {. + proc getProcAddress(lib: THINSTANCE, name: cstring): TProcAddr {. importc: "GetProcAddress", header: "", stdcall.} proc nimUnloadLibrary(lib: TLibHandle) = - FreeLibrary(cast[THINSTANCE](lib)) + freeLibrary(cast[THINSTANCE](lib)) proc nimLoadLibrary(path: string): TLibHandle = result = cast[TLibHandle](winLoadLibrary(path)) proc nimGetProcAddr(lib: TLibHandle, name: cstring): TProcAddr = - result = GetProcAddress(cast[THINSTANCE](lib), name) - if result == nil: ProcAddrError(name) + result = getProcAddress(cast[THINSTANCE](lib), name) + if result == nil: procAddrError(name) elif defined(mac): # diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 68e8b423d..2daa3eafa 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -151,7 +151,7 @@ template gcTrace(cell, state: expr): stmt {.immediate.} = # forward declarations: proc collectCT(gch: var TGcHeap) -proc IsOnStack*(p: pointer): bool {.noinline.} +proc isOnStack*(p: pointer): bool {.noinline.} proc forAllChildren(cell: PCell, op: TWalkOp) proc doOperation(p: pointer, op: TWalkOp) proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp) @@ -669,7 +669,7 @@ proc doOperation(p: pointer, op: TWalkOp) = proc nimGCvisit(d: pointer, op: int) {.compilerRtl.} = doOperation(d, TWalkOp(op)) -proc CollectZCT(gch: var TGcHeap): bool +proc collectZCT(gch: var TGcHeap): bool when useMarkForDebug or useBackupGc: proc markStackAndRegistersForSweep(gch: var TGcHeap) {.noinline, cdecl.} diff --git a/lib/system/repr.nim b/lib/system/repr.nim index a51864ac2..f0d620952 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -72,7 +72,7 @@ proc reprEnum(e: int, typ: PNimType): string {.compilerRtl.} = result = $e & " (invalid data!)" type - pbyteArray = ptr array[0.. 0xffff, int8] + PByteArray = ptr array[0.. 0xffff, int8] proc addSetElem(result: var string, elem: int, typ: PNimType) = case typ.kind diff --git a/lib/system/syslocks.nim b/lib/system/syslocks.nim index 4d81dee01..0f67af40c 100644 --- a/lib/system/syslocks.nim +++ b/lib/system/syslocks.nim @@ -22,48 +22,48 @@ when defined(Windows): TSysCond = THandle - proc InitSysLock(L: var TSysLock) {.stdcall, noSideEffect, + proc initSysLock(L: var TSysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "InitializeCriticalSection".} ## Initializes the lock `L`. - proc TryAcquireSysAux(L: var TSysLock): int32 {.stdcall, noSideEffect, + proc tryAcquireSysAux(L: var TSysLock): int32 {.stdcall, noSideEffect, dynlib: "kernel32", importc: "TryEnterCriticalSection".} ## Tries to acquire the lock `L`. - proc TryAcquireSys(L: var TSysLock): bool {.inline.} = + proc tryAcquireSys(L: var TSysLock): bool {.inline.} = result = TryAcquireSysAux(L) != 0'i32 - proc AcquireSys(L: var TSysLock) {.stdcall, noSideEffect, + proc acquireSys(L: var TSysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "EnterCriticalSection".} ## Acquires the lock `L`. - proc ReleaseSys(L: var TSysLock) {.stdcall, noSideEffect, + proc releaseSys(L: var TSysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "LeaveCriticalSection".} ## Releases the lock `L`. - proc DeinitSys(L: var TSysLock) {.stdcall, noSideEffect, + proc deinitSys(L: var TSysLock) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "DeleteCriticalSection".} - proc CreateEvent(lpEventAttributes: pointer, + proc createEvent(lpEventAttributes: pointer, bManualReset, bInitialState: int32, lpName: cstring): TSysCond {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CreateEventA".} - proc CloseHandle(hObject: THandle) {.stdcall, noSideEffect, + proc closeHandle(hObject: THandle) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "CloseHandle".} - proc WaitForSingleObject(hHandle: THandle, dwMilliseconds: int32): int32 {. + proc waitForSingleObject(hHandle: THandle, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} - proc SignalSysCond(hEvent: TSysCond) {.stdcall, noSideEffect, + proc signalSysCond(hEvent: TSysCond) {.stdcall, noSideEffect, dynlib: "kernel32", importc: "SetEvent".} - proc InitSysCond(cond: var TSysCond) {.inline.} = - cond = CreateEvent(nil, 0'i32, 0'i32, nil) - proc DeinitSysCond(cond: var TSysCond) {.inline.} = - CloseHandle(cond) - proc WaitSysCond(cond: var TSysCond, lock: var TSysLock) = + proc initSysCond(cond: var TSysCond) {.inline.} = + cond = createEvent(nil, 0'i32, 0'i32, nil) + proc deinitSysCond(cond: var TSysCond) {.inline.} = + closeHandle(cond) + proc waitSysCond(cond: var TSysCond, lock: var TSysLock) = releaseSys(lock) - discard WaitForSingleObject(cond, -1'i32) + discard waitForSingleObject(cond, -1'i32) acquireSys(lock) else: @@ -73,29 +73,29 @@ else: TSysCond {.importc: "pthread_cond_t", pure, final, header: "".} = object - proc InitSysLock(L: var TSysLock, attr: pointer = nil) {. + proc initSysLock(L: var TSysLock, attr: pointer = nil) {. importc: "pthread_mutex_init", header: "", noSideEffect.} - proc AcquireSys(L: var TSysLock) {.noSideEffect, + proc acquireSys(L: var TSysLock) {.noSideEffect, importc: "pthread_mutex_lock", header: "".} - proc TryAcquireSysAux(L: var TSysLock): cint {.noSideEffect, + proc tryAcquireSysAux(L: var TSysLock): cint {.noSideEffect, importc: "pthread_mutex_trylock", header: "".} - proc TryAcquireSys(L: var TSysLock): bool {.inline.} = - result = TryAcquireSysAux(L) == 0'i32 + proc tryAcquireSys(L: var TSysLock): bool {.inline.} = + result = tryAcquireSysAux(L) == 0'i32 - proc ReleaseSys(L: var TSysLock) {.noSideEffect, + proc releaseSys(L: var TSysLock) {.noSideEffect, importc: "pthread_mutex_unlock", header: "".} - proc DeinitSys(L: var TSysLock) {. + proc deinitSys(L: var TSysLock) {. importc: "pthread_mutex_destroy", header: "".} - proc InitSysCond(cond: var TSysCond, cond_attr: pointer = nil) {. + proc initSysCond(cond: var TSysCond, cond_attr: pointer = nil) {. importc: "pthread_cond_init", header: "".} - proc WaitSysCond(cond: var TSysCond, lock: var TSysLock) {. + proc waitSysCond(cond: var TSysCond, lock: var TSysLock) {. importc: "pthread_cond_wait", header: "".} - proc SignalSysCond(cond: var TSysCond) {. + proc signalSysCond(cond: var TSysCond) {. importc: "pthread_cond_signal", header: "".} - proc DeinitSysCond(cond: var TSysCond) {. + proc deinitSysCond(cond: var TSysCond) {. importc: "pthread_cond_destroy", header: "".} diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 264285d09..c2089906a 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -96,25 +96,25 @@ const CREATE_UNICODE_ENVIRONMENT* = 1024'i32 -proc CloseHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc closeHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", importc: "CloseHandle".} -proc ReadFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32, +proc readFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32, lpNumberOfBytesRead: var int32, lpOverlapped: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "ReadFile".} -proc WriteFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: int32, +proc writeFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToWrite: int32, lpNumberOfBytesWritten: var int32, lpOverlapped: pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteFile".} -proc CreatePipe*(hReadPipe, hWritePipe: var THandle, +proc createPipe*(hReadPipe, hWritePipe: var THandle, lpPipeAttributes: var TSECURITY_ATTRIBUTES, nSize: int32): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreatePipe".} when useWinUnicode: - proc CreateProcessW*(lpApplicationName, lpCommandLine: widecstring, + proc createProcessW*(lpApplicationName, lpCommandLine: widecstring, lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, @@ -124,7 +124,7 @@ when useWinUnicode: stdcall, dynlib: "kernel32", importc: "CreateProcessW".} else: - proc CreateProcessA*(lpApplicationName, lpCommandLine: cstring, + proc createProcessA*(lpApplicationName, lpCommandLine: cstring, lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, @@ -134,74 +134,76 @@ else: stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc SuspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc suspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", importc: "SuspendThread".} -proc ResumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc resumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", importc: "ResumeThread".} -proc WaitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {. +proc waitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} -proc TerminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall, +proc terminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} -proc GetExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {. +proc getExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc GetStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32", +proc getStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32", importc: "GetStdHandle".} -proc SetStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall, +proc setStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetStdHandle".} -proc FlushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc flushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", importc: "FlushFileBuffers".} -proc GetLastError*(): int32 {.importc, stdcall, dynlib: "kernel32".} +proc getLastError*(): int32 {.importc: "GetLastError", + stdcall, dynlib: "kernel32".} when useWinUnicode: - proc FormatMessageW*(dwFlags: int32, lpSource: pointer, + proc formatMessageW*(dwFlags: int32, lpSource: pointer, dwMessageId, dwLanguageId: int32, lpBuffer: pointer, nSize: int32, Arguments: pointer): int32 {. - importc, stdcall, dynlib: "kernel32".} + importc: "FormatMessageW", stdcall, dynlib: "kernel32".} else: - proc FormatMessageA*(dwFlags: int32, lpSource: pointer, + proc formatMessageA*(dwFlags: int32, lpSource: pointer, dwMessageId, dwLanguageId: int32, lpBuffer: pointer, nSize: int32, Arguments: pointer): int32 {. - importc, stdcall, dynlib: "kernel32".} + importc: "FormatMessageA", stdcall, dynlib: "kernel32".} -proc LocalFree*(p: pointer) {.importc, stdcall, dynlib: "kernel32".} +proc localFree*(p: pointer) {. + importc: "LocalFree", stdcall, dynlib: "kernel32".} when useWinUnicode: - proc GetCurrentDirectoryW*(nBufferLength: int32, + proc getCurrentDirectoryW*(nBufferLength: int32, lpBuffer: widecstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc SetCurrentDirectoryW*(lpPathName: widecstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc CreateDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {. + importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall.} + proc setCurrentDirectoryW*(lpPathName: widecstring): int32 {. + importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall.} + proc createDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {. importc: "CreateDirectoryW", dynlib: "kernel32", stdcall.} - proc RemoveDirectoryW*(lpPathName: widecstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc SetEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {. - stdcall, dynlib: "kernel32", importc.} + proc removeDirectoryW*(lpPathName: widecstring): int32 {. + importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall.} + proc setEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {. + stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} - proc GetModuleFileNameW*(handle: THandle, buf: wideCString, - size: int32): int32 {.importc, + proc getModuleFileNameW*(handle: THandle, buf: wideCString, + size: int32): int32 {.importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall.} else: - proc GetCurrentDirectoryA*(nBufferLength: int32, lpBuffer: cstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc SetCurrentDirectoryA*(lpPathName: cstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc CreateDirectoryA*(pathName: cstring, security: Pointer=nil): int32 {. + proc getCurrentDirectoryA*(nBufferLength: int32, lpBuffer: cstring): int32 {. + importc: "GetCurrentDirectoryA", dynlib: "kernel32", stdcall.} + proc setCurrentDirectoryA*(lpPathName: cstring): int32 {. + importc: "SetCurrentDirectoryA", dynlib: "kernel32", stdcall.} + proc createDirectoryA*(pathName: cstring, security: Pointer=nil): int32 {. importc: "CreateDirectoryA", dynlib: "kernel32", stdcall.} - proc RemoveDirectoryA*(lpPathName: cstring): int32 {. - importc, dynlib: "kernel32", stdcall.} - proc SetEnvironmentVariableA*(lpName, lpValue: cstring): int32 {. - stdcall, dynlib: "kernel32", importc.} + proc removeDirectoryA*(lpPathName: cstring): int32 {. + importc: "RemoveDirectoryA", dynlib: "kernel32", stdcall.} + proc setEnvironmentVariableA*(lpName, lpValue: cstring): int32 {. + stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableA".} - proc GetModuleFileNameA*(handle: THandle, buf: CString, size: int32): int32 {. - importc, dynlib: "kernel32", stdcall.} + proc getModuleFileNameA*(handle: THandle, buf: CString, size: int32): int32 {. + importc: "GetModuleFileNameA", dynlib: "kernel32", stdcall.} const FILE_ATTRIBUTE_ARCHIVE* = 32'i32 @@ -228,65 +230,71 @@ type cAlternateFileName*: array[0..13, TWinChar] when useWinUnicode: - proc FindFirstFileW*(lpFileName: widecstring, + proc findFirstFileW*(lpFileName: widecstring, lpFindFileData: var TWIN32_FIND_DATA): THANDLE {. stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - proc FindNextFileW*(hFindFile: THANDLE, + proc findNextFileW*(hFindFile: THANDLE, lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileW".} else: - proc FindFirstFileA*(lpFileName: cstring, + proc findFirstFileA*(lpFileName: cstring, lpFindFileData: var TWIN32_FIND_DATA): THANDLE {. stdcall, dynlib: "kernel32", importc: "FindFirstFileA".} - proc FindNextFileA*(hFindFile: THANDLE, + proc findNextFileA*(hFindFile: THANDLE, lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc FindClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32", +proc findClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32", importc: "FindClose".} when useWinUnicode: - proc GetFullPathNameW*(lpFileName: widecstring, nBufferLength: int32, + proc getFullPathNameW*(lpFileName: widecstring, nBufferLength: int32, lpBuffer: widecstring, lpFilePart: var widecstring): int32 {. - stdcall, dynlib: "kernel32", importc.} - proc GetFileAttributesW*(lpFileName: widecstring): int32 {. - stdcall, dynlib: "kernel32", importc.} - proc SetFileAttributesW*(lpFileName: widecstring, + stdcall, dynlib: "kernel32", + importc: "GetFullPathNameW".} + proc getFileAttributesW*(lpFileName: widecstring): int32 {. + stdcall, dynlib: "kernel32", + importc: "GetFileAttributesW".} + proc setFileAttributesW*(lpFileName: widecstring, dwFileAttributes: int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".} - proc CopyFileW*(lpExistingFileName, lpNewFileName: wideCString, + proc copyFileW*(lpExistingFileName, lpNewFileName: wideCString, bFailIfExists: cint): cint {. - importc, stdcall, dynlib: "kernel32".} + importc: "CopyFileW", stdcall, dynlib: "kernel32".} - proc GetEnvironmentStringsW*(): widecstring {. - stdcall, dynlib: "kernel32", importc.} - proc FreeEnvironmentStringsW*(para1: widecstring): int32 {. - stdcall, dynlib: "kernel32", importc.} + proc getEnvironmentStringsW*(): widecstring {. + stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW".} + proc freeEnvironmentStringsW*(para1: widecstring): int32 {. + stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW".} - proc GetCommandLineW*(): wideCString {.importc, stdcall, dynlib: "kernel32".} + proc getCommandLineW*(): wideCString {.importc: "GetCommandLineW", + stdcall, dynlib: "kernel32".} else: - proc GetFullPathNameA*(lpFileName: cstring, nBufferLength: int32, + proc getFullPathNameA*(lpFileName: cstring, nBufferLength: int32, lpBuffer: cstring, lpFilePart: var cstring): int32 {. - stdcall, dynlib: "kernel32", importc.} - proc GetFileAttributesA*(lpFileName: cstring): int32 {. - stdcall, dynlib: "kernel32", importc.} - proc SetFileAttributesA*(lpFileName: cstring, + stdcall, dynlib: "kernel32", + importc: "GetFullPathNameA".} + proc getFileAttributesA*(lpFileName: cstring): int32 {. + stdcall, dynlib: "kernel32", + importc: "GetFileAttributesA".} + proc setFileAttributesA*(lpFileName: cstring, dwFileAttributes: int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "SetFileAttributesA".} - proc CopyFileA*(lpExistingFileName, lpNewFileName: CString, + proc copyFileA*(lpExistingFileName, lpNewFileName: CString, bFailIfExists: cint): cint {. - importc, stdcall, dynlib: "kernel32".} + importc: "CopyFileA", stdcall, dynlib: "kernel32".} - proc GetEnvironmentStringsA*(): cstring {. - stdcall, dynlib: "kernel32", importc.} - proc FreeEnvironmentStringsA*(para1: cstring): int32 {. - stdcall, dynlib: "kernel32", importc.} + proc getEnvironmentStringsA*(): cstring {. + stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsA".} + proc freeEnvironmentStringsA*(para1: cstring): int32 {. + stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsA".} - proc GetCommandLineA*(): CString {.importc, stdcall, dynlib: "kernel32".} + proc getCommandLineA*(): cstring {. + importc: "GetCommandLineA", stdcall, dynlib: "kernel32".} proc rdFileTime*(f: TFILETIME): int64 = result = ze64(f.dwLowDateTime) or (ze64(f.dwHighDateTime) shl 32) @@ -294,25 +302,25 @@ proc rdFileTime*(f: TFILETIME): int64 = proc rdFileSize*(f: TWin32FindData): int64 = result = ze64(f.nFileSizeLow) or (ze64(f.nFileSizeHigh) shl 32) -proc GetSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {. +proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {. importc: "GetSystemTimeAsFileTime", dynlib: "kernel32", stdcall.} -proc Sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32", +proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32", importc: "Sleep".} when useWinUnicode: - proc ShellExecuteW*(HWND: THandle, lpOperation, lpFile, + proc shellExecuteW*(HWND: THandle, lpOperation, lpFile, lpParameters, lpDirectory: widecstring, nShowCmd: int32): THandle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} else: - proc ShellExecuteA*(HWND: THandle, lpOperation, lpFile, + proc shellExecuteA*(HWND: THandle, lpOperation, lpFile, lpParameters, lpDirectory: cstring, nShowCmd: int32): THandle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteA".} -proc GetFileInformationByHandle*(hFile: THandle, +proc getFileInformationByHandle*(hFile: THandle, lpFileInformation: ptr TBY_HANDLE_FILE_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetFileInformationByHandle".} @@ -526,7 +534,7 @@ type TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THANDLE] PWOHandleArray* = ptr TWOHandleArray -proc WaitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray, +proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray, bWaitAll: WINBOOL, dwMilliseconds: DWORD): DWORD{. stdcall, dynlib: "kernel32", importc: "WaitForMultipleObjects".} @@ -558,40 +566,40 @@ const ERROR_ACCESS_DENIED* = 5 when useWinUnicode: - proc CreateFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD, + proc createFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD, lpSecurityAttributes: pointer, dwCreationDisposition, dwFlagsAndAttributes: DWORD, hTemplateFile: THANDLE): THANDLE {. stdcall, dynlib: "kernel32", importc: "CreateFileW".} - proc DeleteFileW*(pathName: widecstring): int32 {. + proc deleteFileW*(pathName: widecstring): int32 {. importc: "DeleteFileW", dynlib: "kernel32", stdcall.} else: - proc CreateFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD, + proc createFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD, lpSecurityAttributes: pointer, dwCreationDisposition, dwFlagsAndAttributes: DWORD, hTemplateFile: THANDLE): THANDLE {. stdcall, dynlib: "kernel32", importc: "CreateFileA".} - proc DeleteFileA*(pathName: cstring): int32 {. + proc deleteFileA*(pathName: cstring): int32 {. importc: "DeleteFileA", dynlib: "kernel32", stdcall.} -proc SetEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc setEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetEndOfFile".} -proc SetFilePointer*(hFile: THANDLE, lDistanceToMove: LONG, +proc setFilePointer*(hFile: THANDLE, lDistanceToMove: LONG, lpDistanceToMoveHigh: ptr LONG, dwMoveMethod: DWORD): DWORD {. stdcall, dynlib: "kernel32", importc: "SetFilePointer".} -proc GetFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, +proc getFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "GetFileSize".} -proc MapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD, +proc mapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD, dwFileOffsetHigh, dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: DWORD, lpBaseAddress: pointer): pointer{. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} -proc CreateFileMappingW*(hFile: THANDLE, +proc createFileMappingW*(hFile: THANDLE, lpFileMappingAttributes: pointer, flProtect, dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, @@ -599,12 +607,12 @@ proc CreateFileMappingW*(hFile: THANDLE, stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} when not useWinUnicode: - proc CreateFileMappingA*(hFile: THANDLE, + proc createFileMappingA*(hFile: THANDLE, lpFileMappingAttributes: pointer, flProtect, dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, lpName: cstring): THANDLE {. stdcall, dynlib: "kernel32", importc: "CreateFileMappingA".} -proc UnmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall, +proc unmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall, dynlib: "kernel32", importc: "UnmapViewOfFile".} diff --git a/todo.txt b/todo.txt index 5aaa15a4d..e70e96f91 100644 --- a/todo.txt +++ b/todo.txt @@ -4,6 +4,8 @@ version 0.9.4 - document new templating symbol binding rules - convert all with "nimrod pretty" - make '--implicitStatic:on' the default +- test&finish first class iterators: + * nested iterators - special rule for ``[]=`` - ``=`` should be overloadable; requires specialization for ``=``; general @@ -11,6 +13,7 @@ version 0.9.4 - built-in 'getImpl' - optimize 'genericReset'; 'newException' leads to code bloat - stack-less GC +- fix eval in macros.nim Bugs @@ -50,8 +53,6 @@ version 0.9.x version 0.9.X ============= -- test&finish first class iterators: - * nested iterators - implement the missing features wrt inheritance - better support for macros that rewrite procs - macros need access to types and symbols (partially implemented) -- cgit 1.4.1-2-gfad0 From 92b8fac94a7243cde785d985db3fd86b6025b079 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 27 Dec 2013 23:10:36 +0100 Subject: case consistency part 4 --- compiler/aliases.nim | 6 +- compiler/ast.nim | 22 +- compiler/astalgo.nim | 58 +- compiler/babelcmd.nim | 6 +- compiler/ccgcalls.nim | 4 +- compiler/ccgexprs.nim | 204 ++-- compiler/ccgmerge.nim | 12 +- compiler/ccgstmts.nim | 54 +- compiler/ccgtrav.nim | 4 +- compiler/ccgtypes.nim | 70 +- compiler/ccgutils.nim | 10 +- compiler/cgen.nim | 68 +- compiler/cgendata.nim | 4 +- compiler/cgmeth.nim | 16 +- compiler/commands.nim | 92 +- compiler/condsyms.nim | 8 +- compiler/crc.nim | 8 +- compiler/depends.nim | 2 +- compiler/docgen.nim | 24 +- compiler/evaltempl.nim | 12 +- compiler/extccomp.nim | 98 +- compiler/filter_tmpl.nim | 106 +- compiler/filters.nim | 28 +- compiler/guards.nim | 6 +- compiler/hlo.nim | 4 +- compiler/idgen.nim | 6 +- compiler/importer.nim | 38 +- compiler/jsgen.nim | 80 +- compiler/jstypes.nim | 8 +- compiler/lambdalifting.nim | 48 +- compiler/lexer.nim | 122 +- compiler/lists.nim | 16 +- compiler/llstream.nim | 26 +- compiler/lookups.nim | 14 +- compiler/magicsys.nim | 14 +- compiler/main.nim | 104 +- compiler/modules.nim | 22 +- compiler/msgs.nim | 32 +- compiler/nimconf.nim | 14 +- compiler/nimlexbase.nim | 14 +- compiler/nimrod.nim | 2 +- compiler/nimsets.nim | 24 +- compiler/options.nim | 14 +- compiler/parampatterns.nim | 4 +- compiler/parser.nim | 14 +- compiler/passaux.nim | 6 +- compiler/passes.nim | 8 +- compiler/patterns.nim | 12 +- compiler/platform.nim | 8 +- compiler/pragmas.nim | 132 +-- compiler/pretty.nim | 4 +- compiler/procfind.nim | 10 +- compiler/renderer.nim | 20 +- compiler/rodread.nim | 108 +- compiler/rodutils.nim | 2 +- compiler/rodwrite.nim | 52 +- compiler/ropes.nim | 14 +- compiler/saturate.nim | 12 +- compiler/sem.nim | 30 +- compiler/semcall.nim | 10 +- compiler/semdata.nim | 10 +- compiler/semdestruct.nim | 10 +- compiler/semexprs.nim | 178 +-- compiler/semfold.nim | 58 +- compiler/semgnrc.nim | 18 +- compiler/seminst.nim | 32 +- compiler/semmagic.nim | 14 +- compiler/sempass2.nim | 18 +- compiler/semstmts.nim | 152 +-- compiler/semtempl.nim | 54 +- compiler/semthreads.nim | 36 +- compiler/semtypes.nim | 140 +-- compiler/semtypinst.nim | 48 +- compiler/service.nim | 8 +- compiler/sigmatch.nim | 50 +- compiler/suggest.nim | 34 +- compiler/syntaxes.nim | 28 +- compiler/transf.nim | 26 +- compiler/treetab.nim | 2 +- compiler/types.nim | 94 +- compiler/vm.nim | 22 +- compiler/vmdeps.nim | 4 +- compiler/vmgen.nim | 24 +- compiler/wordrecg.nim | 4 +- lib/packages/docutils/highlite.nim | 6 +- lib/packages/docutils/rst.nim | 168 +-- lib/packages/docutils/rstast.nim | 24 +- lib/packages/docutils/rstgen.nim | 48 +- lib/pure/algorithm.nim | 4 +- lib/pure/collections/intsets.nim | 14 +- lib/pure/collections/sequtils.nim | 2 +- lib/pure/collections/tables.nim | 6 +- lib/pure/hashes.nim | 12 +- lib/pure/json.nim | 40 +- lib/pure/lexbase.nim | 4 +- lib/pure/math.nim | 8 +- lib/pure/memfiles.nim | 38 +- lib/pure/os.nim | 56 +- lib/pure/osproc.nim | 84 +- lib/pure/parseopt.nim | 6 +- lib/pure/parseutils.nim | 14 +- lib/pure/sockets.nim | 108 +- lib/pure/streams.nim | 4 +- lib/pure/strtabs.nim | 16 +- lib/pure/strutils.nim | 2212 ++++++++++++++++++------------------ lib/pure/times.nim | 16 +- lib/pure/unicode.nim | 40 +- lib/system.nim | 74 +- lib/system/alloc.nim | 46 +- lib/system/ansi_c.nim | 14 +- lib/system/assign.nim | 34 +- lib/system/cellsets.nim | 4 +- lib/system/chcks.nim | 2 +- lib/system/excpt.nim | 4 +- lib/system/gc.nim | 26 +- lib/system/hti.nim | 2 +- lib/system/mmdisp.nim | 2 +- lib/system/repr.nim | 28 +- lib/system/sysio.nim | 12 +- lib/system/sysstr.nim | 16 +- lib/system/widestrs.nim | 296 ++--- lib/windows/winlean.nim | 120 +- 122 files changed, 3322 insertions(+), 3322 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/aliases.nim b/compiler/aliases.nim index 7accb8ce3..5be7b5f12 100644 --- a/compiler/aliases.nim +++ b/compiler/aliases.nim @@ -42,7 +42,7 @@ proc isPartOfAux(n: PNode, b: PType, marker: var TIntSet): TAnalysisResult = proc isPartOfAux(a, b: PType, marker: var TIntSet): TAnalysisResult = result = arNo if a == nil or b == nil: return - if ContainsOrIncl(marker, a.id): return + if containsOrIncl(marker, a.id): return if compareTypes(a, b, dcEqIgnoreDistinct): return arYes case a.kind of tyObject: @@ -58,7 +58,7 @@ proc isPartOfAux(a, b: PType, marker: var TIntSet): TAnalysisResult = proc isPartOf(a, b: PType): TAnalysisResult = ## checks iff 'a' can be part of 'b'. Iterates over VALUE types! - var marker = InitIntSet() + var marker = initIntSet() # watch out: parameters reversed because I'm too lazy to change the code... result = isPartOfAux(b, a, marker) @@ -115,7 +115,7 @@ proc isPartOf*(a, b: PNode): TAnalysisResult = var x = if a[1].kind == nkHiddenStdConv: a[1][1] else: a[1] var y = if b[1].kind == nkHiddenStdConv: b[1][1] else: b[1] - if SameValue(x, y): result = arYes + if sameValue(x, y): result = arYes else: result = arNo # else: maybe and no are accurate else: diff --git a/compiler/ast.nim b/compiler/ast.nim index a511e08ce..292283daf 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -548,9 +548,9 @@ type flags*: TNodeFlags case Kind*: TNodeKind of nkCharLit..nkUInt64Lit: - intVal*: biggestInt + intVal*: BiggestInt of nkFloatLit..nkFloat128Lit: - floatVal*: biggestFloat + floatVal*: BiggestFloat of nkStrLit..nkTripleStrLit: strVal*: string of nkSym: @@ -911,7 +911,7 @@ template fileIdx*(c: PSym): int32 = template filename*(c: PSym): string = # XXX: this should be used only on module symbols - c.position.int32.toFileName + c.position.int32.toFilename proc appendToModule*(m: PSym, n: PNode) = ## The compiler will use this internally to add nodes that will be @@ -930,7 +930,7 @@ const # for all kind of hash tables: proc copyStrTable(dest: var TStrTable, src: TStrTable) = dest.counter = src.counter if isNil(src.data): return - setlen(dest.data, len(src.data)) + setLen(dest.data, len(src.data)) for i in countup(0, high(src.data)): dest.data[i] = src.data[i] proc copyIdTable(dest: var TIdTable, src: TIdTable) = @@ -942,13 +942,13 @@ proc copyIdTable(dest: var TIdTable, src: TIdTable) = proc copyTable(dest: var TTable, src: TTable) = dest.counter = src.counter if isNil(src.data): return - setlen(dest.data, len(src.data)) + setLen(dest.data, len(src.data)) for i in countup(0, high(src.data)): dest.data[i] = src.data[i] proc copyObjectSet(dest: var TObjectSet, src: TObjectSet) = dest.counter = src.counter if isNil(src.data): return - setlen(dest.data, len(src.data)) + setLen(dest.data, len(src.data)) for i in countup(0, high(src.data)): dest.data[i] = src.data[i] proc discardSons(father: PNode) = @@ -1204,7 +1204,7 @@ proc newSons(father: PType, length: int) = if isNil(father.sons): newSeq(father.sons, length) else: - setlen(father.sons, length) + setLen(father.sons, length) proc sonsLen(n: PNode): int = if isNil(n.sons): result = 0 @@ -1214,7 +1214,7 @@ proc newSons(father: PNode, length: int) = if isNil(father.sons): newSeq(father.sons, length) else: - setlen(father.sons, length) + setLen(father.sons, length) proc propagateToOwner*(owner, elem: PType) = const HaveTheirOwnEmpty = {tySequence, tySet} @@ -1257,7 +1257,7 @@ proc delSon(father: PNode, idx: int) = if isNil(father.sons): return var length = sonsLen(father) for i in countup(idx, length - 2): father.sons[i] = father.sons[i + 1] - setlen(father.sons, length - 1) + setLen(father.sons, length - 1) proc copyNode(src: PNode): PNode = # does not copy its sons! @@ -1365,14 +1365,14 @@ proc sonsNotNil(n: PNode): bool = return false result = true -proc getInt*(a: PNode): biggestInt = +proc getInt*(a: PNode): BiggestInt = case a.kind of nkIntLit..nkUInt64Lit: result = a.intVal else: internalError(a.info, "getInt") result = 0 -proc getFloat*(a: PNode): biggestFloat = +proc getFloat*(a: PNode): BiggestFloat = case a.kind of nkFloatLit..nkFloat128Lit: result = a.floatVal else: diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index b04cff598..83218b31d 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -165,7 +165,7 @@ proc lookupInRecord(n: PNode, field: PIdent): PSym = result = lookupInRecord(n.sons[i], field) if result != nil: return of nkRecCase: - if (n.sons[0].kind != nkSym): InternalError(n.info, "lookupInRecord") + if (n.sons[0].kind != nkSym): internalError(n.info, "lookupInRecord") result = lookupInRecord(n.sons[0], field) if result != nil: return for i in countup(1, sonsLen(n) - 1): @@ -202,7 +202,7 @@ proc spaces(x: int): PRope = # returns x spaces result = toRope(repeatChar(x)) -proc toYamlChar(c: Char): string = +proc toYamlChar(c: char): string = case c of '\0'..'\x1F', '\x80'..'\xFF': result = "\\u" & strutils.toHex(ord(c), 4) of '\'', '\"', '\\': result = '\\' & c @@ -261,7 +261,7 @@ proc strTableToYaml(n: TStrTable, marker: var TIntSet, indent: int, app(result, "]") assert(mycount == n.counter) -proc ropeConstr(indent: int, c: openarray[PRope]): PRope = +proc ropeConstr(indent: int, c: openArray[PRope]): PRope = # array of (name, value) pairs var istr = spaces(indent + 2) result = toRope("{") @@ -276,7 +276,7 @@ proc symToYamlAux(n: PSym, marker: var TIntSet, indent: int, maxRecDepth: int): PRope = if n == nil: result = toRope("null") - elif ContainsOrIncl(marker, n.id): + elif containsOrIncl(marker, n.id): result = ropef("\"$1 @$2\"", [toRope(n.name.s), toRope( strutils.toHex(cast[TAddress](n), sizeof(n) * 2))]) else: @@ -297,7 +297,7 @@ proc typeToYamlAux(n: PType, marker: var TIntSet, indent: int, maxRecDepth: int): PRope = if n == nil: result = toRope("null") - elif ContainsOrIncl(marker, n.id): + elif containsOrIncl(marker, n.id): result = ropef("\"$1 @$2\"", [toRope($n.kind), toRope( strutils.toHex(cast[TAddress](n), sizeof(n) * 2))]) else: @@ -314,7 +314,7 @@ proc typeToYamlAux(n: PType, marker: var TIntSet, indent: int, makeYamlString($n.kind), toRope("sym"), symToYamlAux(n.sym, marker, indent + 2, maxRecDepth - 1), toRope("n"), treeToYamlAux(n.n, marker, - indent + 2, maxRecDepth - 1), toRope("flags"), FlagsToStr(n.flags), + indent + 2, maxRecDepth - 1), toRope("flags"), flagsToStr(n.flags), toRope("callconv"), makeYamlString(CallingConvToStr[n.callConv]), toRope("size"), toRope(n.size), @@ -335,7 +335,7 @@ proc treeToYamlAux(n: PNode, marker: var TIntSet, indent: int, appf(result, ",$N$1\"intVal\": $2", [istr, toRope(n.intVal)]) of nkFloatLit, nkFloat32Lit, nkFloat64Lit: appf(result, ",$N$1\"floatVal\": $2", - [istr, toRope(n.floatVal.ToStrMaxPrecision)]) + [istr, toRope(n.floatVal.toStrMaxPrecision)]) of nkStrLit..nkTripleStrLit: appf(result, ",$N$1\"strVal\": $2", [istr, makeYamlString(n.strVal)]) of nkSym: @@ -359,15 +359,15 @@ proc treeToYamlAux(n: PNode, marker: var TIntSet, indent: int, appf(result, "$N$1}", [spaces(indent)]) proc treeToYaml(n: PNode, indent: int = 0, maxRecDepth: int = - 1): PRope = - var marker = InitIntSet() + var marker = initIntSet() result = treeToYamlAux(n, marker, indent, maxRecDepth) proc typeToYaml(n: PType, indent: int = 0, maxRecDepth: int = - 1): PRope = - var marker = InitIntSet() + var marker = initIntSet() result = typeToYamlAux(n, marker, indent, maxRecDepth) proc symToYaml(n: PSym, indent: int = 0, maxRecDepth: int = - 1): PRope = - var marker = InitIntSet() + var marker = initIntSet() result = symToYamlAux(n, marker, indent, maxRecDepth) proc debugTree(n: PNode, indent: int, maxRecDepth: int): PRope @@ -405,7 +405,7 @@ proc debugTree(n: PNode, indent: int, maxRecDepth: int): PRope = appf(result, ",$N$1\"intVal\": $2", [istr, toRope(n.intVal)]) of nkFloatLit, nkFloat32Lit, nkFloat64Lit: appf(result, ",$N$1\"floatVal\": $2", - [istr, toRope(n.floatVal.ToStrMaxPrecision)]) + [istr, toRope(n.floatVal.toStrMaxPrecision)]) of nkStrLit..nkTripleStrLit: appf(result, ",$N$1\"strVal\": $2", [istr, makeYamlString(n.strVal)]) of nkSym: @@ -463,7 +463,7 @@ proc objectSetContains(t: TObjectSet, obj: PObject): bool = result = false proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) = - var h: THash = HashNode(obj) and high(data) + var h: THash = hashNode(obj) and high(data) while data[h] != nil: assert(data[h] != obj) h = nextTry(h, high(data)) @@ -484,7 +484,7 @@ proc objectSetIncl(t: var TObjectSet, obj: PObject) = proc objectSetContainsOrIncl(t: var TObjectSet, obj: PObject): bool = # returns true if obj is already in the string table: - var h: THash = HashNode(obj) and high(t.data) + var h: THash = hashNode(obj) and high(t.data) while true: var it = t.data[h] if it == nil: break @@ -541,7 +541,7 @@ proc tableEnlarge(t: var TTable) = swap(t.data, n) proc tablePut(t: var TTable, key, val: PObject) = - var index = TableRawGet(t, key) + var index = tableRawGet(t, key) if index >= 0: t.data[index].val = val else: @@ -585,12 +585,12 @@ proc strTableEnlarge(t: var TStrTable) = var n: TSymSeq newSeq(n, len(t.data) * growthFactor) 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) proc strTableAdd(t: var TStrTable, n: PSym) = - if mustRehash(len(t.data), t.counter): StrTableEnlarge(t) - StrTableRawInsert(t.data, n) + if mustRehash(len(t.data), t.counter): strTableEnlarge(t) + strTableRawInsert(t.data, n) inc(t.counter) proc strTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = @@ -607,8 +607,8 @@ proc strTableIncl*(t: var TStrTable, n: PSym): bool {.discardable.} = return true # found it h = nextTry(h, high(t.data)) if mustRehash(len(t.data), t.counter): - StrTableEnlarge(t) - StrTableRawInsert(t.data, n) + strTableEnlarge(t) + strTableRawInsert(t.data, n) else: assert(t.data[h] == nil) t.data[h] = n @@ -627,7 +627,7 @@ proc initIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym = ti.h = s.h ti.name = s if tab.Counter == 0: result = nil - else: result = NextIdentIter(ti, tab) + else: result = nextIdentIter(ti, tab) proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = var h, start: THash @@ -649,7 +649,7 @@ proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, var start = h result = tab.data[h] while result != nil: - if result.Name.id == ti.name.id and not Contains(excluding, result.id): + if result.Name.id == ti.name.id and not contains(excluding, result.id): break h = nextTry(h, high(tab.data)) if h == start: @@ -657,21 +657,21 @@ proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, break result = tab.data[h] ti.h = nextTry(h, high(tab.data)) - if result != nil and Contains(excluding, result.id): result = nil + if result != nil and contains(excluding, result.id): result = nil proc firstIdentExcluding*(ti: var TIdentIter, tab: TStrTable, s: PIdent, excluding: TIntSet): PSym = ti.h = s.h ti.name = s if tab.Counter == 0: result = nil - else: result = NextIdentExcluding(ti, tab, excluding) + else: result = nextIdentExcluding(ti, tab, excluding) proc initTabIter(ti: var TTabIter, tab: TStrTable): PSym = ti.h = 0 # we start by zero ... if tab.counter == 0: result = nil # FIX 1: removed endless loop else: - result = NextIter(ti, tab) + result = nextIter(ti, tab) proc nextIter(ti: var TTabIter, tab: TStrTable): PSym = result = nil @@ -736,7 +736,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) = var index: int n: TIdPairSeq - index = IdTableRawGet(t, key.id) + index = idTableRawGet(t, key.id) if index >= 0: assert(t.data[index].key != nil) t.data[index].val = val @@ -745,10 +745,10 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) = newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): 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) assert(hasEmptySlot(n)) swap(t.data, n) - IdTableRawInsert(t.data, key, val) + idTableRawInsert(t.data, key, val) inc(t.counter) iterator idTablePairs*(t: TIdTable): tuple[key: PIdObj, val: PObject] = @@ -785,7 +785,7 @@ proc idNodeTableRawInsert(data: var TIdNodePairSeq, key: PIdObj, val: PNode) = data[h].val = val proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) = - var index = IdNodeTableRawGet(t, key) + var index = idNodeTableRawGet(t, key) if index >= 0: assert(t.data[index].key != nil) t.data[index].val = val @@ -837,7 +837,7 @@ proc iiTableRawInsert(data: var TIIPairSeq, key, val: int) = data[h].val = val proc iiTablePut(t: var TIITable, key, val: int) = - var index = IITableRawGet(t, key) + var index = iiTableRawGet(t, key) if index >= 0: assert(t.data[index].key != InvalidKey) t.data[index].val = val diff --git a/compiler/babelcmd.nim b/compiler/babelcmd.nim index b67a26040..65a2fe545 100644 --- a/compiler/babelcmd.nim +++ b/compiler/babelcmd.nim @@ -45,9 +45,9 @@ proc `<.`(a, b: string): bool = proc addPackage(packages: PStringTable, p: string) = let x = versionSplitPos(p) - let name = p.subStr(0, x-1) + let name = p.substr(0, x-1) if x < p.len: - let version = p.subStr(x+1) + let version = p.substr(x+1) if packages[name] <. version: packages[name] = version else: @@ -60,7 +60,7 @@ iterator chosen(packages: PStringTable): string = proc addBabelPath(p: string, info: TLineInfo) = if not contains(options.searchPaths, p): - if gVerbosity >= 1: Message(info, hintPath, p) + if gVerbosity >= 1: message(info, hintPath, p) lists.PrependStr(options.lazyPaths, p) proc addPathWithNimFiles(p: string, info: TLineInfo) = diff --git a/compiler/ccgcalls.nim b/compiler/ccgcalls.nim index 07fba95a3..ec1250155 100644 --- a/compiler/ccgcalls.nim +++ b/compiler/ccgcalls.nim @@ -88,7 +88,7 @@ proc openArrayLoc(p: BProc, n: PNode): PRope = result = ropef("$1->data, $1->$2", [a.rdLoc, lenField()]) of tyArray, tyArrayConstr: result = ropef("$1, $2", [rdLoc(a), toRope(lengthOrd(a.t))]) - else: InternalError("openArrayLoc: " & typeToString(a.t)) + else: internalError("openArrayLoc: " & typeToString(a.t)) proc genArgStringToCString(p: BProc, n: PNode): PRope {.inline.} = @@ -243,7 +243,7 @@ proc genNamedParamCall(p: BProc, ri: PNode, d: var TLoc) = for i in countup(3, length-1): assert(sonsLen(typ) == sonsLen(typ.n)) if i >= sonsLen(typ): - InternalError(ri.info, "varargs for objective C method?") + internalError(ri.info, "varargs for objective C method?") assert(typ.n.sons[i].kind == nkSym) var param = typ.n.sons[i].sym app(pl, ~" ") diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index a9097a264..b10d306a7 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -22,7 +22,7 @@ proc intLiteral(i: biggestInt): PRope = else: result = ~"(IL64(-9223372036854775807) - IL64(1))" -proc int32Literal(i: Int): PRope = +proc int32Literal(i: int): PRope = if i == int(low(int32)): result = ~"(-2147483647 -1)" else: @@ -39,7 +39,7 @@ proc getStrLit(m: BModule, s: string): PRope = discard cgsym(m, "TGenericSeq") result = con("TMP", toRope(backendId())) appf(m.s[cfsData], "STRING_LITERAL($1, $2, $3);$n", - [result, makeCString(s), ToRope(len(s))]) + [result, makeCString(s), toRope(len(s))]) proc genLiteral(p: BProc, n: PNode, ty: PType): PRope = if ty == nil: internalError(n.info, "genLiteral: ty is nil") @@ -62,7 +62,7 @@ proc genLiteral(p: BProc, n: PNode, ty: PType): PRope = of nkNilLit: let t = skipTypes(ty, abstractVarRange) if t.kind == tyProc and t.callConv == ccClosure: - var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId) + var id = nodeTableTestOrSet(p.module.dataCache, n, gBackendId) result = con("TMP", toRope(id)) if id == gBackendId: # not found in cache: @@ -74,7 +74,7 @@ proc genLiteral(p: BProc, n: PNode, ty: PType): PRope = result = toRope("NIM_NIL") of nkStrLit..nkTripleStrLit: if skipTypes(ty, abstractVarRange).kind == tyString: - var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId) + var id = nodeTableTestOrSet(p.module.dataCache, n, gBackendId) if id == gBackendId: # string literal not found in the cache: result = ropecg(p.module, "((#NimStringDesc*) &$1)", @@ -84,9 +84,9 @@ proc genLiteral(p: BProc, n: PNode, ty: PType): PRope = else: result = makeCString(n.strVal) of nkFloatLit..nkFloat64Lit: - result = toRope(n.floatVal.ToStrMaxPrecision) + result = toRope(n.floatVal.toStrMaxPrecision) else: - InternalError(n.info, "genLiteral(" & $n.kind & ')') + internalError(n.info, "genLiteral(" & $n.kind & ')') result = nil proc genLiteral(p: BProc, n: PNode): PRope = @@ -96,7 +96,7 @@ proc bitSetToWord(s: TBitSet, size: int): BiggestInt = result = 0 when true: for j in countup(0, size - 1): - if j < len(s): result = result or `shl`(Ze64(s[j]), j * 8) + if j < len(s): result = result or `shl`(ze64(s[j]), j * 8) else: # not needed, too complex thinking: if CPU[platform.hostCPU].endian == CPU[targetCPU].endian: @@ -117,7 +117,7 @@ proc genRawSetData(cs: TBitSet, size: int): PRope = else: frmt = "0x$1, " else: frmt = "0x$1}$n" - appf(result, frmt, [toRope(toHex(Ze64(cs[i]), 2))]) + appf(result, frmt, [toRope(toHex(ze64(cs[i]), 2))]) else: result = intLiteral(bitSetToWord(cs, size)) # result := toRope('0x' + ToHex(bitSetToWord(cs, size), size * 2)) @@ -127,7 +127,7 @@ proc genSetNode(p: BProc, n: PNode): PRope = var size = int(getSize(n.typ)) toBitSet(n, cs) if size > 8: - var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId) + var id = nodeTableTestOrSet(p.module.dataCache, n, gBackendId) result = con("TMP", toRope(id)) if id == gBackendId: # not found in cache: @@ -155,7 +155,7 @@ proc getStorageLoc(n: PNode): TStorageLoc = of tyVar: result = OnUnknown of tyPtr: result = OnStack of tyRef: result = OnHeap - else: InternalError(n.info, "getStorageLoc") + else: internalError(n.info, "getStorageLoc") of nkBracketExpr, nkDotExpr, nkObjDownConv, nkObjUpConv: result = getStorageLoc(n.sons[0]) else: result = OnUnknown @@ -343,7 +343,7 @@ proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) = of tyPtr, tyPointer, tyChar, tyBool, tyEnum, tyCString, tyInt..tyUInt64, tyRange, tyVar: linefmt(p, cpsStmts, "$1 = $2;$n", rdLoc(dest), rdLoc(src)) - else: InternalError("genAssignment(" & $ty.kind & ')') + else: internalError("genAssignment(" & $ty.kind & ')') proc getDestLoc(p: BProc, d: var TLoc, typ: PType) = if d.k == locNone: getTemp(p, typ, d) @@ -373,48 +373,48 @@ proc putIntoDest(p: BProc, d: var TLoc, t: PType, r: PRope) = proc binaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a, b: TLoc - if d.k != locNone: InternalError(e.info, "binaryStmt") - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + if d.k != locNone: internalError(e.info, "binaryStmt") + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) lineCg(p, cpsStmts, frmt, rdLoc(a), rdLoc(b)) proc unaryStmt(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a: TLoc - if d.k != locNone: InternalError(e.info, "unaryStmt") - InitLocExpr(p, e.sons[1], a) + if d.k != locNone: internalError(e.info, "unaryStmt") + initLocExpr(p, e.sons[1], a) lineCg(p, cpsStmts, frmt, [rdLoc(a)]) proc binaryStmtChar(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a, b: TLoc - if (d.k != locNone): InternalError(e.info, "binaryStmtChar") - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + if (d.k != locNone): internalError(e.info, "binaryStmtChar") + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) lineCg(p, cpsStmts, frmt, [rdCharLoc(a), rdCharLoc(b)]) proc binaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a, b: TLoc assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a), rdLoc(b)])) proc binaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a, b: TLoc assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [a.rdCharLoc, b.rdCharLoc])) proc unaryExpr(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a: TLoc - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdLoc(a)])) proc unaryExprChar(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a: TLoc - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) putIntoDest(p, d, e.typ, ropecg(p.module, frmt, [rdCharLoc(a)])) proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = @@ -427,8 +427,8 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = var a, b: TLoc assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) var t = skipTypes(e.typ, abstractRange) if optOverflowCheck notin p.options: putIntoDest(p, d, e.typ, ropef("(NI$4)($2 $1 $3)", [toRope(opr[m]), @@ -460,7 +460,7 @@ proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = a: TLoc t: PType assert(e.sons[1].typ != nil) - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) t = skipTypes(e.typ, abstractRange) if optOverflowCheck in p.options: linefmt(p, cpsStmts, "if ($1 == $2) #raiseOverflow();$n", @@ -526,11 +526,11 @@ proc binaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) = "($1 != $2)"] # Xor var a, b: TLoc - s: biggestInt + s: BiggestInt assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) # BUGFIX: cannot use result-type here, as it may be a boolean s = max(getSize(a.t), getSize(b.t)) * 8 putIntoDest(p, d, e.typ, @@ -541,8 +541,8 @@ proc genEqProc(p: BProc, e: PNode, d: var TLoc) = var a, b: TLoc assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) if a.t.callConv == ccClosure: putIntoDest(p, d, e.typ, ropef("($1.ClPrc == $2.ClPrc && $1.ClEnv == $2.ClEnv)", [ @@ -585,7 +585,7 @@ proc unaryArith(p: BProc, e: PNode, d: var TLoc, op: TMagic) = a: TLoc t: PType assert(e.sons[1].typ != nil) - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) t = skipTypes(e.typ, abstractRange) putIntoDest(p, d, e.typ, ropef(unArithTab[op], [rdLoc(a), toRope(getSize(t) * 8), @@ -606,21 +606,21 @@ proc genDeref(p: BProc, e: PNode, d: var TLoc) = d.s = OnUnknown of tyPtr: d.s = OnUnknown # BUGFIX! - else: InternalError(e.info, "genDeref " & $a.t.kind) + else: internalError(e.info, "genDeref " & $a.t.kind) putIntoDest(p, d, a.t.sons[0], ropef("(*$1)", [rdLoc(a)])) proc genAddr(p: BProc, e: PNode, d: var TLoc) = # careful 'addr(myptrToArray)' needs to get the ampersand: if e.sons[0].typ.skipTypes(abstractInst).kind in {tyRef, tyPtr}: var a: TLoc - InitLocExpr(p, e.sons[0], a) + initLocExpr(p, e.sons[0], a) putIntoDest(p, d, e.typ, con("&", a.r)) #Message(e.info, warnUser, "HERE NEW &") elif mapType(e.sons[0].typ) == ctArray: expr(p, e.sons[0], d) else: var a: TLoc - InitLocExpr(p, e.sons[0], a) + initLocExpr(p, e.sons[0], a) putIntoDest(p, d, e.typ, addrLoc(a)) template inheritLocation(d: var TLoc, a: TLoc) = @@ -630,7 +630,7 @@ template inheritLocation(d: var TLoc, a: TLoc) = proc genRecordFieldAux(p: BProc, e: PNode, d, a: var TLoc): PType = initLocExpr(p, e.sons[0], a) - if e.sons[1].kind != nkSym: InternalError(e.info, "genRecordFieldAux") + if e.sons[1].kind != nkSym: internalError(e.info, "genRecordFieldAux") d.inheritLocation(a) discard getTypeDesc(p.module, a.t) # fill the record's fields.loc result = a.t @@ -664,13 +664,13 @@ proc genRecordField(p: BProc, e: PNode, d: var TLoc) = var field: PSym = nil while ty != nil: if ty.kind notin {tyTuple, tyObject}: - InternalError(e.info, "genRecordField") + internalError(e.info, "genRecordField") field = lookupInRecord(ty.n, f.name) if field != nil: break if gCmd != cmdCompileToCpp: app(r, ".Sup") - ty = GetUniqueType(ty.sons[0]) - if field == nil: InternalError(e.info, "genRecordField 2 ") - if field.loc.r == nil: InternalError(e.info, "genRecordField 3") + ty = getUniqueType(ty.sons[0]) + if field == nil: internalError(e.info, "genRecordField 2 ") + if field.loc.r == nil: internalError(e.info, "genRecordField 3") appf(r, ".$1", [field.loc.r]) putIntoDest(p, d, field.typ, r) @@ -686,11 +686,11 @@ proc genFieldCheck(p: BProc, e: PNode, obj: PRope, field: PSym) = if op.magic == mNot: it = it.sons[1] assert(it.sons[2].kind == nkSym) initLoc(test, locNone, it.typ, OnStack) - InitLocExpr(p, it.sons[1], u) + initLocExpr(p, it.sons[1], u) initLoc(v, locExpr, it.sons[2].typ, OnUnknown) v.r = ropef("$1.$2", [obj, it.sons[2].sym.loc.r]) genInExprAux(p, it, u, v, test) - let id = NodeTableTestOrSet(p.module.dataCache, + let id = nodeTableTestOrSet(p.module.dataCache, newStrNode(nkStrLit, field.name.s), gBackendId) let strLit = if id == gBackendId: getStrLit(p.module, field.name.s) else: con("TMP", toRope(id)) @@ -720,9 +720,9 @@ proc genCheckedRecordField(p: BProc, e: PNode, d: var TLoc) = if field != nil: break if gCmd != cmdCompileToCpp: app(r, ".Sup") ty = getUniqueType(ty.sons[0]) - if field == nil: InternalError(e.info, "genCheckedRecordField") + if field == nil: internalError(e.info, "genCheckedRecordField") if field.loc.r == nil: - InternalError(e.info, "genCheckedRecordField") # generate the checks: + internalError(e.info, "genCheckedRecordField") # generate the checks: genFieldCheck(p, e, r, field) app(r, rfmt(nil, ".$1", field.loc.r)) putIntoDest(p, d, field.typ, r) @@ -774,7 +774,7 @@ proc genOpenArrayElem(p: BProc, e: PNode, d: var TLoc) = putIntoDest(p, d, elemType(skipTypes(a.t, abstractVar)), rfmt(nil, "$1[$2]", rdLoc(a), rdCharLoc(b))) -proc genSeqElem(p: BPRoc, e: PNode, d: var TLoc) = +proc genSeqElem(p: BProc, e: PNode, d: var TLoc) = var a, b: TLoc initLocExpr(p, e.sons[0], a) initLocExpr(p, e.sons[1], b) @@ -873,11 +873,11 @@ proc genStrConcat(p: BProc, e: PNode, d: var TLoc) = # compute the length expression: initLocExpr(p, e.sons[i + 1], a) if skipTypes(e.sons[i + 1].Typ, abstractVarRange).kind == tyChar: - Inc(L) + inc(L) app(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a))) else: if e.sons[i + 1].kind in {nkStrLit..nkTripleStrLit}: - Inc(L, len(e.sons[i + 1].strVal)) + inc(L, len(e.sons[i + 1].strVal)) else: appf(lens, "$1->$2 + ", [rdLoc(a), lenField()]) app(appends, rfmt(p.module, "#appendString($1, $2);$n", tmp.r, rdLoc(a))) @@ -911,12 +911,12 @@ proc genStrAppend(p: BProc, e: PNode, d: var TLoc) = # compute the length expression: initLocExpr(p, e.sons[i + 2], a) if skipTypes(e.sons[i + 2].Typ, abstractVarRange).kind == tyChar: - Inc(L) + inc(L) app(appends, rfmt(p.module, "#appendChar($1, $2);$n", rdLoc(dest), rdLoc(a))) else: if e.sons[i + 2].kind in {nkStrLit..nkTripleStrLit}: - Inc(L, len(e.sons[i + 2].strVal)) + inc(L, len(e.sons[i + 2].strVal)) else: appf(lens, "$1->$2 + ", [rdLoc(a), lenField()]) app(appends, rfmt(p.module, "#appendString($1, $2);$n", @@ -935,8 +935,8 @@ proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) = else: "$1 = ($2) #incrSeq($1, sizeof($3));$n" var a, b, dest: TLoc - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) lineCg(p, cpsStmts, seqAppendPattern, [ rdLoc(a), getTypeDesc(p.module, skipTypes(e.sons[1].typ, abstractVar)), @@ -948,7 +948,7 @@ proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) = proc genReset(p: BProc, n: PNode) = var a: TLoc - InitLocExpr(p, n.sons[1], a) + initLocExpr(p, n.sons[1], a) linefmt(p, cpsStmts, "#genericReset((void*)$1, $2);$n", addrLoc(a), genTypeInfo(p.module, skipTypes(a.t, abstractVarRange))) @@ -959,8 +959,8 @@ proc rawGenNew(p: BProc, a: TLoc, sizeExpr: PRope) = initLoc(b, locExpr, a.t, OnHeap) if sizeExpr.isNil: sizeExpr = ropef("sizeof($1)", - getTypeDesc(p.module, skipTypes(reftype.sons[0], abstractRange))) - let args = [getTypeDesc(p.module, reftype), + getTypeDesc(p.module, skipTypes(refType.sons[0], abstractRange))) + let args = [getTypeDesc(p.module, refType), genTypeInfo(p.module, refType), sizeExpr] if a.s == OnHeap and usesNativeGC(): @@ -979,11 +979,11 @@ proc rawGenNew(p: BProc, a: TLoc, sizeExpr: PRope) = proc genNew(p: BProc, e: PNode) = var a: TLoc - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) # 'genNew' also handles 'unsafeNew': if e.len == 3: var se: TLoc - InitLocExpr(p, e.sons[2], se) + initLocExpr(p, e.sons[2], se) rawGenNew(p, a, se.rdLoc) else: rawGenNew(p, a, nil) @@ -991,7 +991,7 @@ proc genNew(p: BProc, e: PNode) = proc genNewSeqAux(p: BProc, dest: TLoc, length: PRope) = let seqtype = skipTypes(dest.t, abstractVarRange) let args = [getTypeDesc(p.module, seqtype), - genTypeInfo(p.module, seqType), length] + genTypeInfo(p.module, seqtype), length] var call: TLoc initLoc(call, locExpr, dest.t, OnHeap) if dest.s == OnHeap and usesNativeGC(): @@ -1007,8 +1007,8 @@ proc genNewSeqAux(p: BProc, dest: TLoc, length: PRope) = proc genNewSeq(p: BProc, e: PNode) = var a, b: TLoc - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) genNewSeqAux(p, a, b.rdLoc) proc genObjConstr(p: BProc, e: PNode, d: var TLoc) = @@ -1032,8 +1032,8 @@ proc genObjConstr(p: BProc, e: PNode, d: var TLoc) = field = lookupInRecord(ty.n, it.sons[0].sym.name) if field != nil: break if gCmd != cmdCompileToCpp: app(tmp2.r, ".Sup") - ty = GetUniqueType(ty.sons[0]) - if field == nil or field.loc.r == nil: InternalError(e.info, "genObjConstr") + ty = getUniqueType(ty.sons[0]) + if field == nil or field.loc.r == nil: internalError(e.info, "genObjConstr") if it.len == 3 and optFieldCheck in p.options: genFieldCheck(p, it.sons[2], r, field) app(tmp2.r, ".") @@ -1088,14 +1088,14 @@ proc genNewFinalize(p: BProc, e: PNode) = ti: PRope oldModule: BModule refType = skipTypes(e.sons[1].typ, abstractVarRange) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], f) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], f) initLoc(b, locExpr, a.t, OnHeap) ti = genTypeInfo(p.module, refType) appf(p.module.s[cfsTypeInit3], "$1->finalizer = (void*)$2;$n", [ti, rdLoc(f)]) b.r = ropecg(p.module, "($1) #newObj($2, sizeof($3))", [ getTypeDesc(p.module, refType), - ti, getTypeDesc(p.module, skipTypes(reftype.sons[0], abstractRange))]) + ti, getTypeDesc(p.module, skipTypes(refType.sons[0], abstractRange))]) genAssignment(p, a, b, {needToKeepAlive}) # set the object type: bt = skipTypes(refType.sons[0], abstractRange) genObjectInit(p, cpsStmts, bt, a, false) @@ -1116,7 +1116,7 @@ proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) = app(r, ~".Sup") t = skipTypes(t.sons[0], typedescInst) if isObjLackingTypeField(t): - GlobalError(x.info, errGenerated, + globalError(x.info, errGenerated, "no 'of' operator available for pure objects") if nilCheck != nil: r = rfmt(p.module, "(($1) && #isObj($2.m_type, $3))", @@ -1132,7 +1132,7 @@ proc genOf(p: BProc, n: PNode, d: var TLoc) = proc genRepr(p: BProc, e: PNode, d: var TLoc) = # XXX we don't generate keep alive info for now here var a: TLoc - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) var t = skipTypes(e.sons[1].typ, abstractVarRange) case t.kind of tyInt..tyInt64, tyUInt..tyUInt64: @@ -1164,7 +1164,7 @@ proc genRepr(p: BProc, e: PNode, d: var TLoc) = of tyArray, tyArrayConstr: putIntoDest(p, b, e.typ, ropef("$1, $2", [rdLoc(a), toRope(lengthOrd(a.t))])) - else: InternalError(e.sons[0].info, "genRepr()") + else: internalError(e.sons[0].info, "genRepr()") putIntoDest(p, d, e.typ, ropecg(p.module, "#reprOpenArray($1, $2)", [rdLoc(b), genTypeInfo(p.module, elemType(t))])) @@ -1183,7 +1183,7 @@ proc genGetTypeInfo(p: BProc, e: PNode, d: var TLoc) = proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) = var a: TLoc - InitLocExpr(p, n.sons[1], a) + initLocExpr(p, n.sons[1], a) a.r = ropecg(p.module, frmt, [rdLoc(a)]) if d.k == locNone: getTemp(p, n.typ, d) genAssignment(p, d, a, {needToKeepAlive}) @@ -1208,15 +1208,15 @@ proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) = else: unaryExpr(p, e, d, "$1->len") of tyArray, tyArrayConstr: # YYY: length(sideeffect) is optimized away incorrectly? - if op == mHigh: putIntoDest(p, d, e.typ, toRope(lastOrd(Typ))) + if op == mHigh: putIntoDest(p, d, e.typ, toRope(lastOrd(typ))) else: putIntoDest(p, d, e.typ, toRope(lengthOrd(typ))) - else: InternalError(e.info, "genArrayLen()") + else: internalError(e.info, "genArrayLen()") proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) = var a, b: TLoc assert(d.k == locNone) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) var t = skipTypes(e.sons[1].typ, abstractVar) let setLenPattern = if gCmd != cmdCompileToCpp: "$1 = ($3) #setLengthSeq(&($1)->Sup, sizeof($4), $2);$n" @@ -1230,7 +1230,7 @@ proc genSetLengthSeq(p: BProc, e: PNode, d: var TLoc) = proc genSetLengthStr(p: BProc, e: PNode, d: var TLoc) = binaryStmt(p, e, d, "$1 = #setLengthStr($1, $2);$n") - keepAlive(P, d) + keepAlive(p, d) proc genSwap(p: BProc, e: PNode, d: var TLoc) = # swap(a, b) --> @@ -1239,8 +1239,8 @@ proc genSwap(p: BProc, e: PNode, d: var TLoc) = # b = temp var a, b, tmp: TLoc getTemp(p, skipTypes(e.sons[1].typ, abstractVar), tmp) - InitLocExpr(p, e.sons[1], a) # eval a - InitLocExpr(p, e.sons[2], b) # eval b + initLocExpr(p, e.sons[1], a) # eval a + initLocExpr(p, e.sons[2], b) # eval b genAssignment(p, tmp, a, {}) genAssignment(p, a, b, {}) genAssignment(p, b, tmp, {}) @@ -1256,7 +1256,7 @@ proc rdSetElemLoc(a: TLoc, setType: PType): PRope = proc fewCmps(s: PNode): bool = # this function estimates whether it is better to emit code # for constructing the set or generating a bunch of comparisons directly - if s.kind != nkCurly: InternalError(s.info, "fewCmps") + if s.kind != nkCurly: internalError(s.info, "fewCmps") if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags): result = false # it is better to emit the set generation code elif elemType(s.typ).Kind in {tyInt, tyInt16..tyInt64}: @@ -1278,8 +1278,8 @@ proc genInExprAux(p: BProc, e: PNode, a, b, d: var TLoc) = proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) = var a, b: TLoc assert(d.k == locNone) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) lineF(p, cpsStmts, frmt, [rdLoc(a), rdSetElemLoc(b, a.t)]) proc genInOp(p: BProc, e: PNode, d: var TLoc) = @@ -1299,12 +1299,12 @@ proc genInOp(p: BProc, e: PNode, d: var TLoc) = var length = sonsLen(e.sons[1]) for i in countup(0, length - 1): if e.sons[1].sons[i].Kind == nkRange: - InitLocExpr(p, e.sons[1].sons[i].sons[0], x) - InitLocExpr(p, e.sons[1].sons[i].sons[1], y) + initLocExpr(p, e.sons[1].sons[i].sons[0], x) + initLocExpr(p, e.sons[1].sons[i].sons[1], y) appf(b.r, "$1 >= $2 && $1 <= $3", [rdCharLoc(a), rdCharLoc(x), rdCharLoc(y)]) else: - InitLocExpr(p, e.sons[1].sons[i], x) + initLocExpr(p, e.sons[1].sons[i], x) appf(b.r, "$1 == $2", [rdCharLoc(a), rdCharLoc(x)]) if i < length - 1: app(b.r, " || ") app(b.r, ")") @@ -1312,8 +1312,8 @@ proc genInOp(p: BProc, e: PNode, d: var TLoc) = else: assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) genInExprAux(p, e, a, b, d) proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = @@ -1391,7 +1391,7 @@ proc genSomeCast(p: BProc, e: PNode, d: var TLoc) = # we use whatever C gives us. Except if we have a value-type, we need to go # through its address: var a: TLoc - InitLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[1], a) let etyp = skipTypes(e.typ, abstractRange) if etyp.kind in ValueTypes and lfIndirect notin a.flags: putIntoDest(p, d, e.typ, ropef("(*($1*) ($2))", @@ -1433,13 +1433,13 @@ proc genRangeChck(p: BProc, n: PNode, d: var TLoc, magic: string) = var dest = skipTypes(n.typ, abstractVar) # range checks for unsigned turned out to be buggy and annoying: if optRangeCheck notin p.options or dest.kind in {tyUInt..tyUInt64}: - InitLocExpr(p, n.sons[0], a) + initLocExpr(p, n.sons[0], a) putIntoDest(p, d, n.typ, ropef("(($1) ($2))", [getTypeDesc(p.module, dest), rdCharLoc(a)])) else: - InitLocExpr(p, n.sons[0], a) + initLocExpr(p, n.sons[0], a) if leValue(n.sons[2], n.sons[1]): - InternalError(n.info, "range check will always fail; empty range") + internalError(n.info, "range check will always fail; empty range") putIntoDest(p, d, dest, ropecg(p.module, "(($1)#$5($2, $3, $4))", [ getTypeDesc(p.module, dest), rdCharLoc(a), genLiteral(p, n.sons[1], dest), genLiteral(p, n.sons[2], dest), @@ -1486,8 +1486,8 @@ proc binaryFloatArith(p: BProc, e: PNode, d: var TLoc, m: TMagic) = var a, b: TLoc assert(e.sons[1].typ != nil) assert(e.sons[2].typ != nil) - InitLocExpr(p, e.sons[1], a) - InitLocExpr(p, e.sons[2], b) + initLocExpr(p, e.sons[1], a) + initLocExpr(p, e.sons[2], b) putIntoDest(p, d, e.typ, rfmt(nil, "(($4)($2) $1 ($4)($3))", toRope(opr[m]), rdLoc(a), rdLoc(b), getSimpleTypeDesc(p.module, e[1].typ))) @@ -1593,7 +1593,7 @@ proc handleConstExpr(p: BProc, n: PNode, d: var TLoc): bool = if (nfAllConst in n.flags) and (d.k == locNone) and (sonsLen(n) > 0): var t = getUniqueType(n.typ) discard getTypeDesc(p.module, t) # so that any fields are initialized - var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId) + var id = nodeTableTestOrSet(p.module.dataCache, n, gBackendId) fillLoc(d, locData, t, con("TMP", toRope(id)), OnHeap) if id == gBackendId: # expression not found in the cache: @@ -1760,7 +1760,7 @@ proc downConv(p: BProc, n: PNode, d: var TLoc) = proc exprComplexConst(p: BProc, n: PNode, d: var TLoc) = var t = getUniqueType(n.typ) discard getTypeDesc(p.module, t) # so that any fields are initialized - var id = NodeTableTestOrSet(p.module.dataCache, n, gBackendId) + var id = nodeTableTestOrSet(p.module.dataCache, n, gBackendId) var tmp = con("TMP", toRope(id)) if id == gBackendId: @@ -1790,7 +1790,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = of skProc, skConverter, skIterator: genProc(p.module, sym) if sym.loc.r == nil or sym.loc.t == nil: - InternalError(n.info, "expr: proc not init " & sym.name.s) + internalError(n.info, "expr: proc not init " & sym.name.s) putLocIntoDest(p, d, sym.loc) of skConst: if sfFakeConst in sym.flags: @@ -1805,9 +1805,9 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = of skVar, skForVar, skResult, skLet: if sfGlobal in sym.flags: genVarPrototype(p.module, sym) if sym.loc.r == nil or sym.loc.t == nil: - InternalError(n.info, "expr: var not init " & sym.name.s) + internalError(n.info, "expr: var not init " & sym.name.s) if sfThread in sym.flags: - AccessThreadLocalVar(p, sym) + accessThreadLocalVar(p, sym) if emulatedThreadVars(): putIntoDest(p, d, sym.loc.t, con("NimTV->", sym.loc.r)) else: @@ -1816,13 +1816,13 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = putLocIntoDest(p, d, sym.loc) of skTemp: if sym.loc.r == nil or sym.loc.t == nil: - InternalError(n.info, "expr: temp not init " & sym.name.s) + internalError(n.info, "expr: temp not init " & sym.name.s) putLocIntoDest(p, d, sym.loc) of skParam: if sym.loc.r == nil or sym.loc.t == nil: - InternalError(n.info, "expr: param not init " & sym.name.s) + internalError(n.info, "expr: param not init " & sym.name.s) putLocIntoDest(p, d, sym.loc) - else: InternalError(n.info, "expr(" & $sym.kind & "); unknown symbol") + else: internalError(n.info, "expr(" & $sym.kind & "); unknown symbol") of nkNilLit: if not isEmptyType(n.typ): putIntoDest(p, d, n.typ, genLiteral(p, n)) @@ -1876,7 +1876,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = of tySequence, tyString: genSeqElem(p, n, d) of tyCString: genCStringElem(p, n, d) of tyTuple: genTupleElem(p, n, d) - else: InternalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') + else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') of nkDerefExpr, nkHiddenDeref: genDeref(p, n, d) of nkDotExpr: genRecordField(p, n, d) of nkCheckedFieldExpr: genCheckedRecordField(p, n, d) @@ -1896,7 +1896,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = var sym = n.sons[namePos].sym genProc(p.module, sym) if sym.loc.r == nil or sym.loc.t == nil: - InternalError(n.info, "expr: proc not init " & sym.name.s) + internalError(n.info, "expr: proc not init " & sym.name.s) putLocIntoDest(p, d, sym.loc) of nkClosure: genClosure(p, n, d) of nkMetaNode: expr(p, n.sons[0], d) @@ -1952,7 +1952,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = of nkState: genState(p, n) of nkGotoState: genGotoState(p, n) of nkBreakState: genBreakState(p, n) - else: InternalError(n.info, "expr(" & $n.kind & "); unknown node kind") + else: internalError(n.info, "expr(" & $n.kind & "); unknown node kind") proc genNamedConstExpr(p: BProc, n: PNode): PRope = if n.kind == nkExprColonExpr: result = genConstExpr(p, n.sons[1]) diff --git a/compiler/ccgmerge.nim b/compiler/ccgmerge.nim index de207c532..0ea30bd04 100644 --- a/compiler/ccgmerge.nim +++ b/compiler/ccgmerge.nim @@ -187,7 +187,7 @@ proc readVerbatimSection(L: var TBaseLexer): PRope = buf = L.buf r.add(tnl) of '\0': - InternalError("ccgmerge: expected: " & NimMergeEndMark) + internalError("ccgmerge: expected: " & NimMergeEndMark) break else: if atEndMark(buf, pos): @@ -224,7 +224,7 @@ proc readTypeCache(L: var TBaseLexer, result: var TIdTable) = # XXX little hack: we create a "fake" type object with the correct Id # better would be to adapt the data structure to not even store the # object as key, but only the Id - IdTablePut(result, newFakeType(key), value.toRope) + idTablePut(result, newFakeType(key), value.toRope) inc L.bufpos proc readIntSet(L: var TBaseLexer, result: var TIntSet) = @@ -250,13 +250,13 @@ proc processMergeInfo(L: var TBaseLexer, m: BModule) = of "typeInfo": readIntSet(L, m.typeInfoMarker) of "labels": m.labels = decodeVInt(L.buf, L.bufpos) of "hasframe": m.FrameDeclared = decodeVInt(L.buf, L.bufpos) != 0 - else: InternalError("ccgmerge: unkown key: " & k) + else: internalError("ccgmerge: unkown key: " & k) when not defined(nimhygiene): {.pragma: inject.} template withCFile(cfilename: string, body: stmt) {.immediate.} = - var s = LLStreamOpen(cfilename, fmRead) + var s = llStreamOpen(cfilename, fmRead) if s == nil: return var L {.inject.}: TBaseLexer openBaseLexer(L, s) @@ -300,9 +300,9 @@ proc readMergeSections(cfilename: string, m: var TMergeSections) = if sectionB >= 0 and sectionB <= high(TCProcSection).int: m.p[TCProcSection(sectionB)] = verbatim else: - InternalError("ccgmerge: unknown section: " & k) + internalError("ccgmerge: unknown section: " & k) else: - InternalError("ccgmerge: '*/' expected") + internalError("ccgmerge: '*/' expected") proc mergeRequired*(m: BModule): bool = for i in cfsHeaders..cfsProcs: diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index 9b56556fc..eb738b574 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -16,7 +16,7 @@ const # above X strings a hash-switch for strings is generated proc registerGcRoot(p: BProc, v: PSym) = - if gSelectedGc in {gcMarkAndSweep, gcGenerational} and + if gSelectedGC in {gcMarkAndSweep, gcGenerational} and containsGarbageCollectedRef(v.loc.t): # we register a specialized marked proc here; this has the advantage # that it works out of the box for thread local storage then :-) @@ -26,7 +26,7 @@ proc registerGcRoot(p: BProc, v: PSym) = proc genVarTuple(p: BProc, n: PNode) = var tup, field: TLoc - if n.kind != nkVarTuple: InternalError(n.info, "genVarTuple") + if n.kind != nkVarTuple: internalError(n.info, "genVarTuple") var L = sonsLen(n) genLineDir(p, n) initLocExpr(p, n.sons[L-1], tup) @@ -45,7 +45,7 @@ proc genVarTuple(p: BProc, n: PNode) = if t.kind == tyTuple: field.r = ropef("$1.Field$2", [rdLoc(tup), toRope(i)]) else: - if t.n.sons[i].kind != nkSym: InternalError(n.info, "genVarTuple") + if t.n.sons[i].kind != nkSym: internalError(n.info, "genVarTuple") field.r = ropef("$1.$2", [rdLoc(tup), mangleRecFieldName(t.n.sons[i].sym, t)]) putLocIntoDest(p, v.loc, field) @@ -62,7 +62,7 @@ proc startBlock(p: BProc, start: TFormatStr = "{$n", lineCg(p, cpsStmts, start, args) inc(p.labels) result = len(p.blocks) - setlen(p.blocks, result + 1) + setLen(p.blocks, result + 1) p.blocks[result].id = p.labels p.blocks[result].nestedTryStmts = p.nestedTryStmts.len.int16 @@ -81,7 +81,7 @@ proc endBlock(p: BProc, blockEnd: PRope) = let topBlock = p.blocks.len-1 # the block is merged into the parent block app(p.blocks[topBlock-1].sections[cpsStmts], p.blocks[topBlock].blockBody) - setlen(p.blocks, topBlock) + setLen(p.blocks, topBlock) # this is done after the block is popped so $n is # properly indented when pretty printing is enabled line(p, cpsStmts, blockEnd) @@ -200,7 +200,7 @@ proc genConstStmt(p: BProc, t: PNode) = for i in countup(0, sonsLen(t) - 1): var it = t.sons[i] if it.kind == nkCommentStmt: continue - if it.kind != nkConstDef: InternalError(t.info, "genConstStmt") + if it.kind != nkConstDef: internalError(t.info, "genConstStmt") var c = it.sons[0].sym if c.typ.containsCompileTimeOnly: continue if sfFakeConst in c.flags: @@ -242,17 +242,17 @@ proc genIf(p: BProc, n: PNode, d: var TLoc) = if it.len == 2: when newScopeForIf: startBlock(p) initLocExpr(p, it.sons[0], a) - Lelse = getLabel(p) + lelse = getLabel(p) inc(p.labels) lineFF(p, cpsStmts, "if (!$1) goto $2;$n", "br i1 $1, label %LOC$3, label %$2$nLOC$3: $n", - [rdLoc(a), Lelse, toRope(p.labels)]) + [rdLoc(a), lelse, toRope(p.labels)]) when not newScopeForIf: startBlock(p) expr(p, it.sons[1], d) endBlock(p) if sonsLen(n) > 1: lineFF(p, cpsStmts, "goto $1;$n", "br label %$1$n", [lend]) - fixLabel(p, Lelse) + fixLabel(p, lelse) elif it.len == 1: startBlock(p) expr(p, it.sons[0], d) @@ -296,7 +296,7 @@ proc genReturnStmt(p: BProc, t: PNode) = proc genComputedGoto(p: BProc; n: PNode) = # first pass: Generate array of computed labels: var casePos = -1 - var arraySize: Int + var arraySize: int for i in 0 .. = 0 and not p.blocks[idx].isLoop: dec idx if idx < 0 or not p.blocks[idx].isLoop: - InternalError(t.info, "no loop to break") + internalError(t.info, "no loop to break") let label = assignLabel(p.blocks[idx]) blockLeaveActions(p, p.nestedTryStmts.len - p.blocks[idx].nestedTryStmts) genLineDir(p, t) @@ -469,7 +469,7 @@ proc genRaiseStmt(p: BProc, t: PNode) = genSimpleBlock(p, finallyBlock.sons[0]) if t.sons[0].kind != nkEmpty: var a: TLoc - InitLocExpr(p, t.sons[0], a) + initLocExpr(p, t.sons[0], a) var e = rdLoc(a) var typ = skipTypes(t.sons[0].typ, abstractPtrs) genLineDir(p, t) @@ -598,7 +598,7 @@ proc ifSwitchSplitPoint(p: BProc, n: PNode): int = var stmtBlock = lastSon(branch) if stmtBlock.stmtsContainPragma(wLinearScanEnd): result = i - elif hasSwitchRange notin CC[ccompiler].props: + elif hasSwitchRange notin CC[cCompiler].props: if branch.kind == nkOfBranch and branchHasTooBigRange(branch): result = i @@ -606,7 +606,7 @@ proc genCaseRange(p: BProc, branch: PNode) = var length = branch.len for j in 0 .. length-2: if branch[j].kind == nkRange: - if hasSwitchRange in CC[ccompiler].props: + if hasSwitchRange in CC[cCompiler].props: lineF(p, cpsStmts, "case $1 ... $2:$n", [ genLiteral(p, branch[j][0]), genLiteral(p, branch[j][1])]) @@ -614,13 +614,13 @@ proc genCaseRange(p: BProc, branch: PNode) = var v = copyNode(branch[j][0]) while v.intVal <= branch[j][1].intVal: lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, v)]) - Inc(v.intVal) + inc(v.intVal) else: lineF(p, cpsStmts, "case $1:$n", [genLiteral(p, branch[j])]) proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) = # analyse 'case' statement: - var splitPoint = IfSwitchSplitPoint(p, n) + var splitPoint = ifSwitchSplitPoint(p, n) # generate if part (might be empty): var a: TLoc @@ -644,7 +644,7 @@ proc genOrdinalCase(p: BProc, n: PNode, d: var TLoc) = hasDefault = true exprBlock(p, branch.lastSon, d) lineF(p, cpsStmts, "break;$n") - if (hasAssume in CC[ccompiler].props) and not hasDefault: + if (hasAssume in CC[cCompiler].props) and not hasDefault: lineF(p, cpsStmts, "default: __assume(0);$n") lineF(p, cpsStmts, "}$n") if lend != nil: fixLabel(p, lend) @@ -850,9 +850,9 @@ proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): PRope = r = mangleName(sym) sym.loc.r = r # but be consequent! res.add(r.ropeToStr) - else: InternalError(t.sons[i].info, "genAsmOrEmitStmt()") + else: internalError(t.sons[i].info, "genAsmOrEmitStmt()") - if isAsmStmt and hasGnuAsm in CC[ccompiler].props: + if isAsmStmt and hasGnuAsm in CC[cCompiler].props: for x in splitLines(res): var j = 0 while x[j] in {' ', '\t'}: inc(j) @@ -873,9 +873,9 @@ proc genAsmStmt(p: BProc, t: PNode) = var s = genAsmOrEmitStmt(p, t, isAsmStmt=true) if p.prc == nil: # top level asm statement? - appf(p.module.s[cfsProcHeaders], CC[ccompiler].asmStmtFrmt, [s]) + appf(p.module.s[cfsProcHeaders], CC[cCompiler].asmStmtFrmt, [s]) else: - lineF(p, cpsStmts, CC[ccompiler].asmStmtFrmt, [s]) + lineF(p, cpsStmts, CC[cCompiler].asmStmtFrmt, [s]) proc genEmit(p: BProc, t: PNode) = genLineDir(p, t) @@ -944,7 +944,7 @@ proc genDiscriminantCheck(p: BProc, a, tmp: TLoc, objtype: PType, assert t.kind == tyObject discard genTypeInfo(p.module, t) var L = lengthOrd(field.typ) - if not ContainsOrIncl(p.module.declaredThings, field.id): + if not containsOrIncl(p.module.declaredThings, field.id): appcg(p.module, cfsVars, "extern $1", discriminatorTableDecl(p.module, t, field)) lineCg(p, cpsStmts, @@ -957,7 +957,7 @@ proc asgnFieldDiscriminant(p: BProc, e: PNode) = var dotExpr = e.sons[0] var d: PSym if dotExpr.kind == nkCheckedFieldExpr: dotExpr = dotExpr.sons[0] - InitLocExpr(p, e.sons[0], a) + initLocExpr(p, e.sons[0], a) getTemp(p, a.t, tmp) expr(p, e.sons[1], tmp) genDiscriminantCheck(p, a, tmp, dotExpr.sons[0].typ, dotExpr.sons[1].sym) @@ -965,9 +965,9 @@ proc asgnFieldDiscriminant(p: BProc, e: PNode) = proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) = genLineDir(p, e) - if not FieldDiscriminantCheckNeeded(p, e): + if not fieldDiscriminantCheckNeeded(p, e): var a: TLoc - InitLocExpr(p, e.sons[0], a) + initLocExpr(p, e.sons[0], a) if fastAsgn: incl(a.flags, lfNoDeepCopy) assert(a.t != nil) loadInto(p, e.sons[0], e.sons[1], a) diff --git a/compiler/ccgtrav.nim b/compiler/ccgtrav.nim index 9534eae91..6de425cfd 100644 --- a/compiler/ccgtrav.nim +++ b/compiler/ccgtrav.nim @@ -28,7 +28,7 @@ proc genTraverseProc(c: var TTraversalClosure, accessor: PRope, n: PNode) = for i in countup(0, sonsLen(n) - 1): genTraverseProc(c, accessor, n.sons[i]) of nkRecCase: - if (n.sons[0].kind != nkSym): InternalError(n.info, "genTraverseProc") + if (n.sons[0].kind != nkSym): internalError(n.info, "genTraverseProc") var p = c.p let disc = n.sons[0].sym lineF(p, cpsStmts, "switch ($1.$2) {$n", accessor, disc.loc.r) @@ -74,7 +74,7 @@ proc genTraverseProc(c: var TTraversalClosure, accessor: PRope, typ: PType) = genTraverseProc(c, accessor.parentObj, typ.sons[i]) if typ.n != nil: genTraverseProc(c, accessor, typ.n) of tyTuple: - let typ = GetUniqueType(typ) + let typ = getUniqueType(typ) for i in countup(0, sonsLen(typ) - 1): genTraverseProc(c, rfmt(nil, "$1.Field$2", accessor, i.toRope), typ.sons[i]) of tyRef, tyString, tySequence: diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index 66441af5e..9d3629085 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -76,7 +76,7 @@ proc mangleName(s: PSym): PRope = else: result = ~"%" of skTemp, skParam, skType, skEnumField, skModule: result = ~"%" - else: InternalError(s.info, "mangleName") + else: internalError(s.info, "mangleName") when oKeepVariableNames: let keepOrigName = s.kind in skLocalVars - {skForVar} and {sfFromGeneric, sfGlobal, sfShadowed, sfGenSym} * s.flags == {} and @@ -150,7 +150,7 @@ proc getTypeName(typ: PType): PRope = typ.loc.r = if gCmd != cmdCompileToLLVM: con(typ.typeName, typ.id.toRope) else: con([~"%", typ.typeName, typ.id.toRope]) result = typ.loc.r - if result == nil: InternalError("getTypeName: " & $typ.kind) + if result == nil: internalError("getTypeName: " & $typ.kind) proc mapSetType(typ: PType): TCTypeKind = case int(getSize(typ)) @@ -194,7 +194,7 @@ proc mapType(typ: PType): TCTypeKind = of tyCString: result = ctCString of tyInt..tyUInt64: result = TCTypeKind(ord(typ.kind) - ord(tyInt) + ord(ctInt)) - else: InternalError("mapType") + else: internalError("mapType") proc mapReturnType(typ: PType): TCTypeKind = if skipTypes(typ, typedescInst).kind == tyArray: result = ctPtr @@ -262,7 +262,7 @@ proc ccgIntroducedPtr(s: PSym): bool = proc fillResult(param: PSym) = fillLoc(param.loc, locParam, param.typ, ~"Result", OnStack) - if (mapReturnType(param.typ) != ctArray) and IsInvalidReturnType(param.typ): + if (mapReturnType(param.typ) != ctArray) and isInvalidReturnType(param.typ): incl(param.loc.flags, lfIndirect) param.loc.s = OnUnknown @@ -288,7 +288,7 @@ proc genProcParams(m: BModule, t: PType, rettype, params: var PRope, else: rettype = getTypeDescAux(m, t.sons[0], check) for i in countup(1, sonsLen(t.n) - 1): - if t.n.sons[i].kind != nkSym: InternalError(t.n.info, "genProcParams") + if t.n.sons[i].kind != nkSym: internalError(t.n.info, "genProcParams") var param = t.n.sons[i].sym if isCompileTimeOnly(param.typ): continue if params != nil: app(params, ~", ") @@ -375,14 +375,14 @@ proc getTypePre(m: BModule, typ: PType): PRope = if typ == nil: result = toRope("void") else: result = getSimpleTypeDesc(m, typ) - if result == nil: result = CacheGetType(m.typeCache, typ) + if result == nil: result = cacheGetType(m.typeCache, typ) proc getForwardStructFormat(): string = if gCmd == cmdCompileToCpp: result = "struct $1;$n" else: result = "typedef struct $1 $1;$n" proc getTypeForward(m: BModule, typ: PType): PRope = - result = CacheGetType(m.forwTypeCache, typ) + result = cacheGetType(m.forwTypeCache, typ) if result != nil: return result = getTypePre(m, typ) if result != nil: return @@ -391,8 +391,8 @@ proc getTypeForward(m: BModule, typ: PType): PRope = result = getTypeName(typ) if not isImportedType(typ): appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result]) - IdTablePut(m.forwTypeCache, typ, result) - else: InternalError("getTypeForward(" & $typ.kind & ')') + idTablePut(m.forwTypeCache, typ, result) + else: internalError("getTypeForward(" & $typ.kind & ')') proc mangleRecFieldName(field: PSym, rectype: PType): PRope = if (rectype.sym != nil) and @@ -400,7 +400,7 @@ proc mangleRecFieldName(field: PSym, rectype: PType): PRope = result = field.loc.r else: result = toRope(mangleField(field.name.s)) - if result == nil: InternalError(field.info, "mangleRecFieldName") + if result == nil: internalError(field.info, "mangleRecFieldName") proc genRecordFieldsAux(m: BModule, n: PNode, accessExpr: PRope, rectype: PType, @@ -415,7 +415,7 @@ proc genRecordFieldsAux(m: BModule, n: PNode, for i in countup(0, sonsLen(n) - 1): app(result, genRecordFieldsAux(m, n.sons[i], accessExpr, rectype, check)) of nkRecCase: - if (n.sons[0].kind != nkSym): InternalError(n.info, "genRecordFieldsAux") + if (n.sons[0].kind != nkSym): internalError(n.info, "genRecordFieldsAux") app(result, genRecordFieldsAux(m, n.sons[0], accessExpr, rectype, check)) uname = toRope(mangle(n.sons[0].sym.name.s) & 'U') if accessExpr != nil: ae = ropef("$1.$2", [accessExpr, uname]) @@ -497,15 +497,15 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = # returns only the type's name var name, rettype, desc, recdesc: PRope - n: biggestInt + n: BiggestInt t, et: PType t = getUniqueType(typ) - if t == nil: InternalError("getTypeDescAux: t == nil") + if t == nil: internalError("getTypeDescAux: t == nil") if t.sym != nil: useHeader(m, t.sym) result = getTypePre(m, t) if result != nil: return - if ContainsOrIncl(check, t.id): - InternalError("cannot generate C type for: " & typeToString(typ)) + if containsOrIncl(check, t.id): + internalError("cannot generate C type for: " & typeToString(typ)) # XXX: this BUG is hard to fix -> we need to introduce helper structs, # but determining when this needs to be done is hard. We should split # C type generation into an analysis and a code generation phase somehow. @@ -521,25 +521,25 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = # no restriction! We have a forward declaration for structs name = getTypeForward(m, et) result = con(name, "*") - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) pushType(m, et) of tySequence: # no restriction! We have a forward declaration for structs name = getTypeForward(m, et) result = con(name, "**") - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) pushType(m, et) else: # else we have a strong dependency :-( result = con(getTypeDescAux(m, et, check), "*") - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) of tyOpenArray, tyVarargs: et = getUniqueType(t.sons[0]) result = con(getTypeDescAux(m, et, check), "*") - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) of tyProc: result = getTypeName(t) - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) genProcParams(m, t, rettype, desc, check) if not isImportedType(t): if t.callConv != ccClosure: # procedure vars may need a closure! @@ -553,14 +553,14 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = of tySequence: # we cannot use getTypeForward here because then t would be associated # with the name of the struct, not with the pointer to the struct: - result = CacheGetType(m.forwTypeCache, t) + result = cacheGetType(m.forwTypeCache, t) if result == nil: result = getTypeName(t) if not isImportedType(t): appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result]) - IdTablePut(m.forwTypeCache, t, result) + idTablePut(m.forwTypeCache, t, result) assert(CacheGetType(m.typeCache, t) == nil) - IdTablePut(m.typeCache, t, con(result, "*")) + idTablePut(m.typeCache, t, con(result, "*")) if not isImportedType(t): if skipTypes(t.sons[0], typedescInst).kind != tyEmpty: const @@ -579,18 +579,18 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = if n <= 0: n = 1 # make an array of at least one element result = getTypeName(t) - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) if not isImportedType(t): appf(m.s[cfsTypes], "typedef $1 $2[$3];$n", - [getTypeDescAux(m, t.sons[1], check), result, ToRope(n)]) + [getTypeDescAux(m, t.sons[1], check), result, toRope(n)]) of tyObject, tyTuple: - result = CacheGetType(m.forwTypeCache, t) + result = cacheGetType(m.forwTypeCache, t) if result == nil: result = getTypeName(t) if not isImportedType(t): appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result]) - IdTablePut(m.forwTypeCache, t, result) - IdTablePut(m.typeCache, t, result) # always call for sideeffects: + idTablePut(m.forwTypeCache, t, result) + idTablePut(m.typeCache, t, result) # always call for sideeffects: if t.kind != tyTuple: recdesc = getRecordDesc(m, t, result, check) else: recdesc = getTupleDesc(m, t, result, check) if not isImportedType(t): app(m.s[cfsTypes], recdesc) @@ -602,7 +602,7 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = of 8: result = toRope("NU64") else: result = getTypeName(t) - IdTablePut(m.typeCache, t, result) + idTablePut(m.typeCache, t, result) if not isImportedType(t): appf(m.s[cfsTypes], "typedef NU8 $1[$2];$n", [result, toRope(getSize(t))]) @@ -610,7 +610,7 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = tyIter, tyTypeDesc: result = getTypeDescAux(m, lastSon(t), check) else: - InternalError("getTypeDescAux(" & $t.kind & ')') + internalError("getTypeDescAux(" & $t.kind & ')') result = nil # fixes bug #145: excl(check, t.id) @@ -737,10 +737,10 @@ proc discriminatorTableName(m: BModule, objtype: PType, d: PSym): PRope = var objtype = objtype while lookupInRecord(objtype.n, d.name) == nil: objtype = objtype.sons[0] - if objType.sym == nil: - InternalError(d.info, "anonymous obj with discriminator") + if objtype.sym == nil: + internalError(d.info, "anonymous obj with discriminator") result = ropef("NimDT_$1_$2", [ - toRope(objType.sym.name.s.mangle), toRope(d.name.s.mangle)]) + toRope(objtype.sym.name.s.mangle), toRope(d.name.s.mangle)]) proc discriminatorTableDecl(m: BModule, objtype: PType, d: PSym): PRope = discard cgsym(m, "TNimNode") @@ -911,7 +911,7 @@ include ccgtrav proc genTypeInfo(m: BModule, t: PType): PRope = var t = getUniqueType(t) result = ropef("NTI$1", [toRope(t.id)]) - if ContainsOrIncl(m.typeInfoMarker, t.id): + if containsOrIncl(m.typeInfoMarker, t.id): return con("(&".toRope, result, ")".toRope) let owner = t.skipTypes(typedescPtrs).owner.getModule if owner != m.module: @@ -948,7 +948,7 @@ proc genTypeInfo(m: BModule, t: PType): PRope = # BUGFIX: use consistently RTTI without proper field names; otherwise # results are not deterministic! genTupleInfo(m, t, result) - else: InternalError("genTypeInfo(" & $t.kind & ')') + else: internalError("genTypeInfo(" & $t.kind & ')') result = con("(&".toRope, result, ")".toRope) proc genTypeSection(m: BModule, n: PNode) = diff --git a/compiler/ccgutils.nim b/compiler/ccgutils.nim index accb7a261..1c2d7e038 100644 --- a/compiler/ccgutils.nim +++ b/compiler/ccgutils.nim @@ -27,14 +27,14 @@ proc getPragmaStmt*(n: PNode, w: TSpecialWord): PNode = proc stmtsContainPragma*(n: PNode, w: TSpecialWord): bool = result = getPragmaStmt(n, w) != nil -proc hashString*(s: string): biggestInt = +proc hashString*(s: string): BiggestInt = # has to be the same algorithm as system.hashString! if CPU[targetCPU].bit == 64: # we have to use the same bitwidth # as the target CPU var b = 0'i64 for i in countup(0, len(s) - 1): - b = b +% Ord(s[i]) + b = b +% ord(s[i]) b = b +% `shl`(b, 10) b = b xor `shr`(b, 6) b = b +% `shl`(b, 3) @@ -44,7 +44,7 @@ proc hashString*(s: string): biggestInt = else: var a = 0'i32 for i in countup(0, len(s) - 1): - a = a +% Ord(s[i]).int32 + a = a +% ord(s[i]).int32 a = a +% `shl`(a, 10'i32) a = a xor `shr`(a, 6'i32) a = a +% `shl`(a, 3'i32) @@ -57,7 +57,7 @@ var gCanonicalTypes: array[TTypeKind, PType] proc initTypeTables() = - for i in countup(low(TTypeKind), high(TTypeKind)): InitIdTable(gTypeTable[i]) + for i in countup(low(TTypeKind), high(TTypeKind)): initIdTable(gTypeTable[i]) proc resetCaches* = ## XXX: fix that more properly @@ -169,7 +169,7 @@ proc makeLLVMString*(s: string): PRope = for i in countup(0, len(s) - 1): if (i + 1) mod MaxLineLength == 0: app(result, toRope(res)) - setlen(res, 0) + setLen(res, 0) case s[i] of '\0'..'\x1F', '\x80'..'\xFF', '\"', '\\': add(res, '\\') diff --git a/compiler/cgen.nim b/compiler/cgen.nim index ad1dfa89e..97177a0ec 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -52,7 +52,7 @@ proc emitLazily(s: PSym): bool {.inline.} = proc initLoc(result: var TLoc, k: TLocKind, typ: PType, s: TStorageLoc) = result.k = k result.s = s - result.t = GetUniqueType(typ) + result.t = getUniqueType(typ) result.r = nil result.a = - 1 result.flags = {} @@ -103,7 +103,7 @@ proc ropecg(m: BModule, frmt: TFormatStr, args: varargs[PRope]): PRope = of '0'..'9': var j = 0 while true: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) if i >= length or not (frmt[i] in {'0'..'9'}): break num = j @@ -116,7 +116,7 @@ proc ropecg(m: BModule, frmt: TFormatStr, args: varargs[PRope]): PRope = of 'N': app(result, rnl) inc(i) - else: InternalError("ropes: invalid format string $" & frmt[i]) + else: internalError("ropes: invalid format string $" & frmt[i]) elif frmt[i] == '#' and frmt[i+1] in IdentStartChars: inc(i) var j = i @@ -128,7 +128,7 @@ proc ropecg(m: BModule, frmt: TFormatStr, args: varargs[PRope]): PRope = inc(i, 2) var j = 0 while frmt[i] in Digits: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) app(result, cgsym(m, args[j-1].ropeToStr)) var start = i @@ -522,8 +522,8 @@ proc assignGlobalVar(p: BProc, s: PSym) = if lfDynamicLib in s.loc.flags: var q = findPendingModule(p.module, s) - if q != nil and not ContainsOrIncl(q.declaredThings, s.id): - VarInDynamicLib(q, s) + if q != nil and not containsOrIncl(q.declaredThings, s.id): + varInDynamicLib(q, s) else: s.loc.r = mangleDynLibProc(s) return @@ -578,7 +578,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) proc genProcPrototype(m: BModule, sym: PSym) proc putLocIntoDest(p: BProc, d: var TLoc, s: TLoc) proc genAssignment(p: BProc, dest, src: TLoc, flags: TAssignmentFlags) -proc intLiteral(i: biggestInt): PRope +proc intLiteral(i: BiggestInt): PRope proc genLiteral(p: BProc, n: PNode): PRope proc initLocExpr(p: BProc, e: PNode, result: var TLoc) = @@ -610,7 +610,7 @@ proc loadDynamicLib(m: BModule, lib: PLib) = var s: TStringSeq = @[] libCandidates(lib.path.strVal, s) if gVerbosity >= 2: - MsgWriteln("Dependency: " & lib.path.strVal) + msgWriteln("Dependency: " & lib.path.strVal) var loadlib: PRope = nil for i in countup(0, high(s)): inc(m.labels) @@ -632,7 +632,7 @@ proc loadDynamicLib(m: BModule, lib: PLib) = "if (!($1 = #nimLoadLibrary($2))) #nimLoadLibraryError($2);$n", [tmp, rdLoc(dest)]) - if lib.name == nil: InternalError("loadDynamicLib") + if lib.name == nil: internalError("loadDynamicLib") proc mangleDynLibProc(sym: PSym): PRope = if sfCompilerProc in sym.flags: @@ -672,7 +672,7 @@ proc symInDynamicLib(m: BModule, sym: PSym) = elif idx.len == 1 and idx[0] in {'0'..'9'}: app(m.extensionLoaders[idx[0]], load) else: - InternalError(sym.info, "wrong index: " & idx) + internalError(sym.info, "wrong index: " & idx) else: appcg(m, m.s[cfsDynLibInit], "\t$1 = ($2) #nimGetProcAddr($3, $4);$n", @@ -708,7 +708,7 @@ proc cgsym(m: BModule, name: string): PRope = of skProc, skMethod, skConverter, skIterator: genProc(m, sym) of skVar, skResult, skLet: genVarPrototype(m, sym) of skType: discard getTypeDesc(m, sym.typ) - else: InternalError("cgsym: " & name) + else: internalError("cgsym: " & name) else: # we used to exclude the system module from this check, but for DLL # generation support this sloppyness leads to hard to detect bugs, so @@ -747,7 +747,7 @@ proc closureSetup(p: BProc, prc: PSym) = # prc.ast[paramsPos].last contains the type we're after: var ls = lastSon(prc.ast[paramsPos]) if ls.kind != nkSym: - InternalError(prc.info, "closure generation failed") + internalError(prc.info, "closure generation failed") var env = ls.sym #echo "created environment: ", env.id, " for ", prc.name.s assignLocalVar(p, env) @@ -793,7 +793,7 @@ proc genProcAux(m: BModule, prc: PSym) = app(generatedProc, initGCFrame(p)) if optStackTrace in prc.options: app(generatedProc, p.s(cpsLocals)) - var procname = CStringLit(p, generatedProc, prc.name.s) + var procname = cstringLit(p, generatedProc, prc.name.s) app(generatedProc, initFrame(p, procname, prc.info.quotedFilename)) else: app(generatedProc, p.s(cpsLocals)) @@ -814,13 +814,13 @@ proc genProcPrototype(m: BModule, sym: PSym) = if lfNoDecl in sym.loc.Flags: return if lfDynamicLib in sym.loc.Flags: if getModule(sym).id != m.module.id and - not ContainsOrIncl(m.declaredThings, sym.id): + not containsOrIncl(m.declaredThings, sym.id): app(m.s[cfsVars], rfmt(nil, "extern $1 $2;$n", getTypeDesc(m, sym.loc.t), mangleDynLibProc(sym))) if gCmd == cmdCompileToLLVM: incl(sym.loc.flags, lfIndirect) - elif not ContainsOrIncl(m.declaredProtos, sym.id): + elif not containsOrIncl(m.declaredProtos, sym.id): var header = genProcHeader(m, sym) - if sfPure in sym.flags and hasNakedAttribute in CC[ccompiler].props: + if sfPure in sym.flags and hasNakedAttribute in CC[cCompiler].props: header.app(" __attribute__((naked))") app(m.s[cfsProcHeaders], rfmt(nil, "$1;$n", header)) @@ -837,16 +837,16 @@ proc genProcNoForward(m: BModule, prc: PSym) = # We add inline procs to the calling module to enable C based inlining. # This also means that a check with ``q.declaredThings`` is wrong, we need # a check for ``m.declaredThings``. - if not ContainsOrIncl(m.declaredThings, prc.id): genProcAux(m, prc) + if not containsOrIncl(m.declaredThings, prc.id): genProcAux(m, prc) elif lfDynamicLib in prc.loc.flags: var q = findPendingModule(m, prc) - if q != nil and not ContainsOrIncl(q.declaredThings, prc.id): - SymInDynamicLib(q, prc) + if q != nil and not containsOrIncl(q.declaredThings, prc.id): + symInDynamicLib(q, prc) else: - SymInDynamicLibPartial(m, prc) + symInDynamicLibPartial(m, prc) elif sfImportc notin prc.flags: var q = findPendingModule(m, prc) - if q != nil and not ContainsOrIncl(q.declaredThings, prc.id): + if q != nil and not containsOrIncl(q.declaredThings, prc.id): genProcAux(q, prc) proc requestConstImpl(p: BProc, sym: PSym) = @@ -857,12 +857,12 @@ proc requestConstImpl(p: BProc, sym: PSym) = if lfNoDecl in sym.loc.Flags: return # declare implementation: var q = findPendingModule(m, sym) - if q != nil and not ContainsOrIncl(q.declaredThings, sym.id): + if q != nil and not containsOrIncl(q.declaredThings, sym.id): assert q.initProc.module == q appf(q.s[cfsData], "NIM_CONST $1 $2 = $3;$n", [getTypeDesc(q, sym.typ), sym.loc.r, genConstExpr(q.initProc, sym.ast)]) # declare header: - if q != m and not ContainsOrIncl(m.declaredThings, sym.id): + if q != m and not containsOrIncl(m.declaredThings, sym.id): assert(sym.loc.r != nil) let headerDecl = ropef("extern NIM_CONST $1 $2;$n", [getTypeDesc(m, sym.loc.t), sym.loc.r]) @@ -882,14 +882,14 @@ proc genProc(m: BModule, prc: PSym) = generatedHeader != nil and lfNoDecl notin prc.loc.Flags: genProcPrototype(generatedHeader, prc) if prc.typ.callConv == ccInline: - if not ContainsOrIncl(generatedHeader.declaredThings, prc.id): + if not containsOrIncl(generatedHeader.declaredThings, prc.id): genProcAux(generatedHeader, prc) proc genVarPrototypeAux(m: BModule, sym: PSym) = assert(sfGlobal in sym.flags) useHeader(m, sym) fillLoc(sym.loc, locGlobalVar, sym.typ, mangleName(sym), OnHeap) - if (lfNoDecl in sym.loc.Flags) or ContainsOrIncl(m.declaredThings, sym.id): + if (lfNoDecl in sym.loc.Flags) or containsOrIncl(m.declaredThings, sym.id): return if sym.owner.id != m.module.id: # else we already have the symbol generated! @@ -1058,7 +1058,7 @@ proc genInitCode(m: BModule) = # declare it nevertheless: m.FrameDeclared = true if not m.PreventStackTrace: - var procname = CStringLit(m.initProc, prc, m.module.name.s) + var procname = cstringLit(m.initProc, prc, m.module.name.s) app(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename)) else: app(prc, ~"\tTFrame F; F.len = 0;$N") @@ -1127,7 +1127,7 @@ proc initProcOptions(m: BModule): TOptions = proc rawNewModule(module: PSym, filename: string): BModule = new(result) - InitLinkedList(result.headerFiles) + initLinkedList(result.headerFiles) result.declaredThings = initIntSet() result.declaredProtos = initIntSet() result.cfilename = filename @@ -1159,7 +1159,7 @@ proc nullify[T](arr: var T) = proc resetModule*(m: var BModule) = # between two compilations in CAAS mode, we can throw # away all the data that was written to disk - InitLinkedList(m.headerFiles) + initLinkedList(m.headerFiles) m.declaredProtos = initIntSet() initIdTable(m.forwTypeCache) m.initProc = newProc(nil, m) @@ -1210,7 +1210,7 @@ proc newModule(module: PSym): BModule = if (optDeadCodeElim in gGlobalOptions): if (sfDeadCodeElim in module.flags): - InternalError("added pending module twice: " & module.filename) + internalError("added pending module twice: " & module.filename) proc myOpen(module: PSym): PPassContext = result = newModule(module) @@ -1263,19 +1263,19 @@ proc finishModule(m: BModule) = # a ``for`` loop here var prc = m.forwardedProcs[i] if sfForward in prc.flags: - InternalError(prc.info, "still forwarded: " & prc.name.s) + internalError(prc.info, "still forwarded: " & prc.name.s) genProcNoForward(m, prc) inc(i) assert(gForwardedProcsCounter >= i) dec(gForwardedProcsCounter, i) - setlen(m.forwardedProcs, 0) + setLen(m.forwardedProcs, 0) proc shouldRecompile(code: PRope, cfile, cfilenoext: string): bool = result = true if optForceFullMake notin gGlobalOptions: var objFile = toObjFile(cfilenoext) if writeRopeIfNotEqual(code, cfile): return - if ExistsFile(objFile) and os.FileNewer(objFile, cfile): result = false + if existsFile(objFile) and os.FileNewer(objFile, cfile): result = false else: writeRope(code, cfile) @@ -1296,7 +1296,7 @@ proc writeModule(m: BModule, pending: bool) = if sfMainModule in m.module.flags: # generate main file: app(m.s[cfsProcHeaders], mainModProcs) - GenerateThreadVarsSize(m) + generateThreadVarsSize(m) var code = genModule(m, cfilenoext) when hasTinyCBackend: @@ -1313,7 +1313,7 @@ proc writeModule(m: BModule, pending: bool) = var code = genModule(m, cfilenoext) writeRope(code, cfile) addFileToCompile(cfilenoext) - elif not ExistsFile(toObjFile(cfilenoext)): + elif not existsFile(toObjFile(cfilenoext)): # Consider: first compilation compiles ``system.nim`` and produces # ``system.c`` but then compilation fails due to an error. This means # that ``system.o`` is missing, so we need to call the C compiler for it: diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim index a803c0ba1..58584552d 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -78,7 +78,7 @@ type maxFrameLen*: int # max length of frame descriptor module*: BModule # used to prevent excessive parameter passing withinLoop*: int # > 0 if we are within a loop - gcFrameId*: natural # for the GC stack marking + gcFrameId*: Natural # for the GC stack marking gcFrameType*: PRope # the struct {} we put the GC markers into TTypeSeq* = seq[PType] @@ -108,7 +108,7 @@ type forwardedProcs*: TSymSeq # keep forwarded procs here typeNodes*, nimTypes*: int # used for type info generation typeNodesName*, nimTypesName*: PRope # used for type info generation - labels*: natural # for generating unique module-scope names + labels*: Natural # for generating unique module-scope names extensionLoaders*: array['0'..'9', PRope] # special procs for the # OpenGL wrapper injectStmt*: PRope diff --git a/compiler/cgmeth.nim b/compiler/cgmeth.nim index 3467fea7e..9613eb525 100644 --- a/compiler/cgmeth.nim +++ b/compiler/cgmeth.nim @@ -18,16 +18,16 @@ proc genConv(n: PNode, d: PType, downcast: bool): PNode = var source = skipTypes(n.typ, abstractPtrs) if (source.kind == tyObject) and (dest.kind == tyObject): var diff = inheritanceDiff(dest, source) - if diff == high(int): InternalError(n.info, "cgmeth.genConv") + if diff == high(int): internalError(n.info, "cgmeth.genConv") if diff < 0: result = newNodeIT(nkObjUpConv, n.info, d) addSon(result, n) - if downCast: InternalError(n.info, "cgmeth.genConv: no upcast allowed") + if downcast: internalError(n.info, "cgmeth.genConv: no upcast allowed") elif diff > 0: result = newNodeIT(nkObjDownConv, n.info, d) addSon(result, n) - if not downCast: - InternalError(n.info, "cgmeth.genConv: no downcast allowed") + if not downcast: + internalError(n.info, "cgmeth.genConv: no downcast allowed") else: result = n else: @@ -112,12 +112,12 @@ proc relevantCol(methods: TSymSeq, col: int): bool = if t.kind == tyObject: for i in countup(1, high(methods)): let t2 = skipTypes(methods[i].typ.sons[col], skipPtrs) - if not SameType(t2, t): + if not sameType(t2, t): return true proc cmpSignatures(a, b: PSym, relevantCols: TIntSet): int = for col in countup(1, sonsLen(a.typ) - 1): - if Contains(relevantCols, col): + if contains(relevantCols, col): var aa = skipTypes(a.typ.sons[col], skipPtrs) var bb = skipTypes(b.typ.sons[col], skipPtrs) var d = inheritanceDiff(aa, bb) @@ -154,7 +154,7 @@ proc genDispatcher(methods: TSymSeq, relevantCols: TIntSet): PSym = var curr = methods[meth] # generate condition: var cond: PNode = nil for col in countup(1, paramLen - 1): - if Contains(relevantCols, col): + if contains(relevantCols, col): var isn = newNodeIT(nkCall, base.info, getSysType(tyBool)) addSon(isn, newSymNode(iss)) addSon(isn, newSymNode(base.typ.n.sons[col].sym)) @@ -195,7 +195,7 @@ proc generateMethodDispatchers*(): PNode = for bucket in countup(0, len(gMethods) - 1): var relevantCols = initIntSet() for col in countup(1, sonsLen(gMethods[bucket][0].typ) - 1): - if relevantCol(gMethods[bucket], col): Incl(relevantCols, col) + if relevantCol(gMethods[bucket], col): incl(relevantCols, col) sortBucket(gMethods[bucket], relevantCols) addSon(result, newSymNode(genDispatcher(gMethods[bucket], relevantCols))) diff --git a/compiler/commands.nim b/compiler/commands.nim index e67b0d422..acb9af8ac 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -22,7 +22,7 @@ type passPP # preprocessor called ProcessCommand() proc processCommand*(switch: string, pass: TCmdLinePass) -proc processSwitch*(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) +proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) # implementation @@ -36,7 +36,7 @@ const proc getCommandLineDesc(): string = result = (HelpMessage % [VersionAsString, platform.os[platform.hostOS].name, - cpu[platform.hostCPU].name]) & Usage + CPU[platform.hostCPU].name]) & Usage proc helpOnError(pass: TCmdLinePass) = if pass == passCmd1: @@ -47,14 +47,14 @@ proc writeAdvancedUsage(pass: TCmdLinePass) = if pass == passCmd1: msgWriteln(`%`(HelpMessage, [VersionAsString, platform.os[platform.hostOS].name, - cpu[platform.hostCPU].name]) & AdvancedUsage) + CPU[platform.hostCPU].name]) & AdvancedUsage) quit(0) proc writeVersionInfo(pass: TCmdLinePass) = if pass == passCmd1: msgWriteln(`%`(HelpMessage, [VersionAsString, platform.os[platform.hostOS].name, - cpu[platform.hostCPU].name])) + CPU[platform.hostCPU].name])) quit(0) var @@ -88,14 +88,14 @@ proc splitSwitch(switch: string, cmd, arg: var string, pass: TCmdLinePass, elif switch[i] in {':', '=', '['}: arg = substr(switch, i + 1) else: invalidCmdLineOption(pass, switch, info) -proc processOnOffSwitch(op: TOptions, arg: string, pass: TCmdlinePass, +proc processOnOffSwitch(op: TOptions, arg: string, pass: TCmdLinePass, info: TLineInfo) = case whichKeyword(arg) of wOn: gOptions = gOptions + op of wOff: gOptions = gOptions - op else: localError(info, errOnOrOffExpectedButXFound, arg) -proc processOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdlinePass, +proc processOnOffSwitchG(op: TGlobalOptions, arg: string, pass: TCmdLinePass, info: TLineInfo) = case whichKeyword(arg) of wOn: gGlobalOptions = gGlobalOptions + op @@ -108,7 +108,7 @@ proc expectArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = proc expectNoArg(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = if arg != "": localError(info, errCmdLineNoArgExpected, addPrefix(switch)) -proc processSpecificNote(arg: string, state: TSpecialWord, pass: TCmdlinePass, +proc processSpecificNote(arg: string, state: TSpecialWord, pass: TCmdLinePass, info: TLineInfo) = var id = "" # arg = "X]:on|off" var i = 0 @@ -234,7 +234,7 @@ proc track(arg: string, info: TLineInfo) = optTrackPos = newLineInfo(a[0], line, column) msgs.addCheckpoint(optTrackPos) -proc dynlibOverride(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = +proc dynlibOverride(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = if pass in {passCmd2, passPP}: expectArg(switch, arg, pass, info) options.inclDynlibOverride(arg) @@ -252,7 +252,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = if pass in {passCmd2, passPP}: expectArg(switch, arg, pass, info) let path = processPath(arg, notRelativeToProj=true) - babelpath(path, info) + babelPath(path, info) of "excludepath": expectArg(switch, arg, pass, info) let path = processPath(arg) @@ -269,10 +269,10 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = optMainModule = arg of "define", "d": expectArg(switch, arg, pass, info) - DefineSymbol(arg) + defineSymbol(arg) of "undef", "u": expectArg(switch, arg, pass, info) - UndefSymbol(arg) + undefSymbol(arg) of "compile": expectArg(switch, arg, pass, info) if pass in {passCmd2, passPP}: processCompile(arg) @@ -321,40 +321,40 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = defineSymbol("nogc") else: localError(info, errNoneBoehmRefcExpectedButXFound, arg) of "warnings", "w": processOnOffSwitch({optWarns}, arg, pass, info) - of "warning": ProcessSpecificNote(arg, wWarning, pass, info) - of "hint": ProcessSpecificNote(arg, wHint, pass, info) - of "hints": ProcessOnOffSwitch({optHints}, arg, pass, info) - of "threadanalysis": ProcessOnOffSwitchG({optThreadAnalysis}, arg, pass, info) - of "stacktrace": ProcessOnOffSwitch({optStackTrace}, arg, pass, info) - of "linetrace": ProcessOnOffSwitch({optLineTrace}, arg, pass, info) + of "warning": processSpecificNote(arg, wWarning, pass, info) + of "hint": processSpecificNote(arg, wHint, pass, info) + of "hints": processOnOffSwitch({optHints}, arg, pass, info) + of "threadanalysis": processOnOffSwitchG({optThreadAnalysis}, arg, pass, info) + of "stacktrace": processOnOffSwitch({optStackTrace}, arg, pass, info) + of "linetrace": processOnOffSwitch({optLineTrace}, arg, pass, info) of "debugger": - ProcessOnOffSwitch({optEndb}, arg, pass, info) - if optEndb in gOptions: DefineSymbol("endb") - else: UndefSymbol("endb") + processOnOffSwitch({optEndb}, arg, pass, info) + if optEndb in gOptions: defineSymbol("endb") + else: undefSymbol("endb") of "profiler": - ProcessOnOffSwitch({optProfiler}, arg, pass, info) - if optProfiler in gOptions: DefineSymbol("profiler") - else: UndefSymbol("profiler") - of "checks", "x": ProcessOnOffSwitch(checksOptions, arg, pass, info) + processOnOffSwitch({optProfiler}, arg, pass, info) + if optProfiler in gOptions: defineSymbol("profiler") + else: undefSymbol("profiler") + of "checks", "x": processOnOffSwitch(checksOptions, arg, pass, info) of "floatchecks": - ProcessOnOffSwitch({optNanCheck, optInfCheck}, arg, pass, info) - of "infchecks": ProcessOnOffSwitch({optInfCheck}, arg, pass, info) - of "nanchecks": ProcessOnOffSwitch({optNanCheck}, arg, pass, info) - of "objchecks": ProcessOnOffSwitch({optObjCheck}, arg, pass, info) - of "fieldchecks": ProcessOnOffSwitch({optFieldCheck}, arg, pass, info) - of "rangechecks": ProcessOnOffSwitch({optRangeCheck}, arg, pass, info) - of "boundchecks": ProcessOnOffSwitch({optBoundsCheck}, arg, pass, info) - of "overflowchecks": ProcessOnOffSwitch({optOverflowCheck}, arg, pass, info) - of "linedir": ProcessOnOffSwitch({optLineDir}, arg, pass, info) - of "assertions", "a": ProcessOnOffSwitch({optAssert}, arg, pass, info) - of "deadcodeelim": ProcessOnOffSwitchG({optDeadCodeElim}, arg, pass, info) - of "threads": ProcessOnOffSwitchG({optThreads}, arg, pass, info) - of "tlsemulation": ProcessOnOffSwitchG({optTlsEmulation}, arg, pass, info) - of "taintmode": ProcessOnOffSwitchG({optTaintMode}, arg, pass, info) + processOnOffSwitch({optNanCheck, optInfCheck}, arg, pass, info) + of "infchecks": processOnOffSwitch({optInfCheck}, arg, pass, info) + of "nanchecks": processOnOffSwitch({optNanCheck}, arg, pass, info) + of "objchecks": processOnOffSwitch({optObjCheck}, arg, pass, info) + of "fieldchecks": processOnOffSwitch({optFieldCheck}, arg, pass, info) + of "rangechecks": processOnOffSwitch({optRangeCheck}, arg, pass, info) + of "boundchecks": processOnOffSwitch({optBoundsCheck}, arg, pass, info) + of "overflowchecks": processOnOffSwitch({optOverflowCheck}, arg, pass, info) + of "linedir": processOnOffSwitch({optLineDir}, arg, pass, info) + of "assertions", "a": processOnOffSwitch({optAssert}, arg, pass, info) + of "deadcodeelim": processOnOffSwitchG({optDeadCodeElim}, arg, pass, info) + of "threads": processOnOffSwitchG({optThreads}, arg, pass, info) + of "tlsemulation": processOnOffSwitchG({optTlsEmulation}, arg, pass, info) + of "taintmode": processOnOffSwitchG({optTaintMode}, arg, pass, info) of "implicitstatic": - ProcessOnOffSwitch({optImplicitStatic}, arg, pass, info) + processOnOffSwitch({optImplicitStatic}, arg, pass, info) of "patterns": - ProcessOnOffSwitch({optPatterns}, arg, pass, info) + processOnOffSwitch({optPatterns}, arg, pass, info) of "opt": expectArg(switch, arg, pass, info) case arg.normalize @@ -367,7 +367,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = of "none": excl(gOptions, optOptimizeSpeed) excl(gOptions, optOptimizeSize) - else: LocalError(info, errNoneSpeedOrSizeExpectedButXFound, arg) + else: localError(info, errNoneSpeedOrSizeExpectedButXFound, arg) of "app": expectArg(switch, arg, pass, info) case arg.normalize @@ -389,7 +389,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = excl(gGlobalOptions, optGenGuiApp) defineSymbol("library") defineSymbol("staticlib") - else: LocalError(info, errGuiConsoleOrLibExpectedButXFound, arg) + else: localError(info, errGuiConsoleOrLibExpectedButXFound, arg) of "passc", "t": expectArg(switch, arg, pass, info) if pass in {passCmd2, passPP}: extccomp.addCompileOption(arg) @@ -409,7 +409,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = headerFile = arg incl(gGlobalOptions, optGenIndex) of "index": - ProcessOnOffSwitchG({optGenIndex}, arg, pass, info) + processOnOffSwitchG({optGenIndex}, arg, pass, info) of "import": expectArg(switch, arg, pass, info) if pass in {passCmd2, passPP}: implicitImports.add arg @@ -426,7 +426,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = expectArg(switch, arg, pass, info) if pass in {passCmd1, passPP}: theOS = platform.NameToOS(arg) - if theOS == osNone: LocalError(info, errUnknownOS, arg) + if theOS == osNone: localError(info, errUnknownOS, arg) elif theOS != platform.hostOS: setTarget(theOS, targetCPU) condsyms.InitDefines() @@ -434,7 +434,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = expectArg(switch, arg, pass, info) if pass in {passCmd1, passPP}: cpu = platform.NameToCPU(arg) - if cpu == cpuNone: LocalError(info, errUnknownCPU, arg) + if cpu == cpuNone: localError(info, errUnknownCPU, arg) elif cpu != platform.hostCPU: setTarget(targetOS, cpu) condsyms.InitDefines() @@ -457,7 +457,7 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = expectNoArg(switch, arg, pass, info) helpOnError(pass) of "symbolfiles": - ProcessOnOffSwitchG({optSymbolFiles}, arg, pass, info) + processOnOffSwitchG({optSymbolFiles}, arg, pass, info) of "skipcfg": expectNoArg(switch, arg, pass, info) incl(gGlobalOptions, optSkipConfigFile) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index 71dce9529..575cda412 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -78,11 +78,11 @@ proc initDefines*() = of osMacOSX: defineSymbol("macintosh") defineSymbol("unix") - DefineSymbol("posix") + defineSymbol("posix") else: discard - defineSymbol("cpu" & $cpu[targetCPU].bit) - defineSymbol(normalize(endianToStr[cpu[targetCPU].endian])) - defineSymbol(cpu[targetCPU].name) + defineSymbol("cpu" & $CPU[targetCPU].bit) + defineSymbol(normalize(EndianToStr[CPU[targetCPU].endian])) + defineSymbol(CPU[targetCPU].name) defineSymbol(platform.os[targetOS].name) if platform.OS[targetOS].props.contains(ospLacksThreadVars): defineSymbol("emulatedthreadvars") diff --git a/compiler/crc.nim b/compiler/crc.nim index a3b181e20..3291ce7c0 100644 --- a/compiler/crc.nim +++ b/compiler/crc.nim @@ -18,8 +18,8 @@ const InitAdler32* = int32(1) proc updateCrc32*(val: int8, crc: TCrc32): TCrc32 {.inline.} -proc updateCrc32*(val: Char, crc: TCrc32): TCrc32 {.inline.} -proc crcFromBuf*(buf: Pointer, length: int): TCrc32 +proc updateCrc32*(val: char, crc: TCrc32): TCrc32 {.inline.} +proc crcFromBuf*(buf: pointer, length: int): TCrc32 proc strCrc32*(s: string): TCrc32 proc crcFromFile*(filename: string): TCrc32 proc updateAdler32*(adler: int32, buf: pointer, length: int): int32 @@ -75,7 +75,7 @@ const 755167117] 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)) proc updateCrc32(val: Char, crc: TCrc32): TCrc32 = @@ -102,7 +102,7 @@ proc crcFromFile(filename: string): TCrc32 = const bufSize = 8000 # don't use 8K for the memory allocator! var - bin: tfile + bin: TFile result = InitCrc32 if not open(bin, filename): return # not equal if file does not exist diff --git a/compiler/depends.nim b/compiler/depends.nim index 1468cbdb9..5b02275c6 100644 --- a/compiler/depends.nim +++ b/compiler/depends.nim @@ -43,7 +43,7 @@ proc addDotDependency(c: PPassContext, n: PNode): PNode = proc generateDot(project: string) = writeRope(ropef("digraph $1 {$n$2}$n", [ - toRope(changeFileExt(extractFileName(project), "")), gDotGraph]), + toRope(changeFileExt(extractFilename(project), "")), gDotGraph]), changeFileExt(project, "dot")) proc myOpen(module: PSym): PPassContext = diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 018dcd270..b38f53015 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -40,11 +40,11 @@ proc compilerMsgHandler(filename: string, line, col: int, of mwRedefinitionOfLabel: k = warnRedefinitionOfLabel of mwUnknownSubstitution: k = warnUnknownSubstitutionX of mwUnsupportedLanguage: k = warnLanguageXNotSupported - GlobalError(newLineInfo(filename, line, col), k, arg) + globalError(newLineInfo(filename, line, col), k, arg) proc parseRst(text, filename: string, line, column: int, hasToc: var bool, - rstOptions: TRstParseOptions): PRstNode = + rstOptions: TRstParseOptions): PRSTNode = result = rstParse(text, filename, line, column, hasToc, rstOptions, options.FindFile, compilerMsgHandler) @@ -55,18 +55,18 @@ proc newDocumentor*(filename: string, config: PStringTable): PDoc = options.FindFile, compilerMsgHandler) 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) else: appf(dest, tex, args) -proc getVarIdx(varnames: openarray[string], id: string): int = +proc getVarIdx(varnames: openArray[string], id: string): int = for i in countup(0, high(varnames)): if cmpIgnoreStyle(varnames[i], id) == 0: return i result = -1 -proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openarray[string], - varvalues: openarray[PRope]): PRope = +proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openArray[string], + varvalues: openArray[PRope]): PRope = var i = 0 var L = len(frmt) result = nil @@ -85,7 +85,7 @@ proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openarray[string], of '0'..'9': var j = 0 while true: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) if (i > L + 0 - 1) or not (frmt[i] in {'0'..'9'}): break if j > high(varvalues) + 1: internalError("ropeFormatNamedVars") @@ -112,7 +112,7 @@ proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openarray[string], var idx = getVarIdx(varnames, id) if idx >= 0: app(result, varvalues[idx]) else: rawMessage(errUnkownSubstitionVar, id) - else: InternalError("ropeFormatNamedVars") + else: internalError("ropeFormatNamedVars") var start = i while i < L: if frmt[i] != '$': inc(i) @@ -124,7 +124,7 @@ proc genComment(d: PDoc, n: PNode): string = var dummyHasToc: bool if n.comment != nil and startsWith(n.comment, "##"): renderRstToOut(d[], parseRst(n.comment, toFilename(n.info), - toLineNumber(n.info), toColumn(n.info), + toLinenumber(n.info), toColumn(n.info), dummyHasToc, d.options + {roSkipPounds}), result) proc genRecComment(d: PDoc, n: PNode): PRope = @@ -152,7 +152,7 @@ proc extractDocComment*(s: PSym, d: PDoc = nil): string = if not d.isNil: var dummyHasToc: bool renderRstToOut(d[], parseRst(n.comment, toFilename(n.info), - toLineNumber(n.info), toColumn(n.info), + toLinenumber(n.info), toColumn(n.info), dummyHasToc, d.options + {roSkipPounds}), result) else: @@ -186,7 +186,7 @@ proc getName(d: PDoc, n: PNode, splitAfter = -1): string = internalError(n.info, "getName()") result = "" -proc getRstName(n: PNode): PRstNode = +proc getRstName(n: PNode): PRSTNode = case n.kind of nkPostfix: result = getRstName(n.sons[1]) of nkPragmaExpr: result = getRstName(n.sons[0]) @@ -272,7 +272,7 @@ proc genJSONItem(d: PDoc, n, nameNode: PNode, k: TSymKind): PJsonNode = result["code"] = %r.buf proc checkForFalse(n: PNode): bool = - result = n.kind == nkIdent and IdentEq(n.ident, "false") + result = n.kind == nkIdent and identEq(n.ident, "false") proc traceDeps(d: PDoc, n: PNode) = const k = skModule diff --git a/compiler/evaltempl.nim b/compiler/evaltempl.nim index 4bff9ae5e..14202dbca 100644 --- a/compiler/evaltempl.nim +++ b/compiler/evaltempl.nim @@ -37,11 +37,11 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) = result.add copyTree(x) else: InternalAssert sfGenSym in s.flags - var x = PSym(IdTableGet(c.mapping, s)) + var x = PSym(idTableGet(c.mapping, s)) if x == nil: x = copySym(s, false) x.owner = c.genSymOwner - IdTablePut(c.mapping, s, x) + idTablePut(c.mapping, s, x) result.add newSymNode(x, if c.instLines: actual.info else: templ.info) else: result.add copyNode(c, templ, actual) @@ -62,13 +62,13 @@ proc evalTemplateArgs(n: PNode, s: PSym): PNode = a = sonsLen(n) else: a = 0 var f = s.typ.sonsLen - if a > f: GlobalError(n.info, errWrongNumberOfArguments) + if a > f: globalError(n.info, errWrongNumberOfArguments) result = newNodeI(nkArgList, n.info) for i in countup(1, f - 1): var arg = if i < a: n.sons[i] else: copyTree(s.typ.n.sons[i].sym.ast) if arg == nil or arg.kind == nkEmpty: - LocalError(n.info, errWrongNumberOfArguments) + localError(n.info, errWrongNumberOfArguments) addSon(result, arg) var evalTemplateCounter* = 0 @@ -77,7 +77,7 @@ var evalTemplateCounter* = 0 proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym): PNode = inc(evalTemplateCounter) if evalTemplateCounter > 100: - GlobalError(n.info, errTemplateInstantiationTooNested) + globalError(n.info, errTemplateInstantiationTooNested) result = n # replace each param by the corresponding node: @@ -93,7 +93,7 @@ proc evalTemplate*(n: PNode, tmpl, genSymOwner: PSym): PNode = evalTemplateAux(body, args, ctx, result) if result.len == 1: result = result.sons[0] else: - GlobalError(result.info, errIllFormedAstX, + globalError(result.info, errIllFormedAstX, renderTree(result, {renderNoComments})) else: result = copyNode(body) diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index 629cf95eb..afcba8b4b 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -346,13 +346,13 @@ proc getConfigVar(c: TSystemCC, suffix: string): string = result = getConfigVar(CC[c].name & suffix) proc setCC*(ccname: string) = - ccompiler = nameToCC(ccname) - if ccompiler == ccNone: rawMessage(errUnknownCcompiler, ccname) - compileOptions = getConfigVar(ccompiler, ".options.always") - linkOptions = getConfigVar(ccompiler, ".options.linker") - ccompilerpath = getConfigVar(ccompiler, ".path") + cCompiler = nameToCC(ccname) + if cCompiler == ccNone: rawMessage(errUnknownCcompiler, ccname) + compileOptions = getConfigVar(cCompiler, ".options.always") + linkOptions = getConfigVar(cCompiler, ".options.linker") + ccompilerpath = getConfigVar(cCompiler, ".path") for i in countup(low(CC), high(CC)): undefSymbol(CC[i].name) - defineSymbol(CC[ccompiler].name) + defineSymbol(CC[cCompiler].name) proc addOpt(dest: var string, src: string) = if len(dest) == 0 or dest[len(dest)-1] != ' ': add(dest, " ") @@ -368,20 +368,20 @@ proc addCompileOption*(option: string) = proc initVars*() = # we need to define the symbol here, because ``CC`` may have never been set! for i in countup(low(CC), high(CC)): undefSymbol(CC[i].name) - defineSymbol(CC[ccompiler].name) + defineSymbol(CC[cCompiler].name) if gCmd == cmdCompileToCpp: cExt = ".cpp" elif gCmd == cmdCompileToOC: cExt = ".m" - addCompileOption(getConfigVar(ccompiler, ".options.always")) - addLinkOption(getConfigVar(ccompiler, ".options.linker")) - if len(ccompilerPath) == 0: - ccompilerpath = getConfigVar(ccompiler, ".path") + addCompileOption(getConfigVar(cCompiler, ".options.always")) + addLinkOption(getConfigVar(cCompiler, ".options.linker")) + if len(ccompilerpath) == 0: + ccompilerpath = getConfigVar(cCompiler, ".path") proc completeCFilePath*(cfile: string, createSubDir: bool = true): string = result = completeGeneratedFilePath(cfile, createSubDir) proc toObjFile*(filenameWithoutExt: string): string = # Object file for compilation - result = changeFileExt(filenameWithoutExt, cc[ccompiler].objExt) + result = changeFileExt(filenameWithoutExt, CC[cCompiler].objExt) proc addFileToCompile*(filename: string) = appendStr(toCompile, filename) @@ -400,7 +400,7 @@ proc addFileToLink*(filename: string) = # BUGFIX: was ``appendStr`` proc execExternalProgram*(cmd: string) = - if optListCmd in gGlobalOptions or gVerbosity > 0: MsgWriteln(cmd) + if optListCmd in gGlobalOptions or gVerbosity > 0: msgWriteln(cmd) if execCmd(cmd) != 0: rawMessage(errExecutionOfProgramFailed, "") proc generateScript(projectFile: string, script: PRope) = @@ -411,17 +411,17 @@ proc generateScript(projectFile: string, script: PRope) = proc getOptSpeed(c: TSystemCC): string = result = getConfigVar(c, ".options.speed") if result == "": - result = cc[c].optSpeed # use default settings from this file + result = CC[c].optSpeed # use default settings from this file proc getDebug(c: TSystemCC): string = result = getConfigVar(c, ".options.debug") if result == "": - result = cc[c].debug # use default settings from this file + result = CC[c].debug # use default settings from this file proc getOptSize(c: TSystemCC): string = result = getConfigVar(c, ".options.size") if result == "": - result = cc[c].optSize # use default settings from this file + result = CC[c].optSize # use default settings from this file proc noAbsolutePaths: bool {.inline.} = # We used to check current OS != specified OS, but this makes no sense @@ -436,7 +436,7 @@ const var fileCounter: int -proc add(s: var string, many: openarray[string]) = +proc add(s: var string, many: openArray[string]) = s.add many.join proc cFileSpecificOptions(cfilename: string): string = @@ -445,69 +445,69 @@ proc cFileSpecificOptions(cfilename: string): string = if optCDebug in gGlobalOptions: var key = trunk & ".debug" if existsConfigVar(key): addOpt(result, getConfigVar(key)) - else: addOpt(result, getDebug(ccompiler)) + else: addOpt(result, getDebug(cCompiler)) if optOptimizeSpeed in gOptions: var key = trunk & ".speed" if existsConfigVar(key): addOpt(result, getConfigVar(key)) - else: addOpt(result, getOptSpeed(ccompiler)) + else: addOpt(result, getOptSpeed(cCompiler)) elif optOptimizeSize in gOptions: var key = trunk & ".size" if existsConfigVar(key): addOpt(result, getConfigVar(key)) - else: addOpt(result, getOptSize(ccompiler)) + else: addOpt(result, getOptSize(cCompiler)) var key = trunk & ".always" if existsConfigVar(key): addOpt(result, getConfigVar(key)) proc getCompileOptions: string = - result = CFileSpecificOptions("__dummy__") + result = cFileSpecificOptions("__dummy__") proc getLinkOptions: string = result = linkOptions for linkedLib in items(cLinkedLibs): - result.add(cc[ccompiler].linkLibCmd % linkedLib.quoteShell) + result.add(CC[cCompiler].linkLibCmd % linkedLib.quoteShell) for libDir in items(cLibs): - result.add([cc[ccompiler].linkDirCmd, libDir.quoteShell]) + result.add([CC[cCompiler].linkDirCmd, libDir.quoteShell]) proc needsExeExt(): bool {.inline.} = result = (optGenScript in gGlobalOptions and targetOS == osWindows) or (platform.hostOS == osWindows) proc getCompileCFileCmd*(cfilename: string, isExternal = false): string = - var c = ccompiler - var options = CFileSpecificOptions(cfilename) + var c = cCompiler + var options = cFileSpecificOptions(cfilename) var exe = getConfigVar(c, ".exe") - if exe.len == 0: exe = cc[c].compilerExe + if exe.len == 0: exe = CC[c].compilerExe if needsExeExt(): exe = addFileExt(exe, "exe") if optGenDynLib in gGlobalOptions and ospNeedsPIC in platform.OS[targetOS].props: - add(options, ' ' & cc[c].pic) + add(options, ' ' & CC[c].pic) var includeCmd, compilePattern: string if not noAbsolutePaths(): # compute include paths: - includeCmd = cc[c].includeCmd & quoteShell(libpath) + includeCmd = CC[c].includeCmd & quoteShell(libpath) for includeDir in items(cIncludes): - includeCmd.add([cc[c].includeCmd, includeDir.quoteShell]) + includeCmd.add([CC[c].includeCmd, includeDir.quoteShell]) - compilePattern = JoinPath(ccompilerpath, exe) + compilePattern = joinPath(ccompilerpath, exe) else: includeCmd = "" - compilePattern = cc[c].compilerExe + compilePattern = CC[c].compilerExe - var cfile = if noAbsolutePaths(): extractFileName(cfilename) + var cfile = if noAbsolutePaths(): extractFilename(cfilename) else: cfilename var objfile = if not isExternal or noAbsolutePaths(): toObjFile(cfile) else: completeCFilePath(toObjFile(cfile)) - cfile = quoteShell(AddFileExt(cfile, cExt)) + cfile = quoteShell(addFileExt(cfile, cExt)) objfile = quoteShell(objfile) result = quoteShell(compilePattern % [ "file", cfile, "objfile", objfile, "options", options, "include", includeCmd, "nimrod", getPrefixDir(), "lib", libpath]) add(result, ' ') - addf(result, cc[c].compileTmpl, [ + addf(result, CC[c].compileTmpl, [ "file", cfile, "objfile", objfile, "options", options, "include", includeCmd, "nimrod", quoteShell(getPrefixDir()), @@ -561,7 +561,7 @@ proc callCCompiler*(projectfile: string) = return # speed up that call if only compiling and no script shall be # generated fileCounter = 0 - var c = ccompiler + var c = cCompiler var script: PRope = nil var cmds: TStringSeq = @[] compileCFile(toCompile, script, cmds, false) @@ -591,40 +591,40 @@ proc callCCompiler*(projectfile: string) = let objFile = if noAbsolutePaths(): it.data.extractFilename else: it.data add(objfiles, ' ') add(objfiles, quoteShell( - addFileExt(objFile, cc[ccompiler].objExt))) + addFileExt(objFile, CC[cCompiler].objExt))) it = PStrEntry(it.next) if optGenStaticLib in gGlobalOptions: - linkcmd = cc[c].buildLib % ["libfile", (libNameTmpl() % gProjectName), + linkCmd = CC[c].buildLib % ["libfile", (libNameTmpl() % gProjectName), "objfiles", objfiles] if optCompileOnly notin gGlobalOptions: execExternalProgram(linkCmd) else: var linkerExe = getConfigVar(c, ".linkerexe") - if len(linkerExe) == 0: linkerExe = cc[c].linkerExe + if len(linkerExe) == 0: linkerExe = CC[c].linkerExe if needsExeExt(): linkerExe = addFileExt(linkerExe, "exe") if noAbsolutePaths(): linkCmd = quoteShell(linkerExe) - else: linkCmd = quoteShell(JoinPath(ccompilerpath, linkerExe)) - if optGenGuiApp in gGlobalOptions: buildGui = cc[c].buildGui - else: buildGui = "" + else: linkCmd = quoteShell(joinPath(ccompilerpath, linkerExe)) + if optGenGuiApp in gGlobalOptions: buildgui = CC[c].buildGui + else: buildgui = "" var exefile: string if optGenDynLib in gGlobalOptions: - exefile = platform.os[targetOS].dllFrmt % splitFile(projectFile).name - buildDll = cc[c].buildDll + exefile = platform.os[targetOS].dllFrmt % splitFile(projectfile).name + builddll = CC[c].buildDll else: - exefile = splitFile(projectFile).name & platform.os[targetOS].exeExt - buildDll = "" + exefile = splitFile(projectfile).name & platform.os[targetOS].exeExt + builddll = "" if options.outFile.len > 0: exefile = options.outFile if not noAbsolutePaths(): - if not exeFile.isAbsolute(): - exefile = joinPath(splitFile(projectFile).dir, exefile) + if not exefile.isAbsolute(): + exefile = joinPath(splitFile(projectfile).dir, exefile) exefile = quoteShell(exefile) let linkOptions = getLinkOptions() linkCmd = quoteShell(linkCmd % ["builddll", builddll, "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles, "exefile", exefile, "nimrod", getPrefixDir(), "lib", libpath]) linkCmd.add ' ' - addf(linkCmd, cc[c].linkTmpl, ["builddll", builddll, + addf(linkCmd, CC[c].linkTmpl, ["builddll", builddll, "buildgui", buildgui, "options", linkOptions, "objfiles", objfiles, "exefile", exefile, "nimrod", quoteShell(getPrefixDir()), @@ -635,7 +635,7 @@ proc callCCompiler*(projectfile: string) = if optGenScript in gGlobalOptions: app(script, linkCmd) app(script, tnl) - generateScript(projectFile, script) + generateScript(projectfile, script) proc genMappingFiles(list: TLinkedList): PRope = var it = PStrEntry(list.head) diff --git a/compiler/filter_tmpl.nim b/compiler/filter_tmpl.nim index d16639d08..749d38b34 100644 --- a/compiler/filter_tmpl.nim +++ b/compiler/filter_tmpl.nim @@ -27,7 +27,7 @@ type indent, emitPar: int x: string # the current input line outp: PLLStream # the ouput will be parsed by pnimsyn - subsChar, NimDirective: Char + subsChar, NimDirective: char emit, conc, toStr: string curly, bracket, par: int pendingExprLine: bool @@ -37,11 +37,11 @@ const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '.', '_'} proc newLine(p: var TTmplParser) = - LLStreamWrite(p.outp, repeatChar(p.emitPar, ')')) + llStreamWrite(p.outp, repeatChar(p.emitPar, ')')) p.emitPar = 0 - if p.info.line > int16(1): LLStreamWrite(p.outp, "\n") + if p.info.line > int16(1): llStreamWrite(p.outp, "\n") if p.pendingExprLine: - LLStreamWrite(p.outp, repeatChar(2)) + llStreamWrite(p.outp, repeatChar(2)) p.pendingExprLine = false proc scanPar(p: var TTmplParser, d: int) = @@ -87,26 +87,26 @@ proc parseLine(p: var TTmplParser) = dec(p.indent, 2) else: p.info.col = int16(j) - LocalError(p.info, errXNotAllowedHere, "end") - LLStreamWrite(p.outp, repeatChar(p.indent)) - LLStreamWrite(p.outp, "#end") + localError(p.info, errXNotAllowedHere, "end") + llStreamWrite(p.outp, repeatChar(p.indent)) + llStreamWrite(p.outp, "#end") of wIf, wWhen, wTry, wWhile, wFor, wBlock, wCase, wProc, wIterator, wConverter, wMacro, wTemplate, wMethod: - LLStreamWrite(p.outp, repeatChar(p.indent)) - LLStreamWrite(p.outp, substr(p.x, d)) + llStreamWrite(p.outp, repeatChar(p.indent)) + llStreamWrite(p.outp, substr(p.x, d)) inc(p.indent, 2) of wElif, wOf, wElse, wExcept, wFinally: - LLStreamWrite(p.outp, repeatChar(p.indent - 2)) - LLStreamWrite(p.outp, substr(p.x, d)) + llStreamWrite(p.outp, repeatChar(p.indent - 2)) + llStreamWrite(p.outp, substr(p.x, d)) of wLet, wVar, wConst, wType: - LLStreamWrite(p.outp, repeatChar(p.indent)) - LLStreamWrite(p.outp, substr(p.x, d)) + llStreamWrite(p.outp, repeatChar(p.indent)) + llStreamWrite(p.outp, substr(p.x, d)) if not p.x.contains({':', '='}): # no inline element --> treat as block: inc(p.indent, 2) else: - LLStreamWrite(p.outp, repeatChar(p.indent)) - LLStreamWrite(p.outp, substr(p.x, d)) + llStreamWrite(p.outp, repeatChar(p.indent)) + llStreamWrite(p.outp, substr(p.x, d)) p.state = psDirective else: # data line @@ -118,15 +118,15 @@ proc parseLine(p: var TTmplParser) = case p.state of psTempl: # next line of string literal: - LLStreamWrite(p.outp, p.conc) - LLStreamWrite(p.outp, "\n") - LLStreamWrite(p.outp, repeatChar(p.indent + 2)) - LLStreamWrite(p.outp, "\"") + llStreamWrite(p.outp, p.conc) + llStreamWrite(p.outp, "\n") + llStreamWrite(p.outp, repeatChar(p.indent + 2)) + llStreamWrite(p.outp, "\"") of psDirective: newLine(p) - LLStreamWrite(p.outp, repeatChar(p.indent)) - LLStreamWrite(p.outp, p.emit) - LLStreamWrite(p.outp, "(\"") + llStreamWrite(p.outp, repeatChar(p.indent)) + llStreamWrite(p.outp, p.emit) + llStreamWrite(p.outp, "(\"") inc(p.emitPar) p.state = psTempl while true: @@ -134,17 +134,17 @@ proc parseLine(p: var TTmplParser) = of '\0': break of '\x01'..'\x1F', '\x80'..'\xFF': - LLStreamWrite(p.outp, "\\x") - LLStreamWrite(p.outp, toHex(ord(p.x[j]), 2)) + llStreamWrite(p.outp, "\\x") + llStreamWrite(p.outp, toHex(ord(p.x[j]), 2)) inc(j) of '\\': - LLStreamWrite(p.outp, "\\\\") + llStreamWrite(p.outp, "\\\\") inc(j) of '\'': - LLStreamWrite(p.outp, "\\\'") + llStreamWrite(p.outp, "\\\'") inc(j) of '\"': - LLStreamWrite(p.outp, "\\\"") + llStreamWrite(p.outp, "\\\"") inc(j) else: if p.x[j] == p.subsChar: @@ -153,59 +153,59 @@ proc parseLine(p: var TTmplParser) = case p.x[j] of '{': p.info.col = int16(j) - LLStreamWrite(p.outp, '\"') - LLStreamWrite(p.outp, p.conc) - LLStreamWrite(p.outp, p.toStr) - LLStreamWrite(p.outp, '(') + llStreamWrite(p.outp, '\"') + llStreamWrite(p.outp, p.conc) + llStreamWrite(p.outp, p.toStr) + llStreamWrite(p.outp, '(') inc(j) curly = 0 while true: case p.x[j] of '\0': - LocalError(p.info, errXExpected, "}") + localError(p.info, errXExpected, "}") break of '{': inc(j) inc(curly) - LLStreamWrite(p.outp, '{') + llStreamWrite(p.outp, '{') of '}': inc(j) if curly == 0: break if curly > 0: dec(curly) - LLStreamWrite(p.outp, '}') + llStreamWrite(p.outp, '}') else: - LLStreamWrite(p.outp, p.x[j]) + llStreamWrite(p.outp, p.x[j]) inc(j) - LLStreamWrite(p.outp, ')') - LLStreamWrite(p.outp, p.conc) - LLStreamWrite(p.outp, '\"') + llStreamWrite(p.outp, ')') + llStreamWrite(p.outp, p.conc) + llStreamWrite(p.outp, '\"') of 'a'..'z', 'A'..'Z', '\x80'..'\xFF': - LLStreamWrite(p.outp, '\"') - LLStreamWrite(p.outp, p.conc) - LLStreamWrite(p.outp, p.toStr) - LLStreamWrite(p.outp, '(') + llStreamWrite(p.outp, '\"') + llStreamWrite(p.outp, p.conc) + llStreamWrite(p.outp, p.toStr) + llStreamWrite(p.outp, '(') while p.x[j] in PatternChars: - LLStreamWrite(p.outp, p.x[j]) + llStreamWrite(p.outp, p.x[j]) inc(j) - LLStreamWrite(p.outp, ')') - LLStreamWrite(p.outp, p.conc) - LLStreamWrite(p.outp, '\"') + llStreamWrite(p.outp, ')') + llStreamWrite(p.outp, p.conc) + llStreamWrite(p.outp, '\"') else: if p.x[j] == p.subsChar: - LLStreamWrite(p.outp, p.subsChar) + llStreamWrite(p.outp, p.subsChar) inc(j) else: p.info.col = int16(j) - LocalError(p.info, errInvalidExpression, "$") + localError(p.info, errInvalidExpression, "$") else: - LLStreamWrite(p.outp, p.x[j]) + llStreamWrite(p.outp, p.x[j]) inc(j) - LLStreamWrite(p.outp, "\\n\"") + llStreamWrite(p.outp, "\\n\"") proc filterTmpl(stdin: PLLStream, filename: string, call: PNode): PLLStream = var p: TTmplParser p.info = newLineInfo(filename, 0, 0) - p.outp = LLStreamOpen("") + p.outp = llStreamOpen("") p.inp = stdin p.subsChar = charArg(call, "subschar", 1, '$') p.nimDirective = charArg(call, "metachar", 2, '#') @@ -213,9 +213,9 @@ proc filterTmpl(stdin: PLLStream, filename: string, call: PNode): PLLStream = p.conc = strArg(call, "conc", 4, " & ") p.toStr = strArg(call, "tostring", 5, "$") p.x = newStringOfCap(120) - while LLStreamReadLine(p.inp, p.x): + while llStreamReadLine(p.inp, p.x): p.info.line = p.info.line + int16(1) parseLine(p) newLine(p) result = p.outp - LLStreamClose(p.inp) + llStreamClose(p.inp) diff --git a/compiler/filters.nim b/compiler/filters.nim index 19da11bca..db8731d8c 100644 --- a/compiler/filters.nim +++ b/compiler/filters.nim @@ -16,13 +16,13 @@ import proc filterReplace*(stdin: PLLStream, filename: string, call: PNode): PLLStream proc filterStrip*(stdin: PLLStream, filename: string, call: PNode): PLLStream # helpers to retrieve arguments: -proc charArg*(n: PNode, name: string, pos: int, default: Char): Char +proc charArg*(n: PNode, name: string, pos: int, default: char): char proc strArg*(n: PNode, name: string, pos: int, default: string): string proc boolArg*(n: PNode, name: string, pos: int, default: bool): bool # implementation proc invalidPragma(n: PNode) = - LocalError(n.info, errXNotAllowedHere, renderTree(n, {renderNoComments})) + localError(n.info, errXNotAllowedHere, renderTree(n, {renderNoComments})) proc getArg(n: PNode, name: string, pos: int): PNode = result = nil @@ -30,7 +30,7 @@ proc getArg(n: PNode, name: string, pos: int): PNode = for i in countup(1, sonsLen(n) - 1): if n.sons[i].kind == nkExprEqExpr: if n.sons[i].sons[0].kind != nkIdent: invalidPragma(n) - if IdentEq(n.sons[i].sons[0].ident, name): + if identEq(n.sons[i].sons[0].ident, name): return n.sons[i].sons[1] elif i == pos: return n.sons[i] @@ -50,30 +50,30 @@ proc strArg(n: PNode, name: string, pos: int, default: string): string = proc boolArg(n: PNode, name: string, pos: int, default: bool): bool = var x = getArg(n, name, pos) if x == nil: result = default - elif (x.kind == nkIdent) and IdentEq(x.ident, "true"): result = true - elif (x.kind == nkIdent) and IdentEq(x.ident, "false"): result = false + elif (x.kind == nkIdent) and identEq(x.ident, "true"): result = true + elif (x.kind == nkIdent) and identEq(x.ident, "false"): result = false else: invalidPragma(n) proc filterStrip(stdin: PLLStream, filename: string, call: PNode): PLLStream = var pattern = strArg(call, "startswith", 1, "") var leading = boolArg(call, "leading", 2, true) var trailing = boolArg(call, "trailing", 3, true) - result = LLStreamOpen("") + result = llStreamOpen("") var line = newStringOfCap(80) - while LLStreamReadLine(stdin, line): + while llStreamReadLine(stdin, line): var stripped = strip(line, leading, trailing) if (len(pattern) == 0) or startsWith(stripped, pattern): - LLStreamWriteln(result, stripped) + llStreamWriteln(result, stripped) else: - LLStreamWriteln(result, line) - LLStreamClose(stdin) + llStreamWriteln(result, line) + llStreamClose(stdin) proc filterReplace(stdin: PLLStream, filename: string, call: PNode): PLLStream = var sub = strArg(call, "sub", 1, "") if len(sub) == 0: invalidPragma(call) var by = strArg(call, "by", 2, "") - result = LLStreamOpen("") + result = llStreamOpen("") var line = newStringOfCap(80) - while LLStreamReadLine(stdin, line): - LLStreamWriteln(result, replace(line, sub, by)) - LLStreamClose(stdin) + while llStreamReadLine(stdin, line): + llStreamWriteln(result, replace(line, sub, by)) + llStreamClose(stdin) diff --git a/compiler/guards.nim b/compiler/guards.nim index 8d271fa6d..b35d9b872 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -251,7 +251,7 @@ proc invalidateFacts*(m: var TModel, n: PNode) = proc valuesUnequal(a, b: PNode): bool = if a.isValue and b.isValue: - result = not SameValue(a, b) + result = not sameValue(a, b) proc pred(n: PNode): PNode = if n.kind in {nkCharLit..nkUInt64Lit} and n.intVal != low(biggestInt): @@ -484,7 +484,7 @@ proc factImplies(fact, prop: PNode): TImplication = if a == b: return ~a return impUnknown else: - InternalError(fact.info, "invalid fact") + internalError(fact.info, "invalid fact") of mAnd: result = factImplies(fact.sons[1], prop) if result != impUnknown: return result @@ -575,4 +575,4 @@ proc checkFieldAccess*(m: TModel, n: PNode) = for i in 1..n.len-1: let check = buildProperFieldCheck(n.sons[0], n.sons[i]) if m.doesImply(check) != impYes: - Message(n.info, warnProveField, renderTree(n.sons[0])); break + message(n.info, warnProveField, renderTree(n.sons[0])); break diff --git a/compiler/hlo.nim b/compiler/hlo.nim index 1492ed76f..7905761dd 100644 --- a/compiler/hlo.nim +++ b/compiler/hlo.nim @@ -28,7 +28,7 @@ proc evalPattern(c: PContext, n, orig: PNode): PNode = else: result = semDirectOp(c, n, {}) if optHints in gOptions and hintPattern in gNotes: - Message(orig.info, hintPattern, rule & " --> '" & + message(orig.info, hintPattern, rule & " --> '" & renderTree(result, {renderNoComments}) & "'") proc applyPatterns(c: PContext, n: PNode): PNode = @@ -45,7 +45,7 @@ proc applyPatterns(c: PContext, n: PNode): PNode = # better be safe than sorry, so check evalTemplateCounter too: inc(evalTemplateCounter) if evalTemplateCounter > 100: - GlobalError(n.info, errTemplateInstantiationTooNested) + globalError(n.info, errTemplateInstantiationTooNested) # deactivate this pattern: c.patterns[i] = nil if x.kind == nkStmtList: diff --git a/compiler/idgen.nim b/compiler/idgen.nim index f47e2e3b6..5a1c90930 100644 --- a/compiler/idgen.nim +++ b/compiler/idgen.nim @@ -38,7 +38,7 @@ proc setId*(id: int) {.inline.} = gFrontEndId = max(gFrontEndId, id + 1) proc idSynchronizationPoint*(idRange: int) = - gFrontEndId = (gFrontEndId div IdRange + 1) * IdRange + 1 + gFrontEndId = (gFrontEndId div idRange + 1) * idRange + 1 proc toGid(f: string): string = # we used to use ``f.addFileExt("gid")`` (aka ``$project.gid``), but this @@ -49,7 +49,7 @@ proc toGid(f: string): string = proc saveMaxIds*(project: string) = var f = open(project.toGid, fmWrite) f.writeln($gFrontEndId) - f.writeln($gBackEndId) + f.writeln($gBackendId) f.close() proc loadMaxIds*(project: string) = @@ -61,5 +61,5 @@ proc loadMaxIds*(project: string) = if f.readLine(line): var backEndId = parseInt(line) gFrontEndId = max(gFrontEndId, frontEndId) - gBackEndId = max(gBackEndId, backEndId) + gBackendId = max(gBackendId, backEndId) f.close() diff --git a/compiler/importer.nim b/compiler/importer.nim index 8b854bcc6..24779f2ae 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -22,7 +22,7 @@ proc getModuleName*(n: PNode): string = # The proc won't perform any checks that the path is actually valid case n.kind of nkStrLit, nkRStrLit, nkTripleStrLit: - result = UnixToNativePath(n.strVal) + result = unixToNativePath(n.strVal) of nkIdent: result = n.ident.s of nkSym: @@ -50,7 +50,7 @@ proc checkModuleName*(n: PNode): int32 = let modulename = n.getModuleName let fullPath = findModule(modulename, n.info.toFullPath) if fullPath.len == 0: - LocalError(n.info, errCannotOpenFile, modulename) + localError(n.info, errCannotOpenFile, modulename) result = InvalidFileIDX else: result = fullPath.fileInfoIdx @@ -59,32 +59,32 @@ proc rawImportSymbol(c: PContext, s: PSym) = # This does not handle stubs, because otherwise loading on demand would be # pointless in practice. So importing stubs is fine here! # check if we have already a symbol of the same name: - var check = StrTableGet(c.importTable.symbols, s.name) + var check = strTableGet(c.importTable.symbols, s.name) if check != nil and check.id != s.id: if s.kind notin OverloadableSyms: # s and check need to be qualified: - Incl(c.AmbiguousSymbols, s.id) - Incl(c.AmbiguousSymbols, check.id) + incl(c.AmbiguousSymbols, s.id) + incl(c.AmbiguousSymbols, check.id) # thanks to 'export' feature, it could be we import the same symbol from # multiple sources, so we need to call 'StrTableAdd' here: - StrTableAdd(c.importTable.symbols, s) + strTableAdd(c.importTable.symbols, s) if s.kind == skType: var etyp = s.typ if etyp.kind in {tyBool, tyEnum} and sfPure notin s.flags: for j in countup(0, sonsLen(etyp.n) - 1): var e = etyp.n.sons[j].sym if e.Kind != skEnumField: - InternalError(s.info, "rawImportSymbol") + internalError(s.info, "rawImportSymbol") # BUGFIX: because of aliases for enums the symbol may already # have been put into the symbol table # BUGFIX: but only iff they are the same symbols! var it: TIdentIter - check = InitIdentIter(it, c.importTable.symbols, e.name) + check = initIdentIter(it, c.importTable.symbols, e.name) while check != nil: if check.id == e.id: e = nil break - check = NextIdentIter(it, c.importTable.symbols) + check = nextIdentIter(it, c.importTable.symbols) if e != nil: rawImportSymbol(c, e) else: @@ -94,36 +94,36 @@ proc rawImportSymbol(c: PContext, s: PSym) = proc importSymbol(c: PContext, n: PNode, fromMod: PSym) = let ident = lookups.considerAcc(n) - let s = StrTableGet(fromMod.tab, ident) + let s = strTableGet(fromMod.tab, ident) if s == nil: - LocalError(n.info, errUndeclaredIdentifier, ident.s) + localError(n.info, errUndeclaredIdentifier, ident.s) else: if s.kind == skStub: loadStub(s) if s.Kind notin ExportableSymKinds: - InternalError(n.info, "importSymbol: 2") + internalError(n.info, "importSymbol: 2") # for an enumeration we have to add all identifiers case s.Kind of skProc, skMethod, skIterator, skMacro, skTemplate, skConverter: # for a overloadable syms add all overloaded routines var it: TIdentIter - var e = InitIdentIter(it, fromMod.tab, s.name) + var e = initIdentIter(it, fromMod.tab, s.name) while e != nil: - if e.name.id != s.Name.id: InternalError(n.info, "importSymbol: 3") + if e.name.id != s.Name.id: internalError(n.info, "importSymbol: 3") rawImportSymbol(c, e) - e = NextIdentIter(it, fromMod.tab) + e = nextIdentIter(it, fromMod.tab) else: rawImportSymbol(c, s) proc importAllSymbolsExcept(c: PContext, fromMod: PSym, exceptSet: TIntSet) = var i: TTabIter - var s = InitTabIter(i, fromMod.tab) + var s = initTabIter(i, fromMod.tab) while s != nil: if s.kind != skModule: if s.kind != skEnumField: if s.Kind notin ExportableSymKinds: - InternalError(s.info, "importAllSymbols: " & $s.kind) + internalError(s.info, "importAllSymbols: " & $s.kind) if exceptSet.empty or s.name.id notin exceptSet: rawImportSymbol(c, s) - s = NextIter(i, fromMod.tab) + s = nextIter(i, fromMod.tab) proc importAllSymbols*(c: PContext, fromMod: PSym) = var exceptSet: TIntSet @@ -160,7 +160,7 @@ proc myImportModule(c: PContext, n: PNode): PSym = if f != InvalidFileIDX: result = importModuleAs(n, gImportModule(c.module, f)) if sfDeprecated in result.flags: - Message(n.info, warnDeprecated, result.name.s) + message(n.info, warnDeprecated, result.name.s) proc evalImport(c: PContext, n: PNode): PNode = result = n diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index a3c88824d..8fd72623a 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -175,7 +175,7 @@ proc useMagic(p: PProc, name: string) = # we used to exclude the system module from this check, but for DLL # generation support this sloppyness leads to hard to detect bugs, so # we're picky here for the system module too: - if p.prc != nil: GlobalError(p.prc.info, errSystemNeeds, name) + if p.prc != nil: globalError(p.prc.info, errSystemNeeds, name) else: rawMessage(errSystemNeeds, name) proc isSimpleExpr(n: PNode): bool = @@ -504,7 +504,7 @@ proc genWhileStmt(p: PProc, n: PNode) = genLineDir(p, n) inc(p.unique) var length = len(p.blocks) - setlen(p.blocks, length + 1) + setLen(p.blocks, length + 1) p.blocks[length].id = -p.unique p.blocks[length].isLoop = true let labl = p.unique.toRope @@ -514,7 +514,7 @@ proc genWhileStmt(p: PProc, n: PNode) = [cond.res, labl]) genStmt(p, n.sons[1]) appf(p.body, "}$n" | "end ::L$#::$n", [labl]) - setlen(p.blocks, length) + setLen(p.blocks, length) proc moveInto(p: PProc, src: var TCompRes, dest: TCompRes) = if src.kind != resNone: @@ -579,7 +579,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = useMagic(p, "isObj") for j in countup(0, blen - 2): if n.sons[i].sons[j].kind != nkType: - InternalError(n.info, "genTryStmt") + internalError(n.info, "genTryStmt") if orExpr != nil: app(orExpr, "||" | " or ") appf(orExpr, "isObj($1.exc.m_type, $2)", [safePoint, genTypeInfo(p, n.sons[i].sons[j].typ)]) @@ -641,13 +641,13 @@ proc genCaseJS(p: PProc, n: PNode, r: var TCompRes) = while v.intVal <= e.sons[1].intVal: gen(p, v, cond) appf(p.body, "case $1: ", [cond.rdLoc]) - Inc(v.intVal) + inc(v.intVal) else: if stringSwitch: case e.kind of nkStrLit..nkTripleStrLit: appf(p.body, "case $1: ", [makeJSString(e.strVal)]) - else: InternalError(e.info, "jsgen.genCaseStmt: 2") + else: internalError(e.info, "jsgen.genCaseStmt: 2") else: gen(p, e, cond) appf(p.body, "case $1: ", [cond.rdLoc]) @@ -694,7 +694,7 @@ proc genCaseLua(p: PProc, n: PNode, r: var TCompRes) = case e.kind of nkStrLit..nkTripleStrLit: appf(p.body, "eqStr($1, $2)", [tmp, makeJSString(e.strVal)]) - else: InternalError(e.info, "jsgen.genCaseStmt: 2") + else: internalError(e.info, "jsgen.genCaseStmt: 2") else: gen(p, e, cond) appf(p.body, "$1 == $2", [tmp, cond.rdLoc]) @@ -713,17 +713,17 @@ proc genBlock(p: PProc, n: PNode, r: var TCompRes) = let idx = len(p.blocks) if n.sons[0].kind != nkEmpty: # named block? - if (n.sons[0].kind != nkSym): InternalError(n.info, "genBlock") + if (n.sons[0].kind != nkSym): internalError(n.info, "genBlock") var sym = n.sons[0].sym sym.loc.k = locOther sym.loc.a = idx - setlen(p.blocks, idx + 1) + setLen(p.blocks, idx + 1) p.blocks[idx].id = - p.unique # negative because it isn't used yet let labl = p.unique appf(p.body, "L$1: do {$n" | "", labl.toRope) gen(p, n.sons[1], r) appf(p.body, "} while(false);$n" | "$n::L$#::$n", labl.toRope) - setlen(p.blocks, idx) + setLen(p.blocks, idx) proc genBreakStmt(p: PProc, n: PNode) = var idx: int @@ -739,7 +739,7 @@ proc genBreakStmt(p: PProc, n: PNode) = idx = len(p.blocks) - 1 while idx >= 0 and not p.blocks[idx].isLoop: dec idx if idx < 0 or not p.blocks[idx].isLoop: - InternalError(n.info, "no loop to break") + internalError(n.info, "no loop to break") p.blocks[idx].id = abs(p.blocks[idx].id) # label is used appf(p.body, "break L$1;$n" | "goto ::L$1::;$n", [toRope(p.blocks[idx].id)]) @@ -750,7 +750,7 @@ proc genAsmStmt(p: PProc, n: PNode) = case n.sons[i].Kind of nkStrLit..nkTripleStrLit: app(p.body, n.sons[i].strVal) of nkSym: app(p.body, mangleName(n.sons[i].sym)) - else: InternalError(n.sons[i].info, "jsgen: genAsmStmt()") + else: internalError(n.sons[i].info, "jsgen: genAsmStmt()") proc genIf(p: PProc, n: PNode, r: var TCompRes) = var cond, stmt: TCompRes @@ -851,7 +851,7 @@ proc getFieldPosition(f: PNode): int = case f.kind of nkIntLit..nkUInt64Lit: result = int(f.intVal) of nkSym: result = f.sym.position - else: InternalError(f.info, "genFieldPosition") + else: internalError(f.info, "genFieldPosition") proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) = var a: TCompRes @@ -861,7 +861,7 @@ proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) = if skipTypes(b.sons[0].typ, abstractVarRange).kind == tyTuple: r.res = makeJSString("Field" & $getFieldPosition(b.sons[1])) else: - if b.sons[1].kind != nkSym: InternalError(b.sons[1].info, "genFieldAddr") + if b.sons[1].kind != nkSym: internalError(b.sons[1].info, "genFieldAddr") var f = b.sons[1].sym if f.loc.r == nil: f.loc.r = mangleName(f) r.res = makeJSString(ropeToStr(f.loc.r)) @@ -875,7 +875,7 @@ proc genFieldAccess(p: PProc, n: PNode, r: var TCompRes) = if skipTypes(n.sons[0].typ, abstractVarRange).kind == tyTuple: r.res = ropef("$1.Field$2", [r.res, getFieldPosition(n.sons[1]).toRope]) else: - if n.sons[1].kind != nkSym: InternalError(n.sons[1].info, "genFieldAddr") + if n.sons[1].kind != nkSym: internalError(n.sons[1].info, "genFieldAddr") var f = n.sons[1].sym if f.loc.r == nil: f.loc.r = mangleName(f) r.res = ropef("$1.$2", [r.res, f.loc.r]) @@ -890,14 +890,14 @@ proc genCheckedFieldAccess(p: PProc, n: PNode, r: var TCompRes) = proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) = var a, b: TCompRes - first: biggestInt + first: BiggestInt r.typ = etyBaseIndex gen(p, n.sons[0], a) gen(p, n.sons[1], b) InternalAssert a.typ != etyBaseIndex and b.typ != etyBaseIndex r.address = a.res 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]) else: first = 0 if optBoundsCheck in p.options and not isConstExpr(n.sons[1]): useMagic(p, "chckIndx") @@ -918,9 +918,9 @@ proc genArrayAccess(p: PProc, n: PNode, r: var TCompRes) = genArrayAddr(p, n, r) of tyTuple: genFieldAddr(p, n, r) - else: InternalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') + else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') r.typ = etyNone - if r.res == nil: InternalError(n.info, "genArrayAccess") + if r.res == nil: internalError(n.info, "genArrayAccess") r.res = ropef("$1[$2]", [r.address, r.res]) r.address = nil r.kind = resExpr @@ -929,7 +929,7 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = case n.sons[0].kind of nkSym: let s = n.sons[0].sym - if s.loc.r == nil: InternalError(n.info, "genAddr: 3") + if s.loc.r == nil: internalError(n.info, "genAddr: 3") case s.kind of skVar, skLet, skResult: r.kind = resExpr @@ -948,8 +948,8 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = r.address = s.loc.r r.res = toRope("0") else: - InternalError(n.info, "genAddr: 4") - else: InternalError(n.info, "genAddr: 2") + internalError(n.info, "genAddr: 4") + else: internalError(n.info, "genAddr: 2") of nkCheckedFieldExpr: genCheckedFieldAddr(p, n, r) of nkDotExpr: @@ -963,15 +963,15 @@ proc genAddr(p: PProc, n: PNode, r: var TCompRes) = genArrayAddr(p, n, r) of tyTuple: genFieldAddr(p, n, r) - else: InternalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') - else: InternalError(n.info, "genAddr") + else: internalError(n.info, "expr(nkBracketExpr, " & $ty.kind & ')') + else: internalError(n.info, "genAddr") proc genSym(p: PProc, n: PNode, r: var TCompRes) = var s = n.sym case s.kind of skVar, skLet, skParam, skTemp, skResult: if s.loc.r == nil: - InternalError(n.info, "symbol has no generated name: " & s.name.s) + internalError(n.info, "symbol has no generated name: " & s.name.s) var k = mapType(s.typ) if k == etyBaseIndex: r.typ = etyBaseIndex @@ -988,7 +988,7 @@ proc genSym(p: PProc, n: PNode, r: var TCompRes) = of skConst: genConstant(p, s) if s.loc.r == nil: - InternalError(n.info, "symbol has no generated name: " & s.name.s) + internalError(n.info, "symbol has no generated name: " & s.name.s) r.res = s.loc.r of skProc, skConverter, skMethod: discard mangleName(s) @@ -1010,7 +1010,7 @@ proc genSym(p: PProc, n: PNode, r: var TCompRes) = else: app(p.g.code, newp) else: if s.loc.r == nil: - InternalError(n.info, "symbol has no generated name: " & s.name.s) + internalError(n.info, "symbol has no generated name: " & s.name.s) r.res = s.loc.r r.kind = resVal @@ -1020,7 +1020,7 @@ proc genDeref(p: PProc, n: PNode, r: var TCompRes) = else: var a: TCompRes gen(p, n.sons[0], a) - if a.typ != etyBaseIndex: InternalError(n.info, "genDeref") + if a.typ != etyBaseIndex: internalError(n.info, "genDeref") r.res = ropef("$1[$2]", [a.address, a.res]) proc genArg(p: PProc, n: PNode, r: var TCompRes) = @@ -1051,7 +1051,7 @@ proc genInfixCall(p: PProc, n: PNode, r: var TCompRes) = gen(p, n.sons[1], r) if r.typ == etyBaseIndex: if r.address == nil: - GlobalError(n.info, "cannot invoke with infix syntax") + globalError(n.info, "cannot invoke with infix syntax") r.res = ropef("$1[$2]", [r.address, r.res]) r.address = nil r.typ = etyNone @@ -1093,7 +1093,7 @@ proc createRecordVarAux(p: PProc, rec: PNode, c: var int): PRope = app(result, ": ") app(result, createVar(p, rec.sym.typ, false)) inc(c) - else: InternalError(rec.info, "createRecordVarAux") + else: internalError(rec.info, "createRecordVarAux") proc createVar(p: PProc, typ: PType, indirect: bool): PRope = var t = skipTypes(typ, abstractInst) @@ -1125,7 +1125,7 @@ proc createVar(p: PProc, typ: PType, indirect: bool): PRope = app(result, "]") of tyTuple: result = toRope("{") - for i in 0.. 0: app(result, ", ") appf(result, "Field$1: $2" | "Field$# = $#", i.toRope, createVar(p, t.sons[i], false)) @@ -1173,7 +1173,7 @@ proc genVarInit(p: PProc, v: PSym, n: PNode) = useMagic(p, "NimCopy") s = ropef("NimCopy($1, $2)", [a.res, genTypeInfo(p, n.typ)]) of etyBaseIndex: - if (a.typ != etyBaseIndex): InternalError(n.info, "genVarInit") + if (a.typ != etyBaseIndex): internalError(n.info, "genVarInit") if {sfAddrTaken, sfGlobal} * v.flags != {}: appf(p.body, "var $1 = [$2, $3];$n" | "local $1 = {$2, $3};$n", [v.loc.r, a.address, a.res]) @@ -1227,7 +1227,7 @@ proc genOrd(p: PProc, n: PNode, r: var TCompRes) = case skipTypes(n.sons[1].typ, abstractVar).kind of tyEnum, tyInt..tyInt64, tyChar: gen(p, n.sons[1], r) of tyBool: unaryExpr(p, n, r, "", "($1 ? 1:0)" | "toBool($#)") - else: InternalError(n.info, "genOrd") + else: internalError(n.info, "genOrd") proc genConStrStr(p: PProc, n: PNode, r: var TCompRes) = var a: TCompRes @@ -1451,7 +1451,7 @@ proc convStrToCStr(p: PProc, n: PNode, r: var TCompRes) = gen(p, n.sons[0].sons[0], r) else: gen(p, n.sons[0], r) - if r.res == nil: InternalError(n.info, "convStrToCStr") + if r.res == nil: internalError(n.info, "convStrToCStr") useMagic(p, "toJSStr") r.res = ropef("toJSStr($1)", [r.res]) r.kind = resExpr @@ -1463,13 +1463,13 @@ proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) = gen(p, n.sons[0].sons[0], r) else: gen(p, n.sons[0], r) - if r.res == nil: InternalError(n.info, "convCStrToStr") + if r.res == nil: internalError(n.info, "convCStrToStr") useMagic(p, "cstrToNimstr") r.res = ropef("cstrToNimstr($1)", [r.res]) r.kind = resExpr proc genReturnStmt(p: PProc, n: PNode) = - if p.procDef == nil: InternalError(n.info, "genReturnStmt") + if p.procDef == nil: internalError(n.info, "genReturnStmt") p.BeforeRetNeeded = true if (n.sons[0].kind != nkEmpty): genStmt(p, n.sons[0]) @@ -1564,7 +1564,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) = elif f == 0.5 * f: if f > 0.0: r.res = toRope"Infinity" else: r.res = toRope"-Infinity" - else: r.res = toRope(f.ToStrMaxPrecision) + else: r.res = toRope(f.toStrMaxPrecision) of nkCallKinds: if (n.sons[0].kind == nkSym) and (n.sons[0].sym.magic != mNone): genMagic(p, n, r) @@ -1640,7 +1640,7 @@ proc gen(p: PProc, n: PNode, r: var TCompRes) = r.res = nil of nkGotoState, nkState: internalError(n.info, "first class iterators not implemented") - else: InternalError(n.info, "gen: unknown node type: " & $n.kind) + else: internalError(n.info, "gen: unknown node type: " & $n.kind) var globals: PGlobals @@ -1671,7 +1671,7 @@ proc myProcess(b: PPassContext, n: PNode): PNode = if passes.skipCodegen(n): return n result = n var m = BModule(b) - if m.module == nil: InternalError(n.info, "myProcess") + if m.module == nil: internalError(n.info, "myProcess") var p = newProc(globals, m, nil, m.module.options) genModule(p, n) app(p.g.code, p.locals) @@ -1702,7 +1702,7 @@ proc myClose(b: PPassContext, n: PNode): PNode = discard writeRopeIfNotEqual(con(genHeader(), code), outfile) proc myOpenCached(s: PSym, rd: PRodReader): PPassContext = - InternalError("symbol files are not possible with the JS code generator") + internalError("symbol files are not possible with the JS code generator") result = nil proc myOpen(s: PSym): PPassContext = diff --git a/compiler/jstypes.nim b/compiler/jstypes.nim index 0be1e99dc..cbe87bbc1 100644 --- a/compiler/jstypes.nim +++ b/compiler/jstypes.nim @@ -37,7 +37,7 @@ proc genObjectFields(p: PProc, typ: PType, n: PNode): PRope = [mangleName(field), s, makeJSString(field.name.s)]) of nkRecCase: length = sonsLen(n) - if (n.sons[0].kind != nkSym): InternalError(n.info, "genObjectFields") + if (n.sons[0].kind != nkSym): internalError(n.info, "genObjectFields") field = n.sons[0].sym s = genTypeInfo(p, field.typ) for i in countup(1, length - 1): @@ -98,7 +98,7 @@ proc genEnumInfo(p: PProc, typ: PType, name: PRope) = let length = sonsLen(typ.n) var s: PRope = nil for i in countup(0, length - 1): - if (typ.n.sons[i].kind != nkSym): InternalError(typ.n.info, "genEnumInfo") + if (typ.n.sons[i].kind != nkSym): internalError(typ.n.info, "genEnumInfo") let field = typ.n.sons[i].sym if i > 0: app(s, ", " & tnl) let extName = if field.ast == nil: field.name.s else: field.ast.strVal @@ -119,7 +119,7 @@ proc genTypeInfo(p: PProc, typ: PType): PRope = var t = typ if t.kind == tyGenericInst: t = lastSon(t) result = ropef("NTI$1", [toRope(t.id)]) - if ContainsOrIncl(p.g.TypeInfoGenerated, t.id): return + if containsOrIncl(p.g.TypeInfoGenerated, t.id): return case t.kind of tyDistinct: result = genTypeInfo(p, typ.sons[0]) @@ -145,4 +145,4 @@ proc genTypeInfo(p: PProc, typ: PType): PRope = of tyEnum: genEnumInfo(p, t, result) of tyObject: genObjectInfo(p, t, result) of tyTuple: genTupleInfo(p, t, result) - else: InternalError("genTypeInfo(" & $t.kind & ')') + else: internalError("genTypeInfo(" & $t.kind & ')') diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index dd48a0bc3..558b2cfd3 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -236,8 +236,8 @@ proc addClosureParam(i: PInnerContext, e: PEnv) = proc dummyClosureParam(o: POuterContext, i: PInnerContext) = var e = o.currentEnv - if IdTableGet(o.lambdasToEnv, i.fn) == nil: - IdTablePut(o.lambdasToEnv, i.fn, e) + if idTableGet(o.lambdasToEnv, i.fn) == nil: + idTablePut(o.lambdasToEnv, i.fn, e) if i.closureParam == nil: addClosureParam(i, e) proc illegalCapture(s: PSym): bool {.inline.} = @@ -249,13 +249,13 @@ proc captureVar(o: POuterContext, i: PInnerContext, local: PSym, info: TLineInfo) = # for inlined variables the owner is still wrong, so it can happen that it's # not a captured variable at all ... *sigh* - var it = PEnv(IdTableGet(o.localsToEnv, local)) + var it = PEnv(idTableGet(o.localsToEnv, local)) if it == nil: return if illegalCapture(local) or o.fn.id != local.owner.id or i.fn.typ.callConv notin {ccClosure, ccDefault}: # Currently captures are restricted to a single level of nesting: - LocalError(info, errIllegalCaptureX, local.name.s) + localError(info, errIllegalCaptureX, local.name.s) i.fn.typ.callConv = ccClosure #echo "captureVar ", i.fn.name.s, i.fn.id, " ", local.name.s, local.id @@ -263,11 +263,11 @@ proc captureVar(o: POuterContext, i: PInnerContext, local: PSym, # we need to remember which inner most closure belongs to this lambda: var e = o.currentEnv - if IdTableGet(o.lambdasToEnv, i.fn) == nil: - IdTablePut(o.lambdasToEnv, i.fn, e) + if idTableGet(o.lambdasToEnv, i.fn) == nil: + idTablePut(o.lambdasToEnv, i.fn, e) # variable already captured: - if IdNodeTableGet(i.localsToAccess, local) != nil: return + if idNodeTableGet(i.localsToAccess, local) != nil: return if i.closureParam == nil: addClosureParam(i, e) # check which environment `local` belongs to: @@ -281,7 +281,7 @@ proc captureVar(o: POuterContext, i: PInnerContext, local: PSym, access = indirectAccess(access, addDep(e, it, i.fn), info) access = indirectAccess(access, local, info) incl(o.capturedVars, local.id) - IdNodeTablePut(i.localsToAccess, local, access) + idNodeTablePut(i.localsToAccess, local, access) proc interestingVar(s: PSym): bool {.inline.} = result = s.kind in {skVar, skLet, skTemp, skForVar, skParam, skResult} and @@ -309,11 +309,11 @@ proc gatherVars(o: POuterContext, i: PInnerContext, n: PNode) = elif isInnerProc(s, o.fn) and tfCapturesEnv in s.typ.flags and s != i.fn: # call to some other inner proc; we need to track the dependencies for # this: - let env = PEnv(IdTableGet(o.lambdasToEnv, i.fn)) - if env == nil: InternalError(n.info, "no environment computed") + let env = PEnv(idTableGet(o.lambdasToEnv, i.fn)) + if env == nil: internalError(n.info, "no environment computed") if o.currentEnv != env: discard addDep(o.currentEnv, env, i.fn) - InternalError(n.info, "too complex environment handling required") + internalError(n.info, "too complex environment handling required") of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit: nil else: for k in countup(0, sonsLen(n) - 1): @@ -365,7 +365,7 @@ proc transformInnerProc(o: POuterContext, i: PInnerContext, n: PNode): PNode = result = makeClosure(s, i.closureParam, n.info) else: # captured symbol? - result = IdNodeTableGet(i.localsToAccess, n.sym) + result = idNodeTableGet(i.localsToAccess, n.sym) of nkLambdaKinds: result = transformInnerProc(o, i, n.sons[namePos]) of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, @@ -425,18 +425,18 @@ proc searchForInnerProcs(o: POuterContext, n: PNode) = if it.kind == nkCommentStmt: nil elif it.kind == nkIdentDefs: var L = sonsLen(it) - if it.sons[0].kind != nkSym: InternalError(it.info, "transformOuter") + if it.sons[0].kind != nkSym: internalError(it.info, "transformOuter") #echo "set: ", it.sons[0].sym.name.s, " ", o.currentBlock == nil - IdTablePut(o.localsToEnv, it.sons[0].sym, o.currentEnv) + idTablePut(o.localsToEnv, it.sons[0].sym, o.currentEnv) searchForInnerProcs(o, it.sons[L-1]) elif it.kind == nkVarTuple: var L = sonsLen(it) for j in countup(0, L-3): #echo "set: ", it.sons[j].sym.name.s, " ", o.currentBlock == nil - IdTablePut(o.localsToEnv, it.sons[j].sym, o.currentEnv) + idTablePut(o.localsToEnv, it.sons[j].sym, o.currentEnv) searchForInnerProcs(o, it.sons[L-1]) else: - InternalError(it.info, "transformOuter") + internalError(it.info, "transformOuter") of nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, nkIteratorDef: # don't recurse here: @@ -490,7 +490,7 @@ proc generateClosureCreation(o: POuterContext, scope: PEnv): PNode = # maybe later: (sfByCopy in local.flags) # add ``env.param = param`` result.add(newAsgnStmt(fieldAccess, newSymNode(local), env.info)) - IdNodeTablePut(o.localsToAccess, local, fieldAccess) + idNodeTablePut(o.localsToAccess, local, fieldAccess) # add support for 'up' references: for e, field in items(scope.deps): # add ``env.up = env2`` @@ -503,7 +503,7 @@ proc transformOuterProc(o: POuterContext, n: PNode): PNode = of nkEmpty..pred(nkSym), succ(nkSym)..nkNilLit: nil of nkSym: var local = n.sym - var closure = PEnv(IdTableGet(o.lambdasToEnv, local)) + var closure = PEnv(idTableGet(o.lambdasToEnv, local)) if closure != nil: # we need to replace the lambda with '(lambda, env)': let a = closure.closure @@ -521,7 +521,7 @@ proc transformOuterProc(o: POuterContext, n: PNode): PNode = return makeClosure(local, x, n.info) if not contains(o.capturedVars, local.id): return - var env = PEnv(IdTableGet(o.localsToEnv, local)) + var env = PEnv(idTableGet(o.localsToEnv, local)) if env == nil: return var scope = env.attachedNode assert scope.kind == nkStmtList @@ -531,7 +531,7 @@ proc transformOuterProc(o: POuterContext, n: PNode): PNode = # change 'local' to 'closure.local', unless it's a 'byCopy' variable: # if sfByCopy notin local.flags: - result = IdNodeTableGet(o.localsToAccess, local) + result = idNodeTableGet(o.localsToAccess, local) assert result != nil, "cannot find: " & local.name.s # else it is captured by copy and this means that 'outer' should continue # to access the local as a local. @@ -564,13 +564,13 @@ proc liftLambdas*(fn: PSym, body: PNode): PNode = let params = fn.typ.n for i in 1.. ' ': tok.indent = indent break @@ -725,7 +725,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = getOperator(L, tok) of ',': tok.toktype = tkComma - Inc(L.bufpos) + inc(L.bufpos) of 'l': # if we parsed exactly one character and its a small L (l), this # is treated as a warning because it may be confused with the number 1 @@ -734,58 +734,58 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = getSymbol(L, tok) of 'r', 'R': if L.buf[L.bufPos + 1] == '\"': - Inc(L.bufPos) + inc(L.bufPos) getString(L, tok, true) else: getSymbol(L, tok) of '(': - Inc(L.bufpos) + inc(L.bufpos) if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': tok.toktype = tkParDotLe - Inc(L.bufpos) + inc(L.bufpos) else: tok.toktype = tkParLe of ')': tok.toktype = tkParRi - Inc(L.bufpos) + inc(L.bufpos) of '[': - Inc(L.bufpos) + inc(L.bufpos) if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': tok.toktype = tkBracketDotLe - Inc(L.bufpos) + inc(L.bufpos) else: tok.toktype = tkBracketLe of ']': tok.toktype = tkBracketRi - Inc(L.bufpos) + inc(L.bufpos) of '.': if L.buf[L.bufPos+1] == ']': tok.tokType = tkBracketDotRi - Inc(L.bufpos, 2) + inc(L.bufpos, 2) elif L.buf[L.bufPos+1] == '}': tok.tokType = tkCurlyDotRi - Inc(L.bufpos, 2) + inc(L.bufpos, 2) elif L.buf[L.bufPos+1] == ')': tok.tokType = tkParDotRi - Inc(L.bufpos, 2) + inc(L.bufpos, 2) else: getOperator(L, tok) of '{': - Inc(L.bufpos) + inc(L.bufpos) if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': tok.toktype = tkCurlyDotLe - Inc(L.bufpos) + inc(L.bufpos) else: tok.toktype = tkCurlyLe of '}': tok.toktype = tkCurlyRi - Inc(L.bufpos) + inc(L.bufpos) of ';': tok.toktype = tkSemiColon - Inc(L.bufpos) + inc(L.bufpos) of '`': tok.tokType = tkAccent - Inc(L.bufpos) + inc(L.bufpos) of '\"': # check for extended raw string literal: var rawMode = L.bufpos > 0 and L.buf[L.bufpos-1] in SymChars @@ -810,6 +810,6 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = tok.literal = $c tok.tokType = tkInvalid lexMessage(L, errInvalidToken, c & " (\\" & $(ord(c)) & ')') - Inc(L.bufpos) + inc(L.bufpos) dummyIdent = getIdent("") diff --git a/compiler/lists.nim b/compiler/lists.nim index 70e177ba3..93448c0b2 100644 --- a/compiler/lists.nim +++ b/compiler/lists.nim @@ -22,7 +22,7 @@ type head*, tail*: PListEntry Counter*: int - TCompareProc* = proc (entry: PListEntry, closure: Pointer): bool {.nimcall.} + TCompareProc* = proc (entry: PListEntry, closure: pointer): bool {.nimcall.} proc initLinkedList*(list: var TLinkedList) = list.Counter = 0 @@ -30,7 +30,7 @@ proc initLinkedList*(list: var TLinkedList) = list.tail = nil proc append*(list: var TLinkedList, entry: PListEntry) = - Inc(list.counter) + inc(list.counter) entry.next = nil entry.prev = list.tail if list.tail != nil: @@ -54,11 +54,11 @@ proc appendStr*(list: var TLinkedList, data: string) = append(list, newStrEntry(data)) proc includeStr*(list: var TLinkedList, data: string): bool = - if Contains(list, data): return true - AppendStr(list, data) # else: add to list + if contains(list, data): return true + appendStr(list, data) # else: add to list proc prepend*(list: var TLinkedList, entry: PListEntry) = - Inc(list.counter) + inc(list.counter) entry.prev = nil entry.next = list.head if list.head != nil: @@ -75,14 +75,14 @@ proc insertBefore*(list: var TLinkedList, pos, entry: PListEntry) = if pos == list.head: prepend(list, entry) else: - Inc(list.counter) + inc(list.counter) entry.next = pos entry.prev = pos.prev if pos.prev != nil: pos.prev.next = entry pos.prev = entry proc remove*(list: var TLinkedList, entry: PListEntry) = - Dec(list.counter) + dec(list.counter) if entry == list.tail: list.tail = entry.prev if entry == list.head: @@ -110,7 +110,7 @@ proc excludeStr*(list: var TLinkedList, data: string) = if PStrEntry(it).data == data: remove(list, it) it = nxt -proc find*(list: TLinkedList, fn: TCompareProc, closure: Pointer): PListEntry = +proc find*(list: TLinkedList, fn: TCompareProc, closure: pointer): PListEntry = result = list.head while result != nil: if fn(result, closure): return diff --git a/compiler/llstream.nim b/compiler/llstream.nim index 68ad4d587..6eac08dbd 100644 --- a/compiler/llstream.nim +++ b/compiler/llstream.nim @@ -23,7 +23,7 @@ type llsStdIn # stream encapsulates stdin TLLStream* = object of TObject kind*: TLLStreamKind # accessible for low-level access (lexbase uses this) - f*: tfile + f*: TFile s*: string rd*, wr*: int # for string streams lineOffset*: int # for fake stdin line numbers @@ -31,7 +31,7 @@ type PLLStream* = ref TLLStream proc llStreamOpen*(data: string): PLLStream -proc llStreamOpen*(f: var tfile): PLLStream +proc llStreamOpen*(f: var TFile): PLLStream proc llStreamOpen*(filename: string, mode: TFileMode): PLLStream proc llStreamOpen*(): PLLStream proc llStreamOpenStdIn*(): PLLStream @@ -40,7 +40,7 @@ proc llStreamRead*(s: PLLStream, buf: pointer, bufLen: int): int proc llStreamReadLine*(s: PLLStream, line: var string): bool proc llStreamReadAll*(s: PLLStream): string proc llStreamWrite*(s: PLLStream, data: string) -proc llStreamWrite*(s: PLLStream, data: Char) +proc llStreamWrite*(s: PLLStream, data: char) proc llStreamWrite*(s: PLLStream, buf: pointer, buflen: int) proc llStreamWriteln*(s: PLLStream, data: string) # implementation @@ -99,7 +99,7 @@ proc endsWithOpr*(x: string): bool = result = x.endsWith(LineContinuationOprs) proc continueLine(line: string, inTripleString: bool): bool {.inline.} = - result = inTriplestring or + result = inTripleString or line[0] == ' ' or line.endsWith(LineContinuationOprs+AdditionalLineContinuationOprs) @@ -116,7 +116,7 @@ proc llReadFromStdin(s: PLLStream, buf: pointer, bufLen: int): int = s.rd = 0 var line = newStringOfCap(120) var triples = 0 - while ReadLineFromStdin(if s.s.len == 0: ">>> " else: "... ", line): + while readLineFromStdin(if s.s.len == 0: ">>> " else: "... ", line): add(s.s, line) add(s.s, "\n") inc triples, countTriples(line) @@ -139,7 +139,7 @@ proc llStreamRead(s: PLLStream, buf: pointer, bufLen: int): int = of llsFile: result = readBuffer(s.f, buf, bufLen) of llsStdIn: - result = LLreadFromStdin(s, buf, bufLen) + result = llReadFromStdin(s, buf, bufLen) proc llStreamReadLine(s: PLLStream, line: var string): bool = setLen(line, 0) @@ -196,12 +196,12 @@ proc llStreamWrite(s: PLLStream, buf: pointer, buflen: int) = of llsNone, llsStdIn: discard of llsString: - if bufLen > 0: - setlen(s.s, len(s.s) + bufLen) - copyMem(addr(s.s[0 + s.wr]), buf, bufLen) - inc(s.wr, bufLen) + if buflen > 0: + setLen(s.s, len(s.s) + buflen) + copyMem(addr(s.s[0 + s.wr]), buf, buflen) + inc(s.wr, buflen) of llsFile: - discard writeBuffer(s.f, buf, bufLen) + discard writeBuffer(s.f, buf, buflen) proc llStreamReadAll(s: PLLStream): string = const @@ -218,7 +218,7 @@ proc llStreamReadAll(s: PLLStream): string = var bytes = readBuffer(s.f, addr(result[0]), bufSize) var i = bytes while bytes == bufSize: - setlen(result, i + bufSize) + setLen(result, i + bufSize) bytes = readBuffer(s.f, addr(result[i + 0]), bufSize) inc(i, bytes) - setlen(result, i) + setLen(result, i) diff --git a/compiler/lookups.nim b/compiler/lookups.nim index 951998d15..379e00b0e 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -135,20 +135,20 @@ proc wrongRedefinition*(info: TLineInfo, s: string) = proc addDecl*(c: PContext, sym: PSym) = if c.currentScope.addUniqueSym(sym) == Failure: - WrongRedefinition(sym.info, sym.Name.s) + wrongRedefinition(sym.info, sym.Name.s) proc addPrelimDecl*(c: PContext, sym: PSym) = discard c.currentScope.addUniqueSym(sym) proc addDeclAt*(scope: PScope, sym: PSym) = if scope.addUniqueSym(sym) == Failure: - WrongRedefinition(sym.info, sym.Name.s) + wrongRedefinition(sym.info, sym.Name.s) proc addInterfaceDeclAux(c: PContext, sym: PSym) = if sfExported in sym.flags: # add to interface: - if c.module != nil: StrTableAdd(c.module.tab, sym) - else: InternalError(sym.info, "AddInterfaceDeclAux") + if c.module != nil: strTableAdd(c.module.tab, sym) + else: internalError(sym.info, "AddInterfaceDeclAux") proc addInterfaceDeclAt*(c: PContext, scope: PScope, sym: PSym) = addDeclAt(scope, sym) @@ -158,7 +158,7 @@ proc addOverloadableSymAt*(scope: PScope, fn: PSym) = if fn.kind notin OverloadableSyms: internalError(fn.info, "addOverloadableSymAt") return - var check = StrTableGet(scope.symbols, fn.name) + var check = strTableGet(scope.symbols, fn.name) if check != nil and check.Kind notin OverloadableSyms: wrongRedefinition(fn.info, fn.Name.s) else: @@ -275,7 +275,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = result = initIdentIter(o.it, c.topLevelScope.symbols, ident) o.mode = oimSelfModule else: - result = InitIdentIter(o.it, o.m.tab, ident) + result = initIdentIter(o.it, o.m.tab, ident) else: localError(n.sons[1].info, errIdentifierExpected, renderTree(n.sons[1])) @@ -317,7 +317,7 @@ proc nextOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = of oimSymChoice: if o.symChoiceIndex < sonsLen(n): result = n.sons[o.symChoiceIndex].sym - Incl(o.inSymChoice, result.id) + incl(o.inSymChoice, result.id) inc o.symChoiceIndex elif n.kind == nkOpenSymChoice: # try 'local' symbols too for Koenig's lookup: diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index 066ccc6cd..f81347fae 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -36,7 +36,7 @@ proc newSysType(kind: TTypeKind, size: int): PType = result.align = size proc getSysSym(name: string): PSym = - result = StrTableGet(systemModule.tab, getIdent(name)) + result = strTableGet(systemModule.tab, getIdent(name)) if result == nil: rawMessage(errSystemNeeds, name) result = newSym(skError, getIdent(name), systemModule, systemModule.info) @@ -46,11 +46,11 @@ proc getSysSym(name: string): PSym = proc getSysMagic*(name: string, m: TMagic): PSym = var ti: TIdentIter let id = getIdent(name) - result = InitIdentIter(ti, systemModule.tab, id) + result = initIdentIter(ti, systemModule.tab, id) while result != nil: if result.kind == skStub: loadStub(result) if result.magic == m: return result - result = NextIdentIter(ti, systemModule.tab) + result = nextIdentIter(ti, systemModule.tab) rawMessage(errSystemNeeds, name) result = newSym(skError, id, systemModule, systemModule.info) result.typ = newType(tyError, systemModule) @@ -82,11 +82,11 @@ proc getSysType(kind: TTypeKind): PType = of tyCstring: result = sysTypeFromName("cstring") of tyPointer: result = sysTypeFromName("pointer") of tyNil: result = newSysType(tyNil, ptrSize) - else: InternalError("request for typekind: " & $kind) + else: internalError("request for typekind: " & $kind) gSysTypes[kind] = result if result.kind != kind: - InternalError("wanted: " & $kind & " got: " & $result.kind) - if result == nil: InternalError("type not found: " & $kind) + internalError("wanted: " & $kind & " got: " & $result.kind) + if result == nil: internalError("type not found: " & $kind) var intTypeCache: array[-5..64, PType] @@ -164,7 +164,7 @@ proc getCompilerProc(name: string): PSym = var ident = getIdent(name, hashIgnoreStyle(name)) result = strTableGet(compilerprocs, ident) if result == nil: - result = strTableGet(rodCompilerProcs, ident) + result = strTableGet(rodCompilerprocs, ident) if result != nil: strTableAdd(compilerprocs, result) if result.kind == skStub: loadStub(result) diff --git a/compiler/main.nim b/compiler/main.nim index 3f8b6aeba..275d65781 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -123,9 +123,9 @@ proc commandCompileToJS = #incl(gGlobalOptions, optSafeCode) setTarget(osJS, cpuJS) #initDefines() - DefineSymbol("nimrod") # 'nimrod' is always defined - DefineSymbol("ecmascript") # For backward compatibility - DefineSymbol("js") + defineSymbol("nimrod") # 'nimrod' is always defined + defineSymbol("ecmascript") # For backward compatibility + defineSymbol("js") semanticPasses() registerPass(jsgenPass) compileProject() @@ -134,7 +134,7 @@ proc interactivePasses = #incl(gGlobalOptions, optSafeCode) #setTarget(osNimrodVM, cpuNimrodVM) initDefines() - DefineSymbol("nimrodvm") + defineSymbol("nimrodvm") when hasFFI: DefineSymbol("nimffi") registerPass(verbosePass) registerPass(semPass) @@ -142,14 +142,14 @@ proc interactivePasses = proc commandInteractive = msgs.gErrorMax = high(int) # do not stop after first error - InteractivePasses() + interactivePasses() compileSystemModule() if commandArgs.len > 0: - discard CompileModule(fileInfoIdx(gProjectFull), {}) + discard compileModule(fileInfoIdx(gProjectFull), {}) else: var m = makeStdinModule() incl(m.flags, sfMainModule) - processModule(m, LLStreamOpenStdIn(), nil) + processModule(m, llStreamOpenStdIn(), nil) const evalPasses = [verbosePass, semPass, evalPass] @@ -157,8 +157,8 @@ proc evalNim(nodes: PNode, module: PSym) = carryPasses(nodes, module, evalPasses) proc commandEval(exp: string) = - if SystemModule == nil: - InteractivePasses() + if systemModule == nil: + interactivePasses() compileSystemModule() var echoExp = "echo \"eval\\t\", " & "repr(" & exp & ")" evalNim(echoExp.parseString, makeStdinModule()) @@ -178,7 +178,7 @@ proc commandPretty = proc commandScan = var f = addFileExt(mainCommandArg(), nimExt) - var stream = LLStreamOpen(f, fmRead) + var stream = llStreamOpen(f, fmRead) if stream != nil: var L: TLexer @@ -187,9 +187,9 @@ proc commandScan = openLexer(L, f, stream) while true: rawGetTok(L, tok) - PrintTok(tok) + printTok(tok) if tok.tokType == tkEof: break - CloseLexer(L) + closeLexer(L) else: rawMessage(errCannotOpenFile, f) @@ -200,7 +200,7 @@ proc commandSuggest = # issuing the first compile command. This will leave the compiler # cache in a state where "no recompilation is necessary", but the # cgen pass was never executed at all. - CommandCompileToC() + commandCompileToC() if gDirtyBufferIdx != 0: discard compileModule(gDirtyBufferIdx, {sfDirty}) resetModule(gDirtyBufferIdx) @@ -219,7 +219,7 @@ proc commandSuggest = proc wantMainModule = if gProjectFull.len == 0: if optMainModule.len == 0: - Fatal(gCmdLineInfo, errCommandExpectsFilename) + fatal(gCmdLineInfo, errCommandExpectsFilename) else: gProjectName = optMainModule gProjectFull = gProjectPath / gProjectName @@ -228,7 +228,7 @@ proc wantMainModule = proc requireMainModuleOption = if optMainModule.len == 0: - Fatal(gCmdLineInfo, errMainModuleMustBeSpecified) + fatal(gCmdLineInfo, errMainModuleMustBeSpecified) else: gProjectName = optMainModule gProjectFull = gProjectPath / gProjectName @@ -297,7 +297,7 @@ proc mainCommand* = if gProjectFull.len != 0: # current path is always looked first for modules prependStr(searchPaths, gProjectPath) - setID(100) + setId(100) passes.gIncludeFile = includeModule passes.gImportModule = importModule case command.normalize @@ -305,20 +305,20 @@ proc mainCommand* = # compile means compileToC currently gCmd = cmdCompileToC wantMainModule() - CommandCompileToC() + commandCompileToC() of "cpp", "compiletocpp": extccomp.cExt = ".cpp" gCmd = cmdCompileToCpp if cCompiler == ccGcc: setCC("gpp") wantMainModule() - DefineSymbol("cpp") - CommandCompileToC() + defineSymbol("cpp") + commandCompileToC() of "objc", "compiletooc": extccomp.cExt = ".m" gCmd = cmdCompileToOC wantMainModule() - DefineSymbol("objc") - CommandCompileToC() + defineSymbol("objc") + commandCompileToC() of "run": gCmd = cmdRun wantMainModule() @@ -330,7 +330,7 @@ proc mainCommand* = of "js", "compiletojs": gCmd = cmdCompileToJS wantMainModule() - CommandCompileToJS() + commandCompileToJS() of "compiletollvm": gCmd = cmdCompileToLLVM wantMainModule() @@ -341,52 +341,52 @@ proc mainCommand* = of "pretty": gCmd = cmdPretty wantMainModule() - CommandPretty() + commandPretty() of "doc": gCmd = cmdDoc - LoadConfigs(DocConfig) + loadConfigs(DocConfig) wantMainModule() - CommandDoc() + commandDoc() of "doc2": gCmd = cmdDoc - LoadConfigs(DocConfig) + loadConfigs(DocConfig) wantMainModule() - DefineSymbol("nimdoc") - CommandDoc2() + defineSymbol("nimdoc") + commandDoc2() of "rst2html": gCmd = cmdRst2html - LoadConfigs(DocConfig) + loadConfigs(DocConfig) wantMainModule() - CommandRst2Html() + commandRst2Html() of "rst2tex": gCmd = cmdRst2tex - LoadConfigs(DocTexConfig) + loadConfigs(DocTexConfig) wantMainModule() - CommandRst2TeX() + commandRst2TeX() of "jsondoc": gCmd = cmdDoc - LoadConfigs(DocConfig) + loadConfigs(DocConfig) wantMainModule() - DefineSymbol("nimdoc") - CommandJSON() + defineSymbol("nimdoc") + commandJSON() of "buildindex": gCmd = cmdDoc - LoadConfigs(DocConfig) - CommandBuildIndex() + loadConfigs(DocConfig) + commandBuildIndex() of "gendepend": gCmd = cmdGenDepend wantMainModule() - CommandGenDepend() + commandGenDepend() of "dump": - gcmd = cmdDump - if getconfigvar("dump.format") == "json": + gCmd = cmdDump + if getConfigVar("dump.format") == "json": requireMainModuleOption() var definedSymbols = newJArray() for s in definedSymbolNames(): definedSymbols.elems.add(%s) var libpaths = newJArray() - for dir in itersearchpath(searchpaths): libpaths.elems.add(%dir) + for dir in itersearchpath(searchPaths): libpaths.elems.add(%dir) var dumpdata = % [ (key: "version", val: %VersionAsString), @@ -395,17 +395,17 @@ proc mainCommand* = (key: "lib_paths", val: libpaths) ] - outWriteLn($dumpdata) + outWriteln($dumpdata) else: - outWriteLn("-- list of currently defined symbols --") - for s in definedSymbolNames(): outWriteLn(s) - outWriteLn("-- end of list --") + outWriteln("-- list of currently defined symbols --") + for s in definedSymbolNames(): outWriteln(s) + outWriteln("-- end of list --") - for it in iterSearchPath(searchpaths): msgWriteLn(it) + for it in iterSearchPath(searchPaths): msgWriteln(it) of "check": gCmd = cmdCheck wantMainModule() - CommandCheck() + commandCheck() of "parse": gCmd = cmdParse wantMainModule() @@ -413,11 +413,11 @@ proc mainCommand* = of "scan": gCmd = cmdScan wantMainModule() - CommandScan() - MsgWriteln("Beware: Indentation tokens depend on the parser\'s state!") + commandScan() + msgWriteln("Beware: Indentation tokens depend on the parser\'s state!") of "i": gCmd = cmdInteractive - CommandInteractive() + commandInteractive() of "e": # XXX: temporary command for easier testing commandEval(mainCommandArg()) @@ -429,12 +429,12 @@ proc mainCommand* = commandEval(gEvalExpr) else: wantMainModule() - CommandSuggest() + commandSuggest() of "serve": isServing = true gGlobalOptions.incl(optCaasEnabled) msgs.gErrorMax = high(int) # do not stop after first error - serve(MainCommand) + serve(mainCommand) else: rawMessage(errInvalidCommandX, command) diff --git a/compiler/modules.nim b/compiler/modules.nim index 15af40363..e1fc1ad95 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -68,7 +68,7 @@ proc doCRC(fileIdx: int32) = # echo "FIRST CRC: ", fileIdx.ToFilename gMemCacheData[fileIdx].crc = crcFromFile(fileIdx.toFilename) -proc addDep(x: Psym, dep: int32) = +proc addDep(x: PSym, dep: int32) = growCache gMemCacheData, dep gMemCacheData[x.position].deps.safeAdd(dep) @@ -130,7 +130,7 @@ proc newModule(fileIdx: int32): PSym = incl(result.flags, sfUsed) initStrTable(result.tab) - StrTableAdd(result.tab, result) # a module knows itself + strTableAdd(result.tab, result) # a module knows itself proc compileModule*(fileIdx: int32, flags: TSymFlags): PSym = result = getModule(fileIdx) @@ -144,7 +144,7 @@ proc compileModule*(fileIdx: int32, flags: TSymFlags): PSym = if gCmd in {cmdCompileToC, cmdCompileToCpp, cmdCheck, cmdIdeTools}: rd = handleSymbolFile(result) if result.id < 0: - InternalError("handleSymbolFile should have set the module\'s ID") + internalError("handleSymbolFile should have set the module\'s ID") return else: result.id = getID() @@ -155,7 +155,7 @@ proc compileModule*(fileIdx: int32, flags: TSymFlags): PSym = doCRC fileIdx else: if checkDepMem(fileIdx) == Yes: - result = CompileModule(fileIdx, flags) + result = compileModule(fileIdx, flags) else: result = gCompiledModules[fileIdx] @@ -164,14 +164,14 @@ proc importModule*(s: PSym, fileIdx: int32): PSym {.procvar.} = result = compileModule(fileIdx, {}) if optCaasEnabled in gGlobalOptions: addDep(s, fileIdx) if sfSystemModule in result.flags: - LocalError(result.info, errAttemptToRedefine, result.Name.s) + localError(result.info, errAttemptToRedefine, result.Name.s) proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} = result = syntaxes.parseFile(fileIdx) if optCaasEnabled in gGlobalOptions: growCache gMemCacheData, fileIdx addDep(s, fileIdx) - doCrc(fileIdx) + doCRC(fileIdx) proc `==^`(a, b: string): bool = try: @@ -181,16 +181,16 @@ proc `==^`(a, b: string): bool = proc compileSystemModule* = if magicsys.SystemModule == nil: - SystemFileIdx = fileInfoIdx(options.libpath/"system.nim") - discard CompileModule(SystemFileIdx, {sfSystemModule}) + systemFileIdx = fileInfoIdx(options.libpath/"system.nim") + discard compileModule(systemFileIdx, {sfSystemModule}) proc compileProject*(projectFile = gProjectMainIdx) = let systemFileIdx = fileInfoIdx(options.libpath / "system.nim") - if projectFile == SystemFileIdx: - discard CompileModule(projectFile, {sfMainModule, sfSystemModule}) + if projectFile == systemFileIdx: + discard compileModule(projectFile, {sfMainModule, sfSystemModule}) else: compileSystemModule() - discard CompileModule(projectFile, {sfMainModule}) + discard compileModule(projectFile, {sfMainModule}) var stdinModule: PSym proc makeStdinModule*(): PSym = diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 44139b576..edc1dade3 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -445,7 +445,7 @@ type TErrorOutputs* = set[TErrorOutput] ERecoverableError* = object of EInvalidValue - ESuggestDone* = object of EBase + ESuggestDone* = object of E_Base const InvalidFileIDX* = int32(-1) @@ -455,7 +455,7 @@ var fileInfos*: seq[TFileInfo] = @[] systemFileIdx*: int32 -proc toCChar*(c: Char): string = +proc toCChar*(c: char): string = case c of '\0'..'\x1F', '\x80'..'\xFF': result = '\\' & toOctal(c) of '\'', '\"', '\\': result = '\\' & c @@ -474,7 +474,7 @@ proc makeCString*(s: string): PRope = add(res, '\"') add(res, tnl) app(result, toRope(res)) # reset: - setlen(res, 1) + setLen(res, 1) res[0] = '\"' add(res, toCChar(s[i])) add(res, '\"') @@ -552,7 +552,7 @@ proc unknownLineInfo*(): TLineInfo = var msgContext: seq[TLineInfo] = @[] - lastError = UnknownLineInfo() + lastError = unknownLineInfo() bufferedMsgs*: seq[string] errorOutputs* = {eStdOut, eStdErr} @@ -563,9 +563,9 @@ proc clearBufferedMsgs* = proc suggestWriteln*(s: string) = if eStdOut in errorOutputs: when useCaas: - if isNil(stdoutSocket): Writeln(stdout, s) + if isNil(stdoutSocket): writeln(stdout, s) else: - Writeln(stdout, s) + writeln(stdout, s) stdoutSocket.send(s & "\c\L") else: Writeln(stdout, s) @@ -601,12 +601,12 @@ proc pushInfoContext*(info: TLineInfo) = msgContext.add(info) proc popInfoContext*() = - setlen(msgContext, len(msgContext) - 1) + setLen(msgContext, len(msgContext) - 1) proc getInfoContext*(index: int): TLineInfo = let L = msgContext.len let i = if index < 0: L + index else: index - if i >=% L: result = UnknownLineInfo() + if i >=% L: result = unknownLineInfo() else: result = msgContext[i] proc toFilename*(fileIdx: int32): string = @@ -658,16 +658,16 @@ proc addCheckpoint*(filename: string, line: int) = proc outWriteln*(s: string) = ## Writes to stdout. Always. - if eStdOut in errorOutputs: Writeln(stdout, s) + if eStdOut in errorOutputs: writeln(stdout, s) proc msgWriteln*(s: string) = ## Writes to stdout. If --stdout option is given, writes to stderr instead. if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return if optStdout in gGlobalOptions: - if eStdErr in errorOutputs: Writeln(stderr, s) + if eStdErr in errorOutputs: writeln(stderr, s) else: - if eStdOut in errorOutputs: Writeln(stdout, s) + if eStdOut in errorOutputs: writeln(stdout, s) if eInMemory in errorOutputs: bufferedMsgs.safeAdd(s) @@ -677,7 +677,7 @@ proc coordToStr(coord: int): string = proc msgKindToString*(kind: TMsgKind): string = # later versions may provide translated error messages - result = msgKindToStr[kind] + result = MsgKindToStr[kind] proc getMessageStr(msg: TMsgKind, arg: string): string = result = msgKindToString(msg) % [arg] @@ -721,16 +721,16 @@ proc `==`*(a, b: TLineInfo): bool = result = a.line == b.line and a.fileIndex == b.fileIndex proc writeContext(lastinfo: TLineInfo) = - var info = lastInfo + var info = lastinfo 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]), coordToStr(msgContext[i].line), coordToStr(msgContext[i].col), getMessageStr(errInstantiationFrom, "")]) info = msgContext[i] -proc rawMessage*(msg: TMsgKind, args: openarray[string]) = +proc rawMessage*(msg: TMsgKind, args: openArray[string]) = var frmt: string case msg of errMin..errMax: @@ -813,7 +813,7 @@ proc internalError*(info: TLineInfo, errMsg: string) = proc internalError*(errMsg: string) = if gCmd == cmdIdeTools: return - writeContext(UnknownLineInfo()) + writeContext(unknownLineInfo()) rawMessage(errInternal, errMsg) template assertNotNil*(e: expr): expr = diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index d7ce0d57f..50f24043b 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -60,7 +60,7 @@ var condStack: seq[bool] = @[] proc doEnd(L: var TLexer, tok: var TToken) = if high(condStack) < 0: lexMessage(L, errTokenExpected, "@if") ppGetTok(L, tok) # skip 'end' - setlen(condStack, high(condStack)) + setLen(condStack, high(condStack)) type TJumpDest = enum @@ -75,7 +75,7 @@ proc doElse(L: var TLexer, tok: var TToken) = proc doElif(L: var TLexer, tok: var TToken) = if high(condStack) < 0: lexMessage(L, errTokenExpected, "@if") - var res = EvalppIf(L, tok) + var res = evalppIf(L, tok) if condStack[high(condStack)] or not res: jumpToDirective(L, tok, jdElseEndif) else: condStack[high(condStack)] = true @@ -86,7 +86,7 @@ proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = ppGetTok(L, tok) case whichKeyword(tok.ident) of wIf: - Inc(nestedIfs) + inc(nestedIfs) of wElse: if (dest == jdElseEndif) and (nestedIfs == 0): doElse(L, tok) @@ -99,7 +99,7 @@ proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = if nestedIfs == 0: doEnd(L, tok) break - if nestedIfs > 0: Dec(nestedIfs) + if nestedIfs > 0: dec(nestedIfs) else: nil ppGetTok(L, tok) @@ -112,8 +112,8 @@ proc parseDirective(L: var TLexer, tok: var TToken) = ppGetTok(L, tok) # skip @ case whichKeyword(tok.ident) of wIf: - setlen(condStack, len(condStack) + 1) - var res = EvalppIf(L, tok) + setLen(condStack, len(condStack) + 1) + var res = evalppIf(L, tok) condStack[high(condStack)] = res if not res: jumpToDirective(L, tok, jdElseEndif) of wElif: doElif(L, tok) @@ -196,7 +196,7 @@ proc readConfigFile(filename: string) = L: TLexer tok: TToken stream: PLLStream - stream = LLStreamOpen(filename, fmRead) + stream = llStreamOpen(filename, fmRead) if stream != nil: initToken(tok) openLexer(L, filename, stream) diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim index 2e4f8dec7..1dcb927ce 100644 --- a/compiler/nimlexbase.nim +++ b/compiler/nimlexbase.nim @@ -69,7 +69,7 @@ const proc closeBaseLexer(L: var TBaseLexer) = dealloc(L.buf) - LLStreamClose(L.stream) + llStreamClose(L.stream) proc fillBuffer(L: var TBaseLexer) = var @@ -83,9 +83,9 @@ proc fillBuffer(L: var TBaseLexer) = toCopy = L.BufLen - L.sentinel - 1 assert(toCopy >= 0) if toCopy > 0: - MoveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) + moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) # "moveMem" handles overlapping regions - charsRead = LLStreamRead(L.stream, addr(L.buf[toCopy]), + charsRead = llStreamRead(L.stream, addr(L.buf[toCopy]), (L.sentinel + 1) * chrSize) div chrSize s = toCopy + charsRead if charsRead < L.sentinel + 1: @@ -96,7 +96,7 @@ proc fillBuffer(L: var TBaseLexer) = dec(s) # BUGFIX (valgrind) while true: assert(s < L.bufLen) - while (s >= 0) and not (L.buf[s] in NewLines): Dec(s) + while (s >= 0) and not (L.buf[s] in NewLines): dec(s) if s >= 0: # we found an appropriate character for a sentinel: L.sentinel = s @@ -108,7 +108,7 @@ proc fillBuffer(L: var TBaseLexer) = L.bufLen = L.BufLen * 2 L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) 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 if charsRead < oldBufLen: L.buf[oldBufLen + charsRead] = EndOfFile @@ -153,7 +153,7 @@ proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) = L.linenumber = 1 # lines start at 1 L.stream = inputstream fillBuffer(L) - skip_UTF_8_BOM(L) + skipUTF8BOM(L) proc getColNumber(L: TBaseLexer, pos: int): int = result = abs(pos - L.lineStart) @@ -166,4 +166,4 @@ proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = inc(i) result.add("\n") if marker: - result.add(RepeatChar(getColNumber(L, L.bufpos)) & '^' & "\n") + result.add(repeatChar(getColNumber(L, L.bufpos)) & '^' & "\n") diff --git a/compiler/nimrod.nim b/compiler/nimrod.nim index 33c899647..c4c4f887c 100644 --- a/compiler/nimrod.nim +++ b/compiler/nimrod.nim @@ -36,7 +36,7 @@ proc handleCmdLine() = writeCommandLineUsage() else: # Process command line arguments: - ProcessCmdLine(passCmd1, "") + processCmdLine(passCmd1, "") if gProjectName != "": try: gProjectFull = canonicalizePath(gProjectName) diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index 8c2fc42d3..8e5de4194 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -32,7 +32,7 @@ proc cardSet*(s: PNode): BiggestInt proc inSet(s: PNode, elem: PNode): bool = if s.kind != nkCurly: - InternalError(s.info, "inSet") + internalError(s.info, "inSet") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: @@ -61,7 +61,7 @@ proc overlap(a, b: PNode): bool = proc SomeInSet(s: PNode, a, b: PNode): bool = # checks if some element of a..b is in the set s if s.kind != nkCurly: - InternalError(s.info, "SomeInSet") + internalError(s.info, "SomeInSet") return false for i in countup(0, sonsLen(s) - 1): if s.sons[i].kind == nkRange: @@ -82,10 +82,10 @@ proc toBitSet(s: PNode, b: var TBitSet) = if s.sons[i].kind == nkRange: j = getOrdValue(s.sons[i].sons[0]) while j <= getOrdValue(s.sons[i].sons[1]): - BitSetIncl(b, j - first) + bitSetIncl(b, j - first) inc(j) else: - BitSetIncl(b, getOrdValue(s.sons[i]) - first) + bitSetIncl(b, getOrdValue(s.sons[i]) - first) proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = var @@ -103,9 +103,9 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = a = e b = e while true: - Inc(b) + inc(b) if (b >= len(s) * elemSize) or not bitSetIn(s, b): break - Dec(b) + dec(b) if a == b: addSon(result, newIntTypeNode(nkIntLit, a + first, elemType)) else: @@ -115,7 +115,7 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = addSon(n, newIntTypeNode(nkIntLit, b + first, elemType)) addSon(result, n) e = b - Inc(e) + inc(e) template nodeSetOp(a, b: PNode, op: expr) {.dirty.} = var x, y: TBitSet @@ -124,10 +124,10 @@ template nodeSetOp(a, b: PNode, op: expr) {.dirty.} = op(x, y) result = toTreeSet(x, a.typ, a.info) -proc unionSets(a, b: PNode): PNode = nodeSetOp(a, b, BitSetUnion) -proc diffSets(a, b: PNode): PNode = nodeSetOp(a, b, BitSetDiff) -proc intersectSets(a, b: PNode): PNode = nodeSetOp(a, b, BitSetIntersect) -proc symdiffSets(a, b: PNode): PNode = nodeSetOp(a, b, BitSetSymDiff) +proc unionSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetUnion) +proc diffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetDiff) +proc intersectSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetIntersect) +proc symdiffSets(a, b: PNode): PNode = nodeSetOp(a, b, bitSetSymDiff) proc containsSets(a, b: PNode): bool = var x, y: TBitSet @@ -156,7 +156,7 @@ proc cardSet(s: PNode): BiggestInt = result = result + getOrdValue(s.sons[i].sons[1]) - getOrdValue(s.sons[i].sons[0]) + 1 else: - Inc(result) + inc(result) proc setHasRange(s: PNode): bool = if s.kind != nkCurly: diff --git a/compiler/options.nim b/compiler/options.nim index d792b487e..ae62af1c5 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -142,7 +142,7 @@ const # additional configuration variables: var gConfigVars* = newStringTable(modeStyleInsensitive) - gDllOverrides = newStringtable(modeCaseInsensitive) + gDllOverrides = newStringTable(modeCaseInsensitive) libpath* = "" gProjectName* = "" # holds a name like 'nimrod' gProjectPath* = "" # holds a path like /home/alice/projects/nimrod/compiler/ @@ -184,7 +184,7 @@ proc getOutFile*(filename, ext: string): string = proc getPrefixDir*(): string = ## gets the application directory - result = SplitPath(getAppDir()).head + result = splitPath(getAppDir()).head proc canonicalizePath*(path: string): string = result = path.expandFilename @@ -261,8 +261,8 @@ iterator iterSearchPath*(SearchPaths: TLinkedList): string = it = PStrEntry(it.Next) proc rawFindFile(f: string): string = - for it in iterSearchPath(SearchPaths): - result = JoinPath(it, f) + for it in iterSearchPath(searchPaths): + result = joinPath(it, f) if existsFile(result): return result.canonicalizePath result = "" @@ -270,7 +270,7 @@ proc rawFindFile(f: string): string = proc rawFindFile2(f: string): string = var it = PStrEntry(lazyPaths.head) while it != nil: - result = JoinPath(it.data, f) + result = joinPath(it.data, f) if existsFile(result): bringToFront(lazyPaths, it) return result.canonicalizePath @@ -292,7 +292,7 @@ proc findModule*(modulename, currentModule: string): string = let currentPath = currentModule.splitFile.dir result = currentPath / m if not existsFile(result): - result = FindFile(m) + result = findFile(m) proc libCandidates*(s: string, dest: var seq[string]) = var le = strutils.find(s, '(') @@ -319,7 +319,7 @@ proc inclDynlibOverride*(lib: string) = proc isDynlibOverride*(lib: string): bool = result = gDllOverrides.hasKey(lib.canonDynlibName) -proc binaryStrSearch*(x: openarray[string], y: string): int = +proc binaryStrSearch*(x: openArray[string], y: string): int = var a = 0 var b = len(x) - 1 while a <= b: diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim index 283f83906..91c230ccb 100644 --- a/compiler/parampatterns.nim +++ b/compiler/parampatterns.nim @@ -42,7 +42,7 @@ const MaxStackSize* = 64 ## max required stack size by the VM proc patternError(n: PNode) = - LocalError(n.info, errIllFormedAstX, renderTree(n, {renderNoComments})) + localError(n.info, errIllFormedAstX, renderTree(n, {renderNoComments})) proc add(code: var TPatternCode, op: TOpcode) {.inline.} = add(code, chr(ord(op))) @@ -125,7 +125,7 @@ proc semNodeKindConstraints*(p: PNode): PNode = for i in 1.. maxStackSize-1: - InternalError(p.info, "parameter pattern too complex") + internalError(p.info, "parameter pattern too complex") else: patternError(p) result.strVal.add(ppEof) diff --git a/compiler/parser.nim b/compiler/parser.nim index 652883360..47e8e9a54 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -77,12 +77,12 @@ proc getTok(p: var TParser) = proc openParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream) = initToken(p.tok) - openLexer(p.lex, fileIdx, inputstream) + openLexer(p.lex, fileIdx, inputStream) getTok(p) # read the first token p.firstTok = true proc openParser*(p: var TParser, filename: string, inputStream: PLLStream) = - openParser(p, filename.fileInfoIdx, inputStream) + openParser(p, filename.fileInfoIdx, inputstream) proc closeParser(p: var TParser) = closeLexer(p.lex) @@ -141,7 +141,7 @@ proc expectIdent(p: TParser) = proc eat(p: var TParser, TokType: TTokType) = if p.tok.TokType == TokType: getTok(p) - else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType]) + else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[TokType]) proc parLineInfo(p: TParser): TLineInfo = result = getLineInfo(p.lex, p.tok) @@ -672,7 +672,7 @@ proc simpleExprAux(p: var TParser, limit: int, mode: TPrimaryMode): PNode = let modeB = if mode == pmTypeDef: pmTypeDesc else: mode # the operator itself must not start on a new line: while opPrec >= limit and p.tok.indent < 0: - var leftAssoc = ord(IsLeftAssociative(p.tok)) + var leftAssoc = ord(isLeftAssociative(p.tok)) var a = newNodeP(nkInfix, p) var opNode = newIdentNodeP(p.tok.ident, p) # skip operator: getTok(p) @@ -846,7 +846,7 @@ proc parseParamList(p: var TParser, retColon = true): PNode = optPar(p) eat(p, tkParRi) let hasRet = if retColon: p.tok.tokType == tkColon - else: p.tok.tokType == tkOpr and IdentEq(p.tok.ident, "->") + else: p.tok.tokType == tkOpr and identEq(p.tok.ident, "->") if hasRet and p.tok.indent < 0: getTok(p) optInd(p, result) @@ -941,7 +941,7 @@ proc primary(p: var TParser, mode: TPrimaryMode): PNode = #| / 'static' primary #| / 'bind' primary if isOperator(p.tok): - let isSigil = IsSigilLike(p.tok) + let isSigil = isSigilLike(p.tok) result = newNodeP(nkPrefix, p) var a = newIdentNodeP(p.tok.ident, p) addSon(result, a) @@ -1877,7 +1877,7 @@ proc parseTopLevelStmt(p: var TParser): PNode = break proc parseString(s: string, filename: string = "", line: int = 0): PNode = - var stream = LLStreamOpen(s) + var stream = llStreamOpen(s) stream.lineOffset = line var parser: TParser diff --git a/compiler/passaux.nim b/compiler/passaux.nim index 4a85c994c..79d11419b 100644 --- a/compiler/passaux.nim +++ b/compiler/passaux.nim @@ -19,12 +19,12 @@ proc verboseOpen(s: PSym): PPassContext = proc verboseProcess(context: PPassContext, n: PNode): PNode = result = n - if context != nil: InternalError("logpass: context is not nil") + if context != nil: internalError("logpass: context is not nil") if gVerbosity == 3: # system.nim deactivates all hints, for verbosity:3 we want the processing # messages nonetheless, so we activate them again unconditionally: incl(msgs.gNotes, hintProcessing) - Message(n.info, hintProcessing, $idgen.gBackendId) + message(n.info, hintProcessing, $idgen.gBackendId) const verbosePass* = makePass(open = verboseOpen, process = verboseProcess) @@ -34,7 +34,7 @@ proc cleanUp(c: PPassContext, n: PNode): PNode = if optDeadCodeElim in gGlobalOptions or n == nil: return case n.kind of nkStmtList: - for i in countup(0, sonsLen(n) - 1): discard cleanup(c, n.sons[i]) + for i in countup(0, sonsLen(n) - 1): discard cleanUp(c, n.sons[i]) of nkProcDef, nkMethodDef: if n.sons[namePos].kind == nkSym: var s = n.sons[namePos].sym diff --git a/compiler/passes.nim b/compiler/passes.nim index 8d228fe9a..3dc31e7ac 100644 --- a/compiler/passes.nim +++ b/compiler/passes.nim @@ -30,8 +30,8 @@ type TPass* = tuple[open: TPassOpen, openCached: TPassOpenCached, process: TPassProcess, close: TPassClose] - TPassData* = tuple[input: PNode, closeOutput: Pnode] - TPasses* = openarray[TPass] + TPassData* = tuple[input: PNode, closeOutput: PNode] + TPasses* = openArray[TPass] # a pass is a tuple of procedure vars ``TPass.close`` may produce additional # nodes. These are passed to the other close procedures. @@ -169,7 +169,7 @@ proc processModule(module: PSym, stream: PLLStream, rd: PRodReader) = openPasses(a, module) if stream == nil: let filename = fileIdx.toFullPath - s = LLStreamOpen(filename, fmRead) + s = llStreamOpen(filename, fmRead) if s == nil: rawMessage(errCannotOpenFile, filename) return @@ -195,7 +195,7 @@ proc processModule(module: PSym, stream: PLLStream, rd: PRodReader) = if s.kind != llsStdIn: break closePasses(a) # id synchronization point for more consistent code generation: - IDsynchronizationPoint(1000) + idSynchronizationPoint(1000) else: openPassesCached(a, module, rd) var n = loadInitSection(rd) diff --git a/compiler/patterns.nim b/compiler/patterns.nim index b7792100f..54f8d3af4 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -87,22 +87,22 @@ proc matchChoice(c: PPatternContext, p, n: PNode): bool = if matches(c, p.sons[i], n): return true proc bindOrCheck(c: PPatternContext, param: PSym, n: PNode): bool = - var pp = GetLazy(c, param) + var pp = getLazy(c, param) if pp != nil: # check if we got the same pattern (already unified): result = sameTrees(pp, n) #matches(c, pp, n) elif n.kind == nkArgList or checkTypes(c, param, n): - PutLazy(c, param, n) + putLazy(c, param, n) result = true proc gather(c: PPatternContext, param: PSym, n: PNode) = - var pp = GetLazy(c, param) + var pp = getLazy(c, param) if pp != nil and pp.kind == nkArgList: pp.add(n) else: pp = newNodeI(nkArgList, n.info, 1) pp.sons[0] = n - PutLazy(c, param, pp) + putLazy(c, param, pp) proc matchNested(c: PPatternContext, p, n: PNode, rpn: bool): bool = # match ``op * param`` or ``op *| param`` @@ -148,7 +148,7 @@ proc matches(c: PPatternContext, p, n: PNode): bool = of "*": result = matchNested(c, p, n, rpn=false) of "**": result = matchNested(c, p, n, rpn=true) of "~": result = not matches(c, p.sons[1], n) - else: InternalError(p.info, "invalid pattern") + else: internalError(p.info, "invalid pattern") # template {add(a, `&` * b)}(a: string{noalias}, b: varargs[string]) = # add(a, b) elif p.kind == nkCurlyExpr: @@ -256,7 +256,7 @@ proc applyRule*(c: PContext, s: PSym, n: PNode): PNode = args = newNodeI(nkArgList, n.info) for i in 1 .. < params.len: let param = params.sons[i].sym - let x = GetLazy(ctx, param) + let x = getLazy(ctx, param) # couldn't bind parameter: if isNil(x): return nil result.add(x) diff --git a/compiler/platform.nim b/compiler/platform.nim index 5245cba6a..2e78d4fc5 100644 --- a/compiler/platform.nim +++ b/compiler/platform.nim @@ -200,10 +200,10 @@ proc setTarget*(o: TSystemOS, c: TSystemCPU) = #echo "new Target: OS: ", o, " CPU: ", c targetCPU = c targetOS = o - intSize = cpu[c].intSize div 8 - floatSize = cpu[c].floatSize div 8 - ptrSize = cpu[c].bit div 8 - tnl = os[o].newLine + intSize = CPU[c].intSize div 8 + floatSize = CPU[c].floatSize div 8 + ptrSize = CPU[c].bit div 8 + tnl = OS[o].newLine proc nameToOS(name: string): TSystemOS = for i in countup(succ(osNone), high(TSystemOS)): diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index 41898caed..5c9247fed 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -70,7 +70,7 @@ proc pragma*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords) # implementation proc invalidPragma(n: PNode) = - LocalError(n.info, errInvalidPragmaX, renderTree(n, {renderNoComments})) + localError(n.info, errInvalidPragmaX, renderTree(n, {renderNoComments})) proc pragmaAsm*(c: PContext, n: PNode): char = result = '\0' @@ -125,7 +125,7 @@ proc newEmptyStrNode(n: PNode): PNode {.noinline.} = proc getStrLitNode(c: PContext, n: PNode): PNode = if n.kind != nkExprColonExpr: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) # error correction: result = newEmptyStrNode(n) else: @@ -169,7 +169,7 @@ proc processMagic(c: PContext, n: PNode, s: PSym) = if substr($m, 1) == v: s.magic = m break - if s.magic == mNone: Message(n.info, warnUnknownMagic, v) + if s.magic == mNone: message(n.info, warnUnknownMagic, v) proc wordToCallConv(sw: TSpecialWord): TCallingConvention = # this assumes that the order of special words and calling conventions is @@ -188,11 +188,11 @@ proc onOff(c: PContext, n: PNode, op: TOptions) = else: gOptions = gOptions - op proc pragmaDeadCodeElim(c: PContext, n: PNode) = - if IsTurnedOn(c, n): incl(c.module.flags, sfDeadCodeElim) + if isTurnedOn(c, n): incl(c.module.flags, sfDeadCodeElim) else: excl(c.module.flags, sfDeadCodeElim) proc pragmaNoForward(c: PContext, n: PNode) = - if IsTurnedOn(c, n): incl(c.module.flags, sfNoForward) + if isTurnedOn(c, n): incl(c.module.flags, sfNoForward) else: excl(c.module.flags, sfNoForward) proc processCallConv(c: PContext, n: PNode) = @@ -201,9 +201,9 @@ proc processCallConv(c: PContext, n: PNode) = case sw of firstCallConv..lastCallConv: POptionEntry(c.optionStack.tail).defaultCC = wordToCallConv(sw) - else: LocalError(n.info, errCallConvExpected) + else: localError(n.info, errCallConvExpected) else: - LocalError(n.info, errCallConvExpected) + localError(n.info, errCallConvExpected) proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib = var it = PLib(c.libs.head) @@ -213,13 +213,13 @@ proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib = it = PLib(it.next) result = newLib(kind) result.path = path - Append(c.libs, result) + append(c.libs, result) if path.kind in {nkStrLit..nkTripleStrLit}: result.isOverriden = options.isDynLibOverride(path.strVal) proc expectDynlibNode(c: PContext, n: PNode): PNode = if n.kind != nkExprColonExpr: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) # error correction: result = newEmptyStrNode(n) else: @@ -229,7 +229,7 @@ proc expectDynlibNode(c: PContext, n: PNode): PNode = if result.kind == nkSym and result.sym.kind == skConst: result = result.sym.ast # look it up if result.typ == nil or result.typ.kind notin {tyPointer, tyString, tyProc}: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) result = newEmptyStrNode(n) proc processDynLib(c: PContext, n: PNode, sym: PSym) = @@ -265,7 +265,7 @@ proc processNote(c: PContext, n: PNode) = of wWarning: var x = findStr(msgs.WarningsToStr, n.sons[0].sons[1].ident.s) if x >= 0: nk = TNoteKind(x + ord(warnMin)) - else: InvalidPragma(n); return + else: invalidPragma(n); return else: invalidPragma(n) return @@ -284,26 +284,26 @@ proc processOption(c: PContext, n: PNode): bool = else: var sw = whichKeyword(n.sons[0].ident) case sw - of wChecks: OnOff(c, n, checksOptions) - of wObjChecks: OnOff(c, n, {optObjCheck}) - of wFieldchecks: OnOff(c, n, {optFieldCheck}) - of wRangechecks: OnOff(c, n, {optRangeCheck}) - of wBoundchecks: OnOff(c, n, {optBoundsCheck}) - of wOverflowchecks: OnOff(c, n, {optOverflowCheck}) - of wNilchecks: OnOff(c, n, {optNilCheck}) - of wFloatChecks: OnOff(c, n, {optNanCheck, optInfCheck}) - of wNaNchecks: OnOff(c, n, {optNanCheck}) - of wInfChecks: OnOff(c, n, {optInfCheck}) - of wAssertions: OnOff(c, n, {optAssert}) - of wWarnings: OnOff(c, n, {optWarns}) - of wHints: OnOff(c, n, {optHints}) + of wChecks: onOff(c, n, checksOptions) + of wObjChecks: onOff(c, n, {optObjCheck}) + of wFieldchecks: onOff(c, n, {optFieldCheck}) + of wRangechecks: onOff(c, n, {optRangeCheck}) + of wBoundchecks: onOff(c, n, {optBoundsCheck}) + of wOverflowchecks: onOff(c, n, {optOverflowCheck}) + of wNilchecks: onOff(c, n, {optNilCheck}) + of wFloatChecks: onOff(c, n, {optNanCheck, optInfCheck}) + of wNaNchecks: onOff(c, n, {optNanCheck}) + of wInfChecks: onOff(c, n, {optInfCheck}) + of wAssertions: onOff(c, n, {optAssert}) + of wWarnings: onOff(c, n, {optWarns}) + of wHints: onOff(c, n, {optHints}) of wCallConv: processCallConv(c, n) - of wLinedir: OnOff(c, n, {optLineDir}) - of wStacktrace: OnOff(c, n, {optStackTrace}) - of wLinetrace: OnOff(c, n, {optLineTrace}) - of wDebugger: OnOff(c, n, {optEndb}) - of wProfiler: OnOff(c, n, {optProfiler}) - of wByRef: OnOff(c, n, {optByRef}) + of wLinedir: onOff(c, n, {optLineDir}) + of wStacktrace: onOff(c, n, {optStackTrace}) + of wLinetrace: onOff(c, n, {optLineTrace}) + of wDebugger: onOff(c, n, {optEndb}) + of wProfiler: onOff(c, n, {optProfiler}) + of wByRef: onOff(c, n, {optByRef}) of wDynLib: processDynLib(c, n, nil) of wOptimization: if n.sons[1].kind != nkIdent: @@ -319,14 +319,14 @@ proc processOption(c: PContext, n: PNode): bool = of "none": excl(gOptions, optOptimizeSpeed) excl(gOptions, optOptimizeSize) - else: LocalError(n.info, errNoneSpeedOrSizeExpected) - of wImplicitStatic: OnOff(c, n, {optImplicitStatic}) - of wPatterns: OnOff(c, n, {optPatterns}) + else: localError(n.info, errNoneSpeedOrSizeExpected) + of wImplicitStatic: onOff(c, n, {optImplicitStatic}) + of wPatterns: onOff(c, n, {optPatterns}) else: result = true proc processPush(c: PContext, n: PNode, start: int) = if n.sons[start-1].kind == nkExprColonExpr: - LocalError(n.info, errGenerated, "':' after 'push' not supported") + localError(n.info, errGenerated, "':' after 'push' not supported") var x = newOptionEntry() var y = POptionEntry(c.optionStack.tail) x.options = gOptions @@ -344,7 +344,7 @@ proc processPush(c: PContext, n: PNode, start: int) = proc processPop(c: PContext, n: PNode) = if c.optionStack.counter <= 1: - LocalError(n.info, errAtPopWithoutPush) + localError(n.info, errAtPopWithoutPush) else: gOptions = POptionEntry(c.optionStack.tail).options gNotes = POptionEntry(c.optionStack.tail).notes @@ -352,15 +352,15 @@ proc processPop(c: PContext, n: PNode) = proc processDefine(c: PContext, n: PNode) = if (n.kind == nkExprColonExpr) and (n.sons[1].kind == nkIdent): - DefineSymbol(n.sons[1].ident.s) - Message(n.info, warnDeprecated, "define") + defineSymbol(n.sons[1].ident.s) + message(n.info, warnDeprecated, "define") else: invalidPragma(n) proc processUndef(c: PContext, n: PNode) = if (n.kind == nkExprColonExpr) and (n.sons[1].kind == nkIdent): - UndefSymbol(n.sons[1].ident.s) - Message(n.info, warnDeprecated, "undef") + undefSymbol(n.sons[1].ident.s) + message(n.info, warnDeprecated, "undef") else: invalidPragma(n) @@ -372,13 +372,13 @@ proc processCompile(c: PContext, n: PNode) = var s = expectStrLit(c, n) var found = findFile(s) if found == "": found = s - var trunc = ChangeFileExt(found, "") + var trunc = changeFileExt(found, "") extccomp.addExternalFileToCompile(found) extccomp.addFileToLink(completeCFilePath(trunc, false)) proc processCommonLink(c: PContext, n: PNode, feature: TLinkFeature) = var f = expectStrLit(c, n) - if splitFile(f).ext == "": f = addFileExt(f, cc[ccompiler].objExt) + if splitFile(f).ext == "": f = addFileExt(f, CC[cCompiler].objExt) var found = findFile(f) if found == "": found = f # use the default case feature @@ -408,7 +408,7 @@ proc semAsmOrEmit*(con: PContext, n: PNode, marker: char): PNode = result = newNode(if n.kind == nkAsmStmt: nkAsmStmt else: nkArgList, n.info) var str = n.sons[1].strVal if str == "": - LocalError(n.info, errEmptyAsm) + localError(n.info, errEmptyAsm) return # now parse the string literal and substitute symbols: var a = 0 @@ -458,9 +458,9 @@ proc pragmaLine(c: PContext, n: PNode) = if x.kind == nkExprColonExpr: x = x.sons[1] if y.kind == nkExprColonExpr: y = y.sons[1] if x.kind != nkStrLit: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) elif y.kind != nkIntLit: - LocalError(n.info, errIntLiteralExpected) + localError(n.info, errIntLiteralExpected) else: n.info.fileIndex = msgs.fileInfoIdx(x.strVal) n.info.line = int16(y.intVal) @@ -476,11 +476,11 @@ proc processPragma(c: PContext, n: PNode, i: int) = elif it.sons[0].kind != nkIdent: invalidPragma(n) elif it.sons[1].kind != nkIdent: invalidPragma(n) - var userPragma = NewSym(skTemplate, it.sons[1].ident, nil, it.info) + var userPragma = newSym(skTemplate, it.sons[1].ident, nil, it.info) var body = newNodeI(nkPragma, n.info) for j in i+1 .. sonsLen(n)-1: addSon(body, n.sons[j]) userPragma.ast = body - StrTableAdd(c.userPragmas, userPragma) + strTableAdd(c.userPragmas, userPragma) proc pragmaRaisesOrTags(c: PContext, n: PNode) = proc processExc(c: PContext, x: PNode) = @@ -503,11 +503,11 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, var it = n.sons[i] var key = if it.kind == nkExprColonExpr: it.sons[0] else: it if key.kind == nkIdent: - var userPragma = StrTableGet(c.userPragmas, key.ident) + var userPragma = strTableGet(c.userPragmas, key.ident) if userPragma != nil: inc c.InstCounter if c.InstCounter > 100: - GlobalError(it.info, errRecursiveDependencyX, userPragma.name.s) + globalError(it.info, errRecursiveDependencyX, userPragma.name.s) pragma(c, sym, userPragma.ast, validPragmas) dec c.InstCounter else: @@ -534,15 +534,15 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wAlign: if sym.typ == nil: invalidPragma(it) var align = expectIntLit(c, it) - if not IsPowerOfTwo(align) and align != 0: - LocalError(it.info, errPowerOfTwoExpected) + if not isPowerOfTwo(align) and align != 0: + localError(it.info, errPowerOfTwoExpected) else: sym.typ.align = align of wSize: if sym.typ == nil: invalidPragma(it) var size = expectIntLit(c, it) - if not IsPowerOfTwo(size) or size <= 0 or size > 8: - LocalError(it.info, errPowerOfTwoExpected) + if not isPowerOfTwo(size) or size <= 0 or size > 8: + localError(it.info, errPowerOfTwoExpected) else: sym.typ.size = size of wNodecl: @@ -572,7 +572,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, incl(sym.flags, sfGlobal) incl(sym.flags, sfPure) of wMerge: - noval(it) + noVal(it) incl(sym.flags, sfMerge) of wHeader: var lib = getLib(c, libHeader, getStrLitNode(c, it)) @@ -640,8 +640,8 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, incl(sym.flags, sfThread) incl(sym.flags, sfProcVar) if sym.typ != nil: incl(sym.typ.flags, tfThread) - of wHint: Message(it.info, hintUser, expectStrLit(c, it)) - of wWarning: Message(it.info, warnUser, expectStrLit(c, it)) + of wHint: message(it.info, hintUser, expectStrLit(c, it)) + of wWarning: message(it.info, warnUser, expectStrLit(c, it)) of wError: if sym != nil and sym.isRoutine: # This is subtle but correct: the error *statement* is only @@ -651,8 +651,8 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, noVal(it) incl(sym.flags, sfError) else: - LocalError(it.info, errUser, expectStrLit(c, it)) - of wFatal: Fatal(it.info, errUser, expectStrLit(c, it)) + localError(it.info, errUser, expectStrLit(c, it)) + of wFatal: fatal(it.info, errUser, expectStrLit(c, it)) of wDefine: processDefine(c, it) of wUndef: processUndef(c, it) of wCompile: processCompile(c, it) @@ -660,8 +660,8 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wLinkSys: processCommonLink(c, it, linkSys) of wPassL: extccomp.addLinkOption(expectStrLit(c, it)) of wPassC: extccomp.addCompileOption(expectStrLit(c, it)) - of wBreakpoint: PragmaBreakpoint(c, it) - of wWatchpoint: PragmaWatchpoint(c, it) + of wBreakpoint: pragmaBreakpoint(c, it) + of wWatchpoint: pragmaWatchpoint(c, it) of wPush: processPush(c, n, i + 1) result = true @@ -684,13 +684,13 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, wPatterns: if processOption(c, it): # calling conventions (boring...): - LocalError(it.info, errOptionExpected) + localError(it.info, errOptionExpected) of firstCallConv..lastCallConv: assert(sym != nil) if sym.typ == nil: invalidPragma(it) else: sym.typ.callConv = wordToCallConv(k) - of wEmit: PragmaEmit(c, it) - of wUnroll: PragmaUnroll(c, it) + of wEmit: pragmaEmit(c, it) + of wUnroll: pragmaUnroll(c, it) of wLinearScanEnd, wComputedGoto: noVal(it) of wEffects: # is later processed in effect analysis: @@ -706,7 +706,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wByRef: noVal(it) if sym == nil or sym.typ == nil: - if processOption(c, it): LocalError(it.info, errOptionExpected) + if processOption(c, it): localError(it.info, errOptionExpected) else: incl(sym.typ.flags, tfByRef) of wByCopy: @@ -718,7 +718,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, # as they are handled directly in 'evalTemplate'. noVal(it) if sym == nil: invalidPragma(it) - of wLine: PragmaLine(c, it) + of wLine: pragmaLine(c, it) of wRaises, wTags: pragmaRaisesOrTags(c, it) of wOperator: if sym == nil: invalidPragma(it) @@ -741,11 +741,11 @@ proc implictPragmas*(c: PContext, sym: PSym, n: PNode, if not o.isNil: for i in countup(0, sonsLen(o) - 1): if singlePragma(c, sym, o, i, validPragmas): - InternalError(n.info, "implicitPragmas") + internalError(n.info, "implicitPragmas") it = it.next.POptionEntry if lfExportLib in sym.loc.flags and sfExportc notin sym.flags: - LocalError(n.info, errDynlibRequiresExportc) + localError(n.info, errDynlibRequiresExportc) var lib = POptionEntry(c.optionstack.tail).dynlib if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and sfImportc in sym.flags and lib != nil: diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 85b138822..a59694d8f 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -46,7 +46,7 @@ proc loadFile(info: TLineInfo) = proc overwriteFiles*() = for i in 0 .. high(gSourceFiles): if not gSourceFiles[i].dirty: continue - let newFile = gSourceFiles[i].fullpath.changeFileExt(".pretty.nim") + let newFile = gSourceFiles[i].fullpath #.changeFileExt(".pretty.nim") try: var f = open(newFile, fmWrite) for line in gSourceFiles[i].lines: @@ -167,7 +167,7 @@ proc checkUse(c: PGen; n: PNode) = let last = first+identLen(line, first)-1 if differ(line, first, last, newName): # last-first+1 != newName.len or - var x = line.subStr(0, first-1) & newName & line.substr(last+1) + var x = line.substr(0, first-1) & newName & line.substr(last+1) when removeTP: # the WinAPI module is full of 'TX = X' which after the substitution # becomes 'X = X'. We remove those lines: diff --git a/compiler/procfind.nim b/compiler/procfind.nim index 1075d5129..a59df1178 100644 --- a/compiler/procfind.nim +++ b/compiler/procfind.nim @@ -44,12 +44,12 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym = if result.Kind == fn.kind and isGenericRoutine(result): let genR = result.ast.sons[genericParamsPos] let genF = fn.ast.sons[genericParamsPos] - if ExprStructuralEquivalent(genR, genF) and - ExprStructuralEquivalent(result.ast.sons[paramsPos], + if exprStructuralEquivalent(genR, genF) and + exprStructuralEquivalent(result.ast.sons[paramsPos], fn.ast.sons[paramsPos]) and equalGenericParams(genR, genF): return - result = NextIdentIter(it, scope.symbols) + result = nextIdentIter(it, scope.symbols) else: while result != nil: if result.Kind == fn.kind and not isGenericRoutine(result): @@ -57,11 +57,11 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym = of paramsEqual: return of paramsIncompatible: - LocalError(fn.info, errNotOverloadable, fn.name.s) + localError(fn.info, errNotOverloadable, fn.name.s) return of paramsNotEqual: nil - result = NextIdentIter(it, scope.symbols) + result = nextIdentIter(it, scope.symbols) when false: proc paramsFitBorrow(child, parent: PNode): bool = diff --git a/compiler/renderer.nim b/compiler/renderer.nim index 27193c229..79486da6b 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -76,7 +76,7 @@ proc initSrcGen(g: var TSrcGen, renderFlags: TRenderFlags) = proc addTok(g: var TSrcGen, kind: TTokType, s: string) = var length = len(g.tokens) - setlen(g.tokens, length + 1) + setLen(g.tokens, length + 1) g.tokens[length].kind = kind g.tokens[length].length = int16(len(s)) add(g.buf, s) @@ -127,7 +127,7 @@ proc putLong(g: var TSrcGen, kind: TTokType, s: string, lineLen: int) = addTok(g, kind, s) g.lineLen = lineLen -proc toNimChar(c: Char): string = +proc toNimChar(c: char): string = case c of '\0': result = "\\0" of '\x01'..'\x1F', '\x80'..'\xFF': result = "\\x" & strutils.toHex(ord(c), 2) @@ -241,14 +241,14 @@ proc containsNL(s: string): bool = proc pushCom(g: var TSrcGen, n: PNode) = var length = len(g.comStack) - setlen(g.comStack, length + 1) + setLen(g.comStack, length + 1) g.comStack[length] = n proc popAllComs(g: var TSrcGen) = - setlen(g.comStack, 0) + setLen(g.comStack, 0) proc popCom(g: var TSrcGen) = - setlen(g.comStack, len(g.comStack) - 1) + setLen(g.comStack, len(g.comStack) - 1) const Space = " " @@ -278,7 +278,7 @@ proc gcoms(g: var TSrcGen) = popAllComs(g) proc lsub(n: PNode): int -proc litAux(n: PNode, x: biggestInt, size: int): string = +proc litAux(n: PNode, x: BiggestInt, size: int): string = proc skip(t: PType): PType = result = t while result.kind in {tyGenericInst, tyRange, tyVar, tyDistinct, tyOrdinal, @@ -295,7 +295,7 @@ proc litAux(n: PNode, x: biggestInt, size: int): string = elif nfBase16 in n.flags: result = "0x" & toHex(x, size * 2) else: result = $x -proc ulitAux(n: PNode, x: biggestInt, size: int): string = +proc ulitAux(n: PNode, x: BiggestInt, size: int): string = if nfBase2 in n.flags: result = "0b" & toBin(x, size * 8) elif nfBase8 in n.flags: result = "0o" & toOct(x, size * 3) elif nfBase16 in n.flags: result = "0x" & toHex(x, size * 2) @@ -341,7 +341,7 @@ proc atom(n: PNode): string = if (n.typ != nil) and (n.typ.sym != nil): result = n.typ.sym.name.s else: result = "[type node]" else: - InternalError("rnimsyn.atom " & $n.kind) + internalError("rnimsyn.atom " & $n.kind) result = "" proc lcomma(n: PNode, start: int = 0, theEnd: int = - 1): int = @@ -1252,7 +1252,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) = put(g, tkParRi, ")") else: #nkNone, nkExplicitTypeListCall: - InternalError(n.info, "rnimsyn.gsub(" & $n.kind & ')') + internalError(n.info, "rnimsyn.gsub(" & $n.kind & ')') proc renderTree(n: PNode, renderFlags: TRenderFlags = {}): string = var g: TSrcGen @@ -1263,7 +1263,7 @@ proc renderTree(n: PNode, renderFlags: TRenderFlags = {}): string = proc renderModule(n: PNode, filename: string, renderFlags: TRenderFlags = {}) = var - f: tfile + f: TFile g: TSrcGen initSrcGen(g, renderFlags) for i in countup(0, sonsLen(n) - 1): diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 9f69f022a..eba876659 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -306,7 +306,7 @@ proc decodeType(r: PRodReader, info: TLineInfo): PType = internalError(info, "decodeType: no id") # here this also avoids endless recursion for recursive type idTablePut(gTypeTable, result, result) - if r.s[r.pos] == '(': result.n = decodeNode(r, UnknownLineInfo()) + if r.s[r.pos] == '(': result.n = decodeNode(r, unknownLineInfo()) if r.s[r.pos] == '$': inc(r.pos) result.flags = cast[TTypeFlags](int32(decodeVInt(r.s, r.pos))) @@ -335,7 +335,7 @@ proc decodeType(r: PRodReader, info: TLineInfo): PType = if r.s[r.pos] == '(': inc(r.pos) if r.s[r.pos] == ')': inc(r.pos) - else: InternalError(info, "decodeType ^(" & r.s[r.pos]) + else: internalError(info, "decodeType ^(" & r.s[r.pos]) rawAddSon(result, nil) else: var d = decodeVInt(r.s, r.pos) @@ -347,10 +347,10 @@ proc decodeLib(r: PRodReader, info: TLineInfo): PLib = new(result) inc(r.pos) result.kind = TLibKind(decodeVInt(r.s, r.pos)) - if r.s[r.pos] != '|': InternalError("decodeLib: 1") + if r.s[r.pos] != '|': internalError("decodeLib: 1") inc(r.pos) result.name = toRope(decodeStr(r.s, r.pos)) - if r.s[r.pos] != '|': InternalError("decodeLib: 2") + if r.s[r.pos] != '|': internalError("decodeLib: 2") inc(r.pos) result.path = decodeNode(r, info) @@ -375,13 +375,13 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = inc(r.pos) ident = getIdent(decodeStr(r.s, r.pos)) else: - InternalError(info, "decodeSym: no ident") + internalError(info, "decodeSym: no ident") #echo "decoding: {", ident.s - result = PSym(IdTableGet(r.syms, id)) + result = PSym(idTableGet(r.syms, id)) if result == nil: new(result) result.id = id - IdTablePut(r.syms, result, result) + idTablePut(r.syms, result, result) if debugIds: registerID(result) elif result.id != id: internalError(info, "decodeSym: wrong id") @@ -427,7 +427,7 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym = result.annex = decodeLib(r, info) if r.s[r.pos] == '#': inc(r.pos) - result.constraint = decodeNode(r, UnknownLineInfo()) + result.constraint = decodeNode(r, unknownLineInfo()) if r.s[r.pos] == '(': if result.kind in routineKinds: result.ast = decodeNodeLazyBody(r, result.info, result) @@ -458,7 +458,7 @@ proc skipSection(r: PRodReader) = else: discard inc(r.pos) else: - InternalError("skipSection " & $r.line) + internalError("skipSection " & $r.line) proc rdWord(r: PRodReader): string = result = "" @@ -472,11 +472,11 @@ proc newStub(r: PRodReader, name: string, id: int): PSym = result.id = id result.name = getIdent(name) result.position = r.readerIndex - setID(id) #MessageOut(result.name.s); + setId(id) #MessageOut(result.name.s); if debugIds: registerID(result) proc processInterf(r: PRodReader, module: PSym) = - if r.interfIdx == 0: InternalError("processInterf") + if r.interfIdx == 0: internalError("processInterf") r.pos = r.interfIdx while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): var w = decodeStr(r.s, r.pos) @@ -485,23 +485,23 @@ proc processInterf(r: PRodReader, module: PSym) = inc(r.pos) # #10 var s = newStub(r, w, key) s.owner = module - StrTableAdd(module.tab, s) - IdTablePut(r.syms, s, s) + strTableAdd(module.tab, s) + idTablePut(r.syms, s, s) proc processCompilerProcs(r: PRodReader, module: PSym) = - if r.compilerProcsIdx == 0: InternalError("processCompilerProcs") + if r.compilerProcsIdx == 0: internalError("processCompilerProcs") r.pos = r.compilerProcsIdx while (r.s[r.pos] > '\x0A') and (r.s[r.pos] != ')'): var w = decodeStr(r.s, r.pos) inc(r.pos) var key = decodeVInt(r.s, r.pos) inc(r.pos) # #10 - var s = PSym(IdTableGet(r.syms, key)) + var s = PSym(idTableGet(r.syms, key)) if s == nil: s = newStub(r, w, key) s.owner = module - IdTablePut(r.syms, s, s) - StrTableAdd(rodCompilerProcs, s) + idTablePut(r.syms, s, s) + strTableAdd(rodCompilerprocs, s) proc processIndex(r: PRodReader; idx: var TIndex; outf: TFile = nil) = var key, val, tmp: int @@ -516,11 +516,11 @@ proc processIndex(r: PRodReader; idx: var TIndex; outf: TFile = nil) = else: key = idx.lastIdxKey + 1 val = tmp + idx.lastIdxVal - IITablePut(idx.tab, key, val) + iiTablePut(idx.tab, key, val) if not outf.isNil: outf.write(key, " ", val, "\n") idx.lastIdxKey = key idx.lastIdxVal = val - setID(key) # ensure that this id will not be used + setId(key) # ensure that this id will not be used if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) @@ -558,7 +558,7 @@ proc processRodFile(r: PRodReader, crc: TCrc32) = of "ID": inc(r.pos) # skip ':' r.moduleID = decodeVInt(r.s, r.pos) - setID(r.moduleID) + setId(r.moduleID) of "ORIGFILE": inc(r.pos) r.origFile = decodeStr(r.s, r.pos) @@ -603,7 +603,7 @@ proc processRodFile(r: PRodReader, crc: TCrc32) = inc(r.pos) # skip ' ' inclCrc = decodeVInt(r.s, r.pos) if r.reason == rrNone: - if not ExistsFile(w) or (inclCrc != int(crcFromFile(w))): + if not existsFile(w) or (inclCrc != int(crcFromFile(w))): r.reason = rrInclDeps if r.s[r.pos] == '\x0A': inc(r.pos) @@ -639,7 +639,7 @@ proc processRodFile(r: PRodReader, crc: TCrc32) = r.initIdx = r.pos + 2 # "(\10" skipSection(r) else: - InternalError("invalid section: '" & section & + internalError("invalid section: '" & section & "' at " & $r.line & " in " & r.filename) #MsgWriteln("skipping section: " & section & # " at " & $r.line & " in " & r.filename) @@ -670,13 +670,13 @@ proc newRodReader(modfilename: string, crc: TCrc32, r.line = 1 r.readerIndex = readerIndex r.filename = modfilename - InitIdTable(r.syms) + initIdTable(r.syms) # we terminate the file explicitely with ``\0``, so the cast to `cstring` # is safe: r.s = cast[cstring](r.memFile.mem) if startsWith(r.s, "NIM:"): - initIITable(r.index.tab) - initIITable(r.imports.tab) # looks like a ROD file + initIiTable(r.index.tab) + initIiTable(r.imports.tab) # looks like a ROD file inc(r.pos, 4) var version = "" while r.s[r.pos] notin {'\0', '\x0A'}: @@ -691,12 +691,12 @@ proc newRodReader(modfilename: string, crc: TCrc32, result = nil proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType = - result = PType(IdTableGet(gTypeTable, id)) + result = PType(idTableGet(gTypeTable, id)) if result == nil: # load the type: var oldPos = r.pos - var d = IITableGet(r.index.tab, id) - if d == invalidKey: InternalError(info, "rrGetType") + var d = iiTableGet(r.index.tab, id) + if d == invalidKey: internalError(info, "rrGetType") r.pos = d + r.dataIdx result = decodeType(r, info) r.pos = oldPos @@ -715,7 +715,7 @@ var gMods*: TFileModuleMap = @[] proc decodeSymSafePos(rd: PRodReader, offset: int, info: TLineInfo): PSym = # all compiled modules - if rd.dataIdx == 0: InternalError(info, "dataIdx == 0") + if rd.dataIdx == 0: internalError(info, "dataIdx == 0") var oldPos = rd.pos rd.pos = offset + rd.dataIdx result = decodeSym(rd, info) @@ -725,7 +725,7 @@ proc findSomeWhere(id: int) = for i in countup(0, high(gMods)): var rd = gMods[i].rd if rd != nil: - var d = IITableGet(rd.index.tab, id) + var d = iiTableGet(rd.index.tab, id) if d != invalidKey: echo "found id ", id, " in ", gMods[i].filename @@ -740,33 +740,33 @@ proc getReader(moduleId: int): PRodReader = return nil proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = - result = PSym(IdTableGet(r.syms, id)) + result = PSym(idTableGet(r.syms, id)) if result == nil: # load the symbol: - var d = IITableGet(r.index.tab, id) + var d = iiTableGet(r.index.tab, id) if d == invalidKey: # import from other module: - var moduleID = IiTableGet(r.imports.tab, id) + var moduleID = iiTableGet(r.imports.tab, id) if moduleID < 0: var x = "" encodeVInt(id, x) - InternalError(info, "missing from both indexes: +" & x) + internalError(info, "missing from both indexes: +" & x) var rd = getReader(moduleID) - d = IITableGet(rd.index.tab, id) + d = iiTableGet(rd.index.tab, id) if d != invalidKey: result = decodeSymSafePos(rd, d, info) else: var x = "" encodeVInt(id, x) when false: findSomeWhere(id) - InternalError(info, "rrGetSym: no reader found: +" & x) + internalError(info, "rrGetSym: no reader found: +" & x) else: # own symbol: result = decodeSymSafePos(r, d, info) if result != nil and result.kind == skStub: rawLoadStub(result) proc loadInitSection(r: PRodReader): PNode = - if r.initIdx == 0 or r.dataIdx == 0: InternalError("loadInitSection") + if r.initIdx == 0 or r.dataIdx == 0: internalError("loadInitSection") var oldPos = r.pos r.pos = r.initIdx result = newNode(nkStmtList) @@ -775,7 +775,7 @@ proc loadInitSection(r: PRodReader): PNode = inc(r.pos) # #10 var p = r.pos r.pos = d + r.dataIdx - addSon(result, decodeNode(r, UnknownLineInfo())) + addSon(result, decodeNode(r, unknownLineInfo())) r.pos = p r.pos = oldPos @@ -783,20 +783,20 @@ proc loadConverters(r: PRodReader) = # We have to ensure that no exported converter is a stub anymore, and the # import mechanism takes care of the rest. if r.convertersIdx == 0 or r.dataIdx == 0: - InternalError("importConverters") + internalError("importConverters") r.pos = r.convertersIdx while r.s[r.pos] > '\x0A': var d = decodeVInt(r.s, r.pos) - discard rrGetSym(r, d, UnknownLineInfo()) + discard rrGetSym(r, d, unknownLineInfo()) if r.s[r.pos] == ' ': inc(r.pos) proc loadMethods(r: PRodReader) = if r.methodsIdx == 0 or r.dataIdx == 0: - InternalError("loadMethods") + internalError("loadMethods") r.pos = r.methodsIdx while r.s[r.pos] > '\x0A': var d = decodeVInt(r.s, r.pos) - r.methods.add(rrGetSym(r, d, UnknownLineInfo())) + r.methods.add(rrGetSym(r, d, unknownLineInfo())) if r.s[r.pos] == ' ': inc(r.pos) proc getCRC*(fileIdx: int32): TCrc32 = @@ -834,7 +834,7 @@ proc checkDep(fileIdx: int32): TReasonForRecompile = # NOTE: we need to process the entire module graph so that no ID will # be used twice! However, compilation speed does not suffer much from # this, since results are cached. - var res = checkDep(SystemFileIdx) + var res = checkDep(systemFileIdx) if res != rrNone: result = rrModDeps for i in countup(0, high(r.modDeps)): res = checkDep(r.modDeps[i]) @@ -858,11 +858,11 @@ proc handleSymbolFile(module: PSym): PRodReader = idgen.loadMaxIds(options.gProjectPath / options.gProjectName) discard checkDep(fileIdx) - if gMods[fileIdx].reason == rrEmpty: InternalError("handleSymbolFile") + if gMods[fileIdx].reason == rrEmpty: internalError("handleSymbolFile") result = gMods[fileIdx].rd if result != nil: module.id = result.moduleID - IdTablePut(result.syms, module, module) + idTablePut(result.syms, module, module) processInterf(result, module) processCompilerProcs(result, module) loadConverters(result) @@ -871,12 +871,12 @@ proc handleSymbolFile(module: PSym): PRodReader = module.id = getID() proc rawLoadStub(s: PSym) = - if s.kind != skStub: InternalError("loadStub") + if s.kind != skStub: internalError("loadStub") var rd = gMods[s.position].rd var theId = s.id # used for later check - var d = IITableGet(rd.index.tab, s.id) - if d == invalidKey: InternalError("loadStub: invalid key") - var rs = decodeSymSafePos(rd, d, UnknownLineInfo()) + var d = iiTableGet(rd.index.tab, s.id) + if d == invalidKey: internalError("loadStub: invalid key") + var rs = decodeSymSafePos(rd, d, unknownLineInfo()) if rs != s: #echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2), # "\ns: ", toHex(cast[int](s.position), int.sizeof * 2) @@ -913,7 +913,7 @@ proc getBody*(s: PSym): PNode = s.offset = 0 initIdTable(gTypeTable) -initStrTable(rodCompilerProcs) +initStrTable(rodCompilerprocs) # viewer: proc writeNode(f: TFile; n: PNode) = @@ -1038,7 +1038,7 @@ proc viewFile(rodfile: string) = of "ID": inc(r.pos) # skip ':' r.moduleID = decodeVInt(r.s, r.pos) - setID(r.moduleID) + setId(r.moduleID) outf.writeln("ID:", $r.moduleID) of "ORIGFILE": inc(r.pos) @@ -1140,12 +1140,12 @@ proc viewFile(rodfile: string) = outf.write("DATA(\n") while r.s[r.pos] != ')': if r.s[r.pos] == '(': - outf.writeNode decodeNode(r, UnknownLineInfo()) + outf.writeNode decodeNode(r, unknownLineInfo()) outf.write("\n") elif r.s[r.pos] == '[': - outf.writeType decodeType(r, UnknownLineInfo()) + outf.writeType decodeType(r, unknownLineInfo()) else: - outf.writeSym decodeSym(r, UnknownLineInfo()) + outf.writeSym decodeSym(r, unknownLineInfo()) if r.s[r.pos] == '\x0A': inc(r.pos) inc(r.line) diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 4527f77da..4433ed4ab 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -119,7 +119,7 @@ template decodeIntImpl() = proc decodeVInt*(s: cstring, pos: var int): int = decodeIntImpl() -proc decodeVBiggestInt*(s: cstring, pos: var int): biggestInt = +proc decodeVBiggestInt*(s: cstring, pos: var int): BiggestInt = decodeIntImpl() iterator decodeVIntArray*(s: cstring): int = diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index 2e52aeaa7..be55a5c17 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -56,7 +56,7 @@ proc fileIdx(w: PRodWriter, filename: string): int = if w.files[i] == filename: return i result = len(w.files) - setlen(w.files, result + 1) + setLen(w.files, result + 1) w.files[result] = filename template filename*(w: PRodWriter): string = @@ -66,8 +66,8 @@ proc newRodWriter(crc: TCrc32, module: PSym): PRodWriter = new(result) result.sstack = @[] result.tstack = @[] - InitIITable(result.index.tab) - InitIITable(result.imports.tab) + initIiTable(result.index.tab) + initIiTable(result.imports.tab) result.index.r = "" result.imports.r = "" result.crc = crc @@ -101,12 +101,12 @@ proc addInclDep(w: PRodWriter, dep: string) = proc pushType(w: PRodWriter, t: PType) = # 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) proc pushSym(w: PRodWriter, s: PSym) = # 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) proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, @@ -120,19 +120,19 @@ proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, # we do not write comments for now # Line information takes easily 20% or more of the filesize! Therefore we # omit line information if it is the same as the father's line information: - if finfo.fileIndex != n.info.fileIndex: + if fInfo.fileIndex != n.info.fileIndex: result.add('?') encodeVInt(n.info.col, result) result.add(',') encodeVInt(n.info.line, result) result.add(',') encodeVInt(fileIdx(w, toFilename(n.info)), result) - elif finfo.line != n.info.line: + elif fInfo.line != n.info.line: result.add('?') encodeVInt(n.info.col, result) result.add(',') encodeVInt(n.info.line, result) - elif finfo.col != n.info.col: + elif fInfo.col != n.info.col: result.add('?') encodeVInt(n.info.col, result) # No need to output the file index, as this is the serialization of one @@ -190,7 +190,7 @@ proc encodeLoc(w: PRodWriter, loc: TLoc, result: var string) = if loc.a != 0: add(result, '?') encodeVInt(loc.a, result) - if oldlen + 1 == result.len: + if oldLen + 1 == result.len: # no data was necessary, so remove the '<' again: setLen(result, oldLen) else: @@ -202,7 +202,7 @@ proc encodeType(w: PRodWriter, t: PType, result: var string) = result.add("[]") return # we need no surrounding [] here because the type is in a line of its own - if t.kind == tyForward: InternalError("encodeType: tyForward") + if t.kind == tyForward: internalError("encodeType: tyForward") # for the new rodfile viewer we use a preceeding [ so that the data section # can easily be disambiguated: add(result, '[') @@ -210,7 +210,7 @@ proc encodeType(w: PRodWriter, t: PType, result: var string) = add(result, '+') encodeVInt(t.id, result) if t.n != nil: - encodeNode(w, UnknownLineInfo(), t.n, result) + encodeNode(w, unknownLineInfo(), t.n, result) if t.flags != {}: add(result, '$') encodeVInt(cast[int32](t.flags), result) @@ -292,7 +292,7 @@ proc encodeSym(w: PRodWriter, s: PSym, result: var string) = if s.annex != nil: encodeLib(w, s.annex, s.info, result) if s.constraint != nil: add(result, '#') - encodeNode(w, UnknownLineInfo(), s.constraint, result) + encodeNode(w, unknownLineInfo(), s.constraint, result) # lazy loading will soon reload the ast lazily, so the ast needs to be # the last entry of a symbol: if s.ast != nil: @@ -322,7 +322,7 @@ proc addToIndex(w: var TIndex, key, val: int) = add(w.r, rodNL) w.lastIdxKey = key w.lastIdxVal = val - IiTablePut(w.tab, key, val) + iiTablePut(w.tab, key, val) const debugWrittenIds = false @@ -336,9 +336,9 @@ proc symStack(w: PRodWriter): int = if sfForward in s.flags: w.sstack[result] = s inc result - elif IiTableGet(w.index.tab, s.id) == invalidKey: + elif iiTableGet(w.index.tab, s.id) == invalidKey: 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): # put definition in here var L = w.data.len @@ -364,7 +364,7 @@ proc symStack(w: PRodWriter): int = if s.kind == skMethod and sfDispatcher notin s.flags: if w.methods.len != 0: add(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) when debugWrittenIds: if not Contains(debugWritten, s.id): @@ -374,7 +374,7 @@ proc symStack(w: PRodWriter): int = debug(m) InternalError("Symbol referred to but never written") inc(i) - setlen(w.sstack, result) + setLen(w.sstack, result) proc typeStack(w: PRodWriter): int = var i = 0 @@ -383,13 +383,13 @@ proc typeStack(w: PRodWriter): int = if t.kind == tyForward: w.tstack[result] = t inc result - elif IiTableGet(w.index.tab, t.id) == invalidKey: + elif iiTableGet(w.index.tab, t.id) == invalidKey: var L = w.data.len addToIndex(w.index, t.id, L) encodeType(w, t, w.data) add(w.data, rodNL) inc(i) - setlen(w.tstack, result) + setLen(w.tstack, result) proc processStacks(w: PRodWriter, finalPass: bool) = var oldS = 0 @@ -401,7 +401,7 @@ proc processStacks(w: PRodWriter, finalPass: bool) = oldS = slen oldT = tlen if finalPass and (oldS != 0 or oldT != 0): - InternalError("could not serialize some forwarded symbols/types") + internalError("could not serialize some forwarded symbols/types") proc rawAddInterfaceSym(w: PRodWriter, s: PSym) = pushSym(w, s) @@ -416,7 +416,7 @@ proc addInterfaceSym(w: PRodWriter, s: PSym) = proc addStmt(w: PRodWriter, n: PNode) = encodeVInt(w.data.len, w.init) add(w.init, rodNL) - encodeNode(w, UnknownLineInfo(), n, w.data) + encodeNode(w, unknownLineInfo(), n, w.data) add(w.data, rodNL) processStacks(w, false) @@ -534,9 +534,9 @@ proc process(c: PPassContext, n: PNode): PNode = of nkProcDef, nkMethodDef, nkIteratorDef, nkConverterDef, nkTemplateDef, nkMacroDef: var s = n.sons[namePos].sym - if s == nil: InternalError(n.info, "rodwrite.process") + if s == nil: internalError(n.info, "rodwrite.process") if n.sons[bodyPos] == nil: - InternalError(n.info, "rodwrite.process: body is nil") + internalError(n.info, "rodwrite.process: body is nil") if n.sons[bodyPos].kind != nkEmpty or s.magic != mNone or sfForward notin s.flags: addInterfaceSym(w, s) @@ -549,7 +549,7 @@ proc process(c: PPassContext, n: PNode): PNode = for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if a.sons[0].kind != nkSym: InternalError(a.info, "rodwrite.process") + if a.sons[0].kind != nkSym: internalError(a.info, "rodwrite.process") var s = a.sons[0].sym addInterfaceSym(w, s) # this takes care of enum fields too @@ -576,8 +576,8 @@ proc process(c: PPassContext, n: PNode): PNode = nil proc myOpen(module: PSym): PPassContext = - if module.id < 0: InternalError("rodwrite: module ID not set") - var w = newRodWriter(module.fileIdx.GetCRC, module) + if module.id < 0: internalError("rodwrite: module ID not set") + var w = newRodWriter(module.fileIdx.getCRC, module) rawAddInterfaceSym(w, module) result = w diff --git a/compiler/ropes.nim b/compiler/ropes.nim index 4f8553375..f3c0a00e0 100644 --- a/compiler/ropes.nim +++ b/compiler/ropes.nim @@ -162,9 +162,9 @@ proc toRope(s: string): PRope = proc ropeSeqInsert(rs: var TRopeSeq, r: PRope, at: Natural) = var length = len(rs) if at > length: - setlen(rs, at + 1) + setLen(rs, at + 1) else: - setlen(rs, length + 1) # move old rope elements: + setLen(rs, length + 1) # move old rope elements: for i in countdown(length, at + 1): rs[i] = rs[i - 1] # this is correct, I used pen and paper to validate it rs[at] = r @@ -228,9 +228,9 @@ proc writeRope*(f: TFile, c: PRope) = write(f, it.data) proc writeRope*(head: PRope, filename: string, useWarning = false) = - var f: tfile + var f: TFile if open(f, filename, fmWrite): - if head != nil: WriteRope(f, head) + if head != nil: writeRope(f, head) close(f) else: errorHandler(rCannotOpenFile, filename, useWarning) @@ -258,7 +258,7 @@ proc ropef(frmt: TFormatStr, args: varargs[PRope]): PRope = of '0'..'9': var j = 0 while true: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) if (i > length + 0 - 1) or not (frmt[i] in {'0'..'9'}): break num = j @@ -296,10 +296,10 @@ proc appf(c: var PRope, frmt: TFormatStr, args: varargs[PRope]) = const bufSize = 1024 # 1 KB is reasonable -proc auxRopeEqualsFile(r: PRope, bin: var tfile, buf: Pointer): bool = +proc auxRopeEqualsFile(r: PRope, bin: var TFile, buf: pointer): bool = if r.data != nil: if r.length > bufSize: - ErrorHandler(rTokenTooLong, r.data) + errorHandler(rTokenTooLong, r.data) return var readBytes = readBuffer(bin, buf, r.length) result = readBytes == r.length and diff --git a/compiler/saturate.nim b/compiler/saturate.nim index e0968843b..ed197bdd1 100644 --- a/compiler/saturate.nim +++ b/compiler/saturate.nim @@ -9,7 +9,7 @@ ## Saturated arithmetic routines. XXX Make part of the stdlib? -proc `|+|`*(a, b: biggestInt): biggestInt = +proc `|+|`*(a, b: BiggestInt): BiggestInt = ## saturated addition. result = a +% b if (result xor a) >= 0'i64 or (result xor b) >= 0'i64: @@ -19,7 +19,7 @@ proc `|+|`*(a, b: biggestInt): biggestInt = else: result = high(result) -proc `|-|`*(a, b: biggestInt): biggestInt = +proc `|-|`*(a, b: BiggestInt): BiggestInt = result = a -% b if (result xor a) >= 0'i64 or (result xor not b) >= 0'i64: return result @@ -28,14 +28,14 @@ proc `|-|`*(a, b: biggestInt): biggestInt = else: result = high(result) -proc `|abs|`*(a: biggestInt): biggestInt = +proc `|abs|`*(a: BiggestInt): BiggestInt = if a != low(a): if a >= 0: result = a else: result = -a else: result = low(a) -proc `|div|`*(a, b: biggestInt): biggestInt = +proc `|div|`*(a, b: BiggestInt): BiggestInt = # (0..5) div (0..4) == (0..5) div (1..4) == (0 div 4) .. (5 div 1) if b == 0'i64: # make the same as ``div 1``: @@ -45,13 +45,13 @@ proc `|div|`*(a, b: biggestInt): biggestInt = else: result = a div b -proc `|mod|`*(a, b: biggestInt): biggestInt = +proc `|mod|`*(a, b: BiggestInt): BiggestInt = if b == 0'i64: result = a else: result = a mod b -proc `|*|`*(a, b: biggestInt): biggestInt = +proc `|*|`*(a, b: BiggestInt): BiggestInt = var resAsFloat, floatProd: float64 result = a *% b diff --git a/compiler/sem.nim b/compiler/sem.nim index ee1019aa8..123a813af 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -47,19 +47,19 @@ proc indexTypesMatch(c: PContext, f, a: PType, arg: PNode): PNode proc typeMismatch(n: PNode, formal, actual: PType) = if formal.kind != tyError and actual.kind != tyError: - LocalError(n.Info, errGenerated, msgKindToString(errTypeMismatch) & + localError(n.Info, errGenerated, msgKindToString(errTypeMismatch) & typeToString(actual) & ") " & `%`(msgKindToString(errButExpectedX), [typeToString(formal)])) proc fitNode(c: PContext, formal: PType, arg: PNode): PNode = if arg.typ.isNil: - LocalError(arg.info, errExprXHasNoType, + localError(arg.info, errExprXHasNoType, renderTree(arg, {renderNoComments})) # error correction: result = copyNode(arg) result.typ = formal else: - result = IndexTypesMatch(c, formal, arg.typ, arg) + result = indexTypesMatch(c, formal, arg.typ, arg) if result == nil: typeMismatch(arg, formal, arg.typ) # error correction: @@ -176,7 +176,7 @@ when false: proc semConstExpr(c: PContext, n: PNode): PNode = var e = semExprWithType(c, n) if e == nil: - LocalError(n.info, errConstExprExpected) + localError(n.info, errConstExprExpected) return n result = getConstExpr(c.module, e) if result == nil: @@ -184,10 +184,10 @@ proc semConstExpr(c: PContext, n: PNode): PNode = if result == nil or result.kind == nkEmpty: if e.info != n.info: pushInfoContext(n.info) - LocalError(e.info, errConstExprExpected) + localError(e.info, errConstExprExpected) popInfoContext() else: - LocalError(e.info, errConstExprExpected) + localError(e.info, errConstExprExpected) # error correction: result = e else: @@ -241,7 +241,7 @@ proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym, semCheck: bool = true): PNode = markUsed(n, sym) if sym == c.p.owner: - GlobalError(n.info, errRecursiveDependencyX, sym.name.s) + globalError(n.info, errRecursiveDependencyX, sym.name.s) #if c.evalContext == nil: # c.evalContext = c.createEvalContext(emStatic) @@ -257,11 +257,11 @@ proc semConstBoolExpr(c: PContext, n: PNode): PNode = let nn = semExprWithType(c, n) result = fitNode(c, getSysType(tyBool), nn) if result == nil: - LocalError(n.info, errConstExprExpected) + localError(n.info, errConstExprExpected) return nn result = getConstExpr(c.module, result) if result == nil: - LocalError(n.info, errConstExprExpected) + localError(n.info, errConstExprExpected) result = nn include semtypes, semtempl, semgnrc, semstmts, semexprs @@ -271,14 +271,14 @@ proc addCodeForGenerics(c: PContext, n: PNode) = var prc = c.generics[i].inst.sym if prc.kind in {skProc, skMethod, skConverter} and prc.magic == mNone: if prc.ast == nil or prc.ast.sons[bodyPos] == nil: - InternalError(prc.info, "no code for " & prc.name.s) + internalError(prc.info, "no code for " & prc.name.s) else: addSon(n, prc.ast) c.lastGenericIdx = c.generics.len proc myOpen(module: PSym): PPassContext = var c = newContext(module) - if c.p != nil: InternalError(module.info, "sem.myOpen") + if c.p != nil: internalError(module.info, "sem.myOpen") c.semConstExpr = semConstExpr c.semExpr = semExpr c.semTryExpr = tryExpr @@ -329,14 +329,14 @@ proc myProcess(context: PPassContext, n: PNode): PNode = var c = PContext(context) # no need for an expensive 'try' if we stop after the first error anyway: if msgs.gErrorMax <= 1: - result = SemStmtAndGenerateGenerics(c, n) + result = semStmtAndGenerateGenerics(c, n) else: let oldContextLen = msgs.getInfoContextLen() let oldInGenericInst = c.InGenericInst try: - result = SemStmtAndGenerateGenerics(c, n) + result = semStmtAndGenerateGenerics(c, n) except ERecoverableError, ESuggestDone: - RecoverContext(c) + recoverContext(c) c.InGenericInst = oldInGenericInst msgs.setInfoContextLen(oldContextLen) if getCurrentException() of ESuggestDone: result = nil @@ -354,7 +354,7 @@ proc myClose(context: PPassContext, n: PNode): PNode = rawCloseScope(c) # imported symbols; don't check for unused ones! result = newNode(nkStmtList) if n != nil: - InternalError(n.info, "n is not nil") #result := n; + internalError(n.info, "n is not nil") #result := n; addCodeForGenerics(c, result) if c.module.ast != nil: result.add(c.module.ast) diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 8fe81c4c6..38ff0f3be 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -150,16 +150,16 @@ proc resolveOverloads(c: PContext, n, orig: PNode, pickBest(callOp) if overloadsState == csEmpty and result.state == csEmpty: - LocalError(n.info, errUndeclaredIdentifier, considerAcc(f).s) + localError(n.info, errUndeclaredIdentifier, considerAcc(f).s) return elif result.state != csMatch: if nfExprCall in n.flags: - LocalError(n.info, errExprXCannotBeCalled, + localError(n.info, errExprXCannotBeCalled, renderTree(n, {renderNoComments})) else: errors = @[] pickBest(f) - NotFoundError(c, n, errors) + notFoundError(c, n, errors) return if alt.state == csMatch and cmpCandidates(result, alt) == 0 and @@ -225,7 +225,7 @@ proc semResolvedCall(c: PContext, n: PNode, x: TCandidate): PNode = result = x.call result.sons[0] = newSymNode(finalCallee, result.sons[0].info) result.typ = finalCallee.typ.sons[0] - if ContainsGenericType(result.typ): result.typ = errorType(c) + if containsGenericType(result.typ): result.typ = errorType(c) return result = x.call instGenericConvertersSons(c, result, x) @@ -260,7 +260,7 @@ proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode = # number of generic type parameters: if safeLen(s.ast.sons[genericParamsPos]) != n.len-1: let expected = safeLen(s.ast.sons[genericParamsPos]) - LocalError(n.info, errGenerated, "cannot instantiate: " & renderTree(n) & + localError(n.info, errGenerated, "cannot instantiate: " & renderTree(n) & "; got " & $(n.len-1) & " type(s) but expected " & $expected) return n result = explicitGenericSym(c, n, s) diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 1ab38c9ce..15f0f71f0 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -133,7 +133,7 @@ proc pushOwner(owner: PSym) = proc popOwner() = var length = len(gOwners) - if length > 0: setlen(gOwners, length - 1) + if length > 0: setLen(gOwners, length - 1) else: internalError("popOwner") proc lastOptionEntry(c: PContext): POptionEntry = @@ -141,7 +141,7 @@ proc lastOptionEntry(c: PContext): POptionEntry = proc pushProcCon*(c: PContext, owner: PSym) {.inline.} = if owner == nil: - InternalError("owner is nil") + internalError("owner is nil") return var x: PProcCon new(x) @@ -160,7 +160,7 @@ proc newOptionEntry(): POptionEntry = proc newContext(module: PSym): PContext = new(result) - result.AmbiguousSymbols = initIntset() + result.AmbiguousSymbols = initIntSet() initLinkedList(result.optionStack) initLinkedList(result.libs) append(result.optionStack, newOptionEntry()) @@ -178,7 +178,7 @@ proc inclSym(sq: var TSymSeq, s: PSym) = var L = len(sq) for i in countup(0, L - 1): if sq[i].id == s.id: return - setlen(sq, L + 1) + setLen(sq, L + 1) sq[L] = s proc addConverter*(c: PContext, conv: PSym) = @@ -234,7 +234,7 @@ proc fillTypeS(dest: PType, kind: TTypeKind, c: PContext) = dest.owner = getCurrOwner() dest.size = - 1 -proc makeRangeType*(c: PContext; first, last: biggestInt; +proc makeRangeType*(c: PContext; first, last: BiggestInt; info: TLineInfo; intType = getSysType(tyInt)): PType = var n = newNodeI(nkRange, info) addSon(n, newIntTypeNode(nkIntLit, first, intType)) diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index 47d783818..6965b36bc 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -22,7 +22,7 @@ new(destructorIsTrivial) var destructorName = getIdent"destroy_" destructorParam = getIdent"this_" - destructorPragma = newIdentNode(getIdent"destructor", UnknownLineInfo()) + destructorPragma = newIdentNode(getIdent"destructor", unknownLineInfo()) rangeDestructorProc*: PSym proc instantiateDestructor(c: PContext, typ: PType): bool @@ -90,7 +90,7 @@ proc generateDestructor(c: PContext, t: PType): PNode = # Tposix_spawnattr if t.n == nil or t.n.sons == nil: return internalAssert t.n.kind == nkRecList - let destructedObj = newIdentNode(destructorParam, UnknownLineInfo()) + let destructedObj = newIdentNode(destructorParam, unknownLineInfo()) # call the destructods of all fields for s in countup(0, t.n.sons.len - 1): case t.n.sons[s].kind @@ -114,7 +114,7 @@ proc instantiateDestructor(c: PContext, typ: PType): bool = if t.destructor != nil: # XXX: This is not entirely correct for recursive types, but we need # it temporarily to hide the "destroy is already defined" problem - return t.destructor notin [AnalyzingDestructor, DestructorIsTrivial] + return t.destructor notin [analyzingDestructor, destructorIsTrivial] case t.kind of tySequence, tyArray, tyArrayConstr, tyOpenArray, tyVarargs: @@ -126,7 +126,7 @@ proc instantiateDestructor(c: PContext, typ: PType): bool = else: return false of tyTuple, tyObject: - t.destructor = AnalyzingDestructor + t.destructor = analyzingDestructor let generated = generateDestructor(c, t) if generated != nil: internalAssert t.sym != nil @@ -150,7 +150,7 @@ proc instantiateDestructor(c: PContext, typ: PType): bool = internalAssert t.destructor != nil return true else: - t.destructor = DestructorIsTrivial + t.destructor = destructorIsTrivial return false else: return false diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 5f41a8dd9..43091aa74 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -30,7 +30,7 @@ proc semOperand(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # XXX tyGenericInst here? if result.typ.kind == tyVar: result = newDeref(result) else: - LocalError(n.info, errExprXHasNoType, + localError(n.info, errExprXHasNoType, renderTree(result, {renderNoComments})) result.typ = errorType(c) @@ -40,9 +40,9 @@ proc semExprWithType(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # do not produce another redundant error message: #raiseRecoverableError("") result = errorNode(c, n) - if result.typ == nil or result.typ == EnforceVoidContext: + if result.typ == nil or result.typ == enforceVoidContext: # we cannot check for 'void' in macros ... - LocalError(n.info, errExprXHasNoType, + localError(n.info, errExprXHasNoType, renderTree(result, {renderNoComments})) result.typ = errorType(c) else: @@ -57,7 +57,7 @@ proc semExprNoDeref(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # do not produce another redundant error message: result = errorNode(c, n) if result.typ == nil: - LocalError(n.info, errExprXHasNoType, + localError(n.info, errExprXHasNoType, renderTree(result, {renderNoComments})) result.typ = errorType(c) else: @@ -117,7 +117,7 @@ proc semSym(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = elif s.ast != nil: result = semExpr(c, s.ast) else: - InternalError(n.info, "no default for") + internalError(n.info, "no default for") result = emptyNode of skType: markUsed(n, s) @@ -175,7 +175,7 @@ proc isCastable(dst, src: PType): bool = # castableTypeKinds = {tyInt, tyPtr, tyRef, tyCstring, tyString, # tySequence, tyPointer, tyNil, tyOpenArray, # tyProc, tySet, tyEnum, tyBool, tyChar} - var ds, ss: biggestInt + var ds, ss: BiggestInt # this is very unrestrictive; cast is allowed if castDest.size >= src.size ds = computeSize(dst) ss = computeSize(src) @@ -193,7 +193,7 @@ proc isSymChoice(n: PNode): bool {.inline.} = proc semConv(c: PContext, n: PNode): PNode = if sonsLen(n) != 2: - LocalError(n.info, errConvNeedsOneArg) + localError(n.info, errConvNeedsOneArg) return n result = newNodeI(nkConv, n.info) result.typ = semTypeNode(c, n.sons[0], nil).skipTypes({tyGenericInst}) @@ -206,9 +206,9 @@ proc semConv(c: PContext, n: PNode): PNode = case status of convOK: nil of convNotNeedeed: - Message(n.info, hintConvFromXtoItselfNotNeeded, result.typ.typeToString) + message(n.info, hintConvFromXtoItselfNotNeeded, result.typ.typeToString) of convNotLegal: - LocalError(n.info, errGenerated, MsgKindToString(errIllegalConvFromXtoY)% + localError(n.info, errGenerated, msgKindToString(errIllegalConvFromXtoY)% [op.typ.typeToString, result.typ.typeToString]) else: for i in countup(0, sonsLen(op) - 1): @@ -229,14 +229,14 @@ proc semCast(c: PContext, n: PNode): PNode = addSon(result, copyTree(n.sons[0])) addSon(result, semExprWithType(c, n.sons[1])) if not isCastable(result.typ, result.sons[1].Typ): - LocalError(result.info, errExprCannotBeCastedToX, + localError(result.info, errExprCannotBeCastedToX, typeToString(result.Typ)) proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode = const opToStr: array[mLow..mHigh, string] = ["low", "high"] if sonsLen(n) != 2: - LocalError(n.info, errXExpectsTypeOrValue, opToStr[m]) + localError(n.info, errXExpectsTypeOrValue, opToStr[m]) else: n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType}) var typ = skipTypes(n.sons[1].typ, abstractVarRange) @@ -252,12 +252,12 @@ proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode = # leave it for now, it will be resolved in semtypinst n.typ = getSysType(tyInt) else: - LocalError(n.info, errInvalidArgForX, opToStr[m]) + localError(n.info, errInvalidArgForX, opToStr[m]) result = n proc semSizeof(c: PContext, n: PNode): PNode = if sonsLen(n) != 2: - LocalError(n.info, errXExpectsTypeOrValue, "sizeof") + localError(n.info, errXExpectsTypeOrValue, "sizeof") else: n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType}) #restoreOldStyleType(n.sons[1]) @@ -276,9 +276,9 @@ proc semOf(c: PContext, n: PNode): PNode = let y = skipTypes(n.sons[2].typ, abstractPtrs-{tyTypeDesc}) if x.kind == tyTypeDesc or y.kind != tyTypeDesc: - LocalError(n.info, errXExpectsObjectTypes, "of") + localError(n.info, errXExpectsObjectTypes, "of") elif b.kind != tyObject or a.kind != tyObject: - LocalError(n.info, errXExpectsObjectTypes, "of") + localError(n.info, errXExpectsObjectTypes, "of") else: let diff = inheritanceDiff(a, b) # | returns: 0 iff `a` == `b` @@ -287,15 +287,15 @@ proc semOf(c: PContext, n: PNode): PNode = # | returns: `maxint` iff `a` and `b` are not compatible at all if diff <= 0: # optimize to true: - Message(n.info, hintConditionAlwaysTrue, renderTree(n)) + message(n.info, hintConditionAlwaysTrue, renderTree(n)) result = newIntNode(nkIntLit, 1) result.info = n.info result.typ = getSysType(tyBool) return result elif diff == high(int): - LocalError(n.info, errXcanNeverBeOfThisSubtype, typeToString(a)) + localError(n.info, errXcanNeverBeOfThisSubtype, typeToString(a)) else: - LocalError(n.info, errXExpectsTwoArguments, "of") + localError(n.info, errXExpectsTwoArguments, "of") n.typ = getSysType(tyBool) result = n @@ -324,15 +324,15 @@ proc isOpImpl(c: PContext, n: PNode): PNode = case t2.kind of tyTypeClasses: var m: TCandidate - InitCandidate(m, t2) + initCandidate(m, t2) match = matchUserTypeClass(c, m, emptyNode, t2, t1) != nil of tyOrdinal: var m: TCandidate - InitCandidate(m, t2) + initCandidate(m, t2) match = isOrdinalType(t1) of tySequence, tyArray, tySet: var m: TCandidate - InitCandidate(m, t2) + initCandidate(m, t2) match = typeRel(m, t2, t1) != isNone else: match = sameType(t1, t2) @@ -343,7 +343,7 @@ proc isOpImpl(c: PContext, n: PNode): PNode = proc semIs(c: PContext, n: PNode): PNode = if sonsLen(n) != 3: - LocalError(n.info, errXExpectsTwoArguments, "is") + localError(n.info, errXExpectsTwoArguments, "is") result = n n.typ = getSysType(tyBool) @@ -394,7 +394,7 @@ proc changeType(n: PNode, newType: PType, check: bool) = changeType(n.sons[i], elemType(newType), check) of nkPar: if newType.kind != tyTuple: - InternalError(n.info, "changeType: no tuple type for constructor") + internalError(n.info, "changeType: no tuple type for constructor") elif newType.n == nil: nil elif sonsLen(n) > 0 and n.sons[0].kind == nkExprColonExpr: for i in countup(0, sonsLen(n) - 1): @@ -419,7 +419,7 @@ proc changeType(n: PNode, newType: PType, check: bool) = if check: let value = n.intVal if value < firstOrd(newType) or value > lastOrd(newType): - LocalError(n.info, errGenerated, "cannot convert " & $value & + localError(n.info, errGenerated, "cannot convert " & $value & " to " & typeToString(newType)) else: nil n.typ = newType @@ -431,7 +431,7 @@ proc arrayConstrType(c: PContext, n: PNode): PType = rawAddSon(typ, newTypeS(tyEmpty, c)) # needs an empty basetype! else: var x = n.sons[0] - var lastIndex: biggestInt = sonsLen(n) - 1 + var lastIndex: BiggestInt = sonsLen(n) - 1 var t = skipTypes(n.sons[0].typ, {tyGenericInst, tyVar, tyOrdinal}) addSonSkipIntLit(typ, t) typ.sons[0] = makeRangeType(c, 0, sonsLen(n) - 1, n.info) @@ -445,7 +445,7 @@ proc semArrayConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = rawAddSon(result.typ, newTypeS(tyEmpty, c)) # needs an empty basetype! else: var x = n.sons[0] - var lastIndex: biggestInt = 0 + var lastIndex: BiggestInt = 0 var indexType = getSysType(tyInt) if x.kind == nkExprColonExpr and sonsLen(x) == 2: var idx = semConstExpr(c, x.sons[0]) @@ -582,7 +582,7 @@ proc analyseIfAddressTakenInCall(c: PContext, n: PNode) = skipTypes(t.sons[i], abstractInst-{tyTypeDesc}).kind == tyVar: if isAssignable(c, n.sons[i]) notin {arLValue, arLocalLValue}: if n.sons[i].kind != nkHiddenAddr: - LocalError(n.sons[i].info, errVarForOutParamNeeded) + localError(n.sons[i].info, errVarForOutParamNeeded) return for i in countup(1, sonsLen(n) - 1): if n.sons[i].kind == nkHiddenCallConv: @@ -642,7 +642,7 @@ proc evalAtCompileTime(c: PContext, n: PNode): PNode = if sfCompileTime in callee.flags: result = evalStaticExpr(c.module, call, c.p.owner) if result.isNil: - LocalError(n.info, errCannotInterpretNodeX, renderTree(call)) + localError(n.info, errCannotInterpretNodeX, renderTree(call)) else: result = evalConstExpr(c.module, call) if result.isNil: result = n @@ -653,7 +653,7 @@ proc semStaticExpr(c: PContext, n: PNode): PNode = let a = semExpr(c, n.sons[0]) result = evalStaticExpr(c.module, a, c.p.owner) if result.isNil: - LocalError(n.info, errCannotInterpretNodeX, renderTree(n)) + localError(n.info, errCannotInterpretNodeX, renderTree(n)) result = emptyNode proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, @@ -670,14 +670,14 @@ proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, {skProc, skMethod, skConverter, skMacro, skTemplate}) if result != nil: if result.sons[0].kind != nkSym: - InternalError("semOverloadedCallAnalyseEffects") + internalError("semOverloadedCallAnalyseEffects") return let callee = result.sons[0].sym case callee.kind of skMacro, skTemplate: nil else: if (callee.kind == skIterator) and (callee.id == c.p.owner.id): - LocalError(n.info, errRecursiveDependencyX, callee.name.s) + localError(n.info, errRecursiveDependencyX, callee.name.s) if sfNoSideEffect notin callee.flags: if {sfImportc, sfSideEffect} * callee.flags != {}: incl(c.p.owner.flags, sfSideEffect) @@ -711,7 +711,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = if m.state != csMatch: if c.inCompilesContext > 0: # speed up error generation: - GlobalError(n.Info, errTypeMismatch, "") + globalError(n.Info, errTypeMismatch, "") return emptyNode else: var hasErrorType = false @@ -726,7 +726,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = if not hasErrorType: add(msg, ")\n" & msgKindToString(errButExpected) & "\n" & typeToString(n.sons[0].typ)) - LocalError(n.Info, errGenerated, msg) + localError(n.Info, errGenerated, msg) return errorNode(c, n) result = nil else: @@ -801,7 +801,7 @@ proc semEcho(c: PContext, n: PNode): PNode = let t = arg.typ if (t == nil or t.skipTypes(abstractInst).kind != tyString) and arg.kind != nkEmpty: - LocalError(n.info, errGenerated, + localError(n.info, errGenerated, "implicitly invoked '$' does not return string") let t = n.sons[0].typ if tfNoSideEffect notin t.flags: incl(c.p.owner.flags, sfSideEffect) @@ -810,11 +810,11 @@ proc semEcho(c: PContext, n: PNode): PNode = proc buildEchoStmt(c: PContext, n: PNode): PNode = # we MUST not check 'n' for semantics again here! result = newNodeI(nkCall, n.info) - var e = StrTableGet(magicsys.systemModule.Tab, getIdent"echo") + var e = strTableGet(magicsys.systemModule.Tab, getIdent"echo") if e != nil: addSon(result, newSymNode(e)) else: - LocalError(n.info, errSystemNeeds, "echo") + localError(n.info, errSystemNeeds, "echo") addSon(result, errorNode(c, n)) var arg = buildStringify(c, n) # problem is: implicit '$' is not checked for semantics yet. So we give up @@ -844,7 +844,7 @@ proc lookupInRecordAndBuildCheck(c: PContext, n, r: PNode, field: PIdent, if result != nil: return of nkRecCase: checkMinSonsLen(r, 2) - if (r.sons[0].kind != nkSym): IllFormedAst(r) + if (r.sons[0].kind != nkSym): illFormedAst(r) result = lookupInRecordAndBuildCheck(c, n, r.sons[0], field, check) if result != nil: return var s = newNodeI(nkCurly, r.info) @@ -906,7 +906,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = # early exit for this; see tests/compile/tbindoverload.nim: if isSymChoice(n.sons[1]): return - var s = qualifiedLookup(c, n, {checkAmbiguity, checkUndeclared}) + var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) if s != nil: return semSym(c, n, s, flags) @@ -1038,7 +1038,7 @@ proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode = n.sons[i] = semExprWithType(c, n.sons[i], flags*{efInTypeof, efDetermineType}) var indexType = if arr.kind == tyArray: arr.sons[0] else: getSysType(tyInt) - var arg = IndexTypesMatch(c, indexType, n.sons[1].typ, n.sons[1]) + var arg = indexTypesMatch(c, indexType, n.sons[1].typ, n.sons[1]) if arg != nil: n.sons[1] = arg result = n @@ -1060,9 +1060,9 @@ proc semSubscript(c: PContext, n: PNode, flags: TExprFlags): PNode = {tyInt..tyInt64}: var idx = getOrdValue(n.sons[1]) if idx >= 0 and idx < sonsLen(arr): n.typ = arr.sons[int(idx)] - else: LocalError(n.info, errInvalidIndexValueForTuple) + else: localError(n.info, errInvalidIndexValueForTuple) else: - LocalError(n.info, errIndexTypesDoNotMatch) + localError(n.info, errIndexTypesDoNotMatch) result = n else: nil @@ -1098,9 +1098,9 @@ proc takeImplicitAddr(c: PContext, n: PNode): PNode = var valid = isAssignable(c, n) if valid != arLValue: if valid == arLocalLValue: - LocalError(n.info, errXStackEscape, renderTree(n, {renderNoComments})) + localError(n.info, errXStackEscape, renderTree(n, {renderNoComments})) else: - LocalError(n.info, errExprHasNoAddress) + localError(n.info, errExprHasNoAddress) result = newNodeIT(nkHiddenAddr, n.info, makePtrType(c, n.typ)) result.add(n) @@ -1149,7 +1149,7 @@ proc semAsgn(c: PContext, n: PNode): PNode = # a = b # b no 'var T' means: a = addr(b) var le = a.typ if skipTypes(le, {tyGenericInst}).kind != tyVar and - IsAssignable(c, a) == arNone: + isAssignable(c, a) == arNone: # Direct assignment to a discriminant is allowed! localError(a.info, errXCannotBeAssignedTo, renderTree(a, {renderNoComments})) @@ -1161,7 +1161,7 @@ proc semAsgn(c: PContext, n: PNode): PNode = rhs = semExprWithType(c, n.sons[1], if lhsIsResult: {efAllowDestructor} else: {}) if lhsIsResult: - n.typ = EnforceVoidContext + n.typ = enforceVoidContext if lhs.sym.typ.kind == tyGenericParam: if matchTypeClass(lhs.typ, rhs.typ): InternalAssert c.p.resultSym != nil @@ -1192,9 +1192,9 @@ proc semReturn(c: PContext, n: PNode): PNode = if n[0][1].kind == nkSym and n[0][1].sym == c.p.resultSym: n.sons[0] = ast.emptyNode else: - LocalError(n.info, errNoReturnTypeDeclared) + localError(n.info, errNoReturnTypeDeclared) else: - LocalError(n.info, errXNotAllowedHere, "\'return\'") + localError(n.info, errXNotAllowedHere, "\'return\'") proc semProcBody(c: PContext, n: PNode): PNode = openScope(c) @@ -1246,16 +1246,16 @@ proc semYield(c: PContext, n: PNode): PNode = result = n checkSonsLen(n, 1) if c.p.owner == nil or c.p.owner.kind != skIterator: - LocalError(n.info, errYieldNotAllowedHere) + localError(n.info, errYieldNotAllowedHere) elif c.p.inTryStmt > 0 and c.p.owner.typ.callConv != ccInline: - LocalError(n.info, errYieldNotAllowedInTryStmt) + localError(n.info, errYieldNotAllowedInTryStmt) elif n.sons[0].kind != nkEmpty: - n.sons[0] = SemExprWithType(c, n.sons[0]) # check for type compatibility: + n.sons[0] = semExprWithType(c, n.sons[0]) # check for type compatibility: var restype = c.p.owner.typ.sons[0] if restype != nil: n.sons[0] = fitNode(c, restype, n.sons[0]) - if n.sons[0].typ == nil: InternalError(n.info, "semYield") - SemYieldVarResult(c, n, restype) + if n.sons[0].typ == nil: internalError(n.info, "semYield") + semYieldVarResult(c, n, restype) else: localError(n.info, errCannotReturnExpr) elif c.p.owner.typ.sons[0] != nil: @@ -1270,12 +1270,12 @@ proc lookUpForDefined(c: PContext, i: PIdent, onlyCurrentScope: bool): PSym = proc lookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym = case n.kind of nkIdent: - result = lookupForDefined(c, n.ident, onlyCurrentScope) + result = lookUpForDefined(c, n.ident, onlyCurrentScope) of nkDotExpr: result = nil if onlyCurrentScope: return checkSonsLen(n, 2) - var m = lookupForDefined(c, n.sons[0], onlyCurrentScope) + var m = lookUpForDefined(c, n.sons[0], onlyCurrentScope) if (m != nil) and (m.kind == skModule): if (n.sons[1].kind == nkIdent): var ident = n.sons[1].ident @@ -1286,7 +1286,7 @@ proc lookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym = else: localError(n.sons[1].info, errIdentifierExpected, "") of nkAccQuoted: - result = lookupForDefined(c, considerAcc(n), onlyCurrentScope) + result = lookUpForDefined(c, considerAcc(n), onlyCurrentScope) of nkSym: result = n.sym else: @@ -1297,7 +1297,7 @@ proc semDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PNode = checkSonsLen(n, 2) # we replace this node by a 'true' or 'false' node: result = newIntNode(nkIntLit, 0) - if LookUpForDefined(c, n.sons[1], onlyCurrentScope) != nil: + if lookUpForDefined(c, n.sons[1], onlyCurrentScope) != nil: result.intVal = 1 elif not onlyCurrentScope and (n.sons[1].kind == nkIdent) and condsyms.isDefined(n.sons[1].ident): @@ -1314,18 +1314,18 @@ proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym = ## The argument to the proc should be nkCall(...) or similar ## Returns the macro/template symbol if isCallExpr(n): - var expandedSym = qualifiedLookup(c, n[0], {checkUndeclared}) + var expandedSym = qualifiedLookUp(c, n[0], {checkUndeclared}) if expandedSym == nil: - LocalError(n.info, errUndeclaredIdentifier, n[0].renderTree) + localError(n.info, errUndeclaredIdentifier, n[0].renderTree) return errorSym(c, n[0]) if expandedSym.kind notin {skMacro, skTemplate}: - LocalError(n.info, errXisNoMacroOrTemplate, expandedSym.name.s) + localError(n.info, errXisNoMacroOrTemplate, expandedSym.name.s) return errorSym(c, n[0]) result = expandedSym else: - LocalError(n.info, errXisNoMacroOrTemplate, n.renderTree) + localError(n.info, errXisNoMacroOrTemplate, n.renderTree) result = errorSym(c, n) proc expectString(c: PContext, n: PNode): string = @@ -1333,10 +1333,10 @@ proc expectString(c: PContext, n: PNode): string = if n.kind in nkStrKinds: return n.strVal else: - LocalError(n.info, errStringLiteralExpected) + localError(n.info, errStringLiteralExpected) proc getMagicSym(magic: TMagic): PSym = - result = newSym(skProc, getIdent($magic), GetCurrOwner(), gCodegenLineInfo) + result = newSym(skProc, getIdent($magic), getCurrOwner(), gCodegenLineInfo) result.magic = magic proc newAnonSym(kind: TSymKind, info: TLineInfo, @@ -1358,7 +1358,7 @@ proc semUsing(c: PContext, n: PNode): PNode = continue else: nil - LocalError(e.info, errUsingNoSymbol, e.renderTree) + localError(e.info, errUsingNoSymbol, e.renderTree) proc semExpandToAst(c: PContext, n: PNode): PNode = var macroCall = n[1] @@ -1422,7 +1422,7 @@ proc semQuoteAst(c: PContext, n: PNode): PNode = # this will store the generated param names if doBlk.kind != nkDo: - LocalError(n.info, errXExpected, "block") + localError(n.info, errXExpected, "block") processQuotations(doBlk.sons[bodyPos], op, quotes, ids) @@ -1476,7 +1476,7 @@ proc tryExpr(c: PContext, n: PNode, c.InGenericInst = oldInGenericInst c.p = oldProcCon msgs.setInfoContextLen(oldContextLen) - setlen(gOwners, oldOwnerLen) + setLen(gOwners, oldOwnerLen) c.currentScope = oldScope dec c.InCompilesContext errorOutputs = oldErrorOutputs @@ -1556,7 +1556,7 @@ proc semWhen(c: PContext, n: PNode, semCheck = true): PNode = # The ``when`` statement implements the mechanism for platform dependent # code. Thus we try to ensure here consistent ID allocation after the # ``when`` statement. - IDsynchronizationPoint(200) + idSynchronizationPoint(200) proc semSetConstr(c: PContext, n: PNode): PNode = result = newNodeI(nkCurly, n.info) @@ -1585,7 +1585,7 @@ proc semSetConstr(c: PContext, n: PNode): PNode = if typ == nil: typ = skipTypes(n.sons[i].typ, {tyGenericInst, tyVar, tyOrdinal}) if not isOrdinalType(typ): - LocalError(n.info, errOrdinalTypeExpected) + localError(n.info, errOrdinalTypeExpected) typ = makeRangeType(c, 0, MaxSetElements - 1, n.info) elif lengthOrd(typ) > MaxSetElements: typ = makeRangeType(c, 0, MaxSetElements - 1, n.info) @@ -1642,11 +1642,11 @@ proc checkPar(n: PNode): TParKind = if result == paTupleFields: if (n.sons[i].kind != nkExprColonExpr) or not (n.sons[i].sons[0].kind in {nkSym, nkIdent}): - LocalError(n.sons[i].info, errNamedExprExpected) + localError(n.sons[i].info, errNamedExprExpected) return paNone else: if n.sons[i].kind == nkExprColonExpr: - LocalError(n.sons[i].info, errNamedExprNotAllowed) + localError(n.sons[i].info, errNamedExprNotAllowed) return paNone proc semTupleFieldsConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = @@ -1661,7 +1661,7 @@ proc semTupleFieldsConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = var id: PIdent if n.sons[i].sons[0].kind == nkIdent: id = n.sons[i].sons[0].ident else: id = n.sons[i].sons[0].sym.name - if ContainsOrIncl(ids, id.id): + if containsOrIncl(ids, id.id): localError(n.sons[i].info, errFieldInitTwice, id.s) n.sons[i].sons[1] = semExprWithType(c, n.sons[i].sons[1], flags*{efAllowDestructor}) @@ -1688,7 +1688,7 @@ proc checkInitialized(n: PNode, ids: TIntSet, info: TLineInfo) = for i in countup(0, sonsLen(n) - 1): checkInitialized(n.sons[i], ids, info) of nkRecCase: - if (n.sons[0].kind != nkSym): InternalError(info, "checkInitialized") + if (n.sons[0].kind != nkSym): internalError(info, "checkInitialized") checkInitialized(n.sons[0], ids, info) when false: # XXX we cannot check here, as we don't know the branch! @@ -1698,7 +1698,7 @@ proc checkInitialized(n: PNode, ids: TIntSet, info: TLineInfo) = else: internalError(info, "checkInitialized") of nkSym: if tfNeedsInit in n.sym.typ.flags and n.sym.name.id notin ids: - Message(info, errGenerated, "field not initialized: " & n.sym.name.s) + message(info, errGenerated, "field not initialized: " & n.sym.name.s) else: internalError(info, "checkInitialized") proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = @@ -1721,7 +1721,7 @@ proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = var id: PIdent if it.sons[0].kind == nkIdent: id = it.sons[0].ident else: id = it.sons[0].sym.name - if ContainsOrIncl(ids, id.id): + if containsOrIncl(ids, id.id): localError(it.info, errFieldInitTwice, id.s) var e = semExprWithType(c, it.sons[1], flags*{efAllowDestructor}) var @@ -1754,7 +1754,7 @@ proc semObjConstr(c: PContext, n: PNode, flags: TExprFlags): PNode = proc semBlock(c: PContext, n: PNode): PNode = result = n - Inc(c.p.nestedBlockCounter) + inc(c.p.nestedBlockCounter) checkSonsLen(n, 2) openScope(c) # BUGFIX: label is in the scope of block! if n.sons[0].kind != nkEmpty: @@ -1768,7 +1768,7 @@ proc semBlock(c: PContext, n: PNode): PNode = if isEmptyType(n.typ): n.kind = nkBlockStmt else: n.kind = nkBlockExpr closeScope(c) - Dec(c.p.nestedBlockCounter) + dec(c.p.nestedBlockCounter) proc buildCall(n: PNode): PNode = if n.kind == nkDotExpr and n.len == 2: @@ -1834,7 +1834,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = if result.kind == nkSym: markIndirect(c, result.sym) if isGenericRoutine(result.sym): - LocalError(n.info, errInstantiateXExplicitely, s.name.s) + localError(n.info, errInstantiateXExplicitely, s.name.s) of nkSym: # because of the changed symbol binding, this does not mean that we # don't have to check the symbol for semantics here again! @@ -1881,7 +1881,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result.kind = nkCall result = semExpr(c, result, flags) of nkBind: - Message(n.info, warnDeprecated, "bind") + message(n.info, warnDeprecated, "bind") result = semExpr(c, n.sons[0], flags) of nkTypeOfExpr, nkTupleTy, nkRefTy..nkEnumTy: var typ = semTypeNode(c, n, nil).skipTypes({tyTypeDesc}) @@ -1891,7 +1891,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = # check if it is an expression macro: checkMinSonsLen(n, 1) let mode = if nfDelegate in n.flags: {} else: {checkUndeclared} - var s = qualifiedLookup(c, n.sons[0], mode) + var s = qualifiedLookUp(c, n.sons[0], mode) if s != nil: case s.kind of skMacro: @@ -1912,8 +1912,8 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semConv(c, n) elif n.len == 1: result = semObjConstr(c, n, flags) - elif Contains(c.AmbiguousSymbols, s.id): - LocalError(n.info, errUseQualifier, s.name.s) + elif contains(c.AmbiguousSymbols, s.id): + localError(n.info, errUseQualifier, s.name.s) elif s.magic == mNone: result = semDirectOp(c, n, flags) else: result = semMagic(c, n, s, flags) of skProc, skMethod, skConverter, skIterator: @@ -1937,7 +1937,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semExpr(c, result, flags) of nkBracketExpr: checkMinSonsLen(n, 1) - var s = qualifiedLookup(c, n.sons[0], {checkUndeclared}) + var s = qualifiedLookUp(c, n.sons[0], {checkUndeclared}) if s != nil and s.kind in {skProc, skMethod, skConverter, skIterator}: # type parameters: partial generic specialization n.sons[0] = semSymGenericInstantiation(c, n.sons[0], s) @@ -1965,7 +1965,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = checkSonsLen(n, 1) n.sons[0] = semExprWithType(c, n.sons[0]) if isAssignable(c, n.sons[0]) notin {arLValue, arLocalLValue}: - LocalError(n.info, errExprHasNoAddress) + localError(n.info, errExprHasNoAddress) n.typ = makePtrType(c, n.sons[0].typ) of nkHiddenAddr, nkHiddenDeref: checkSonsLen(n, 1) @@ -1994,7 +1994,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = of nkVarSection: result = semVarOrLet(c, n, skVar) of nkLetSection: result = semVarOrLet(c, n, skLet) of nkConstSection: result = semConst(c, n) - of nkTypeSection: result = SemTypeSection(c, n) + of nkTypeSection: result = semTypeSection(c, n) of nkDiscardStmt: result = semDiscard(c, n) of nkWhileStmt: result = semWhile(c, n) of nkTryStmt: result = semTry(c, n) @@ -2013,25 +2013,25 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = of nkMacroDef: result = semMacroDef(c, n) of nkTemplateDef: result = semTemplateDef(c, n) of nkImportStmt: - if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "import") + if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import") result = evalImport(c, n) of nkImportExceptStmt: - if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "import") + if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "import") result = evalImportExcept(c, n) of nkFromStmt: - if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "from") + if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "from") result = evalFrom(c, n) of nkIncludeStmt: - if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "include") + if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "include") result = evalInclude(c, n) of nkExportStmt, nkExportExceptStmt: - if not isTopLevel(c): LocalError(n.info, errXOnlyAtModuleScope, "export") + if not isTopLevel(c): localError(n.info, errXOnlyAtModuleScope, "export") result = semExport(c, n) of nkPragmaBlock: result = semPragmaBlock(c, n) of nkStaticStmt: result = semStaticStmt(c, n) else: - LocalError(n.info, errInvalidExpressionX, + localError(n.info, errInvalidExpressionX, renderTree(n, {renderNoComments})) if result != nil: incl(result.flags, nfSem) diff --git a/compiler/semfold.nim b/compiler/semfold.nim index fb1816f9c..731085c3a 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -66,14 +66,14 @@ proc ordinalValToString*(a: PNode): string = of tyEnum: var n = t.n for i in countup(0, sonsLen(n) - 1): - if n.sons[i].kind != nkSym: InternalError(a.info, "ordinalValToString") + if n.sons[i].kind != nkSym: internalError(a.info, "ordinalValToString") var field = n.sons[i].sym if field.position == x: if field.ast == nil: return field.name.s else: return field.ast.strVal - InternalError(a.info, "no symbol for ordinal value: " & $x) + internalError(a.info, "no symbol for ordinal value: " & $x) else: result = $x @@ -92,7 +92,7 @@ proc pickIntRange(a, b: PType): PType = proc isIntRangeOrLit(t: PType): bool = result = isIntRange(t) or isIntLit(t) -proc pickMinInt(n: PNode): biggestInt = +proc pickMinInt(n: PNode): BiggestInt = if n.kind in {nkIntLit..nkUInt64Lit}: result = n.intVal elif isIntLit(n.typ): @@ -100,9 +100,9 @@ proc pickMinInt(n: PNode): biggestInt = elif isIntRange(n.typ): result = firstOrd(n.typ) else: - InternalError(n.info, "pickMinInt") + internalError(n.info, "pickMinInt") -proc pickMaxInt(n: PNode): biggestInt = +proc pickMaxInt(n: PNode): BiggestInt = if n.kind in {nkIntLit..nkUInt64Lit}: result = n.intVal elif isIntLit(n.typ): @@ -110,9 +110,9 @@ proc pickMaxInt(n: PNode): biggestInt = elif isIntRange(n.typ): result = lastOrd(n.typ) else: - InternalError(n.info, "pickMaxInt") + internalError(n.info, "pickMaxInt") -proc makeRange(typ: PType, first, last: biggestInt): PType = +proc makeRange(typ: PType, first, last: BiggestInt): PType = var n = newNode(nkRange) addSon(n, newIntNode(nkIntLit, min(first, last))) addSon(n, newIntNode(nkIntLit, max(first, last))) @@ -120,7 +120,7 @@ proc makeRange(typ: PType, first, last: biggestInt): PType = result.n = n addSonSkipIntLit(result, skipTypes(typ, {tyRange})) -proc makeRangeF(typ: PType, first, last: biggestFloat): PType = +proc makeRangeF(typ: PType, first, last: BiggestFloat): PType = var n = newNode(nkRange) addSon(n, newFloatNode(nkFloatLit, min(first.float, last.float))) addSon(n, newFloatNode(nkFloatLit, max(first.float, last.float))) @@ -303,7 +303,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of tyInt32: result = newIntNodeT(int32(getInt(a)) shl int32(getInt(b)), n) of tyInt64, tyInt, tyUInt..tyUInt64: result = newIntNodeT(`shl`(getInt(a), getInt(b)), n) - else: InternalError(n.info, "constant folding for shl") + else: internalError(n.info, "constant folding for shl") of mShrI, mShrI64: case skipTypes(n.typ, abstractRange).kind of tyInt8: result = newIntNodeT(int8(getInt(a)) shr int8(getInt(b)), n) @@ -311,7 +311,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of tyInt32: result = newIntNodeT(int32(getInt(a)) shr int32(getInt(b)), n) of tyInt64, tyInt, tyUInt..tyUInt64: result = newIntNodeT(`shr`(getInt(a), getInt(b)), n) - else: InternalError(n.info, "constant folding for shr") + else: internalError(n.info, "constant folding for shr") of mDivI, mDivI64: result = newIntNodeT(getInt(a) div getInt(b), n) of mModI, mModI64: result = newIntNodeT(getInt(a) mod getInt(b), n) of mAddF64: result = newFloatNodeT(getFloat(a) + getFloat(b), n) @@ -354,10 +354,10 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of mMulU: result = newIntNodeT(`*%`(getInt(a), getInt(b)), n) of mModU: result = newIntNodeT(`%%`(getInt(a), getInt(b)), n) of mDivU: result = newIntNodeT(`/%`(getInt(a), getInt(b)), n) - of mLeSet: result = newIntNodeT(Ord(containsSets(a, b)), n) - of mEqSet: result = newIntNodeT(Ord(equalSets(a, b)), n) + of mLeSet: result = newIntNodeT(ord(containsSets(a, b)), n) + of mEqSet: result = newIntNodeT(ord(equalSets(a, b)), n) of mLtSet: - result = newIntNodeT(Ord(containsSets(a, b) and not equalSets(a, b)), n) + result = newIntNodeT(ord(containsSets(a, b) and not equalSets(a, b)), n) of mMulSet: result = nimsets.intersectSets(a, b) result.info = n.info @@ -371,7 +371,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = result = nimsets.symdiffSets(a, b) result.info = n.info of mConStrStr: result = newStrNodeT(getStrOrChar(a) & getStrOrChar(b), n) - of mInSet: result = newIntNodeT(Ord(inSet(a, b)), n) + of mInSet: result = newIntNodeT(ord(inSet(a, b)), n) of mRepr: # BUGFIX: we cannot eval mRepr here for reasons that I forgot. of mIntToStr, mInt64ToStr: result = newStrNodeT($(getOrdValue(a)), n) @@ -390,9 +390,9 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = result = copyTree(a) result.typ = n.typ of mCompileOption: - result = newIntNodeT(Ord(commands.testCompileOption(a.getStr, n.info)), n) + result = newIntNodeT(ord(commands.testCompileOption(a.getStr, n.info)), n) of mCompileOptionArg: - result = newIntNodeT(Ord( + result = newIntNodeT(ord( testCompileOptionArg(getStr(a), getStr(b), n.info)), n) of mNewString, mNewStringOfCap, mExit, mInc, ast.mDec, mEcho, mSwap, mAppendStrCh, @@ -402,7 +402,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = discard of mRand: result = newIntNodeT(math.random(a.getInt.int), n) - else: InternalError(a.info, "evalOp(" & $m & ')') + else: internalError(a.info, "evalOp(" & $m & ')') proc getConstIfExpr(c: PSym, n: PNode): PNode = result = nil @@ -452,13 +452,13 @@ proc leValueConv(a, b: PNode): bool = case b.kind of nkCharLit..nkUInt64Lit: result = a.intVal <= b.intVal of nkFloatLit..nkFloat128Lit: result = a.intVal <= round(b.floatVal) - else: InternalError(a.info, "leValueConv") + else: internalError(a.info, "leValueConv") of nkFloatLit..nkFloat128Lit: case b.kind of nkFloatLit..nkFloat128Lit: result = a.floatVal <= b.floatVal of nkCharLit..nkUInt64Lit: result = a.floatVal <= toFloat(int(b.intVal)) - else: InternalError(a.info, "leValueConv") - else: InternalError(a.info, "leValueConv") + else: internalError(a.info, "leValueConv") + else: internalError(a.info, "leValueConv") proc magicCall(m: PSym, n: PNode): PNode = if sonsLen(n) <= 1: return @@ -485,9 +485,9 @@ proc getAppType(n: PNode): PNode = else: result = newStrNodeT("console", n) -proc rangeCheck(n: PNode, value: biggestInt) = +proc rangeCheck(n: PNode, value: BiggestInt) = if value < firstOrd(n.typ) or value > lastOrd(n.typ): - LocalError(n.info, errGenerated, "cannot convert " & $value & + localError(n.info, errGenerated, "cannot convert " & $value & " to " & typeToString(n.typ)) proc foldConv*(n, a: PNode; check = false): PNode = @@ -536,10 +536,10 @@ proc foldArrayAccess(m: PSym, n: PNode): PNode = result = x.sons[int(idx)] if result.kind == nkExprColonExpr: result = result.sons[1] else: - LocalError(n.info, errIndexOutOfBounds) + localError(n.info, errIndexOutOfBounds) of nkBracket, nkMetaNode: if (idx >= 0) and (idx < sonsLen(x)): result = x.sons[int(idx)] - else: LocalError(n.info, errIndexOutOfBounds) + else: localError(n.info, errIndexOutOfBounds) of nkStrLit..nkTripleStrLit: result = newNodeIT(nkCharLit, x.info, n.typ) if (idx >= 0) and (idx < len(x.strVal)): @@ -547,7 +547,7 @@ proc foldArrayAccess(m: PSym, n: PNode): PNode = elif idx == len(x.strVal): nil else: - LocalError(n.info, errIndexOutOfBounds) + localError(n.info, errIndexOutOfBounds) else: discard proc foldFieldAccess(m: PSym, n: PNode): PNode = @@ -634,7 +634,7 @@ proc getConstExpr(m: PSym, n: PNode): PNode = of mSizeOf: var a = n.sons[1] if computeSize(a.typ) < 0: - LocalError(a.info, errCannotEvalXBecauseIncompletelyDefined, + localError(a.info, errCannotEvalXBecauseIncompletelyDefined, "sizeof") result = nil elif skipTypes(a.typ, typedescInst).kind in @@ -677,9 +677,9 @@ proc getConstExpr(m: PSym, n: PNode): PNode = else: result = magicCall(m, n) except EOverflow: - LocalError(n.info, errOverOrUnderflow) + localError(n.info, errOverOrUnderflow) except EDivByZero: - LocalError(n.info, errConstantDivisionByZero) + localError(n.info, errConstantDivisionByZero) of nkAddr: var a = getConstExpr(m, n.sons[0]) if a != nil: @@ -735,7 +735,7 @@ proc getConstExpr(m: PSym, n: PNode): PNode = result = a # a <= x and x <= b result.typ = n.typ else: - LocalError(n.info, errGenerated, `%`( + localError(n.info, errGenerated, `%`( msgKindToString(errIllegalConvFromXtoY), [typeToString(n.sons[0].typ), typeToString(n.typ)])) of nkStringToCString, nkCStringToString: diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index 760fd303f..9f477492c 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -96,10 +96,10 @@ proc semGenericStmt(c: PContext, n: PNode, if gCmd == cmdIdeTools: suggestStmt(c, n) case n.kind of nkIdent, nkAccQuoted: - result = Lookup(c, n, flags, ctx) + result = lookup(c, n, flags, ctx) of nkDotExpr: let luf = if withinMixin notin flags: {checkUndeclared} else: {} - var s = QualifiedLookUp(c, n, luf) + var s = qualifiedLookUp(c, n, luf) if s != nil: result = semGenericStmtSymbol(c, n, s) # XXX for example: ``result.add`` -- ``add`` needs to be looked up here... of nkEmpty, nkSym..nkNilLit: @@ -119,7 +119,7 @@ proc semGenericStmt(c: PContext, n: PNode, # check if it is an expression macro: checkMinSonsLen(n, 1) let fn = n.sons[0] - var s = qualifiedLookup(c, fn, {}) + var s = qualifiedLookUp(c, fn, {}) if s == nil and withinMixin notin flags and fn.kind in {nkIdent, nkAccQuoted} and considerAcc(fn).id notin ctx: localError(n.info, errUndeclaredIdentifier, fn.renderTree) @@ -219,7 +219,7 @@ proc semGenericStmt(c: PContext, n: PNode, for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if (a.kind != nkIdentDefs) and (a.kind != nkVarTuple): IllFormedAst(a) + if (a.kind != nkIdentDefs) and (a.kind != nkVarTuple): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, @@ -230,7 +230,7 @@ proc semGenericStmt(c: PContext, n: PNode, of nkGenericParams: for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if (a.kind != nkIdentDefs): IllFormedAst(a) + if (a.kind != nkIdentDefs): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, @@ -242,7 +242,7 @@ proc semGenericStmt(c: PContext, n: PNode, for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if (a.kind != nkConstDef): IllFormedAst(a) + if (a.kind != nkConstDef): illFormedAst(a) checkSonsLen(a, 3) addPrelimDecl(c, newSymS(skUnknown, getIdentNode(a.sons[0]), c)) a.sons[1] = semGenericStmt(c, a.sons[1], flags+{withinTypeDesc}, ctx) @@ -251,13 +251,13 @@ proc semGenericStmt(c: PContext, n: PNode, for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if (a.kind != nkTypeDef): IllFormedAst(a) + if (a.kind != nkTypeDef): illFormedAst(a) checkSonsLen(a, 3) addPrelimDecl(c, newSymS(skUnknown, getIdentNode(a.sons[0]), c)) for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if (a.kind != nkTypeDef): IllFormedAst(a) + if (a.kind != nkTypeDef): illFormedAst(a) checkSonsLen(a, 3) if a.sons[1].kind != nkEmpty: openScope(c) @@ -285,7 +285,7 @@ proc semGenericStmt(c: PContext, n: PNode, n.sons[0] = semGenericStmt(c, n.sons[0], flags+{withinTypeDesc}, ctx) for i in countup(1, sonsLen(n) - 1): var a = n.sons[i] - if (a.kind != nkIdentDefs): IllFormedAst(a) + if (a.kind != nkIdentDefs): illFormedAst(a) checkMinSonsLen(a, 3) var L = sonsLen(a) a.sons[L-2] = semGenericStmt(c, a.sons[L-2], flags+{withinTypeDesc}, diff --git a/compiler/seminst.nim b/compiler/seminst.nim index 5a4b83240..b03f20259 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -13,28 +13,28 @@ proc instantiateGenericParamList(c: PContext, n: PNode, pt: TIdTable, entry: var TInstantiation) = if n.kind != nkGenericParams: - InternalError(n.info, "instantiateGenericParamList; no generic params") + internalError(n.info, "instantiateGenericParamList; no generic params") newSeq(entry.concreteTypes, n.len) for i in countup(0, n.len - 1): var a = n.sons[i] if a.kind != nkSym: - InternalError(a.info, "instantiateGenericParamList; no symbol") + internalError(a.info, "instantiateGenericParamList; no symbol") var q = a.sym if q.typ.kind notin {tyTypeDesc, tyGenericParam, tyExpr}+tyTypeClasses: continue var s = newSym(skType, q.name, getCurrOwner(), q.info) s.flags = s.flags + {sfUsed, sfFromGeneric} - var t = PType(IdTableGet(pt, q.typ)) + var t = PType(idTableGet(pt, q.typ)) if t == nil: if tfRetType in q.typ.flags: # keep the generic type and allow the return type to be bound # later by semAsgn in return type inference scenario t = q.typ else: - LocalError(a.info, errCannotInstantiateX, s.name.s) + localError(a.info, errCannotInstantiateX, s.name.s) t = errorType(c) elif t.kind == tyGenericParam: - InternalError(a.info, "instantiateGenericParamList: " & q.name.s) + internalError(a.info, "instantiateGenericParamList: " & q.name.s) elif t.kind == tyGenericInvokation: #t = instGenericContainer(c, a, t) t = generateTypeInstance(c, pt, a, t) @@ -50,7 +50,7 @@ proc sameInstantiation(a, b: TInstantiation): bool = flags = {TypeDescExactMatch}): return result = true -proc genericCacheGet(genericSym: Psym, entry: TInstantiation): PSym = +proc genericCacheGet(genericSym: PSym, entry: TInstantiation): PSym = if genericSym.procInstCache != nil: for inst in genericSym.procInstCache: if sameInstantiation(entry, inst[]): @@ -75,11 +75,11 @@ proc removeDefaultParamValues(n: PNode) = proc freshGenSyms(n: PNode, owner: PSym, symMap: var TIdTable) = # we need to create a fresh set of gensym'ed symbols: if n.kind == nkSym and sfGenSym in n.sym.flags: - var x = PSym(IdTableGet(symMap, n.sym)) + var x = PSym(idTableGet(symMap, n.sym)) if x == nil: x = copySym(n.sym, false) x.owner = owner - IdTablePut(symMap, n.sym, x) + idTablePut(symMap, n.sym, x) n.sym = x else: for i in 0 .. 1000: InternalError(fn.ast.info, "nesting too deep") + if c.InstCounter > 1000: internalError(fn.ast.info, "nesting too deep") inc(c.InstCounter) # careful! we copy the whole AST including the possibly nil body! var n = copyTree(fn.ast) @@ -282,7 +282,7 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, pushOwner(result) openScope(c) if n.sons[genericParamsPos].kind == nkEmpty: - InternalError(n.info, "generateInstance") + internalError(n.info, "generateInstance") n.sons[namePos] = newSymNode(result) pushInfoContext(info) var entry = TInstantiation.new @@ -301,7 +301,7 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, if fn.kind != skTemplate: instantiateBody(c, n, result) sideEffectsCheck(c, result) - ParamsTypeCheck(c, result.typ) + paramsTypeCheck(c, result.typ) else: result = oldPrc popInfoContext() diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim index aab4c82f5..e6c5fc574 100644 --- a/compiler/semmagic.nim +++ b/compiler/semmagic.nim @@ -18,7 +18,7 @@ proc expectIntLit(c: PContext, n: PNode): int = let x = c.semConstExpr(c, n) case x.kind of nkIntLit..nkInt64Lit: result = int(x.intVal) - else: LocalError(n.info, errIntLiteralExpected) + else: localError(n.info, errIntLiteralExpected) proc semInstantiationInfo(c: PContext, n: PNode): PNode = result = newNodeIT(nkPar, n.info, n.typ) @@ -28,7 +28,7 @@ proc semInstantiationInfo(c: PContext, n: PNode): PNode = var filename = newNodeIT(nkStrLit, n.info, getSysType(tyString)) filename.strVal = if useFullPaths != 0: info.toFullPath else: info.ToFilename var line = newNodeIT(nkIntLit, n.info, getSysType(tyInt)) - line.intVal = ToLinenumber(info) + line.intVal = toLinenumber(info) result.add(filename) result.add(line) @@ -54,7 +54,7 @@ proc semTypeTraits(c: PContext, n: PNode): PNode = if t.kind == tyTypeDesc and t.len == 0: result = n elif not containsGenericType(t): - result = evalTypeTrait(n[0], t, GetCurrOwner()) + result = evalTypeTrait(n[0], t, getCurrOwner()) else: # a typedesc variable, pass unmodified to evals result = n @@ -70,23 +70,23 @@ proc semBindSym(c: PContext, n: PNode): PNode = let sl = semConstExpr(c, n.sons[1]) if sl.kind notin {nkStrLit, nkRStrLit, nkTripleStrLit}: - LocalError(n.sons[1].info, errStringLiteralExpected) + localError(n.sons[1].info, errStringLiteralExpected) return errorNode(c, n) let isMixin = semConstExpr(c, n.sons[2]) if isMixin.kind != nkIntLit or isMixin.intVal < 0 or isMixin.intVal > high(TSymChoiceRule).int: - LocalError(n.sons[2].info, errConstExprExpected) + localError(n.sons[2].info, errConstExprExpected) return errorNode(c, n) let id = newIdentNode(getIdent(sl.strVal), n.info) - let s = QualifiedLookUp(c, id) + let s = qualifiedLookUp(c, id) if s != nil: # we need to mark all symbols: var sc = symChoice(c, id, s, TSymChoiceRule(isMixin.intVal)) result.add(sc) else: - LocalError(n.sons[1].info, errUndeclaredIdentifier, sl.strVal) + localError(n.sons[1].info, errUndeclaredIdentifier, sl.strVal) proc semLocals(c: PContext, n: PNode): PNode = var counter = 0 diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 7dec557be..efab8ddb6 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -95,12 +95,12 @@ proc useVar(a: PEffects, n: PNode) = if s.id notin a.init: if {tfNeedsInit, tfNotNil} * s.typ.flags != {}: when true: - Message(n.info, warnProveInit, s.name.s) + message(n.info, warnProveInit, s.name.s) else: Message(n.info, errGenerated, "'$1' might not have been initialized" % s.name.s) else: - Message(n.info, warnUninit, s.name.s) + message(n.info, warnUninit, s.name.s) # prevent superfluous warnings about the same variable: a.init.add s.id @@ -162,8 +162,8 @@ proc mergeTags(a: PEffects, b, comesFrom: PNode) = for effect in items(b): addTag(a, effect, useLineInfo=comesFrom != nil) proc listEffects(a: PEffects) = - for e in items(a.exc): Message(e.info, hintUser, typeToString(e.typ)) - for e in items(a.tags): Message(e.info, hintUser, typeToString(e.typ)) + for e in items(a.exc): message(e.info, hintUser, typeToString(e.typ)) + for e in items(a.tags): message(e.info, hintUser, typeToString(e.typ)) proc catches(tracked: PEffects, e: PType) = let e = skipTypes(e, skipPtrs) @@ -310,10 +310,10 @@ proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) = return case impliesNotNil(tracked.guards, n) of impUnknown: - Message(n.info, errGenerated, + message(n.info, errGenerated, "cannot prove '$1' is not nil" % n.renderTree) of impNo: - Message(n.info, errGenerated, "'$1' is provably nil" % n.renderTree) + message(n.info, errGenerated, "'$1' is provably nil" % n.renderTree) of impYes: discard proc trackOperand(tracked: PEffects, n: PNode, paramType: PType) = @@ -549,7 +549,7 @@ proc checkRaisesSpec(spec, real: PNode, msg: string, hints: bool) = if hints: for s in 0 .. 3: - Message(a.info, warnEachIdentIsTuple) + message(a.info, warnEachIdentIsTuple) for j in countup(0, length-3): var v = semIdentDef(c, a.sons[j], symkind) if sfGenSym notin v.flags: addInterfaceDecl(c, v) @@ -383,12 +383,12 @@ proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode = # a shadowed variable is an error unless it appears on the right # side of the '=': if warnShadowIdent in gNotes and not identWithin(def, v.name): - Message(a.info, warnShadowIdent, v.name.s) + message(a.info, warnShadowIdent, v.name.s) if a.kind != nkVarTuple: if def != nil and def.kind != nkEmpty: # this is needed for the evaluation pass and for the guard checking: v.ast = def - if sfThread in v.flags: LocalError(def.info, errThreadvarCannotInit) + if sfThread in v.flags: localError(def.info, errThreadvarCannotInit) v.typ = typ b = newNodeI(nkIdentDefs, a.info) if importantComments(): @@ -410,7 +410,7 @@ proc semConst(c: PContext, n: PNode): PNode = var a = n.sons[i] if gCmd == cmdIdeTools: suggestStmt(c, a) if a.kind == nkCommentStmt: continue - if (a.kind != nkConstDef): IllFormedAst(a) + if (a.kind != nkConstDef): illFormedAst(a) checkSonsLen(a, 3) var v = semIdentDef(c, a.sons[0], skConst) var typ: PType = nil @@ -418,7 +418,7 @@ proc semConst(c: PContext, n: PNode): PNode = var def = semConstExpr(c, a.sons[2]) if def == nil: - LocalError(a.sons[2].info, errConstExprExpected) + localError(a.sons[2].info, errConstExprExpected) continue # check type compatibility between def.typ and typ: if typ != nil: @@ -426,10 +426,10 @@ proc semConst(c: PContext, n: PNode): PNode = else: typ = def.typ if typ == nil: - LocalError(a.sons[2].info, errConstExprExpected) + localError(a.sons[2].info, errConstExprExpected) continue if not typeAllowed(typ, skConst): - LocalError(a.info, errXisNoType, typeToString(typ)) + localError(a.info, errXisNoType, typeToString(typ)) continue v.typ = typ v.ast = def # no need to copy @@ -498,7 +498,7 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = openScope(c.c) inc c.c.InUnrolledContext let body = instFieldLoopBody(fc, lastSon(forLoop), forLoop) - father.add(SemStmt(c.c, body)) + father.add(semStmt(c.c, body)) dec c.c.InUnrolledContext closeScope(c.c) of nkNilLit: discard @@ -506,7 +506,7 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = let L = forLoop.len let call = forLoop.sons[L-2] if call.len > 2: - LocalError(forLoop.info, errGenerated, + localError(forLoop.info, errGenerated, "parallel 'fields' iterator does not work for 'case' objects") return # iterate over the selector: @@ -535,9 +535,9 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = # so that 'break' etc. work as expected, we produce # a 'while true: stmt; break' loop ... result = newNodeI(nkWhileStmt, n.info, 2) - var trueSymbol = StrTableGet(magicsys.systemModule.Tab, getIdent"true") + var trueSymbol = strTableGet(magicsys.systemModule.Tab, getIdent"true") if trueSymbol == nil: - LocalError(n.info, errSystemNeeds, "true") + localError(n.info, errSystemNeeds, "true") trueSymbol = newSym(skUnknown, getIdent"true", getCurrOwner(), n.info) trueSymbol.typ = getSysType(tyBool) @@ -548,7 +548,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = var length = sonsLen(n) var call = n.sons[length-2] if length-2 != sonsLen(call)-1 + ord(m==mFieldPairs): - LocalError(n.info, errWrongNumberOfVariables) + localError(n.info, errWrongNumberOfVariables) return result var tupleTypeA = skipTypes(call.sons[1].typ, abstractVar-{tyTypeDesc}) @@ -557,10 +557,10 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = return result for i in 1..call.len-1: var tupleTypeB = skipTypes(call.sons[i].typ, abstractVar-{tyTypeDesc}) - if not SameType(tupleTypeA, tupleTypeB): + if not sameType(tupleTypeA, tupleTypeB): typeMismatch(call.sons[i], tupleTypeA, tupleTypeB) - Inc(c.p.nestedLoopCounter) + inc(c.p.nestedLoopCounter) if tupleTypeA.kind == tyTuple: var loopBody = n.sons[length-1] for i in 0..sonsLen(tupleTypeA)-1: @@ -571,7 +571,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = fc.replaceByFieldName = m == mFieldPairs var body = instFieldLoopBody(fc, loopBody, n) inc c.InUnrolledContext - stmts.add(SemStmt(c, body)) + stmts.add(semStmt(c, body)) dec c.InUnrolledContext closeScope(c) else: @@ -579,7 +579,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = fc.m = m fc.c = c semForObjectFields(fc, tupleTypeA.n, n, stmts) - Dec(c.p.nestedLoopCounter) + dec(c.p.nestedLoopCounter) # for TR macros this 'while true: ...; break' loop is pretty bad, so # we avoid it now if we can: if hasSonWith(stmts, nkBreakStmt): @@ -595,7 +595,7 @@ proc addForVarDecl(c: PContext, v: PSym) = if shadowed != nil: # XXX should we do this here? #shadowed.flags.incl(sfShadowed) - Message(v.info, warnShadowIdent, v.name.s) + message(v.info, warnShadowIdent, v.name.s) addDecl(c, v) proc symForVar(c: PContext, n: PNode): PSym = @@ -619,9 +619,9 @@ proc semForVars(c: PContext, n: PNode): PNode = n.sons[0] = newSymNode(v) if sfGenSym notin v.flags: addForVarDecl(c, v) else: - LocalError(n.info, errWrongNumberOfVariables) + localError(n.info, errWrongNumberOfVariables) elif length-2 != sonsLen(iter): - LocalError(n.info, errWrongNumberOfVariables) + localError(n.info, errWrongNumberOfVariables) else: for i in countup(0, length - 3): var v = symForVar(c, n.sons[i]) @@ -629,9 +629,9 @@ proc semForVars(c: PContext, n: PNode): PNode = v.typ = iter.sons[i] n.sons[i] = newSymNode(v) if sfGenSym notin v.flags: addForVarDecl(c, v) - Inc(c.p.nestedLoopCounter) - n.sons[length-1] = SemStmt(c, n.sons[length-1]) - Dec(c.p.nestedLoopCounter) + inc(c.p.nestedLoopCounter) + n.sons[length-1] = semStmt(c, n.sons[length-1]) + dec(c.p.nestedLoopCounter) proc implicitIterator(c: PContext, it: string, arg: PNode): PNode = result = newNodeI(nkCall, arg.info) @@ -659,7 +659,7 @@ proc semFor(c: PContext, n: PNode): PNode = elif length == 4: n.sons[length-2] = implicitIterator(c, "pairs", n.sons[length-2]) else: - LocalError(n.sons[length-2].info, errIteratorExpected) + localError(n.sons[length-2].info, errIteratorExpected) result = semForVars(c, n) elif call.sons[0].sym.magic != mNone: if call.sons[0].sym.magic == mOmpParFor: @@ -670,8 +670,8 @@ proc semFor(c: PContext, n: PNode): PNode = else: result = semForVars(c, n) # propagate any enforced VoidContext: - if n.sons[length-1].typ == EnforceVoidContext: - result.typ = EnforceVoidContext + if n.sons[length-1].typ == enforceVoidContext: + result.typ = enforceVoidContext closeScope(c) proc semRaise(c: PContext, n: PNode): PNode = @@ -697,7 +697,7 @@ proc typeSectionLeftSidePass(c: PContext, n: PNode) = var a = n.sons[i] if gCmd == cmdIdeTools: suggestStmt(c, a) if a.kind == nkCommentStmt: continue - if a.kind != nkTypeDef: IllFormedAst(a) + if a.kind != nkTypeDef: illFormedAst(a) checkSonsLen(a, 3) var s = semIdentDef(c, a.sons[0], skType) s.typ = newTypeS(tyForward, c) @@ -712,12 +712,12 @@ proc typeSectionRightSidePass(c: PContext, n: PNode) = for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if (a.kind != nkTypeDef): IllFormedAst(a) + if (a.kind != nkTypeDef): illFormedAst(a) checkSonsLen(a, 3) - if (a.sons[0].kind != nkSym): IllFormedAst(a) + if (a.sons[0].kind != nkSym): illFormedAst(a) var s = a.sons[0].sym if s.magic == mNone and a.sons[2].kind == nkEmpty: - LocalError(a.info, errImplOfXexpected, s.name.s) + localError(a.info, errImplOfXexpected, s.name.s) if s.magic != mNone: processMagicType(c, s) if a.sons[1].kind != nkEmpty: # We have a generic type declaration here. In generic types, @@ -770,7 +770,7 @@ proc typeSectionFinalPass(c: PContext, n: PNode) = for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] if a.kind == nkCommentStmt: continue - if a.sons[0].kind != nkSym: IllFormedAst(a) + if a.sons[0].kind != nkSym: illFormedAst(a) var s = a.sons[0].sym # compute the type's size and check for illegal recursions: if a.sons[1].kind == nkEmpty: @@ -812,12 +812,12 @@ proc addParams(c: PContext, n: PNode, kind: TSymKind) = proc semBorrow(c: PContext, n: PNode, s: PSym) = # search for the correct alias: - var b = SearchForBorrowProc(c, c.currentScope.parent, s) + var b = searchForBorrowProc(c, c.currentScope.parent, s) if b != nil: # store the alias: n.sons[bodyPos] = newSymNode(b) else: - LocalError(n.info, errNoSymbolToBorrowFromFound) + localError(n.info, errNoSymbolToBorrowFromFound) proc addResult(c: PContext, t: PType, info: TLineInfo, owner: TSymKind) = if t != nil: @@ -855,7 +855,7 @@ proc semProcAnnotation(c: PContext, prc: PNode): PNode = prc.sons[namePos] = newIdentNode(idDelegator, prc.info) prc.sons[pragmasPos] = copyExcept(n, i) else: - LocalError(prc.info, errOnlyACallOpCanBeDelegator) + localError(prc.info, errOnlyACallOpCanBeDelegator) continue # we transform ``proc p {.m, rest.}`` into ``m(do: proc p {.rest.})`` and # let the semantic checker deal with it: @@ -888,7 +888,7 @@ proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode = if n.sons[paramsPos].kind != nkEmpty: var gp = newNodeI(nkGenericParams, n.info) semParamList(c, n.sons[ParamsPos], gp, s) - ParamsTypeCheck(c, s.typ) + paramsTypeCheck(c, s.typ) else: s.typ = newTypeS(tyProc, c) rawAddSon(s.typ, nil) @@ -897,7 +897,7 @@ proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode = s.options = gOptions if n.sons[bodyPos].kind != nkEmpty: if sfImportc in s.flags: - LocalError(n.sons[bodyPos].info, errImplOfXNotAllowed, s.name.s) + localError(n.sons[bodyPos].info, errImplOfXNotAllowed, s.name.s) #if efDetermineType notin flags: # XXX not good enough; see tnamedparamanonproc.nim pushProcCon(c, s) @@ -908,7 +908,7 @@ proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode = popProcCon(c) sideEffectsCheck(c, s) else: - LocalError(n.info, errImplOfXexpected, s.name.s) + localError(n.info, errImplOfXexpected, s.name.s) closeScope(c) # close scope for parameters popOwner() result.typ = s.typ @@ -996,7 +996,7 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, n.sons[patternPos] = semPattern(c, n.sons[patternPos]) if s.kind == skIterator: s.typ.flags.incl(tfIterator) - var proto = SearchForProc(c, s.scope, s) + var proto = searchForProc(c, s.scope, s) if proto == nil: s.typ.callConv = lastOptionEntry(c).defaultCC # add it here, so that recursive procs are possible: @@ -1013,9 +1013,9 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, implictPragmas(c, s, n, validPragmas) else: if n.sons[pragmasPos].kind != nkEmpty: - LocalError(n.sons[pragmasPos].info, errPragmaOnlyInHeaderOfProc) + localError(n.sons[pragmasPos].info, errPragmaOnlyInHeaderOfProc) if sfForward notin proto.flags: - WrongRedefinition(n.info, proto.name.s) + wrongRedefinition(n.info, proto.name.s) excl(proto.flags, sfForward) closeScope(c) # close scope with wrong parameter symbols openScope(c) # open scope for old (correct) parameter symbols @@ -1028,7 +1028,7 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, n.sons[genericParamsPos] = proto.ast.sons[genericParamsPos] n.sons[paramsPos] = proto.ast.sons[paramsPos] n.sons[pragmasPos] = proto.ast.sons[pragmasPos] - if n.sons[namePos].kind != nkSym: InternalError(n.info, "semProcAux") + if n.sons[namePos].kind != nkSym: internalError(n.info, "semProcAux") n.sons[namePos].sym = proto if importantComments() and not isNil(proto.ast.comment): n.comment = proto.ast.comment @@ -1040,9 +1040,9 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, if n.sons[bodyPos].kind != nkEmpty: # for DLL generation it is annoying to check for sfImportc! if sfBorrow in s.flags: - LocalError(n.sons[bodyPos].info, errImplOfXNotAllowed, s.name.s) + localError(n.sons[bodyPos].info, errImplOfXNotAllowed, s.name.s) if n.sons[genericParamsPos].kind == nkEmpty: - ParamsTypeCheck(c, s.typ) + paramsTypeCheck(c, s.typ) pushProcCon(c, s) maybeAddResult(c, s, n) if sfImportc notin s.flags: @@ -1062,7 +1062,7 @@ proc semProcAux(c: PContext, n: PNode, kind: TSymKind, # so we just ignore the body after semantic checking for importc: n.sons[bodyPos] = ast.emptyNode else: - if proto != nil: LocalError(n.info, errImplOfXexpected, proto.name.s) + if proto != nil: localError(n.info, errImplOfXexpected, proto.name.s) if {sfImportc, sfBorrow} * s.flags == {} and s.magic == mNone: incl(s.flags, sfForward) elif sfBorrow in s.flags: semBorrow(c, n, s) @@ -1083,7 +1083,7 @@ proc semIterator(c: PContext, n: PNode): PNode = var s = result.sons[namePos].sym var t = s.typ if t.sons[0] == nil and s.typ.callConv != ccClosure: - LocalError(n.info, errXNeedsReturnType, "iterator") + localError(n.info, errXNeedsReturnType, "iterator") # iterators are either 'inline' or 'closure'; for backwards compatibility, # we require first class iterators to be marked with 'closure' explicitly # -- at least for 0.9.2. @@ -1097,7 +1097,7 @@ proc semIterator(c: PContext, n: PNode): PNode = # and they always at least use the 'env' for the state field: incl(s.typ.flags, tfCapturesEnv) if n.sons[bodyPos].kind == nkEmpty and s.magic == mNone: - LocalError(n.info, errImplOfXexpected, s.name.s) + localError(n.info, errImplOfXexpected, s.name.s) proc semProc(c: PContext, n: PNode): PNode = result = semProcAux(c, n, skProc, procPragmas) @@ -1148,11 +1148,11 @@ proc evalInclude(c: PContext, n: PNode): PNode = for i in countup(0, sonsLen(n) - 1): var f = checkModuleName(n.sons[i]) if f != InvalidFileIDX: - if ContainsOrIncl(c.includedFiles, f): - LocalError(n.info, errRecursiveDependencyX, f.toFilename) + if containsOrIncl(c.includedFiles, f): + localError(n.info, errRecursiveDependencyX, f.toFilename) else: addSon(result, semStmt(c, gIncludeFile(c.module, f))) - Excl(c.includedFiles, f) + excl(c.includedFiles, f) proc setLine(n: PNode, info: TLineInfo) = for i in 0 .. resultPos: @@ -215,12 +215,12 @@ proc analyseCall(c: PProcCtx, n: PNode): TThreadOwner = else: result = toNil proc analyseVarTuple(c: PProcCtx, n: PNode) = - if n.kind != nkVarTuple: InternalError(n.info, "analyseVarTuple") + if n.kind != nkVarTuple: internalError(n.info, "analyseVarTuple") var L = n.len - for i in countup(0, L-3): AnalyseAssign(c, n.sons[i], n.sons[L-1]) + for i in countup(0, L-3): analyseAssign(c, n.sons[i], n.sons[L-1]) proc analyseSingleVar(c: PProcCtx, a: PNode) = - if a.sons[2].kind != nkEmpty: AnalyseAssign(c, a.sons[0], a.sons[2]) + if a.sons[2].kind != nkEmpty: analyseAssign(c, a.sons[0], a.sons[2]) proc analyseVarSection(c: PProcCtx, n: PNode): TThreadOwner = for i in countup(0, sonsLen(n) - 1): @@ -238,7 +238,7 @@ proc analyseConstSection(c: PProcCtx, t: PNode): TThreadOwner = for i in countup(0, sonsLen(t) - 1): var it = t.sons[i] if it.kind == nkCommentStmt: continue - if it.kind != nkConstDef: InternalError(t.info, "analyseConstSection") + if it.kind != nkConstDef: internalError(t.info, "analyseConstSection") if sfFakeConst in it.sons[0].sym.flags: analyseSingleVar(c, it) result = toVoid @@ -246,7 +246,7 @@ template aggregateOwner(result, ana: expr) = var a = ana # eval once if result != a: if result == toNil: result = a - elif a != toNil: Message(n.info, warnDifferentHeaps) + elif a != toNil: message(n.info, warnDifferentHeaps) proc analyseArgs(c: PProcCtx, n: PNode, start = 1) = for i in start..n.len-1: discard analyse(c, n[i]) @@ -254,7 +254,7 @@ proc analyseArgs(c: PProcCtx, n: PNode, start = 1) = proc analyseOp(c: PProcCtx, n: PNode): TThreadOwner = if n[0].kind != nkSym or n[0].sym.kind != skProc: if {tfNoSideEffect, tfThread} * n[0].typ.flags == {}: - Message(n.info, warnAnalysisLoophole, renderTree(n)) + message(n.info, warnAnalysisLoophole, renderTree(n)) result = toNil else: var prc = n[0].sym @@ -352,7 +352,7 @@ proc analyse(c: PProcCtx, n: PNode): TThreadOwner = result = analyse(c, n.sons[0]) of nkRaiseStmt: var a = analyse(c, n.sons[0]) - if a != toMine: Message(n.info, warnDifferentHeaps) + if a != toMine: message(n.info, warnDifferentHeaps) result = toVoid of nkVarSection, nkLetSection: result = analyseVarSection(c, n) of nkConstSection: result = analyseConstSection(c, n) @@ -373,7 +373,7 @@ proc analyse(c: PProcCtx, n: PNode): TThreadOwner = result = toVoid of nkExprColonExpr: result = analyse(c, n.sons[1]) - else: InternalError(n.info, "analysis not implemented for: " & $n.kind) + else: internalError(n.info, "analysis not implemented for: " & $n.kind) proc analyseThreadProc*(prc: PSym) = var c = newProcCtx(prc) diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 1f995f5e7..91bbb467e 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -53,9 +53,9 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType = if skipTypes(strVal.typ, abstractInst).kind in {tyString, tyCstring}: x = getOrdValue(v.sons[0]) # first tuple part is the ordinal else: - LocalError(strVal.info, errStringLiteralExpected) + localError(strVal.info, errStringLiteralExpected) else: - LocalError(v.info, errWrongNumberOfVariables) + localError(v.info, errWrongNumberOfVariables) of tyString, tyCstring: strVal = v x = counter @@ -64,7 +64,7 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType = if i != 1: if x != counter: incl(result.flags, tfEnumHasHoles) if x < counter: - LocalError(n.sons[i].info, errInvalidOrderInEnumX, e.name.s) + localError(n.sons[i].info, errInvalidOrderInEnumX, e.name.s) x = counter e.ast = strVal # might be nil counter = x @@ -79,7 +79,7 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType = if result.sym != nil and sfExported in result.sym.flags: incl(e.flags, sfUsed) incl(e.flags, sfExported) - if not isPure: StrTableAdd(c.module.tab, e) + if not isPure: strTableAdd(c.module.tab, e) addSon(result.n, newSymNode(e)) if sfGenSym notin e.flags and not isPure: addDecl(c, e) inc(counter) @@ -93,11 +93,11 @@ proc semSet(c: PContext, n: PNode, prev: PType): PType = if base.kind == tyGenericInst: base = lastSon(base) if base.kind != tyGenericParam: if not isOrdinalType(base): - LocalError(n.info, errOrdinalTypeExpected) + localError(n.info, errOrdinalTypeExpected) elif lengthOrd(base) > MaxSetElements: - LocalError(n.info, errSetTooBig) + localError(n.info, errSetTooBig) else: - LocalError(n.info, errXExpectsOneTypeParam, "set") + localError(n.info, errXExpectsOneTypeParam, "set") addSonSkipIntLit(result, errorType(c)) proc semContainer(c: PContext, n: PNode, kind: TTypeKind, kindStr: string, @@ -107,7 +107,7 @@ proc semContainer(c: PContext, n: PNode, kind: TTypeKind, kindStr: string, var base = semTypeNode(c, n.sons[1], nil) addSonSkipIntLit(result, base) else: - LocalError(n.info, errXExpectsOneTypeParam, kindStr) + localError(n.info, errXExpectsOneTypeParam, kindStr) addSonSkipIntLit(result, errorType(c)) proc semVarargs(c: PContext, n: PNode, prev: PType): PType = @@ -118,7 +118,7 @@ proc semVarargs(c: PContext, n: PNode, prev: PType): PType = if sonsLen(n) == 3: result.n = newIdentNode(considerAcc(n.sons[2]), n.sons[2].info) else: - LocalError(n.info, errXExpectsOneTypeParam, "varargs") + localError(n.info, errXExpectsOneTypeParam, "varargs") addSonSkipIntLit(result, errorType(c)) proc semAnyRef(c: PContext, n: PNode, kind: TTypeKind, prev: PType): PType = @@ -134,7 +134,7 @@ proc semVarType(c: PContext, n: PNode, prev: PType): PType = result = newOrPrevType(tyVar, prev, c) var base = semTypeNode(c, n.sons[0], nil) if base.kind == tyVar: - LocalError(n.info, errVarVarTypeNotAllowed) + localError(n.info, errVarVarTypeNotAllowed) base = base.sons[0] addSonSkipIntLit(result, base) else: @@ -153,17 +153,17 @@ proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = result = newOrPrevType(tyRange, prev, c) result.n = newNodeI(nkRange, n.info) if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty): - LocalError(n.Info, errRangeIsEmpty) + localError(n.Info, errRangeIsEmpty) var a = semConstExpr(c, n[1]) var b = semConstExpr(c, n[2]) if not sameType(a.typ, b.typ): - LocalError(n.info, errPureTypeMismatch) + localError(n.info, errPureTypeMismatch) elif a.typ.kind notin {tyInt..tyInt64,tyEnum,tyBool,tyChar, tyFloat..tyFloat128,tyUInt8..tyUInt32}: - LocalError(n.info, errOrdinalTypeExpected) + localError(n.info, errOrdinalTypeExpected) elif enumHasHoles(a.typ): - LocalError(n.info, errEnumXHasHoles, a.typ.sym.name.s) - elif not leValue(a, b): LocalError(n.Info, errRangeIsEmpty) + localError(n.info, errEnumXHasHoles, a.typ.sym.name.s) + elif not leValue(a, b): localError(n.Info, errRangeIsEmpty) addSon(result.n, a) addSon(result.n, b) addSonSkipIntLit(result, b.typ) @@ -180,10 +180,10 @@ proc semRange(c: PContext, n: PNode, prev: PType): PType = elif n.sons[0].floatVal > 0.0 or n.sons[1].floatVal < 0.0: incl(result.flags, tfNeedsInit) else: - LocalError(n.sons[0].info, errRangeExpected) + localError(n.sons[0].info, errRangeExpected) result = newOrPrevType(tyError, prev, c) else: - LocalError(n.info, errXExpectsOneTypeParam, "range") + localError(n.info, errXExpectsOneTypeParam, "range") result = newOrPrevType(tyError, prev, c) proc semArray(c: PContext, n: PNode, prev: PType): PType = @@ -208,13 +208,13 @@ proc semArray(c: PContext, n: PNode, prev: PType): PType = if indx.kind == tyGenericInst: indx = lastSon(indx) if indx.kind notin {tyGenericParam, tyExpr}: if not isOrdinalType(indx): - LocalError(n.sons[1].info, errOrdinalTypeExpected) + localError(n.sons[1].info, errOrdinalTypeExpected) elif enumHasHoles(indx): - LocalError(n.sons[1].info, errEnumXHasHoles, indx.sym.name.s) + localError(n.sons[1].info, errEnumXHasHoles, indx.sym.name.s) base = semTypeNode(c, n.sons[2], nil) addSonSkipIntLit(result, base) else: - LocalError(n.info, errArrayExpectsTwoTypeParams) + localError(n.info, errArrayExpectsTwoTypeParams) result = newOrPrevType(tyError, prev, c) proc semOrdinal(c: PContext, n: PNode, prev: PType): PType = @@ -223,17 +223,17 @@ proc semOrdinal(c: PContext, n: PNode, prev: PType): PType = var base = semTypeNode(c, n.sons[1], nil) if base.kind != tyGenericParam: if not isOrdinalType(base): - LocalError(n.sons[1].info, errOrdinalTypeExpected) + localError(n.sons[1].info, errOrdinalTypeExpected) addSonSkipIntLit(result, base) else: - LocalError(n.info, errXExpectsOneTypeParam, "ordinal") + localError(n.info, errXExpectsOneTypeParam, "ordinal") result = newOrPrevType(tyError, prev, c) proc semTypeIdent(c: PContext, n: PNode): PSym = if n.kind == nkSym: result = n.sym else: - result = qualifiedLookup(c, n, {checkAmbiguity, checkUndeclared}) + result = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) if result != nil: markUsed(n, result) if result.kind == skParam and result.typ.kind == tyTypeDesc: @@ -245,7 +245,7 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = if bound != nil: return bound return result if result.typ.sym == nil: - LocalError(n.info, errTypeExpected) + localError(n.info, errTypeExpected) return errorSym(c, n) result = result.typ.sym.copySym result.typ = copyType(result.typ, result.typ.owner, true) @@ -253,12 +253,12 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = if result.kind != skType: # this implements the wanted ``var v: V, x: V`` feature ... var ov: TOverloadIter - var amb = InitOverloadIter(ov, c, n) + var amb = initOverloadIter(ov, c, n) while amb != nil and amb.kind != skType: amb = nextOverloadIter(ov, c, n) if amb != nil: result = amb else: - if result.kind != skError: LocalError(n.info, errTypeExpected) + if result.kind != skError: localError(n.info, errTypeExpected) return errorSym(c, n) if result.typ.kind != tyGenericParam: # XXX get rid of this hack! @@ -268,7 +268,7 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = n.sym = result n.info = oldInfo else: - LocalError(n.info, errIdentifierExpected) + localError(n.info, errIdentifierExpected) result = errorSym(c, n) proc semTuple(c: PContext, n: PNode, prev: PType): PType = @@ -280,23 +280,23 @@ proc semTuple(c: PContext, n: PNode, prev: PType): PType = var counter = 0 for i in countup(0, sonsLen(n) - 1): var a = n.sons[i] - if (a.kind != nkIdentDefs): IllFormedAst(a) + if (a.kind != nkIdentDefs): illFormedAst(a) checkMinSonsLen(a, 3) var length = sonsLen(a) if a.sons[length - 2].kind != nkEmpty: typ = semTypeNode(c, a.sons[length - 2], nil) else: - LocalError(a.info, errTypeExpected) + localError(a.info, errTypeExpected) typ = errorType(c) if a.sons[length - 1].kind != nkEmpty: - LocalError(a.sons[length - 1].info, errInitHereNotAllowed) + localError(a.sons[length - 1].info, errInitHereNotAllowed) for j in countup(0, length - 3): var field = newSymG(skField, a.sons[j], c) field.typ = typ field.position = counter inc(counter) - if ContainsOrIncl(check, field.name.id): - LocalError(a.sons[j].info, errAttemptToRedefine, field.name.s) + if containsOrIncl(check, field.name.id): + localError(a.sons[j].info, errAttemptToRedefine, field.name.s) else: addSon(result.n, newSymNode(field)) addSonSkipIntLit(result, typ) @@ -313,7 +313,7 @@ proc semIdentVis(c: PContext, kind: TSymKind, n: PNode, if sfExported in allowed and v.id == ord(wStar): incl(result.flags, sfExported) else: - LocalError(n.sons[0].info, errInvalidVisibilityX, v.s) + localError(n.sons[0].info, errInvalidVisibilityX, v.s) else: illFormedAst(n) else: @@ -341,9 +341,9 @@ proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) = for j in countup(0, sonsLen(t.sons[i]) - 2): if i == branchIndex and j == currentEx: break if overlap(t.sons[i].sons[j].skipConv, ex): - LocalError(ex.info, errDuplicateCaseLabel) + localError(ex.info, errDuplicateCaseLabel) -proc semBranchRange(c: PContext, t, a, b: PNode, covered: var biggestInt): PNode = +proc semBranchRange(c: PContext, t, a, b: PNode, covered: var BiggestInt): PNode = checkMinSonsLen(t, 1) let ac = semConstExpr(c, a) let bc = semConstExpr(c, b) @@ -353,16 +353,16 @@ proc semBranchRange(c: PContext, t, a, b: PNode, covered: var biggestInt): PNode result = newNodeI(nkRange, a.info) result.add(at) result.add(bt) - if emptyRange(ac, bc): LocalError(b.info, errRangeIsEmpty) + if emptyRange(ac, bc): localError(b.info, errRangeIsEmpty) else: covered = covered + getOrdValue(bc) - getOrdValue(ac) + 1 proc semCaseBranchRange(c: PContext, t, b: PNode, - covered: var biggestInt): PNode = + covered: var BiggestInt): PNode = checkSonsLen(b, 3) result = semBranchRange(c, t, b.sons[1], b.sons[2], covered) proc semCaseBranchSetElem(c: PContext, t, b: PNode, - covered: var biggestInt): PNode = + covered: var BiggestInt): PNode = if isRange(b): checkSonsLen(b, 3) result = semBranchRange(c, t, b.sons[1], b.sons[2], covered) @@ -374,7 +374,7 @@ proc semCaseBranchSetElem(c: PContext, t, b: PNode, inc(covered) proc semCaseBranch(c: PContext, t, branch: PNode, branchIndex: int, - covered: var biggestInt) = + covered: var BiggestInt) = for i in countup(0, sonsLen(branch) - 2): var b = branch.sons[i] if b.kind == nkRange: @@ -411,14 +411,14 @@ proc semRecordCase(c: PContext, n: PNode, check: var TIntSet, pos: var int, internalError("semRecordCase: discriminant is no symbol") return incl(a.sons[0].sym.flags, sfDiscriminant) - var covered: biggestInt = 0 + var covered: BiggestInt = 0 var typ = skipTypes(a.sons[0].Typ, abstractVar-{tyTypeDesc}) if not isOrdinalType(typ): - LocalError(n.info, errSelectorMustBeOrdinal) + localError(n.info, errSelectorMustBeOrdinal) elif firstOrd(typ) < 0: - LocalError(n.info, errOrdXMustNotBeNegative, a.sons[0].sym.name.s) + localError(n.info, errOrdXMustNotBeNegative, a.sons[0].sym.name.s) elif lengthOrd(typ) > 0x00007FFF: - LocalError(n.info, errLenXinvalid, a.sons[0].sym.name.s) + localError(n.info, errLenXinvalid, a.sons[0].sym.name.s) var chckCovered = true for i in countup(1, sonsLen(n) - 1): var b = copyTree(n.sons[i]) @@ -452,7 +452,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, checkSonsLen(it, 2) if c.InGenericContext == 0: var e = semConstBoolExpr(c, it.sons[0]) - if e.kind != nkIntLit: InternalError(e.info, "semRecordNodeAux") + if e.kind != nkIntLit: internalError(e.info, "semRecordNodeAux") elif e.intVal != 0 and branch == nil: branch = it.sons[1] else: it.sons[0] = forceBool(c, semExprWithType(c, it.sons[0])) @@ -467,7 +467,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, assign(newCheck, check) var newPos = pos var newf = newNodeI(nkRecList, n.info) - semRecordNodeAux(c, it.sons[idx], newcheck, newpos, newf, rectype) + semRecordNodeAux(c, it.sons[idx], newCheck, newPos, newf, rectype) it.sons[idx] = if newf.len == 1: newf[0] else: newf if c.InGenericContext > 0: addSon(father, n) @@ -493,7 +493,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, localError(n.sons[length-1].info, errInitHereNotAllowed) var typ: PType if n.sons[length-2].kind == nkEmpty: - LocalError(n.info, errTypeExpected) + localError(n.info, errTypeExpected) typ = errorType(c) else: typ = semTypeNode(c, n.sons[length-2], nil) @@ -509,7 +509,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, f.loc.r = toRope(f.name.s) f.flags = f.flags + ({sfImportc, sfExportc} * rec.flags) inc(pos) - if ContainsOrIncl(check, f.name.id): + if containsOrIncl(check, f.name.id): localError(n.sons[i].info, errAttemptToRedefine, f.name.s) if a.kind == nkEmpty: addSon(father, newSymNode(f)) else: addSon(a, newSymNode(f)) @@ -521,7 +521,7 @@ proc addInheritedFieldsAux(c: PContext, check: var TIntSet, pos: var int, n: PNode) = case n.kind of nkRecCase: - if (n.sons[0].kind != nkSym): InternalError(n.info, "addInheritedFieldsAux") + if (n.sons[0].kind != nkSym): internalError(n.info, "addInheritedFieldsAux") addInheritedFieldsAux(c, check, pos, n.sons[0]) for i in countup(1, sonsLen(n) - 1): case n.sons[i].kind @@ -532,9 +532,9 @@ proc addInheritedFieldsAux(c: PContext, check: var TIntSet, pos: var int, for i in countup(0, sonsLen(n) - 1): addInheritedFieldsAux(c, check, pos, n.sons[i]) of nkSym: - Incl(check, n.sym.name.id) + incl(check, n.sym.name.id) inc(pos) - else: InternalError(n.info, "addInheritedFieldsAux()") + else: internalError(n.info, "addInheritedFieldsAux()") proc addInheritedFields(c: PContext, check: var TIntSet, pos: var int, obj: PType) = @@ -565,7 +565,7 @@ proc semObjectNode(c: PContext, n: PNode, prev: PType): PType = if concreteBase.kind != tyError: localError(n.sons[1].info, errInheritanceOnlyWithNonFinalObjects) base = nil - if n.kind != nkObjectTy: InternalError(n.info, "semObjectNode") + if n.kind != nkObjectTy: internalError(n.info, "semObjectNode") result = newOrPrevType(tyObject, prev, c) rawAddSon(result, base) result.n = newNodeI(nkRecList, n.info) @@ -719,7 +719,7 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode, var counter = 0 for i in countup(1, n.len - 1): var a = n.sons[i] - if a.kind != nkIdentDefs: IllFormedAst(a) + if a.kind != nkIdentDefs: illFormedAst(a) checkMinSonsLen(a, 3) var typ: PType = nil @@ -756,8 +756,8 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode, arg.constraint = constraint inc(counter) if def != nil and def.kind != nkEmpty: arg.ast = copyTree(def) - if ContainsOrIncl(check, arg.name.id): - LocalError(a.sons[j].info, errAttemptToRedefine, arg.name.s) + if containsOrIncl(check, arg.name.id): + localError(a.sons[j].info, errAttemptToRedefine, arg.name.s) addSon(result.n, newSymNode(arg)) rawAddSon(result, finalType) addParamOrResult(c, arg, kind) @@ -788,7 +788,7 @@ proc semStmtListType(c: PContext, n: PNode, prev: PType): PType = result = nil proc semBlockType(c: PContext, n: PNode, prev: PType): PType = - Inc(c.p.nestedBlockCounter) + inc(c.p.nestedBlockCounter) checkSonsLen(n, 2) openScope(c) if n.sons[0].kind notin {nkEmpty, nkSym}: @@ -797,7 +797,7 @@ proc semBlockType(c: PContext, n: PNode, prev: PType): PType = n.sons[1].typ = result n.typ = result closeScope(c) - Dec(c.p.nestedBlockCounter) + dec(c.p.nestedBlockCounter) proc semGenericParamInInvokation(c: PContext, n: PNode): PType = # XXX hack 1022 for generics ... would have been nice if the compiler had @@ -824,12 +824,12 @@ proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType = template addToResult(typ) = if typ.isNil: - InternalAssert false + internalAssert false rawAddSon(result, typ) else: addSonSkipIntLit(result, typ) if s.typ == nil: - LocalError(n.info, errCannotInstantiateX, s.name.s) + localError(n.info, errCannotInstantiateX, s.name.s) return newOrPrevType(tyError, prev, c) elif s.typ.kind == tyForward: for i in countup(1, sonsLen(n)-1): @@ -845,7 +845,7 @@ proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType = var err = "cannot instantiate " & typeToString(s.typ) & "\n" & "got: (" & describeArgs(c, n) & ")\n" & "but expected: (" & describeArgs(c, s.typ.n, 0) & ")" - LocalError(n.info, errGenerated, err) + localError(n.info, errGenerated, err) return newOrPrevType(tyError, prev, c) var isConcrete = true @@ -857,7 +857,7 @@ proc semGeneric(c: PContext, n: PNode, s: PSym, prev: PType): PType = if isConcrete: if s.ast == nil: - LocalError(n.info, errCannotInstantiateX, s.name.s) + localError(n.info, errCannotInstantiateX, s.name.s) result = newOrPrevType(tyError, prev, c) else: when oUseLateInstantiation: @@ -870,7 +870,7 @@ proc semTypeExpr(c: PContext, n: PNode): PType = if n.kind == nkSym and n.sym.kind == skType: result = n.sym.typ else: - LocalError(n.info, errTypeExpected, n.renderTree) + localError(n.info, errTypeExpected, n.renderTree) proc freshType(res, prev: PType): PType {.inline.} = if prev.isNil: @@ -905,7 +905,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = if sonsLen(n) == 1: result = semTypeNode(c, n.sons[0], prev) else: # XXX support anon tuple here - LocalError(n.info, errTypeExpected) + localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) of nkCallKinds: if isRange(n): @@ -918,10 +918,10 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = t1 = semTypeNode(c, n.sons[1], nil) t2 = semTypeNode(c, n.sons[2], nil) if t1 == nil: - LocalError(n.sons[1].info, errTypeExpected) + localError(n.sons[1].info, errTypeExpected) result = newOrPrevType(tyError, prev, c) elif t2 == nil: - LocalError(n.sons[2].info, errTypeExpected) + localError(n.sons[2].info, errTypeExpected) result = newOrPrevType(tyError, prev, c) else: result = newTypeS(tyTypeClass, c) @@ -936,7 +936,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = result = freshType(result, prev) result.flags.incl(tfNotNil) else: - LocalError(n.info, errGenerated, "invalid type") + localError(n.info, errGenerated, "invalid type") else: result = semTypeExpr(c, n) else: @@ -966,7 +966,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = of nkIdent, nkDotExpr, nkAccQuoted: var s = semTypeIdent(c, n) if s.typ == nil: - if s.kind != skError: LocalError(n.info, errTypeExpected) + if s.kind != skError: localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) elif s.kind == skParam and s.typ.kind == tyTypeDesc: assert s.typ.len > 0 @@ -991,7 +991,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = result = prev markUsed(n, n.sym) else: - if n.sym.kind != skError: LocalError(n.info, errTypeExpected) + if n.sym.kind != skError: localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) of nkObjectTy: result = semObjectNode(c, n, prev) of nkTupleTy: result = semTuple(c, n, prev) @@ -1016,7 +1016,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = #Message(n.info, warnImplicitClosure, renderTree(n)) else: pragma(c, s, n.sons[1], procTypePragmas) - when useEffectSystem: SetEffectsForProcType(result, n.sons[1]) + when useEffectSystem: setEffectsForProcType(result, n.sons[1]) closeScope(c) if n.kind == nkIteratorTy: result.flags.incl(tfIterator) @@ -1031,7 +1031,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = result = freshType(result, prev) result.flags.incl(tfShared) else: - LocalError(n.info, errTypeExpected) + localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) proc setMagicType(m: PSym, kind: TTypeKind, size: int) = @@ -1081,7 +1081,7 @@ proc processMagicType(c: PContext, m: PSym) = of mSeq: setMagicType(m, tySequence, 0) of mOrdinal: setMagicType(m, tyOrdinal, 0) of mPNimrodNode: nil - else: LocalError(m.info, errTypeExpected) + else: localError(m.info, errTypeExpected) proc semGenericConstraints(c: PContext, x: PType): PType = if x.kind in StructuralEquivTypes and ( diff --git a/compiler/semtypinst.nim b/compiler/semtypinst.nim index d51c1de8c..2afdeb5ae 100644 --- a/compiler/semtypinst.nim +++ b/compiler/semtypinst.nim @@ -13,19 +13,19 @@ import ast, astalgo, msgs, types, magicsys, semdata, renderer proc checkPartialConstructedType(info: TLineInfo, t: PType) = if tfAcyclic in t.flags and skipTypes(t, abstractInst).kind != tyObject: - LocalError(info, errInvalidPragmaX, "acyclic") + localError(info, errInvalidPragmaX, "acyclic") elif t.kind == tyVar and t.sons[0].kind == tyVar: - LocalError(info, errVarVarTypeNotAllowed) + localError(info, errVarVarTypeNotAllowed) proc checkConstructedType*(info: TLineInfo, typ: PType) = var t = typ.skipTypes({tyDistinct}) if t.kind in {tyTypeClass}: nil elif tfAcyclic in t.flags and skipTypes(t, abstractInst).kind != tyObject: - LocalError(info, errInvalidPragmaX, "acyclic") + localError(info, errInvalidPragmaX, "acyclic") elif t.kind == tyVar and t.sons[0].kind == tyVar: - LocalError(info, errVarVarTypeNotAllowed) + localError(info, errVarVarTypeNotAllowed) elif computeSize(t) < 0: - LocalError(info, errIllegalRecursionInTypeX, typeToString(t)) + localError(info, errIllegalRecursionInTypeX, typeToString(t)) when false: if t.kind == tyObject and t.sons[0] != nil: if t.sons[0].kind != tyObject or tfFinal in t.sons[0].flags: @@ -74,8 +74,8 @@ proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode = result = copyNode(n) - result.typ = ReplaceTypeVarsT(cl, n.typ) - if result.kind == nkSym: result.sym = ReplaceTypeVarsS(cl, n.sym) + result.typ = replaceTypeVarsT(cl, n.typ) + if result.kind == nkSym: result.sym = replaceTypeVarsS(cl, n.sym) for i in 0 .. safeLen(n)-1: # XXX HACK: ``f(a, b)``, avoid to instantiate `f` if i == 0: result.add(n[i]) @@ -84,12 +84,12 @@ proc prepareNode(cl: var TReplTypeVars, n: PNode): PNode = proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = if n == nil: return result = copyNode(n) - result.typ = ReplaceTypeVarsT(cl, n.typ) + result.typ = replaceTypeVarsT(cl, n.typ) case n.kind of nkNone..pred(nkSym), succ(nkSym)..nkNilLit: discard of nkSym: - result.sym = ReplaceTypeVarsS(cl, n.sym) + result.sym = replaceTypeVarsS(cl, n.sym) of nkRecWhen: var branch: PNode = nil # the branch to take for i in countup(0, sonsLen(n) - 1): @@ -101,14 +101,14 @@ proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = var cond = prepareNode(cl, it.sons[0]) var e = cl.c.semConstExpr(cl.c, cond) if e.kind != nkIntLit: - InternalError(e.info, "ReplaceTypeVarsN: when condition not a bool") + internalError(e.info, "ReplaceTypeVarsN: when condition not a bool") if e.intVal != 0 and branch == nil: branch = it.sons[1] of nkElse: checkSonsLen(it, 1) if branch == nil: branch = it.sons[0] else: illFormedAst(n) if branch != nil: - result = ReplaceTypeVarsN(cl, branch) + result = replaceTypeVarsN(cl, branch) else: result = newNodeI(nkRecList, n.info) else: @@ -116,7 +116,7 @@ proc replaceTypeVarsN(cl: var TReplTypeVars, n: PNode): PNode = if length > 0: newSons(result, length) for i in countup(0, length - 1): - result.sons[i] = ReplaceTypeVarsN(cl, n.sons[i]) + result.sons[i] = replaceTypeVarsN(cl, n.sons[i]) proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym = if s == nil: return nil @@ -125,23 +125,23 @@ proc replaceTypeVarsS(cl: var TReplTypeVars, s: PSym): PSym = result = copySym(s, false) incl(result.flags, sfFromGeneric) idTablePut(cl.symMap, s, result) - result.typ = ReplaceTypeVarsT(cl, s.typ) + result.typ = replaceTypeVarsT(cl, s.typ) result.owner = s.owner - result.ast = ReplaceTypeVarsN(cl, s.ast) + result.ast = replaceTypeVarsN(cl, s.ast) proc lookupTypeVar(cl: TReplTypeVars, t: PType): PType = result = PType(idTableGet(cl.typeMap, t)) if result == nil: - LocalError(t.sym.info, errCannotInstantiateX, typeToString(t)) + localError(t.sym.info, errCannotInstantiateX, typeToString(t)) result = errorType(cl.c) elif result.kind == tyGenericParam: - InternalError(cl.info, "substitution with generic parameter") + internalError(cl.info, "substitution with generic parameter") proc handleGenericInvokation(cl: var TReplTypeVars, t: PType): PType = # tyGenericInvokation[A, tyGenericInvokation[A, B]] # is difficult to handle: var body = t.sons[0] - if body.kind != tyGenericBody: InternalError(cl.info, "no generic body") + if body.kind != tyGenericBody: internalError(cl.info, "no generic body") var header: PType = nil # search for some instantiation here: result = searchInstTypes(t) @@ -180,11 +180,11 @@ proc handleGenericInvokation(cl: var TReplTypeVars, t: PType): PType = # but we already raised an error! rawAddSon(result, header.sons[i]) - var newbody = ReplaceTypeVarsT(cl, lastSon(body)) + var newbody = replaceTypeVarsT(cl, lastSon(body)) newbody.flags = newbody.flags + t.flags + body.flags result.flags = result.flags + newbody.flags newbody.callConv = body.callConv - newbody.n = ReplaceTypeVarsN(cl, lastSon(body).n) + newbody.n = replaceTypeVarsN(cl, lastSon(body).n) # This type may be a generic alias and we want to resolve it here. # One step is enough, because the recursive nature of # handleGenericInvokation will handle the alias-to-alias-to-alias case @@ -207,8 +207,8 @@ proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = of tyGenericInvokation: result = handleGenericInvokation(cl, t) of tyGenericBody: - InternalError(cl.info, "ReplaceTypeVarsT: tyGenericBody") - result = ReplaceTypeVarsT(cl, lastSon(t)) + internalError(cl.info, "ReplaceTypeVarsT: tyGenericBody") + result = replaceTypeVarsT(cl, lastSon(t)) of tyInt: result = skipIntLit(t) # XXX now there are also float literals @@ -224,10 +224,10 @@ proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = incl(result.flags, tfFromGeneric) result.size = -1 # needs to be recomputed for i in countup(0, sonsLen(result) - 1): - result.sons[i] = ReplaceTypeVarsT(cl, result.sons[i]) - result.n = ReplaceTypeVarsN(cl, result.n) + result.sons[i] = replaceTypeVarsT(cl, result.sons[i]) + result.n = replaceTypeVarsN(cl, result.n) if result.Kind in GenericTypes: - LocalError(cl.info, errCannotInstantiateX, TypeToString(t, preferName)) + localError(cl.info, errCannotInstantiateX, typeToString(t, preferName)) if result.kind == tyProc and result.sons[0] != nil: if result.sons[0].kind == tyEmpty: result.sons[0] = nil diff --git a/compiler/service.nim b/compiler/service.nim index 1cae72f2a..209ccd8e3 100644 --- a/compiler/service.nim +++ b/compiler/service.nim @@ -43,9 +43,9 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = if bracketLe >= 0: var key = substr(p.key, 0, bracketLe - 1) var val = substr(p.key, bracketLe + 1) & ':' & p.val - ProcessSwitch(key, val, pass, gCmdLineInfo) + processSwitch(key, val, pass, gCmdLineInfo) else: - ProcessSwitch(p.key, p.val, pass, gCmdLineInfo) + processSwitch(p.key, p.val, pass, gCmdLineInfo) of cmdArgument: if argsCount == 0: options.command = p.key @@ -79,11 +79,11 @@ proc serve*(action: proc (){.nimcall.}) = if line == "quit": quit() execute line echo "" - FlushFile(stdout) + flushFile(stdout) of "tcp", "": when useCaas: - var server = Socket() + var server = socket() let p = getConfigVar("server.port") let port = if p.len > 0: parseInt(p).TPort else: 6000.TPort server.bindAddr(port, getConfigVar("server.address")) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 7ccb1bdc1..7a30dadc8 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -77,7 +77,7 @@ proc initCandidate*(c: var TCandidate, callee: PType) = initIdTable(c.bindings) proc put(t: var TIdTable, key, val: PType) {.inline.} = - IdTablePut(t, key, val) + idTablePut(t, key, val) proc initCandidate*(c: var TCandidate, callee: PSym, binding: PNode, calleeScope = -1) = @@ -169,11 +169,11 @@ proc cmpCandidates*(a, b: TCandidate): int = result = complexDisambiguation(a.callee, b.callee) proc writeMatches*(c: TCandidate) = - Writeln(stdout, "exact matches: " & $c.exactMatches) - Writeln(stdout, "subtype matches: " & $c.subtypeMatches) - Writeln(stdout, "conv matches: " & $c.convMatches) - Writeln(stdout, "intconv matches: " & $c.intConvMatches) - Writeln(stdout, "generic matches: " & $c.genericMatches) + writeln(stdout, "exact matches: " & $c.exactMatches) + writeln(stdout, "subtype matches: " & $c.subtypeMatches) + writeln(stdout, "conv matches: " & $c.convMatches) + writeln(stdout, "intconv matches: " & $c.intConvMatches) + writeln(stdout, "generic matches: " & $c.genericMatches) proc argTypeToString(arg: PNode): string = if arg.kind in nkSymChoices: @@ -223,7 +223,7 @@ proc concreteType(c: TCandidate, t: PType): PType = # proc sort[T](cmp: proc(a, b: T): int = cmp) if result.kind != tyGenericParam: break of tyGenericInvokation: - InternalError("cannot resolve type: " & typeToString(t)) + internalError("cannot resolve type: " & typeToString(t)) result = t else: result = t # Note: empty is valid here @@ -309,8 +309,8 @@ proc tupleRel(c: var TCandidate, f, a: PType): TTypeRelation = if f.n != nil and a.n != nil: for i in countup(0, sonsLen(f.n) - 1): # check field names: - if f.n.sons[i].kind != nkSym: InternalError(f.n.info, "tupleRel") - elif a.n.sons[i].kind != nkSym: InternalError(a.n.info, "tupleRel") + if f.n.sons[i].kind != nkSym: internalError(f.n.info, "tupleRel") + elif a.n.sons[i].kind != nkSym: internalError(a.n.info, "tupleRel") else: var x = f.n.sons[i].sym var y = a.n.sons[i].sym @@ -552,7 +552,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = if result < isGeneric: result = isNone elif a.kind == tyGenericParam: result = isGeneric - of tyForward: InternalError("forward type in typeRel()") + of tyForward: internalError("forward type in typeRel()") of tyNil: if a.kind == f.kind: result = isEqual of tyTuple: @@ -658,7 +658,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = (sonsLen(x) - 1 == sonsLen(f)): for i in countup(1, sonsLen(f) - 1): if x.sons[i].kind == tyGenericParam: - InternalError("wrong instantiated type!") + internalError("wrong instantiated type!") elif typeRel(c, f.sons[i], x.sons[i]) <= isSubtype: return result = isGeneric else: @@ -668,7 +668,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = for i in countup(1, sonsLen(f) - 1): var x = PType(idTableGet(c.bindings, f.sons[0].sons[i - 1])) if x == nil or x.kind in {tyGenericInvokation, tyGenericParam}: - InternalError("wrong instantiated type!") + internalError("wrong instantiated type!") put(c.bindings, f.sons[i], x) of tyAnd: @@ -764,7 +764,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = proc cmpTypes*(f, a: PType): TTypeRelation = var c: TCandidate - InitCandidate(c, f) + initCandidate(c, f) result = typeRel(c, f, a) proc getInstantiatedType(c: PContext, arg: PNode, m: TCandidate, @@ -773,7 +773,7 @@ proc getInstantiatedType(c: PContext, arg: PNode, m: TCandidate, if result == nil: result = generateTypeInstance(c, m.bindings, arg, f) if result == nil: - InternalError(arg.info, "getInstantiatedType") + internalError(arg.info, "getInstantiatedType") result = errorType(c) proc implicitConv(kind: TNodeKind, f: PType, arg: PNode, m: TCandidate, @@ -786,7 +786,7 @@ proc implicitConv(kind: TNodeKind, f: PType, arg: PNode, m: TCandidate, result.typ = errorType(c) else: result.typ = f - if result.typ == nil: InternalError(arg.info, "implicitConv") + if result.typ == nil: internalError(arg.info, "implicitConv") addSon(result, ast.emptyNode) addSon(result, arg) @@ -1006,7 +1006,7 @@ proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, proc paramTypesMatch*(c: PContext, m: var TCandidate, f, a: PType, arg, argOrig: PNode): PNode = if arg == nil or arg.kind notin nkSymChoices: - result = ParamTypesMatchAux(c, m, f, a, arg, argOrig) + result = paramTypesMatchAux(c, m, f, a, arg, argOrig) else: # CAUTION: The order depends on the used hashing scheme. Thus it is # incorrect to simply use the first fitting match. However, to implement @@ -1041,17 +1041,17 @@ proc paramTypesMatch*(c: PContext, m: var TCandidate, f, a: PType, result = nil elif (y.state == csMatch) and (cmpCandidates(x, y) == 0): if x.state != csMatch: - InternalError(arg.info, "x.state is not csMatch") + internalError(arg.info, "x.state is not csMatch") # ambiguous: more than one symbol fits result = nil else: # only one valid interpretation found: markUsed(arg, arg.sons[best].sym) - result = ParamTypesMatchAux(c, m, f, arg.sons[best].typ, arg.sons[best], + result = paramTypesMatchAux(c, m, f, arg.sons[best].typ, arg.sons[best], argOrig) proc setSon(father: PNode, at: int, son: PNode) = - if sonsLen(father) <= at: setlen(father.sons, at + 1) + if sonsLen(father) <= at: setLen(father.sons, at + 1) father.sons[at] = son # we are allowed to modify the calling node in the 'prepare*' procs: @@ -1122,7 +1122,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode, # check if m.callee has such a param: prepareNamedParam(n.sons[a]) if n.sons[a].sons[0].kind != nkIdent: - LocalError(n.sons[a].info, errNamedParamHasToBeIdent) + localError(n.sons[a].info, errNamedParamHasToBeIdent) m.state = csNoMatch return formal = getSymFromList(m.callee.n, n.sons[a].sons[0].ident, 1) @@ -1130,15 +1130,15 @@ proc matchesAux(c: PContext, n, nOrig: PNode, # no error message! m.state = csNoMatch return - if ContainsOrIncl(marker, formal.position): + if containsOrIncl(marker, formal.position): # already in namedParams: - LocalError(n.sons[a].info, errCannotBindXTwice, formal.name.s) + localError(n.sons[a].info, errCannotBindXTwice, formal.name.s) m.state = csNoMatch return m.baseTypeMatch = false n.sons[a].sons[1] = prepareOperand(c, formal.typ, n.sons[a].sons[1]) n.sons[a].typ = n.sons[a].sons[1].typ - var arg = ParamTypesMatch(c, m, formal.typ, n.sons[a].typ, + var arg = paramTypesMatch(c, m, formal.typ, n.sons[a].typ, n.sons[a].sons[1], nOrig.sons[a].sons[1]) if arg == nil: m.state = csNoMatch @@ -1168,7 +1168,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode, elif formal != nil: m.baseTypeMatch = false n.sons[a] = prepareOperand(c, formal.typ, n.sons[a]) - var arg = ParamTypesMatch(c, m, formal.typ, n.sons[a].typ, + var arg = paramTypesMatch(c, m, formal.typ, n.sons[a].typ, n.sons[a], nOrig.sons[a]) if (arg != nil) and m.baseTypeMatch and (container != nil): addSon(container, arg) @@ -1181,7 +1181,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode, return else: if m.callee.n.sons[f].kind != nkSym: - InternalError(n.sons[a].info, "matches") + internalError(n.sons[a].info, "matches") return formal = m.callee.n.sons[f].sym if containsOrIncl(marker, formal.position): diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 4f3172814..888f958d0 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -48,15 +48,15 @@ proc symToStr(s: PSym, isLocal: bool, section: string, li: TLineInfo): string = result.add(sep) result.add(toFullPath(li)) result.add(sep) - result.add($ToLinenumber(li)) + result.add($toLinenumber(li)) result.add(sep) - result.add($ToColumn(li)) + result.add($toColumn(li)) result.add(sep) when not defined(noDocgen): result.add(s.extractDocComment.escape) proc symToStr(s: PSym, isLocal: bool, section: string): string = - result = SymToStr(s, isLocal, section, s.info) + result = symToStr(s, isLocal, section, s.info) proc filterSym(s: PSym): bool {.inline.} = result = s.name.s[0] in lexer.SymChars and s.kind != skModule @@ -68,7 +68,7 @@ proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} = proc suggestField(c: PContext, s: PSym, outputs: var int) = if filterSym(s) and fieldVisible(c, s): - SuggestWriteln(SymToStr(s, isLocal=true, sectionSuggest)) + suggestWriteln(symToStr(s, isLocal=true, sectionSuggest)) inc outputs when not defined(nimhygiene): @@ -84,7 +84,7 @@ template wholeSymTab(cond, section: expr) {.immediate.} = for item in entries: let it {.inject.} = item if cond: - SuggestWriteln(SymToStr(it, isLocal = isLocal, section)) + suggestWriteln(symToStr(it, isLocal = isLocal, section)) inc outputs proc suggestSymList(c: PContext, list: PNode, outputs: var int) = @@ -144,7 +144,7 @@ proc suggestEverything(c: PContext, n: PNode, outputs: var int) = if scope == c.topLevelScope: isLocal = false for it in items(scope.symbols): if filterSym(it): - SuggestWriteln(SymToStr(it, isLocal = isLocal, sectionSuggest)) + suggestWriteln(symToStr(it, isLocal = isLocal, sectionSuggest)) inc outputs if scope == c.topLevelScope: break @@ -159,12 +159,12 @@ proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = # all symbols accessible, because we are in the current module: for it in items(c.topLevelScope.symbols): if filterSym(it): - SuggestWriteln(SymToStr(it, isLocal=false, sectionSuggest)) + suggestWriteln(symToStr(it, isLocal=false, sectionSuggest)) inc outputs else: for it in items(n.sym.tab): if filterSym(it): - SuggestWriteln(SymToStr(it, isLocal=false, sectionSuggest)) + suggestWriteln(symToStr(it, isLocal=false, sectionSuggest)) inc outputs else: # fallback: @@ -246,16 +246,16 @@ var proc findUsages(node: PNode, s: PSym) = if usageSym == nil and isTracked(node.info, s.name.s.len): usageSym = s - SuggestWriteln(SymToStr(s, isLocal=false, sectionUsage)) + suggestWriteln(symToStr(s, isLocal=false, sectionUsage)) elif s == usageSym: if lastLineInfo != node.info: - SuggestWriteln(SymToStr(s, isLocal=false, sectionUsage, node.info)) + suggestWriteln(symToStr(s, isLocal=false, sectionUsage, node.info)) lastLineInfo = node.info proc findDefinition(node: PNode, s: PSym) = if isTracked(node.info, s.name.s.len): - SuggestWriteln(SymToStr(s, isLocal=false, sectionDef)) - SuggestQuit() + suggestWriteln(symToStr(s, isLocal=false, sectionDef)) + suggestQuit() type TSourceMap = object @@ -281,7 +281,7 @@ proc resetSourceMap*(fileIdx: int32) = ensureIdx(gSourceMaps, fileIdx) gSourceMaps[fileIdx].lines = @[] -proc addToSourceMap(sym: Psym, info: TLineInfo) = +proc addToSourceMap(sym: PSym, info: TLineInfo) = ensureIdx(gSourceMaps, info.fileIndex) ensureSeq(gSourceMaps[info.fileIndex].lines) ensureIdx(gSourceMaps[info.fileIndex].lines, info.line) @@ -302,7 +302,7 @@ proc defFromLine(entries: var seq[TEntry], col: int32) = # that the first expr that ends after the cursor column is # the one we are looking for. if e.pos >= col: - SuggestWriteln(SymToStr(e.sym, isLocal=false, sectionDef)) + suggestWriteln(symToStr(e.sym, isLocal=false, sectionDef)) return proc defFromSourceMap*(i: TLineInfo) = @@ -324,8 +324,8 @@ proc suggestSym*(n: PNode, s: PSym) {.inline.} = proc markUsed(n: PNode, s: PSym) = incl(s.flags, sfUsed) if {sfDeprecated, sfError} * s.flags != {}: - 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 sfDeprecated in s.flags: message(n.info, warnDeprecated, s.name.s) + if sfError in s.flags: localError(n.info, errWrongSymbolX, s.name.s) suggestSym(n, s) proc useSym*(sym: PSym): PNode = @@ -369,7 +369,7 @@ proc suggestExpr*(c: PContext, node: PNode) = suggestCall(c, a, n, outputs) dec(c.InCompilesContext) - if outputs > 0 and optUsages notin gGlobalOptions: SuggestQuit() + if outputs > 0 and optUsages notin gGlobalOptions: suggestQuit() proc suggestStmt*(c: PContext, n: PNode) = suggestExpr(c, n) diff --git a/compiler/syntaxes.nim b/compiler/syntaxes.nim index 6970f0c44..3f2863c7f 100644 --- a/compiler/syntaxes.nim +++ b/compiler/syntaxes.nim @@ -43,14 +43,14 @@ proc parseTopLevelStmt*(p: var TParsers): PNode proc parseFile(fileIdx: int32): PNode = var p: TParsers - f: tfile + f: TFile let filename = fileIdx.toFullPath if not open(f, filename): rawMessage(errCannotOpenFile, filename) return - OpenParsers(p, fileIdx, LLStreamOpen(f)) - result = ParseAll(p) - CloseParsers(p) + openParsers(p, fileIdx, llStreamOpen(f)) + result = parseAll(p) + closeParsers(p) proc parseAll(p: var TParsers): PNode = case p.skin @@ -59,7 +59,7 @@ proc parseAll(p: var TParsers): PNode = of skinBraces: result = pbraces.parseAll(p.parser) of skinEndX: - InternalError("parser to implement") + internalError("parser to implement") result = ast.emptyNode # skinEndX: result := pendx.parseAll(p.parser); @@ -70,7 +70,7 @@ proc parseTopLevelStmt(p: var TParsers): PNode = of skinBraces: result = pbraces.parseTopLevelStmt(p.parser) of skinEndX: - InternalError("parser to implement") + internalError("parser to implement") result = ast.emptyNode #skinEndX: result := pendx.parseTopLevelStmt(p.parser); @@ -88,22 +88,22 @@ proc containsShebang(s: string, i: int): bool = proc parsePipe(filename: string, inputStream: PLLStream): PNode = result = ast.emptyNode - var s = LLStreamOpen(filename, fmRead) + var s = llStreamOpen(filename, fmRead) if s != nil: var line = newStringOfCap(80) - discard LLStreamReadLine(s, line) + discard llStreamReadLine(s, line) var i = utf8Bom(line) if containsShebang(line, i): - discard LLStreamReadLine(s, line) + discard llStreamReadLine(s, line) i = 0 if line[i] == '#' and line[i+1] == '!': inc(i, 2) while line[i] in WhiteSpace: inc(i) var q: TParser - openParser(q, filename, LLStreamOpen(substr(line, i))) + openParser(q, filename, llStreamOpen(substr(line, i))) result = parser.parseAll(q) closeParser(q) - LLStreamClose(s) + llStreamClose(s) proc getFilter(ident: PIdent): TFilterKind = for i in countup(low(TFilterKind), high(TFilterKind)): @@ -165,9 +165,9 @@ proc openParsers(p: var TParsers, fileIdx: int32, inputstream: PLLStream) = var s: PLLStream p.skin = skinStandard let filename = fileIdx.toFullPath - var pipe = parsePipe(filename, inputStream) - if pipe != nil: s = evalPipe(p, pipe, filename, inputStream) - else: s = inputStream + var pipe = parsePipe(filename, inputstream) + if pipe != nil: s = evalPipe(p, pipe, filename, inputstream) + else: s = inputstream case p.skin of skinStandard, skinBraces, skinEndX: parser.openParser(p.parser, fileIdx, s) diff --git a/compiler/transf.nim b/compiler/transf.nim index d6f54eddb..ea9036f1f 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -88,7 +88,7 @@ proc pushTransCon(c: PTransf, t: PTransCon) = c.transCon = t proc popTransCon(c: PTransf) = - if (c.transCon == nil): InternalError("popTransCon") + if (c.transCon == nil): internalError("popTransCon") c.transCon = c.transCon.next proc getCurrOwner(c: PTransf): PSym = @@ -126,7 +126,7 @@ proc transformSymAux(c: PTransf, n: PNode): PNode = else: b = n while tc != nil: - result = IdNodeTableGet(tc.mapping, b.sym) + result = idNodeTableGet(tc.mapping, b.sym) if result != nil: return tc = tc.next result = b @@ -141,14 +141,14 @@ proc transformVarSection(c: PTransf, v: PNode): PTransNode = if it.kind == nkCommentStmt: result[i] = PTransNode(it) 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) var newVar = copySym(it.sons[0].sym) incl(newVar.flags, sfFromGeneric) # fixes a strange bug for rodgen: #include(it.sons[0].sym.flags, sfFromGeneric); newVar.owner = getCurrOwner(c) - IdNodeTablePut(c.transCon.mapping, it.sons[0].sym, newSymNode(newVar)) + idNodeTablePut(c.transCon.mapping, it.sons[0].sym, newSymNode(newVar)) var defs = newTransNode(nkIdentDefs, it.info, 3) if importantComments(): # keep documentation information: @@ -159,14 +159,14 @@ proc transformVarSection(c: PTransf, v: PNode): PTransNode = result[i] = defs else: if it.kind != nkVarTuple: - InternalError(it.info, "transformVarSection: not nkVarTuple") + internalError(it.info, "transformVarSection: not nkVarTuple") var L = sonsLen(it) var defs = newTransNode(it.kind, it.info, L) for j in countup(0, L-3): var newVar = copySym(it.sons[j].sym) incl(newVar.flags, sfFromGeneric) newVar.owner = getCurrOwner(c) - IdNodeTablePut(c.transCon.mapping, it.sons[j].sym, newSymNode(newVar)) + idNodeTablePut(c.transCon.mapping, it.sons[j].sym, newSymNode(newVar)) defs[j] = newSymNode(newVar).PTransNode assert(it.sons[L-2].kind == nkEmpty) defs[L-1] = transform(c, it.sons[L-1]) @@ -179,9 +179,9 @@ proc transformConstSection(c: PTransf, v: PNode): PTransNode = if it.kind == nkCommentStmt: result[i] = PTransNode(it) else: - if it.kind != nkConstDef: InternalError(it.info, "transformConstSection") + if it.kind != nkConstDef: internalError(it.info, "transformConstSection") if it.sons[0].kind != nkSym: - InternalError(it.info, "transformConstSection") + internalError(it.info, "transformConstSection") if sfFakeConst in it[0].sym.flags: var b = newNodeI(nkConstDef, it.info) addSon(b, it[0]) @@ -429,7 +429,7 @@ proc findWrongOwners(c: PTransf, n: PNode) = proc transformFor(c: PTransf, n: PNode): PTransNode = # generate access statements for the parameters (unless they are constant) # put mapping from formal parameters to actual parameters - if n.kind != nkForStmt: InternalError(n.info, "transformFor") + if n.kind != nkForStmt: internalError(n.info, "transformFor") var length = sonsLen(n) var call = n.sons[length - 2] @@ -454,7 +454,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode = var newC = newTransCon(getCurrOwner(c)) newC.forStmt = n newC.forLoopBody = loopBody - if iter.kind != skIterator: InternalError(call.info, "transformFor") + if iter.kind != skIterator: internalError(call.info, "transformFor") # generate access statements for the parameters (unless they are constant) pushTransCon(c, newC) for i in countup(1, sonsLen(call) - 1): @@ -462,16 +462,16 @@ proc transformFor(c: PTransf, n: PNode): PTransNode = var formal = skipTypes(iter.typ, abstractInst).n.sons[i].sym case putArgInto(arg, formal.typ) of paDirectMapping: - IdNodeTablePut(newC.mapping, formal, arg) + idNodeTablePut(newC.mapping, formal, arg) of paFastAsgn: # generate a temporary and produce an assignment statement: var temp = newTemp(c, formal.typ, formal.info) addVar(v, newSymNode(temp)) add(result, newAsgnStmt(c, newSymNode(temp), arg.ptransNode)) - IdNodeTablePut(newC.mapping, formal, newSymNode(temp)) + idNodeTablePut(newC.mapping, formal, newSymNode(temp)) of paVarAsgn: assert(skipTypes(formal.typ, abstractInst).kind == tyVar) - IdNodeTablePut(newC.mapping, formal, arg) + idNodeTablePut(newC.mapping, formal, arg) # XXX BUG still not correct if the arg has a side effect! var body = iter.getBody pushInfoContext(n.info) diff --git a/compiler/treetab.nim b/compiler/treetab.nim index d28dcd236..cccb1096a 100644 --- a/compiler/treetab.nim +++ b/compiler/treetab.nim @@ -77,7 +77,7 @@ proc nodeTableRawInsert(data: var TNodePairSeq, k: THash, key: PNode, proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = var n: TNodePairSeq var k: THash = hashTree(key) - var index = NodeTableRawGet(t, k, key) + var index = nodeTableRawGet(t, k, key) if index >= 0: assert(t.data[index].key != nil) t.data[index].val = val diff --git a/compiler/types.nim b/compiler/types.nim index 3d040fdd5..5870ccacd 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -12,9 +12,9 @@ import intsets, ast, astalgo, trees, msgs, strutils, platform -proc firstOrd*(t: PType): biggestInt -proc lastOrd*(t: PType): biggestInt -proc lengthOrd*(t: PType): biggestInt +proc firstOrd*(t: PType): BiggestInt +proc lastOrd*(t: PType): BiggestInt +proc lengthOrd*(t: PType): BiggestInt type TPreferedDesc* = enum preferName, preferDesc, preferExported @@ -70,9 +70,9 @@ proc containsGarbageCollectedRef*(typ: PType): bool proc containsHiddenPointer*(typ: PType): bool proc canFormAcycle*(typ: PType): bool proc isCompatibleToCString*(a: PType): bool -proc getOrdValue*(n: PNode): biggestInt -proc computeSize*(typ: PType): biggestInt -proc getSize*(typ: PType): biggestInt +proc getOrdValue*(n: PNode): BiggestInt +proc computeSize*(typ: PType): BiggestInt +proc getSize*(typ: PType): BiggestInt proc isPureObject*(typ: PType): bool proc invalidGenericInst*(f: PType): bool # for debugging @@ -103,7 +103,7 @@ proc getOrdValue(n: PNode): biggestInt = of nkNilLit: result = 0 of nkHiddenStdConv: result = getOrdValue(n.sons[1]) else: - LocalError(n.info, errOrdinalTypeExpected) + localError(n.info, errOrdinalTypeExpected) result = 0 proc isIntLit*(t: PType): bool {.inline.} = @@ -184,7 +184,7 @@ proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, if t == nil: return result = iter(t, closure) if result: return - if not ContainsOrIncl(marker, t.id): + if not containsOrIncl(marker, t.id): case t.kind of tyGenericInst, tyGenericBody: result = iterOverTypeAux(marker, lastSon(t), iter, closure) @@ -195,7 +195,7 @@ proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, if t.n != nil: result = iterOverNode(marker, t.n, iter, closure) proc iterOverType(t: PType, iter: TTypeIter, closure: PObject): bool = - var marker = InitIntSet() + var marker = initIntSet() result = iterOverTypeAux(marker, t, iter, closure) proc searchTypeForAux(t: PType, predicate: TTypePredicate, @@ -228,8 +228,8 @@ proc searchTypeForAux(t: PType, predicate: TTypePredicate, # iterates over VALUE types! result = false if t == nil: return - if ContainsOrIncl(marker, t.id): return - result = Predicate(t) + if containsOrIncl(marker, t.id): return + result = predicate(t) if result: return case t.kind of tyObject: @@ -245,7 +245,7 @@ proc searchTypeForAux(t: PType, predicate: TTypePredicate, discard proc searchTypeFor(t: PType, predicate: TTypePredicate): bool = - var marker = InitIntSet() + var marker = initIntSet() result = searchTypeForAux(t, predicate, marker) proc isObjectPredicate(t: PType): bool = @@ -287,7 +287,7 @@ proc analyseObjectWithTypeFieldAux(t: PType, discard proc analyseObjectWithTypeField(t: PType): TTypeFieldResult = - var marker = InitIntSet() + var marker = initIntSet() result = analyseObjectWithTypeFieldAux(t, marker) proc isGCRef(t: PType): bool = @@ -337,7 +337,7 @@ proc canFormAcycleAux(marker: var TIntSet, typ: PType, startId: int): bool = case t.kind of tyTuple, tyObject, tyRef, tySequence, tyArray, tyArrayConstr, tyOpenArray, tyVarargs: - if not ContainsOrIncl(marker, t.id): + if not containsOrIncl(marker, t.id): for i in countup(0, sonsLen(t) - 1): result = canFormAcycleAux(marker, t.sons[i], startId) if result: return @@ -353,7 +353,7 @@ proc canFormAcycleAux(marker: var TIntSet, typ: PType, startId: int): bool = else: nil proc canFormAcycle(typ: PType): bool = - var marker = InitIntSet() + var marker = initIntSet() result = canFormAcycleAux(marker, typ, typ.id) proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator, @@ -377,14 +377,14 @@ proc mutateTypeAux(marker: var TIntSet, t: PType, iter: TTypeMutator, result = nil if t == nil: return result = iter(t, closure) - if not ContainsOrIncl(marker, t.id): + if not containsOrIncl(marker, t.id): for i in countup(0, sonsLen(t) - 1): result.sons[i] = mutateTypeAux(marker, result.sons[i], iter, closure) if t.n != nil: result.n = mutateNode(marker, t.n, iter, closure) assert(result != nil) proc mutateType(t: PType, iter: TTypeMutator, closure: PObject): PType = - var marker = InitIntSet() + var marker = initIntSet() result = mutateTypeAux(marker, t, iter, closure) proc valueToString(a: PNode): string = @@ -396,7 +396,7 @@ proc valueToString(a: PNode): string = proc rangeToStr(n: PNode): string = assert(n.kind == nkRange) - result = ValueToString(n.sons[0]) & ".." & ValueToString(n.sons[1]) + result = valueToString(n.sons[0]) & ".." & valueToString(n.sons[1]) const typeToStr: array[TTypeKind, string] = ["None", "bool", "Char", "empty", @@ -501,7 +501,7 @@ proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string = add(result, typeToString(t.sons[i])) if i < sonsLen(t) - 1: add(result, ", ") add(result, ')') - if t.sons[0] != nil: add(result, ": " & TypeToString(t.sons[0])) + if t.sons[0] != nil: add(result, ": " & typeToString(t.sons[0])) var prag: string if t.callConv != ccDefault: prag = CallingConvToStr[t.callConv] else: prag = "" @@ -625,9 +625,9 @@ proc initSameTypeClosure: TSameTypeClosure = discard proc containsOrIncl(c: var TSameTypeClosure, a, b: PType): bool = - result = not IsNil(c.s) and c.s.contains((a.id, b.id)) + result = not isNil(c.s) and c.s.contains((a.id, b.id)) if not result: - if IsNil(c.s): c.s = @[] + if isNil(c.s): c.s = @[] c.s.add((a.id, b.id)) proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool @@ -636,7 +636,7 @@ proc sameTypeOrNilAux(a, b: PType, c: var TSameTypeClosure): bool = result = true else: if a == nil or b == nil: result = false - else: result = SameTypeAux(a, b, c) + else: result = sameTypeAux(a, b, c) proc sameTypeOrNil*(a, b: PType, flags: TTypeCmpFlags = {}): bool = if a == b: @@ -646,15 +646,15 @@ proc sameTypeOrNil*(a, b: PType, flags: TTypeCmpFlags = {}): bool = else: var c = initSameTypeClosure() c.flags = flags - result = SameTypeAux(a, b, c) + result = sameTypeAux(a, b, c) proc equalParam(a, b: PSym): TParamsEquality = - if SameTypeOrNil(a.typ, b.typ, {TypeDescExactMatch}) and - ExprStructuralEquivalent(a.constraint, b.constraint): + if sameTypeOrNil(a.typ, b.typ, {TypeDescExactMatch}) and + exprStructuralEquivalent(a.constraint, b.constraint): if a.ast == b.ast: result = paramsEqual elif a.ast != nil and b.ast != nil: - if ExprStructuralEquivalent(a.ast, b.ast): result = paramsEqual + if exprStructuralEquivalent(a.ast, b.ast): result = paramsEqual else: result = paramsIncompatible elif a.ast != nil: result = paramsEqual @@ -685,7 +685,7 @@ proc equalParams(a, b: PNode): TParamsEquality = return paramsNotEqual # paramsIncompatible; # continue traversal! If not equal, we can return immediately; else # it stays incompatible - if not SameTypeOrNil(a.sons[0].typ, b.sons[0].typ, {TypeDescExactMatch}): + if not sameTypeOrNil(a.sons[0].typ, b.sons[0].typ, {TypeDescExactMatch}): if (a.sons[0].typ == nil) or (b.sons[0].typ == nil): result = paramsNotEqual # one proc has a result, the other not is OK else: @@ -701,8 +701,8 @@ proc sameLiteral(x, y: PNode): bool = else: assert(false) proc sameRanges(a, b: PNode): bool = - result = SameLiteral(a.sons[0], b.sons[0]) and - SameLiteral(a.sons[1], b.sons[1]) + result = sameLiteral(a.sons[0], b.sons[0]) and + sameLiteral(a.sons[1], b.sons[1]) proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = # two tuples are equivalent iff the names, types and positions are the same; @@ -717,7 +717,7 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = x = skipTypes(x, {tyRange}) y = skipTypes(y, {tyRange}) - result = SameTypeAux(x, y, c) + result = sameTypeAux(x, y, c) if not result: return if a.n != nil and b.n != nil and IgnoreTupleFields notin c.flags: for i in countup(0, sonsLen(a.n) - 1): @@ -727,12 +727,12 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = var y = b.n.sons[i].sym result = x.name.id == y.name.id if not result: break - else: InternalError(a.n.info, "sameTuple") + else: internalError(a.n.info, "sameTuple") else: result = false template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = - if tfFromGeneric notin a.flags + b.flags: + if tfFromGeneric not_in a.flags + b.flags: # fast case: id comparison suffices: result = a.id == b.id else: @@ -966,7 +966,7 @@ proc matchType*(a: PType, pattern: openArray[tuple[k:TTypeKind, i:int]], var a = a for k, i in pattern.items: if a.kind != k: return false - if i >= a.sonslen or a.sons[i] == nil: return false + if i >= a.sonsLen or a.sons[i] == nil: return false a = a.sons[i] result = a.kind == last @@ -986,7 +986,7 @@ proc matchTypeClass*(bindings: var TIdTable, typeClass, t: PType): bool = of tyGenericBody: if t.kind == tyGenericInst and t.sons[0] == req: match = true - IdTablePut(bindings, typeClass, t) + idTablePut(bindings, typeClass, t) of tyTypeClass: match = matchTypeClass(bindings, req, t) elif t.kind == tyTypeClass: @@ -1005,7 +1005,7 @@ proc matchTypeClass*(bindings: var TIdTable, typeClass, t: PType): bool = # or none of them matched. result = if tfAny in typeClass.flags: false else: true if result == true: - IdTablePut(bindings, typeClass, t) + idTablePut(bindings, typeClass, t) proc matchTypeClass*(typeClass, typ: PType): bool = var bindings: TIdTable @@ -1019,7 +1019,7 @@ proc typeAllowedAux(marker: var TIntSet, typ: PType, kind: TSymKind, # evaluation if something is wrong: result = true if typ == nil: return - if ContainsOrIncl(marker, typ.id): return + if containsOrIncl(marker, typ.id): return var t = skipTypes(typ, abstractInst-{tyTypeDesc}) case t.kind of tyVar: @@ -1089,15 +1089,15 @@ proc typeAllowedAux(marker: var TIntSet, typ: PType, kind: TSymKind, result = true proc typeAllowed(t: PType, kind: TSymKind): bool = - var marker = InitIntSet() + var marker = initIntSet() result = typeAllowedAux(marker, t, kind, {}) -proc align(address, alignment: biggestInt): biggestInt = +proc align(address, alignment: BiggestInt): BiggestInt = result = (address + (alignment - 1)) and not (alignment - 1) -proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt -proc computeRecSizeAux(n: PNode, a, currOffset: var biggestInt): biggestInt = - var maxAlign, maxSize, b, res: biggestInt +proc computeSizeAux(typ: PType, a: var BiggestInt): BiggestInt +proc computeRecSizeAux(n: PNode, a, currOffset: var BiggestInt): BiggestInt = + var maxAlign, maxSize, b, res: BiggestInt case n.kind of nkRecCase: assert(n.sons[0].kind == nkSym) @@ -1129,12 +1129,12 @@ proc computeRecSizeAux(n: PNode, a, currOffset: var biggestInt): biggestInt = result = computeSizeAux(n.sym.typ, a) n.sym.offset = int(currOffset) else: - InternalError("computeRecSizeAux()") + internalError("computeRecSizeAux()") a = 1 result = - 1 proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = - var res, maxAlign, length, currOffset: biggestInt + var res, maxAlign, length, currOffset: BiggestInt if typ.size == - 2: # we are already computing the size of the type # --> illegal recursion in type @@ -1147,7 +1147,7 @@ proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = typ.size = - 2 # mark as being computed case typ.kind of tyInt, tyUInt: - result = IntSize + result = intSize a = result of tyInt8, tyUInt8, tyBool, tyChar: result = 1 @@ -1236,7 +1236,7 @@ proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = typ.align = int(a) proc computeSize(typ: PType): biggestInt = - var a: biggestInt = 1 + var a: BiggestInt = 1 result = computeSizeAux(typ, a) proc getReturnType*(s: PSym): PType = @@ -1246,7 +1246,7 @@ proc getReturnType*(s: PSym): PType = proc getSize(typ: PType): biggestInt = result = computeSize(typ) - if result < 0: InternalError("getSize: " & $typ.kind) + if result < 0: internalError("getSize: " & $typ.kind) proc containsGenericTypeIter(t: PType, closure: PObject): bool = @@ -1300,7 +1300,7 @@ proc compatibleEffects*(formal, actual: PType): bool = # if 'se.kind == nkArgList' it is no formal type really, but a # computed effect and as such no spec: # 'r.msgHandler = if isNil(msgHandler): defaultMsgHandler else: msgHandler' - if not IsNil(se) and se.kind != nkArgList: + if not isNil(se) and se.kind != nkArgList: # spec requires some exception or tag, but we don't know anything: if real.len == 0: return false result = compatibleEffectsAux(se, real.sons[exceptionEffects]) diff --git a/compiler/vm.nim b/compiler/vm.nim index a89ad74bd..3d76638bc 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -40,7 +40,7 @@ proc stackTraceAux(c: PCtx; x: PStackFrame; pc: int) = var info = c.debug[pc] # we now use the same format as in system/except.nim var s = toFilename(info) - var line = toLineNumber(info) + var line = toLinenumber(info) if line > 0: add(s, '(') add(s, $line) @@ -48,7 +48,7 @@ proc stackTraceAux(c: PCtx; x: PStackFrame; pc: int) = if x.prc != nil: for k in 1..max(1, 25-s.len): add(s, ' ') add(s, x.prc.name.s) - MsgWriteln(s) + msgWriteln(s) proc stackTrace(c: PCtx, tos: PStackFrame, pc: int, msg: TMsgKind, arg = "") = @@ -716,7 +716,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = of opcFinallyEnd: if c.currentExceptionA != nil: # we are in a cleanup run: - pc = cleanupOnException(c, tos, regs)-1 + pc = cleanUpOnException(c, tos, regs)-1 if pc < 0: bailOut(c, tos) return @@ -725,7 +725,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = c.currentExceptionA = raised c.exceptionInstr = pc # -1 because of the following 'inc' - pc = cleanupOnException(c, tos, regs) - 1 + pc = cleanUpOnException(c, tos, regs) - 1 if pc < 0: bailOut(c, tos) return @@ -776,7 +776,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = regs[ra].strVal = renderTree(regs[rb].skipMeta, {renderNoComments}) of opcQuit: if c.mode in {emRepl, emStaticExpr, emStaticStmt}: - Message(c.debug[pc], hintQuitCalled) + message(c.debug[pc], hintQuitCalled) quit(int(getOrdValue(regs[ra]))) else: return nil @@ -866,7 +866,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = else: stackTrace(c, tos, pc, errFieldXNotFound, "ident") of opcNGetType: - InternalError(c.debug[pc], "unknown opcode " & $instr.opcode) + internalError(c.debug[pc], "unknown opcode " & $instr.opcode) of opcNStrVal: decodeB(nkStrLit) let a = regs[rb].uast @@ -882,16 +882,16 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = of opcNError: stackTrace(c, tos, pc, errUser, regs[ra].strVal) of opcNWarning: - Message(c.debug[pc], warnUser, regs[ra].strVal) + message(c.debug[pc], warnUser, regs[ra].strVal) of opcNHint: - Message(c.debug[pc], hintUser, regs[ra].strVal) + message(c.debug[pc], hintUser, regs[ra].strVal) of opcParseExprToAst: decodeB(nkMetaNode) # c.debug[pc].line.int - countLines(regs[rb].strVal) ? let ast = parseString(regs[rb].strVal, c.debug[pc].toFilename, c.debug[pc].line.int) if sonsLen(ast) != 1: - GlobalError(c.debug[pc], errExprExpected, "multiple statements") + globalError(c.debug[pc], errExprExpected, "multiple statements") setMeta(regs[ra], ast.sons[0]) of opcParseStmtToAst: decodeB(nkMetaNode) @@ -1137,7 +1137,7 @@ proc evalMacroCall*(module: PSym, n, nOrig: PNode, sym: PSym): PNode = # XXX GlobalError() is ugly here, but I don't know a better solution for now inc(evalMacroCounter) if evalMacroCounter > 100: - GlobalError(n.info, errTemplateInstantiationTooNested) + globalError(n.info, errTemplateInstantiationTooNested) setupGlobalCtx(module) var c = globalCtx @@ -1161,7 +1161,7 @@ proc evalMacroCall*(module: PSym, n, nOrig: PNode, sym: PSym): PNode = # temporary storage: for i in L .. = high(TRegister): - InternalError("cannot generate code; too many registers required") + internalError("cannot generate code; too many registers required") result = TRegister(c.maxSlots) inc c.maxSlots, n for k in result .. result+n-1: c.slots[k] = (inUse: true, kind: kind) @@ -257,7 +257,7 @@ proc genBreak(c: PCtx; n: PNode) = if c.prc.blocks[i].label == n.sons[0].sym: c.prc.blocks[i].fixups.add L1 return - InternalError(n.info, "cannot find 'break' target") + internalError(n.info, "cannot find 'break' target") else: c.prc.blocks[c.prc.blocks.high].fixups.add L1 @@ -338,7 +338,7 @@ proc genLiteral(c: PCtx; n: PNode): int = proc unused(n: PNode; x: TDest) {.inline.} = if x >= 0: #debug(n) - InternalError(n.info, "not unused") + internalError(n.info, "not unused") proc genCase(c: PCtx; n: PNode; dest: var TDest) = # if (!expr1) goto L1; @@ -709,7 +709,7 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = c.freeTemp(tmp) c.freeTemp(idx) of mSizeOf: - GlobalError(n.info, errCannotInterpretNodeX, renderTree(n)) + globalError(n.info, errCannotInterpretNodeX, renderTree(n)) of mHigh: if dest < 0: dest = c.getTemp(n.typ) let tmp = c.genx(n.sons[1]) @@ -828,7 +828,7 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = globalError(n.info, "expandToAst requires a call expression") else: # mGCref, mGCunref, - InternalError(n.info, "cannot generate code for: " & $m) + internalError(n.info, "cannot generate code for: " & $m) const atomicTypes = {tyBool, tyChar, @@ -1027,7 +1027,7 @@ proc getNullValueAux(obj: PNode, result: PNode) = getNullValueAux(lastSon(obj.sons[i]), result) of nkSym: addSon(result, getNullValue(obj.sym.typ, result.info)) - else: InternalError(result.info, "getNullValueAux") + else: internalError(result.info, "getNullValueAux") proc getNullValue(typ: PType, info: TLineInfo): PNode = var t = skipTypes(typ, abstractRange-{tyTypeDesc}) @@ -1038,7 +1038,7 @@ proc getNullValue(typ: PType, info: TLineInfo): PNode = of tyUInt..tyUInt64: result = newNodeIT(nkUIntLit, info, t) of tyFloat..tyFloat128: - result = newNodeIt(nkFloatLit, info, t) + result = newNodeIT(nkFloatLit, info, t) of tyVar, tyPointer, tyPtr, tyCString, tySequence, tyString, tyExpr, tyStmt, tyTypeDesc, tyRef: result = newNodeIT(nkNilLit, info, t) @@ -1067,7 +1067,7 @@ proc getNullValue(typ: PType, info: TLineInfo): PNode = addSon(result, getNullValue(t.sons[i], info)) of tySet: result = newNodeIT(nkCurly, info, t) - else: InternalError("getNullValue: " & $t.kind) + else: internalError("getNullValue: " & $t.kind) proc setSlot(c: PCtx; v: PSym) = # XXX generate type initialization here? @@ -1214,13 +1214,13 @@ proc gen(c: PCtx; n: PNode; dest: var TDest) = of skField: InternalAssert dest < 0 if s.position > high(dest): - InternalError(n.info, + internalError(n.info, "too large offset! cannot generate code for: " & s.name.s) dest = s.position of skType: genTypeLit(c, s.typ, dest) else: - InternalError(n.info, "cannot generate code for: " & s.name.s) + internalError(n.info, "cannot generate code for: " & s.name.s) of nkCallKinds: if n.sons[0].kind == nkSym and n.sons[0].sym.magic != mNone: genMagic(c, n, dest) @@ -1309,7 +1309,7 @@ proc gen(c: PCtx; n: PNode; dest: var TDest) = else: localError(n.info, errGenerated, "VM is not allowed to 'cast'") else: - InternalError n.info, "too implement " & $n.kind + internalError n.info, "too implement " & $n.kind proc removeLastEof(c: PCtx) = let last = c.code.len-1 diff --git a/compiler/wordrecg.nim b/compiler/wordrecg.nim index 5f0e5be94..837bb4f50 100644 --- a/compiler/wordrecg.nim +++ b/compiler/wordrecg.nim @@ -166,7 +166,7 @@ const "inout", "bycopy", "byref", "oneway", ] -proc findStr*(a: openarray[string], s: string): int = +proc findStr*(a: openArray[string], s: string): int = for i in countup(low(a), high(a)): if cmpIgnoreStyle(a[i], s) == 0: return i @@ -176,7 +176,7 @@ proc whichKeyword*(id: PIdent): TSpecialWord = if id.id < 0: result = wInvalid else: result = TSpecialWord(id.id) -proc whichKeyword*(id: String): TSpecialWord = +proc whichKeyword*(id: string): TSpecialWord = result = whichKeyword(getIdent(id)) proc initSpecials() = diff --git a/lib/packages/docutils/highlite.nim b/lib/packages/docutils/highlite.nim index 4bfdf5e58..737780a12 100644 --- a/lib/packages/docutils/highlite.nim +++ b/lib/packages/docutils/highlite.nim @@ -321,7 +321,7 @@ proc generalStrLit(g: var TGeneralTokenizer, position: int): int = inc(pos) result = pos -proc isKeyword(x: openarray[string], y: string): int = +proc isKeyword(x: openArray[string], y: string): int = var a = 0 var b = len(x) - 1 while a <= b: @@ -335,7 +335,7 @@ proc isKeyword(x: openarray[string], y: string): int = return mid result = - 1 -proc isKeywordIgnoreCase(x: openarray[string], y: string): int = +proc isKeywordIgnoreCase(x: openArray[string], y: string): int = var a = 0 var b = len(x) - 1 while a <= b: @@ -354,7 +354,7 @@ type hasPreprocessor, hasNestedComments TTokenizerFlags = set[TTokenizerFlag] -proc clikeNextToken(g: var TGeneralTokenizer, keywords: openarray[string], +proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string], flags: TTokenizerFlags) = const hexChars = {'0'..'9', 'A'..'F', 'a'..'f'} diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim index 6dd407155..316476ce0 100644 --- a/lib/packages/docutils/rst.nim +++ b/lib/packages/docutils/rst.nim @@ -58,10 +58,10 @@ const mwUnsupportedLanguage: "language '$1' not supported" ] -proc rstnodeToRefname*(n: PRstNode): string -proc addNodes*(n: PRstNode): string -proc getFieldValue*(n: PRstNode, fieldname: string): string -proc getArgument*(n: PRstNode): string +proc rstnodeToRefname*(n: PRSTNode): string +proc addNodes*(n: PRSTNode): string +proc getFieldValue*(n: PRSTNode, fieldname: string): string +proc getArgument*(n: PRSTNode): string # ----------------------------- scanner part -------------------------------- @@ -242,7 +242,7 @@ proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int = inc(result) while true: inc(length) - setlen(tokens, length) + setLen(tokens, length) rawGetTok(L, tokens[length - 1]) if tokens[length - 1].kind == tkEof: break if tokens[0].kind == tkWhite: @@ -254,7 +254,7 @@ type TLevelMap = array[Char, int] TSubstitution{.final.} = object key*: string - value*: PRstNode + value*: PRSTNode TSharedState {.final.} = object options: TRstParseOptions # parsing options @@ -294,11 +294,11 @@ proc whichMsgClass*(k: TMsgKind): TMsgClass = proc defaultMsgHandler*(filename: string, line, col: int, msgkind: TMsgKind, arg: string) {.procvar.} = - let mc = msgKind.whichMsgClass - let a = messages[msgKind] % arg + let mc = msgkind.whichMsgClass + let a = messages[msgkind] % arg let message = "$1($2, $3) $4: $5" % [filename, $line, $col, $mc, a] if mc == mcError: raise newException(EParseError, message) - else: Writeln(stdout, message) + else: writeln(stdout, message) proc defaultFindFile*(filename: string): string {.procvar.} = if existsFile(filename): result = filename @@ -339,7 +339,7 @@ proc pushInd(p: var TRstParser, ind: int) = add(p.indentStack, ind) proc popInd(p: var TRstParser) = - if len(p.indentStack) > 1: setlen(p.indentStack, len(p.indentStack) - 1) + if len(p.indentStack) > 1: setLen(p.indentStack, len(p.indentStack) - 1) proc initParser(p: var TRstParser, sharedState: PSharedState) = p.indentStack = @[0] @@ -351,7 +351,7 @@ proc initParser(p: var TRstParser, sharedState: PSharedState) = p.line = 1 p.s = sharedState -proc addNodesAux(n: PRstNode, result: var string) = +proc addNodesAux(n: PRSTNode, result: var string) = if n.kind == rnLeaf: add(result, n.text) else: @@ -361,7 +361,7 @@ proc addNodes(n: PRstNode): string = 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: for i in countup(0, len(n.text) - 1): case n.text[i] @@ -391,7 +391,7 @@ proc rstnodeToRefname(n: PRstNode): string = var b = false rstnodeToRefnameAux(n, result, b) -proc findSub(p: var TRstParser, n: PRstNode): int = +proc findSub(p: var TRstParser, n: PRSTNode): int = var key = addNodes(n) # the spec says: if no exact match, try one without case distinction: for i in countup(0, high(p.s.subs)): @@ -402,17 +402,17 @@ proc findSub(p: var TRstParser, n: PRstNode): int = return i 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) for i in countup(0, length - 1): if key == p.s.subs[i].key: p.s.subs[i].value = value return - setlen(p.s.subs, length + 1) + setLen(p.s.subs, length + 1) p.s.subs[length].key = key 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) for i in countup(0, length - 1): if key == p.s.refs[i].key: @@ -421,19 +421,19 @@ proc setRef(p: var TRstParser, key: string, value: PRstNode) = p.s.refs[i].value = value return - setlen(p.s.refs, length + 1) + setLen(p.s.refs, length + 1) p.s.refs[length].key = key 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)): if key == p.s.refs[i].key: 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) -proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = +proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode = var res = newRstNode(rnInner) while true: case p.tok[p.idx].kind @@ -451,7 +451,7 @@ proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = inc(p.idx) result = res -proc untilEol(p: var TRstParser): PRstNode = +proc untilEol(p: var TRstParser): PRSTNode = result = newRstNode(rnInner) while not (p.tok[p.idx].kind in {tkIndent, tkEof}): add(result, newLeaf(p)) @@ -479,7 +479,7 @@ proc isInlineMarkupEnd(p: TRstParser, markup: string): bool = result = false proc isInlineMarkupStart(p: TRstParser, markup: string): bool = - var d: Char + var d: char result = p.tok[p.idx].symbol == markup if not result: return # Rule 1: @@ -550,7 +550,7 @@ proc match(p: TRstParser, start: int, expr: string): bool = inc(i) result = true -proc fixupEmbeddedRef(n, a, b: PRstNode) = +proc fixupEmbeddedRef(n, a, b: PRSTNode) = var sep = - 1 for i in countdown(len(n) - 2, 0): 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(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 if isInlineMarkupEnd(p, "_"): inc(p.idx) @@ -613,9 +613,9 @@ proc matchVerbatim(p: TRstParser, start: int, expr: string): int = inc result 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 - for key, val in items(smilies): + for key, val in items(Smilies): let m = matchVerbatim(p, p.idx, key) if m > 0: p.idx = m @@ -634,7 +634,7 @@ proc isURL(p: TRstParser, i: int): bool = (p.tok[i+3].kind == tkWord) and (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 isURL(p, p.idx): var n = newRstNode(rnStandaloneHyperlink) @@ -654,7 +654,7 @@ proc parseURL(p: var TRstParser, father: PRstNode) = if p.tok[p.idx].symbol == "_": n = parsePostfix(p, 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) if p.tok[p.idx].symbol == "\\\\": add(father, newRstNode(rnLeaf, "\\")) @@ -692,7 +692,7 @@ when false: if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, +proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string, interpretBackslash: bool) = let line = p.tok[p.idx].line @@ -723,7 +723,7 @@ proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, inc(p.idx) else: rstMessage(p, meExpected, postfix, line, col) -proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = +proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode = var args = newRstNode(rnDirArg) if p.tok[p.idx].kind == tkWord: add(args, newLeaf(p)) @@ -753,7 +753,7 @@ proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = add(result, nil) add(result, lb) -proc parseInline(p: var TRstParser, father: PRstNode) = +proc parseInline(p: var TRstParser, father: PRSTNode) = case p.tok[p.idx].kind of tkPunct: if isInlineMarkupStart(p, "***"): @@ -797,7 +797,7 @@ proc parseInline(p: var TRstParser, father: PRstNode) = if n != nil: add(father, n) return - parseUrl(p, father) + parseURL(p, father) of tkAdornment, tkOther, tkWhite: if roSupportSmilies in p.s.options: let n = parseSmiley(p) @@ -828,7 +828,7 @@ proc getDirective(p: var TRstParser): string = else: result = "" -proc parseComment(p: var TRstParser): PRstNode = +proc parseComment(p: var TRstParser): PRSTNode = case p.tok[p.idx].kind of tkIndent, tkEof: if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent: @@ -863,20 +863,20 @@ proc getDirKind(s: string): TDirKind = if i >= 0: result = TDirKind(i) else: result = dkNone -proc parseLine(p: var TRstParser, father: PRstNode) = +proc parseLine(p: var TRstParser, father: PRSTNode) = while True: case p.tok[p.idx].kind of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father) else: break -proc parseUntilNewline(p: var TRstParser, father: PRstNode) = +proc parseUntilNewline(p: var TRstParser, father: PRSTNode) = while True: case p.tok[p.idx].kind of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father) of tkEof, tkIndent: break -proc parseSection(p: var TRstParser, result: PRstNode) -proc parseField(p: var TRstParser): PRstNode = +proc parseSection(p: var TRstParser, result: PRSTNode) +proc parseField(p: var TRstParser): PRSTNode = result = newRstNode(rnField) var col = p.tok[p.idx].col var fieldname = newRstNode(rnFieldname) @@ -892,7 +892,7 @@ proc parseField(p: var TRstParser): PRstNode = add(result, fieldname) add(result, fieldbody) -proc parseFields(p: var TRstParser): PRstNode = +proc parseFields(p: var TRstParser): PRSTNode = result = nil 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 @@ -926,8 +926,8 @@ proc getArgument(n: PRstNode): string = if n.sons[0] == nil: result = "" else: result = addNodes(n.sons[0]) -proc parseDotDot(p: var TRstParser): PRstNode -proc parseLiteralBlock(p: var TRstParser): PRstNode = +proc parseDotDot(p: var TRstParser): PRSTNode +proc parseLiteralBlock(p: var TRstParser): PRSTNode = result = newRstNode(rnLiteralBlock) var n = newRstNode(rnLeaf, "") if p.tok[p.idx].kind == tkIndent: @@ -953,7 +953,7 @@ proc parseLiteralBlock(p: var TRstParser): PRstNode = inc(p.idx) add(result, n) -proc getLevel(map: var TLevelMap, lvl: var int, c: Char): int = +proc getLevel(map: var TLevelMap, lvl: var int, c: char): int = if map[c] == 0: inc(lvl) map[c] = lvl @@ -999,7 +999,7 @@ proc whichSection(p: TRstParser): TRstNodeKind = elif match(p, p.idx + 1, "i"): result = rnOverline else: result = rnLeaf of tkPunct: - if match(p, tokenAfterNewLine(p), "ai"): + if match(p, tokenAfterNewline(p), "ai"): result = rnHeadline elif p.tok[p.idx].symbol == "::": result = rnLiteralBlock @@ -1026,13 +1026,13 @@ proc whichSection(p: TRstParser): TRstNodeKind = else: result = rnParagraph of tkWord, tkOther, tkWhite: - if match(p, tokenAfterNewLine(p), "ai"): result = rnHeadline + if match(p, tokenAfterNewline(p), "ai"): result = rnHeadline elif match(p, p.idx, "e) ") or match(p, p.idx, "e. "): result = rnEnumList elif isDefList(p): result = rnDefList else: result = rnParagraph else: result = rnLeaf -proc parseLineBlock(p: var TRstParser): PRstNode = +proc parseLineBlock(p: var TRstParser): PRSTNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var col = p.tok[p.idx].col @@ -1051,7 +1051,7 @@ proc parseLineBlock(p: var TRstParser): PRstNode = break popInd(p) -proc parseParagraph(p: var TRstParser, result: PRstNode) = +proc parseParagraph(p: var TRstParser, result: PRSTNode) = while True: case p.tok[p.idx].kind of tkIndent: @@ -1082,9 +1082,9 @@ proc parseParagraph(p: var TRstParser, result: PRstNode) = parseInline(p, result) else: break -proc parseHeadline(p: var TRstParser): PRstNode = +proc parseHeadline(p: var TRstParser): PRSTNode = result = newRstNode(rnHeadline) - parseUntilNewLine(p, result) + parseUntilNewline(p, result) assert(p.tok[p.idx].kind == tkIndent) assert(p.tok[p.idx + 1].kind == tkAdornment) var c = p.tok[p.idx + 1].symbol[0] @@ -1101,7 +1101,7 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = var L = 0 while true: inc(L) - setlen(cols, L) + setLen(cols, L) cols[L - 1] = tokEnd(p) assert(p.tok[p.idx].kind == tkAdornment) inc(p.idx) @@ -1112,16 +1112,16 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = # last column has no limit: 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 cols: TIntSeq row: seq[string] i, last, line: int - c: Char + c: char q: TRstParser - a, b: PRstNode + a, b: PRSTNode result = newRstNode(rnTable) cols = @[] row = @[] @@ -1135,7 +1135,7 @@ proc parseSimpleTable(p: var TRstParser): PRstNode = p.idx = last break getColumns(p, cols) - setlen(row, len(cols)) + setLen(row, len(cols)) if a != nil: for j in 0..len(a)-1: a.sons[j].kind = rnTableHeaderCell if p.tok[p.idx].kind == tkEof: break @@ -1167,13 +1167,13 @@ proc parseSimpleTable(p: var TRstParser): PRstNode = add(a, b) add(result, a) -proc parseTransition(p: var TRstParser): PRstNode = +proc parseTransition(p: var TRstParser): PRSTNode = result = newRstNode(rnTransition) 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] inc(p.idx, 2) result = newRstNode(rnOverline) @@ -1192,7 +1192,7 @@ proc parseOverline(p: var TRstParser): PRstNode = inc(p.idx) # XXX: check? if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseBulletList(p: var TRstParser): PRstNode = +proc parseBulletList(p: var TRstParser): PRSTNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var bullet = p.tok[p.idx].symbol @@ -1212,7 +1212,7 @@ proc parseBulletList(p: var TRstParser): PRstNode = break popInd(p) -proc parseOptionList(p: var TRstParser): PRstNode = +proc parseOptionList(p: var TRstParser): PRSTNode = result = newRstNode(rnOptionList) while true: if isOptionList(p): @@ -1241,9 +1241,9 @@ proc parseOptionList(p: var TRstParser): PRstNode = else: break -proc parseDefinitionList(p: var TRstParser): PRstNode = +proc parseDefinitionList(p: var TRstParser): PRSTNode = result = nil - var j = tokenAfterNewLine(p) - 1 + var j = tokenAfterNewline(p) - 1 if (j >= 1) and (p.tok[j].kind == tkIndent) and (p.tok[j].ival > currInd(p)) and (p.tok[j - 1].symbol != "::"): var col = p.tok[p.idx].col @@ -1269,7 +1269,7 @@ proc parseDefinitionList(p: var TRstParser): PRstNode = break if (p.tok[p.idx].kind == tkIndent) and (p.tok[p.idx].ival == col): inc(p.idx) - j = tokenAfterNewLine(p) - 1 + j = tokenAfterNewline(p) - 1 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: nil @@ -1277,7 +1277,7 @@ proc parseDefinitionList(p: var TRstParser): PRstNode = break if len(result) == 0: result = nil -proc parseEnumList(p: var TRstParser): PRstNode = +proc parseEnumList(p: var TRstParser): PRSTNode = const wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "] wildpos: array[0..2, int] = [1, 0, 0] @@ -1290,7 +1290,7 @@ proc parseEnumList(p: var TRstParser): PRstNode = var col = p.tok[p.idx].col result = newRstNode(rnEnumList) inc(p.idx, wildpos[w] + 3) - var j = tokenAfterNewLine(p) + var j = tokenAfterNewline(p) if (p.tok[j].col == p.tok[p.idx].col) or match(p, j, wildcards[w]): pushInd(p, p.tok[p.idx].col) while true: @@ -1307,7 +1307,7 @@ proc parseEnumList(p: var TRstParser): PRstNode = dec(p.idx, wildpos[w] + 3) result = nil -proc sonKind(father: PRstNode, i: int): TRstNodeKind = +proc sonKind(father: PRSTNode, i: int): TRstNodeKind = result = rnLeaf if i < len(father): result = father.sons[i].kind @@ -1328,7 +1328,7 @@ proc parseSection(p: var TRstParser, result: PRstNode) = leave = true break if leave or p.tok[p.idx].kind == tkEof: break - var a: PRstNode = nil + var a: PRSTNode = nil var k = whichSection(p) case k of rnLiteralBlock: @@ -1359,7 +1359,7 @@ proc parseSection(p: var TRstParser, result: PRstNode) = if sonKind(result, 0) == rnParagraph and sonKind(result, 1) != rnParagraph: result.sons[0].kind = rnInner -proc parseSectionWrapper(p: var TRstParser): PRstNode = +proc parseSectionWrapper(p: var TRstParser): PRSTNode = result = newRstNode(rnInner) parseSection(p, result) while (result.kind == rnInner) and (len(result) == 1): @@ -1385,12 +1385,12 @@ type TDirFlag = enum hasArg, hasOptions, argIsFile, argIsWord 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) - var args: PRstNode = nil - var options: PRstNode = nil + var args: PRSTNode = nil + var options: PRSTNode = nil if hasArg in flags: args = newRstNode(rnDirArg) if argIsFile in flags: @@ -1420,7 +1420,7 @@ proc indFollows(p: TRstParser): bool = result = p.tok[p.idx].kind == tkIndent and p.tok[p.idx].ival > currInd(p) proc parseDirective(p: var TRstParser, flags: TDirFlags, - contentParser: TSectionParser): PRstNode = + contentParser: TSectionParser): PRSTNode = result = parseDirective(p, flags) if not isNil(contentParser) and indFollows(p): pushInd(p, p.tok[p.idx].ival) @@ -1430,13 +1430,13 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags, else: add(result, nil) -proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRstNode = +proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRSTNode = if indFollows(p): pushInd(p, p.tok[p.idx].ival) result = contentParser(p) popInd(p) -proc dirInclude(p: var TRstParser): PRstNode = +proc dirInclude(p: var TRstParser): PRSTNode = # #The following options are recognized: # @@ -1474,7 +1474,7 @@ proc dirInclude(p: var TRstParser): PRstNode = # InternalError("Too many binary zeros in include file") result = parseDoc(q) -proc dirCodeBlock(p: var TRstParser): PRstNode = +proc dirCodeBlock(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg, hasOptions}, parseLiteralBlock) var filename = strip(getFieldValue(result, "file")) if filename != "": @@ -1485,34 +1485,34 @@ proc dirCodeBlock(p: var TRstParser): PRstNode = result.sons[2] = n result.kind = rnCodeBlock -proc dirContainer(p: var TRstParser): PRstNode = +proc dirContainer(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, parseSectionWrapper) assert(result.kind == rnDirective) assert(len(result) == 3) result.kind = rnContainer -proc dirImage(p: var TRstParser): PRstNode = +proc dirImage(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil) result.kind = rnImage -proc dirFigure(p: var TRstParser): PRstNode = +proc dirFigure(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, parseSectionWrapper) result.kind = rnFigure -proc dirTitle(p: var TRstParser): PRstNode = +proc dirTitle(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnTitle -proc dirContents(p: var TRstParser): PRstNode = +proc dirContents(p: var TRstParser): PRSTNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnContents -proc dirIndex(p: var TRstParser): PRstNode = +proc dirIndex(p: var TRstParser): PRSTNode = result = parseDirective(p, {}, parseSectionWrapper) 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) = var filename = getFieldValue(result, "file") if filename.len > 0: @@ -1527,7 +1527,7 @@ proc dirRawAux(p: var TRstParser, result: var PRstNode, kind: TRstNodeKind, result.kind = kind add(result, parseDirBody(p, contentParser)) -proc dirRaw(p: var TRstParser): PRstNode = +proc dirRaw(p: var TRstParser): PRSTNode = # #The following options are recognized: # @@ -1581,7 +1581,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = # substitution definitions: inc(p.idx, 2) var a = getReferenceName(p, "|") - var b: PRstNode + var b: PRSTNode if p.tok[p.idx].kind == tkWhite: inc(p.idx) if cmpIgnoreStyle(p.tok[p.idx].symbol, "replace") == 0: inc(p.idx) @@ -1603,7 +1603,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = else: result = parseComment(p) -proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode = +proc resolveSubs(p: var TRstParser, n: PRSTNode): PRSTNode = result = n if n == nil: return case n.kind @@ -1634,7 +1634,7 @@ proc rstParse*(text, filename: string, line, column: int, hasToc: var bool, options: TRstParseOptions, findFile: TFindFileHandler = nil, - msgHandler: TMsgHandler = nil): PRstNode = + msgHandler: TMsgHandler = nil): PRSTNode = var p: TRstParser initParser(p, newSharedState(options, findFile, msgHandler)) p.filename = filename diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim index c2ff53b58..bb0b61889 100644 --- a/lib/packages/docutils/rstast.nim +++ b/lib/packages/docutils/rstast.nim @@ -62,8 +62,8 @@ type # leaf val - PRSTNode* = ref TRstNode ## an RST node - TRstNodeSeq* = seq[PRstNode] + PRSTNode* = ref TRSTNode ## an RST node + TRstNodeSeq* = seq[PRSTNode] TRSTNode* {.acyclic, final.} = object ## an RST node's description kind*: TRstNodeKind ## the node's kind text*: string ## valid for leafs in the AST; and the title of @@ -71,25 +71,25 @@ type level*: int ## valid for some node kinds sons*: TRstNodeSeq ## the node's sons -proc len*(n: PRstNode): int = +proc len*(n: PRSTNode): int = result = len(n.sons) -proc newRstNode*(kind: TRstNodeKind): PRstNode = +proc newRstNode*(kind: TRstNodeKind): PRSTNode = new(result) result.sons = @[] result.kind = kind -proc newRstNode*(kind: TRstNodeKind, s: string): PRstNode = +proc newRstNode*(kind: TRstNodeKind, s: string): PRSTNode = result = newRstNode(kind) result.text = s -proc lastSon*(n: PRstNode): PRstNode = +proc lastSon*(n: PRSTNode): PRSTNode = result = n.sons[len(n.sons)-1] -proc add*(father, son: PRstNode) = +proc add*(father, son: PRSTNode) = add(father.sons, son) -proc addIfNotNil*(father, son: PRstNode) = +proc addIfNotNil*(father, son: PRSTNode) = if son != nil: add(father, son) @@ -98,9 +98,9 @@ type indent: 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): renderRstToRst(d, n.sons[i], result) @@ -132,7 +132,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = var headline = "" renderRstSons(d, n, headline) - let lvl = repeatChar(headline.Len - d.indent, lvlToChar[n.level]) + let lvl = repeatChar(headline.len - d.indent, lvlToChar[n.level]) result.add(lvl) result.add("\n") result.add(headline) @@ -281,7 +281,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = else: 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`. var d: TRenderContext renderRstToRst(d, n, result) diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index 157e04d5b..f43c6e478 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -32,7 +32,7 @@ type outLatex # output is Latex TTocEntry{.final.} = object - n*: PRstNode + n*: PRSTNode refname*, header*: string TMetaEnum* = enum @@ -113,7 +113,7 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, proc writeIndexFile*(g: var TRstGenerator, outfile: string) = if g.theIndex.len > 0: writeFile(outfile, g.theIndex) -proc addXmlChar(dest: var string, c: Char) = +proc addXmlChar(dest: var string, c: char) = case c of '&': add(dest, "&") of '<': add(dest, "<") @@ -121,14 +121,14 @@ proc addXmlChar(dest: var string, c: Char) = of '\"': add(dest, """) else: add(dest, c) -proc addRtfChar(dest: var string, c: Char) = +proc addRtfChar(dest: var string, c: char) = case c of '{': add(dest, "\\{") of '}': add(dest, "\\}") of '\\': add(dest, "\\\\") else: add(dest, c) -proc addTexChar(dest: var string, c: Char) = +proc addTexChar(dest: var string, c: char) = case c of '_': add(dest, "\\_") of '{': add(dest, "\\symbol{123}") @@ -148,7 +148,7 @@ proc addTexChar(dest: var string, c: Char) = var splitter*: string = "" -proc escChar*(target: TOutputTarget, dest: var string, c: Char) {.inline.} = +proc escChar*(target: TOutputTarget, dest: var string, c: char) {.inline.} = case target of outHtml: addXmlChar(dest, c) of outLatex: addTexChar(dest, c) @@ -196,7 +196,7 @@ proc dispA(target: TOutputTarget, dest: var string, if target != outLatex: addf(dest, xml, 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. ## ## 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) ## 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) -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 = "" for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp) if d.target != outLatex: @@ -232,7 +232,7 @@ proc setIndexTerm*(d: var TRstGenerator, id, term: string) = d.theIndex.add(id) d.theIndex.add("\n") -proc hash(n: PRstNode): int = +proc hash(n: PRSTNode): int = if n.kind == rnLeaf: result = hash(n.text) elif n.len > 0: @@ -241,7 +241,7 @@ proc hash(n: PRstNode): int = result = result !& hash(n.sons[i]) 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)) var term = "" renderAux(d, n, term) @@ -314,13 +314,13 @@ 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 = "" for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) var refname = rstnodeToRefname(n) if d.hasToc: var length = len(d.tocPart) - setlen(d.tocPart, length + 1) + setLen(d.tocPart, length + 1) d.tocPart[length].refname = refname d.tocPart[length].n = n d.tocPart[length].header = tmp @@ -336,7 +336,7 @@ proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = $n.level, refname, tmp, $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: for i in countup(0, len(n)-1): 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: result.add(tmp) -proc renderImage(d: PDoc, n: PRstNode, result: var string) = +proc renderImage(d: PDoc, n: PRSTNode, result: var string) = var options = "" var s = getFieldValue(n, "scale") 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]) 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, """""", "\\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 var m = n.sons[2].sons[0] assert m.kind == rnLeaf @@ -433,7 +433,7 @@ proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = deinitGeneralTokenizer(g) dispA(d.target, result, "", "\n\\end{rstpre}\n") -proc renderContainer(d: PDoc, n: PRstNode, result: var string) = +proc renderContainer(d: PDoc, n: PRSTNode, result: var string) = var tmp = "" renderRstToOut(d, n.sons[2], tmp) var arg = strip(getArgument(n)) @@ -442,11 +442,11 @@ proc renderContainer(d: PDoc, n: PRstNode, result: var string) = else: dispA(d.target, result, "
$2
", "$2", [arg, tmp]) -proc texColumns(n: PRstNode): string = +proc texColumns(n: PRSTNode): string = result = "" 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 if d.target == outLatex: var fieldname = addNodes(n.sons[0]) @@ -456,7 +456,7 @@ proc renderField(d: PDoc, n: PRstNode, result: var string) = if d.meta[metaAuthor].len == 0: d.meta[metaAuthor] = fieldval b = true - elif cmpIgnoreStyle(fieldName, "version") == 0: + elif cmpIgnoreStyle(fieldname, "version") == 0: if d.meta[metaVersion].len == 0: d.meta[metaVersion] = fieldval b = true @@ -620,14 +620,14 @@ proc renderRstToOut(d: PDoc, n: PRstNode, result: var string) = # ----------------------------------------------------------------------------- -proc getVarIdx(varnames: openarray[string], id: string): int = +proc getVarIdx(varnames: openArray[string], id: string): int = for i in countup(0, high(varnames)): if cmpIgnoreStyle(varnames[i], id) == 0: return i result = -1 -proc formatNamedVars*(frmt: string, varnames: openarray[string], - varvalues: openarray[string]): string = +proc formatNamedVars*(frmt: string, varnames: openArray[string], + varvalues: openArray[string]): string = var i = 0 var L = len(frmt) result = "" @@ -646,7 +646,7 @@ proc formatNamedVars*(frmt: string, varnames: openarray[string], of '0'..'9': var j = 0 while true: - j = (j * 10) + Ord(frmt[i]) - ord('0') + j = (j * 10) + ord(frmt[i]) - ord('0') inc(i) if i > L-1 or frmt[i] notin {'0'..'9'}: break if j > high(varvalues) + 1: diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 8b44e69d9..df7ae6d17 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -34,7 +34,7 @@ proc reverse*[T](a: var openArray[T]) = ## reverses the array `a`. reverse(a, 0, a.high) -proc binarySearch*[T](a: openarray[T], key: T): int = +proc binarySearch*[T](a: openArray[T], key: T): int = ## binary search for `key` in `a`. Returns -1 if not found. var b = len(a) while result < b: @@ -79,7 +79,7 @@ proc merge[T](a, b: var openArray[T], lo, m, hi: int, inc(bb) inc(j) else: - CopyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1)) + copyMem(addr(b[0]), addr(a[j]), sizeof(T)*(m-j+1)) j = m+1 var i = 0 var k = lo diff --git a/lib/pure/collections/intsets.nim b/lib/pure/collections/intsets.nim index 367caf2e7..f1e67fc0e 100644 --- a/lib/pure/collections/intsets.nim +++ b/lib/pure/collections/intsets.nim @@ -71,8 +71,8 @@ proc intSetEnlarge(t: var TIntSet) = var oldMax = t.max t.max = ((t.max + 1) * 2) - 1 newSeq(n, t.max + 1) - for i in countup(0, oldmax): - if t.data[i] != nil: IntSetRawInsert(t, n, t.data[i]) + for i in countup(0, oldMax): + if t.data[i] != nil: intSetRawInsert(t, n, t.data[i]) swap(t.data, n) proc intSetPut(t: var TIntSet, key: int): PTrunk = @@ -81,7 +81,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk = if t.data[h].key == key: return t.data[h] h = nextTry(h, t.max) - if mustRehash(t.max + 1, t.counter): IntSetEnlarge(t) + if mustRehash(t.max + 1, t.counter): intSetEnlarge(t) inc(t.counter) h = key and t.max while t.data[h] != nil: h = nextTry(h, t.max) @@ -94,7 +94,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk = proc contains*(s: TIntSet, key: int): bool = ## returns true iff `key` is in `s`. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0 @@ -103,14 +103,14 @@ proc contains*(s: TIntSet, key: int): bool = proc incl*(s: var TIntSet, key: int) = ## includes an element `key` in `s`. - var t = IntSetPut(s, `shr`(key, TrunkShift)) + var t = intSetPut(s, `shr`(key, TrunkShift)) var u = key and TrunkMask t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] or `shl`(1, u and IntMask) proc excl*(s: var TIntSet, key: int) = ## excludes `key` from the set `s`. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] and @@ -119,7 +119,7 @@ proc excl*(s: var TIntSet, key: int) = proc containsOrIncl*(s: var TIntSet, key: int): bool = ## returns true if `s` contains `key`, otherwise `key` is included in `s` ## and false is returned. - var t = IntSetGet(s, `shr`(key, TrunkShift)) + var t = intSetGet(s, `shr`(key, TrunkShift)) if t != nil: var u = key and TrunkMask result = (t.bits[`shr`(u, IntShift)] and `shl`(1, u and IntMask)) != 0 diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index 3a009a8cb..3993f1ccc 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -136,7 +136,7 @@ proc delete*[T](s: var seq[T], first=0, last=0) = s[i].shallowCopy(s[j]) inc(i) inc(j) - setlen(s, newLen) + setLen(s, newLen) proc insert*[T](dest: var seq[T], src: openArray[T], pos=0) = ## Inserts items from `src` into `dest` at position `pos`. This modifies diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index ef3a529a1..4b9e8af0e 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -168,7 +168,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] = result.counter = 0 newSeq(result.data, initialSize) -proc toTable*[A, B](pairs: openarray[tuple[key: A, +proc toTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): TTable[A, B] = ## creates a new hash table that contains the given `pairs`. result = initTable[A, B](nextPowerOfTwo(pairs.len+10)) @@ -304,7 +304,7 @@ proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] = result.last = -1 newSeq(result.data, initialSize) -proc toOrderedTable*[A, B](pairs: openarray[tuple[key: A, +proc toOrderedTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): TOrderedTable[A, B] = ## creates a new ordered hash table that contains the given `pairs`. result = initOrderedTable[A, B](nextPowerOfTwo(pairs.len+10)) @@ -463,7 +463,7 @@ proc `$`*[A](t: TCountTable[A]): string = proc inc*[A](t: var TCountTable[A], key: A, val = 1) = ## increments `t[key]` by `val`. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: inc(t.data[index].val, val) else: diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 8a3135f89..1c0c59a7c 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -32,7 +32,7 @@ proc `!$`*(h: THash): THash {.inline.} = result = result xor (result shr 11) result = result +% result shl 15 -proc hashData*(Data: Pointer, Size: int): THash = +proc hashData*(Data: pointer, Size: int): THash = ## hashes an array of bytes of size `size` var h: THash = 0 when defined(js): @@ -41,17 +41,17 @@ proc hashData*(Data: Pointer, Size: int): THash = else: var p = cast[cstring](Data) var i = 0 - var s = size + var s = Size while s > 0: h = h !& ord(p[i]) - Inc(i) - Dec(s) + inc(i) + dec(s) result = !$h when defined(js): var objectID = 0 -proc hash*(x: Pointer): THash {.inline.} = +proc hash*(x: pointer): THash {.inline.} = ## efficient hashing of pointers when defined(js): asm """ @@ -126,6 +126,6 @@ proc hash*(x: float): THash {.inline.} = var y = x + 1.0 result = cast[ptr THash](addr(y))[] -proc hash*[A](x: openarray[A]): THash = +proc hash*[A](x: openArray[A]): THash = for it in items(x): result = result !& hash(it) result = !$result diff --git a/lib/pure/json.nim b/lib/pure/json.nim index df20bd852..f0d0aa0c0 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -135,7 +135,7 @@ proc str*(my: TJsonParser): string {.inline.} = assert(my.kind in {jsonInt, jsonFloat, jsonString}) return my.a -proc getInt*(my: TJsonParser): biggestInt {.inline.} = +proc getInt*(my: TJsonParser): BiggestInt {.inline.} = ## returns the number for the event: ``jsonInt`` assert(my.kind == jsonInt) return parseBiggestInt(my.a) @@ -173,7 +173,7 @@ proc errorMsgExpected*(my: TJsonParser, e: string): string = result = "$1($2, $3) Error: $4" % [ my.filename, $getLine(my), $getColumn(my), e & " expected"] -proc handleHexChar(c: Char, x: var int): bool = +proc handleHexChar(c: char, x: var int): bool = result = true # Success case c of '0'..'9': x = (x shl 4) or (ord(c) - ord('0')) @@ -286,7 +286,7 @@ proc skip(my: var TJsonParser) = else: break of ' ', '\t': - Inc(pos) + inc(pos) of '\c': pos = lexbase.HandleCR(my, pos) buf = my.buf @@ -517,7 +517,7 @@ type of JString: str*: string of JInt: - num*: biggestInt + num*: BiggestInt of JFloat: fnum*: float of JBool: @@ -535,30 +535,30 @@ proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} = ## raises an `EJsonParsingError` exception. raise newException(EJsonParsingError, errorMsgExpected(p, msg)) -proc newJString*(s: String): PJsonNode = +proc newJString*(s: string): PJsonNode = ## Creates a new `JString PJsonNode`. new(result) result.kind = JString result.str = s -proc newJStringMove(s: String): PJsonNode = +proc newJStringMove(s: string): PJsonNode = new(result) result.kind = JString shallowCopy(result.str, s) -proc newJInt*(n: biggestInt): PJsonNode = +proc newJInt*(n: BiggestInt): PJsonNode = ## Creates a new `JInt PJsonNode`. new(result) result.kind = JInt result.num = n -proc newJFloat*(n: Float): PJsonNode = +proc newJFloat*(n: float): PJsonNode = ## Creates a new `JFloat PJsonNode`. new(result) result.kind = JFloat result.fnum = n -proc newJBool*(b: Bool): PJsonNode = +proc newJBool*(b: bool): PJsonNode = ## Creates a new `JBool PJsonNode`. new(result) result.kind = JBool @@ -587,7 +587,7 @@ proc `%`*(s: string): PJsonNode = result.kind = JString result.str = s -proc `%`*(n: biggestInt): PJsonNode = +proc `%`*(n: BiggestInt): PJsonNode = ## Generic constructor for JSON data. Creates a new `JInt PJsonNode`. new(result) result.kind = JInt @@ -612,7 +612,7 @@ proc `%`*(keyVals: openArray[tuple[key: string, val: PJsonNode]]): PJsonNode = newSeq(result.fields, keyVals.len) for i, p in pairs(keyVals): result.fields[i] = p -proc `%`*(elements: openArray[PJSonNode]): PJsonNode = +proc `%`*(elements: openArray[PJsonNode]): PJsonNode = ## Generic constructor for JSON data. Creates a new `JArray PJsonNode` new(result) result.kind = JArray @@ -628,7 +628,7 @@ proc len*(n: PJsonNode): int = of JObject: result = n.fields.len else: nil -proc `[]`*(node: PJsonNode, name: String): PJsonNode = +proc `[]`*(node: PJsonNode, name: string): PJsonNode = ## Gets a field from a `JObject`. Returns nil if the key is not found. assert(node.kind == JObject) for key, item in items(node.fields): @@ -636,17 +636,17 @@ proc `[]`*(node: PJsonNode, name: String): PJsonNode = return item return nil -proc `[]`*(node: PJsonNode, index: Int): PJsonNode = +proc `[]`*(node: PJsonNode, index: int): PJsonNode = ## Gets the node at `index` in an Array. assert(node.kind == JArray) return node.elems[index] -proc hasKey*(node: PJsonNode, key: String): Bool = +proc hasKey*(node: PJsonNode, key: string): bool = ## Checks if `key` exists in `node`. assert(node.kind == JObject) for k, item in items(node.fields): 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` proc add*(father, child: PJsonNode) = @@ -661,7 +661,7 @@ proc add*(obj: PJsonNode, key: string, val: PJsonNode) = assert obj.kind == JObject obj.fields.add((key, val)) -proc `[]=`*(obj: PJsonNode, key: String, val: PJsonNode) = +proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) = ## Sets a field from a `JObject`. Performs a check for duplicate keys. assert(obj.kind == JObject) for i in 0..obj.fields.len-1: @@ -706,7 +706,7 @@ proc copy*(p: PJsonNode): PJsonNode = proc indent(s: var string, i: int) = s.add(repeatChar(i)) -proc newIndent(curr, indent: int, ml: bool): Int = +proc newIndent(curr, indent: int, ml: bool): int = if ml: return curr + indent else: return indent @@ -785,18 +785,18 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True, if lstArr: result.indent(currIndent) result.add("null") -proc pretty*(node: PJsonNode, indent = 2): String = +proc pretty*(node: PJsonNode, indent = 2): string = ## Converts `node` to its JSON Representation, with indentation and ## on multiple lines. result = "" toPretty(result, node, indent) -proc `$`*(node: PJsonNode): String = +proc `$`*(node: PJsonNode): string = ## Converts `node` to its JSON Representation on one line. result = "" 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. assert node.kind == JArray for i in items(node.elems): diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 3b3e3810b..243c7dc4a 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -91,7 +91,7 @@ proc fillBuffer(L: var TBaseLexer) = dec(s) # BUGFIX (valgrind) while true: assert(s < L.bufLen) - while (s >= 0) and not (L.buf[s] in NewLines): Dec(s) + while (s >= 0) and not (L.buf[s] in NewLines): dec(s) if s >= 0: # we found an appropriate character for a sentinel: L.sentinel = s @@ -163,5 +163,5 @@ proc getCurrentLine(L: TBaseLexer, marker: bool = true): string = inc(i) add(result, "\n") if marker: - add(result, RepeatChar(getColNumber(L, L.bufpos)) & "^\n") + add(result, repeatChar(getColNumber(L, L.bufpos)) & "^\n") diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 35b9607e0..062cfae25 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -94,7 +94,7 @@ proc nextPowerOfTwo*(x: int): int = result = result or (result shr 4) result = result or (result shr 2) result = result or (result shr 1) - Inc(result) + inc(result) proc countBits32*(n: int32): int {.noSideEffect.} = ## counts the set bits in `n`. @@ -103,17 +103,17 @@ proc countBits32*(n: int32): int {.noSideEffect.} = v = (v and 0x33333333'i32) +% ((v shr 2'i32) and 0x33333333'i32) result = ((v +% (v shr 4'i32) and 0xF0F0F0F'i32) *% 0x1010101'i32) shr 24'i32 -proc sum*[T](x: openarray[T]): T {.noSideEffect.} = +proc sum*[T](x: openArray[T]): T {.noSideEffect.} = ## computes the sum of the elements in `x`. ## If `x` is empty, 0 is returned. for i in items(x): result = result + i -proc mean*(x: openarray[float]): float {.noSideEffect.} = +proc mean*(x: openArray[float]): float {.noSideEffect.} = ## computes the mean of the elements in `x`. ## If `x` is empty, NaN is returned. result = sum(x) / toFloat(len(x)) -proc variance*(x: openarray[float]): float {.noSideEffect.} = +proc variance*(x: openArray[float]): float {.noSideEffect.} = ## computes the variance of the elements in `x`. ## If `x` is empty, NaN is returned. result = 0.0 diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index 9f4094b40..d8a27fde3 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -52,9 +52,9 @@ proc open*(filename: string, mode: TFileMode = fmRead, when defined(windows): template fail(errCode: TOSErrorCode, msg: expr) = rollback() - if result.fHandle != 0: discard CloseHandle(result.fHandle) - if result.mapHandle != 0: discard CloseHandle(result.mapHandle) - OSError(errCode) + if result.fHandle != 0: discard closeHandle(result.fHandle) + if result.mapHandle != 0: discard closeHandle(result.mapHandle) + osError(errCode) # return false #raise newException(EIO, msg) @@ -69,36 +69,36 @@ proc open*(filename: string, mode: TFileMode = fmRead, 0) when useWinUnicode: - result.fHandle = callCreateFile(CreateFileW, newWideCString(filename)) + result.fHandle = callCreateFile(createFileW, newWideCString(filename)) else: result.fHandle = callCreateFile(CreateFileA, filename) if result.fHandle == INVALID_HANDLE_VALUE: - fail(OSLastError(), "error opening file") + fail(osLastError(), "error opening file") if newFileSize != -1: var sizeHigh = int32(newFileSize shr 32) sizeLow = int32(newFileSize and 0xffffffff) - var status = SetFilePointer(result.fHandle, sizeLow, addr(sizeHigh), + var status = setFilePointer(result.fHandle, sizeLow, addr(sizeHigh), FILE_BEGIN) - let lastErr = OSLastError() + let lastErr = osLastError() if (status == INVALID_SET_FILE_POINTER and lastErr.int32 != NO_ERROR) or - (SetEndOfFile(result.fHandle) == 0): + (setEndOfFile(result.fHandle) == 0): fail(lastErr, "error setting file size") # since the strings are always 'nil', we simply always call # CreateFileMappingW which should be slightly faster anyway: - result.mapHandle = CreateFileMappingW( + result.mapHandle = createFileMappingW( result.fHandle, nil, if readonly: PAGE_READONLY else: PAGE_READWRITE, 0, 0, nil) if result.mapHandle == 0: - fail(OSLastError(), "error creating mapping") + fail(osLastError(), "error creating mapping") - result.mem = MapViewOfFileEx( + result.mem = mapViewOfFileEx( result.mapHandle, if readonly: FILE_MAP_READ else: FILE_MAP_WRITE, int32(offset shr 32), @@ -107,12 +107,12 @@ proc open*(filename: string, mode: TFileMode = fmRead, nil) if result.mem == nil: - fail(OSLastError(), "error mapping view") + fail(osLastError(), "error mapping view") var hi, low: int32 - low = GetFileSize(result.fHandle, addr(hi)) + low = getFileSize(result.fHandle, addr(hi)) if low == INVALID_FILE_SIZE: - fail(OSLastError(), "error getting file size") + fail(osLastError(), "error getting file size") else: var fileSize = (int64(hi) shr 32) or low if mappedSize != -1: result.size = min(fileSize, mappedSize).int @@ -170,10 +170,10 @@ proc close*(f: var TMemFile) = when defined(windows): if f.fHandle != INVALID_HANDLE_VALUE: - lastErr = OSLastError() - error = UnmapViewOfFile(f.mem) == 0 - error = (CloseHandle(f.mapHandle) == 0) or error - error = (CloseHandle(f.fHandle) == 0) or error + lastErr = osLastError() + error = unmapViewOfFile(f.mem) == 0 + error = (closeHandle(f.mapHandle) == 0) or error + error = (closeHandle(f.fHandle) == 0) or error else: if f.handle != 0: lastErr = OSLastError() @@ -189,5 +189,5 @@ proc close*(f: var TMemFile) = else: f.handle = 0 - if error: OSError(lastErr) + if error: osError(lastErr) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 761ed4bc4..fbca89f52 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -189,7 +189,7 @@ proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} = var err = getLastError() if err != 0'i32: when useWinUnicode: - var msgbuf: widecstring + var msgbuf: WideCString if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, err, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf @@ -237,7 +237,7 @@ proc osErrorMsg*(errorCode: TOSErrorCode): string = when defined(Windows): if errorCode != TOSErrorCode(0'i32): when useWinUnicode: - var msgbuf: widecstring + var msgbuf: WideCString if formatMessageW(0x00000100 or 0x00001000 or 0x00000200, nil, errorCode.int32, 0, addr(msgbuf), 0, nil) != 0'i32: result = $msgbuf @@ -282,7 +282,7 @@ proc osLastError*(): TOSErrorCode = ## immediately after an OS call fails. On POSIX systems this is not a problem. when defined(windows): - result = TOSErrorCode(GetLastError()) + result = TOSErrorCode(getLastError()) else: result = TOSErrorCode(errno) {.pop.} @@ -394,11 +394,11 @@ proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_mtime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime)) - findclose(h) + findClose(h) proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} = ## Returns the `file`'s last read or write access time. @@ -407,11 +407,11 @@ proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_atime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime)) - findclose(h) + findClose(h) proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} = ## Returns the `file`'s creation time. @@ -420,11 +420,11 @@ proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} = if stat(file, res) < 0'i32: osError(osLastError()) return res.st_ctime else: - var f: TWIN32_Find_Data + var f: TWIN32_FIND_DATA var h = findFirstFile(file, f) if h == -1'i32: osError(osLastError()) result = winTimeToUnixTime(rdFileTime(f.ftCreationTime)) - findclose(h) + findClose(h) proc fileNewer*(a, b: string): bool {.rtl, extern: "nos$1".} = ## Returns true if the file `a` is newer than file `b`, i.e. if `a`'s @@ -670,7 +670,7 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1", when defined(windows): const bufsize = 3072'i32 when useWinUnicode: - var unused: widecstring + var unused: WideCString var res = newWideCString("", bufsize div 2) var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused) if L <= 0'i32 or L >= bufsize: @@ -957,7 +957,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1", proc moveFile*(source, dest: string) {.rtl, extern: "nos$1", tags: [FReadIO, FWriteIO].} = ## Moves a file from `source` to `dest`. If this fails, `EOS` is raised. - if crename(source, dest) != 0'i32: + if c_rename(source, dest) != 0'i32: raise newException(EOS, $strerror(errno)) when not defined(ENOENT) and not defined(Windows): @@ -1005,7 +1005,7 @@ proc execShellCmd*(command: string): int {.rtl, extern: "nos$1", ## the process has finished. To execute a program without having a ## shell involved, use the `execProcess` proc of the `osproc` ## module. - result = csystem(command) + result = c_system(command) # Environment handling cannot be put into RTL, because the ``envPairs`` # iterator depends on ``environment``. @@ -1018,7 +1018,7 @@ when defined(windows): # because we support Windows GUI applications, things get really # messy here... when useWinUnicode: - proc strEnd(cstr: wideCString, c = 0'i32): wideCString {. + proc strEnd(cstr: WideCString, c = 0'i32): WideCString {. importc: "wcschr", header: "".} else: proc strEnd(cstr: cstring, c = 0'i32): cstring {. @@ -1035,9 +1035,9 @@ when defined(windows): while True: var eend = strEnd(e) add(environment, $e) - e = cast[wideCString](cast[TAddress](eend)+2) + e = cast[WideCString](cast[TAddress](eend)+2) if eend[1].int == 0: break - discard FreeEnvironmentStringsW(env) + discard freeEnvironmentStringsW(env) else: var env = getEnvironmentStringsA() @@ -1099,14 +1099,14 @@ proc getEnv*(key: string): TaintedString {.tags: [FReadEnv].} = if i >= 0: return TaintedString(substr(environment[i], find(environment[i], '=')+1)) else: - var env = cgetenv(key) + var env = c_getenv(key) if env == nil: return TaintedString("") result = TaintedString($env) proc existsEnv*(key: string): bool {.tags: [FReadEnv].} = ## Checks whether the environment variable named `key` exists. ## Returns true if it exists, false otherwise. - if cgetenv(key) != nil: return true + if c_getenv(key) != nil: return true else: return findEnvVar(key) >= 0 proc putEnv*(key, val: string) {.tags: [FWriteEnv].} = @@ -1152,15 +1152,15 @@ iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} = ## notation is supported. when defined(windows): var - f: TWin32FindData + f: TWIN32_FIND_DATA res: int - res = findfirstFile(pattern, f) + res = findFirstFile(pattern, f) if res != -1: while true: if not skipFindData(f): yield splitFile(pattern).dir / extractFilename(getFilename(f)) if findnextFile(res, f) == 0'i32: break - findclose(res) + findClose(res) else: # here we use glob var f: TGlob @@ -1205,8 +1205,8 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {. ## dirA/fileA1.txt ## dirA/fileA2.txt when defined(windows): - var f: TWIN32_Find_Data - var h = findfirstFile(dir / "*", f) + var f: TWIN32_FIND_DATA + var h = findFirstFile(dir / "*", f) if h != -1: while true: var k = pcFile @@ -1215,7 +1215,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {. k = pcDir yield (k, dir / extractFilename(getFilename(f))) if findnextFile(h, f) == 0'i32: break - findclose(h) + findClose(h) else: var d = openDir(dir) if d != nil: @@ -1553,7 +1553,7 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} = # /proc//file when defined(windows): when useWinUnicode: - var buf = cast[wideCString](alloc(256*2)) + var buf = cast[WideCString](alloc(256*2)) var len = getModuleFileNameW(0, buf, 256) result = buf$len else: @@ -1614,15 +1614,15 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [FTime].} = a.tv_nsec = (milsecs mod 1000) * 1000 * 1000 discard posix.nanosleep(a, b) -proc getFileSize*(file: string): biggestInt {.rtl, extern: "nos$1", +proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1", tags: [FReadIO].} = ## returns the file size of `file`. Can raise ``EOS``. when defined(windows): - var a: TWin32FindData - var resA = findfirstFile(file, a) + var a: TWIN32_FIND_DATA + var resA = findFirstFile(file, a) if resA == -1: osError(osLastError()) result = rdFileSize(a) - findclose(resA) + findClose(resA) else: var f: TFile if open(f, file): diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 1f04b7902..49b4b6fab 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -23,7 +23,7 @@ else: type TProcess = object of TObject when defined(windows): - FProcessHandle: Thandle + FProcessHandle: THandle inHandle, outHandle, errHandle: TFileHandle id: THandle else: @@ -108,7 +108,7 @@ proc execCmd*(command: string): int {.rtl, extern: "nosp$1", tags: [FExecIO].} proc startProcess*(command: string, workingDir: string = "", - args: openarray[string] = [], + args: openArray[string] = [], env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess {.rtl, extern: "nosp$1", tags: [FExecIO, FReadEnv].} @@ -219,7 +219,7 @@ proc countProcessors*(): int {.rtl, extern: "nosp$1".} = ## returns the numer of the processors/cores the machine has. ## Returns 0 if it cannot be detected. when defined(windows): - var x = getenv("NUMBER_OF_PROCESSORS") + var x = getEnv("NUMBER_OF_PROCESSORS") if x.len > 0: result = parseInt(x.string) elif defined(macosx) or defined(bsd): var @@ -358,7 +358,7 @@ when defined(Windows) and not defined(useNimRtl): result.readDataImpl = hsReadData result.writeDataImpl = hsWriteData - proc buildCommandLine(a: string, args: openarray[string]): cstring = + proc buildCommandLine(a: string, args: openArray[string]): cstring = var res = quoteShell(a) for i in 0..high(args): res.add(' ') @@ -384,11 +384,11 @@ when defined(Windows) and not defined(useNimRtl): # O_RDONLY {.importc: "_O_RDONLY", header: "".}: int proc createPipeHandles(Rdhandle, WrHandle: var THandle) = - var piInheritablePipe: TSecurityAttributes - piInheritablePipe.nlength = SizeOf(TSecurityAttributes).cint + var piInheritablePipe: TSECURITY_ATTRIBUTES + piInheritablePipe.nlength = sizeof(TSECURITY_ATTRIBUTES).cint piInheritablePipe.lpSecurityDescriptor = nil piInheritablePipe.Binherithandle = 1 - if createPipe(Rdhandle, Wrhandle, piInheritablePipe, 1024) == 0'i32: + if createPipe(Rdhandle, WrHandle, piInheritablePipe, 1024) == 0'i32: osError(osLastError()) proc fileClose(h: THandle) {.inline.} = @@ -400,28 +400,28 @@ when defined(Windows) and not defined(useNimRtl): env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess = var - si: TStartupInfo - procInfo: TProcessInformation + si: TSTARTUPINFO + procInfo: TPROCESS_INFORMATION success: int hi, ho, he: THandle new(result) - SI.cb = SizeOf(SI).cint + si.cb = sizeof(si).cint if poParentStreams notin options: - SI.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or - CreatePipeHandles(SI.hStdInput, HI) - CreatePipeHandles(HO, Si.hStdOutput) + si.dwFlags = STARTF_USESTDHANDLES # STARTF_USESHOWWINDOW or + createPipeHandles(si.hStdInput, hi) + createPipeHandles(ho, si.hStdOutput) if poStdErrToStdOut in options: - SI.hStdError = SI.hStdOutput - HE = HO + si.hStdError = si.hStdOutput + he = ho else: - CreatePipeHandles(HE, Si.hStdError) + createPipeHandles(he, si.hStdError) result.inHandle = TFileHandle(hi) result.outHandle = TFileHandle(ho) result.errHandle = TFileHandle(he) else: - SI.hStdError = GetStdHandle(STD_ERROR_HANDLE) - SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE) - SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE) + si.hStdError = getStdHandle(STD_ERROR_HANDLE) + si.hStdInput = getStdHandle(STD_INPUT_HANDLE) + si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE) result.inHandle = TFileHandle(si.hStdInput) result.outHandle = TFileHandle(si.hStdOutput) result.errHandle = TFileHandle(si.hStdError) @@ -442,17 +442,17 @@ when defined(Windows) and not defined(useNimRtl): var wwd = newWideCString(wd) success = winlean.CreateProcessW(nil, tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT, - ee, wwd, SI, ProcInfo) + ee, wwd, si, procInfo) else: success = winlean.CreateProcessA(nil, cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo) let lastError = osLastError() if poParentStreams notin options: - FileClose(si.hStdInput) - FileClose(si.hStdOutput) + fileClose(si.hStdInput) + fileClose(si.hStdOutput) if poStdErrToStdOut notin options: - FileClose(si.hStdError) + fileClose(si.hStdError) if e != nil: dealloc(e) dealloc(cmdl) @@ -471,10 +471,10 @@ when defined(Windows) and not defined(useNimRtl): discard CloseHandle(p.FProcessHandle) proc suspend(p: PProcess) = - discard SuspendThread(p.FProcessHandle) + discard suspendThread(p.FProcessHandle) proc resume(p: PProcess) = - discard ResumeThread(p.FProcessHandle) + discard resumeThread(p.FProcessHandle) proc running(p: PProcess): bool = var x = waitForSingleObject(p.FProcessHandle, 50) @@ -482,22 +482,22 @@ when defined(Windows) and not defined(useNimRtl): proc terminate(p: PProcess) = if running(p): - discard TerminateProcess(p.FProcessHandle, 0) + discard terminateProcess(p.FProcessHandle, 0) proc waitForExit(p: PProcess, timeout: int = -1): int = - discard WaitForSingleObject(p.FProcessHandle, timeout.int32) + discard waitForSingleObject(p.FProcessHandle, timeout.int32) var res: int32 - discard GetExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.FProcessHandle, res) result = res - discard CloseHandle(p.FProcessHandle) + discard closeHandle(p.FProcessHandle) proc peekExitCode(p: PProcess): int = var b = waitForSingleObject(p.FProcessHandle, 50) == WAIT_TIMEOUT if b: result = -1 else: var res: int32 - discard GetExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.FProcessHandle, res) return res proc inputStream(p: PProcess): PStream = @@ -511,32 +511,32 @@ when defined(Windows) and not defined(useNimRtl): proc execCmd(command: string): int = var - si: TStartupInfo - procInfo: TProcessInformation + si: TSTARTUPINFO + procInfo: TPROCESS_INFORMATION process: THandle L: int32 - SI.cb = SizeOf(SI).cint - SI.hStdError = GetStdHandle(STD_ERROR_HANDLE) - SI.hStdInput = GetStdHandle(STD_INPUT_HANDLE) - SI.hStdOutput = GetStdHandle(STD_OUTPUT_HANDLE) + si.cb = sizeof(si).cint + si.hStdError = getStdHandle(STD_ERROR_HANDLE) + si.hStdInput = getStdHandle(STD_INPUT_HANDLE) + si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE) when useWinUnicode: var c = newWideCString(command) var res = winlean.CreateProcessW(nil, c, nil, nil, 0, - NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) + NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo) else: var res = winlean.CreateProcessA(nil, command, nil, nil, 0, NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) if res == 0: osError(osLastError()) else: - Process = ProcInfo.hProcess - discard CloseHandle(ProcInfo.hThread) - if WaitForSingleObject(Process, INFINITE) != -1: - discard GetExitCodeProcess(Process, L) + process = procInfo.hProcess + discard closeHandle(procInfo.hThread) + if waitForSingleObject(process, INFINITE) != -1: + discard getExitCodeProcess(process, L) result = int(L) else: result = -1 - discard CloseHandle(Process) + discard closeHandle(process) proc select(readfds: var seq[PProcess], timeout = 500): int = assert readfds.len <= MAXIMUM_WAIT_OBJECTS diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim index fa704bbce..1be292af1 100644 --- a/lib/pure/parseopt.nim +++ b/lib/pure/parseopt.nim @@ -50,7 +50,7 @@ when defined(os.ParamCount): result.cmd = cmdline else: result.cmd = "" - for i in countup(1, ParamCount()): + for i in countup(1, paramCount()): result.cmd = result.cmd & quoteIfContainsWhite(paramStr(i).string) & ' ' result.kind = cmdEnd result.key = TaintedString"" @@ -94,8 +94,8 @@ proc next*(p: var TOptParser) {. var i = p.pos while p.cmd[i] in {'\x09', ' '}: inc(i) p.pos = i - setlen(p.key.string, 0) - setlen(p.val.string, 0) + setLen(p.key.string, 0) + setLen(p.val.string, 0) if p.inShortState: handleShortOption(p) return diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim index bccb274d6..6423b3ab0 100644 --- a/lib/pure/parseutils.nim +++ b/lib/pure/parseutils.nim @@ -189,7 +189,7 @@ proc captureBetween*(s: string, first: char, second = '\0', start = 0): string = {.push overflowChecks: on.} # this must be compiled with overflow checking turned on: -proc rawParseInt(s: string, b: var biggestInt, start = 0): int = +proc rawParseInt(s: string, b: var BiggestInt, start = 0): int = var sign: BiggestInt = -1 i = start @@ -207,12 +207,12 @@ proc rawParseInt(s: string, b: var biggestInt, start = 0): int = result = i - start {.pop.} # overflowChecks -proc parseBiggestInt*(s: string, number: var biggestInt, start = 0): int {. +proc parseBiggestInt*(s: string, number: var BiggestInt, start = 0): int {. rtl, extern: "npuParseBiggestInt", noSideEffect.} = ## parses an integer starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there is no integer. ## `EOverflow` is raised if an overflow occurs. - var res: biggestInt + var res: BiggestInt # use 'res' for exception safety (don't write to 'number' in case of an # overflow exception: result = rawParseInt(s, res, start) @@ -223,7 +223,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {. ## parses an integer starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there is no integer. ## `EOverflow` is raised if an overflow occurs. - var res: biggestInt + var res: BiggestInt result = parseBiggestInt(s, res, start) if (sizeof(int) <= 4) and ((res < low(int)) or (res > high(int))): @@ -231,7 +231,7 @@ proc parseInt*(s: string, number: var int, start = 0): int {. else: number = int(res) -proc tenToThePowerOf(b: int): biggestFloat = +proc tenToThePowerOf(b: int): BiggestFloat = var b = b var a = 10.0 result = 1.0 @@ -242,7 +242,7 @@ proc tenToThePowerOf(b: int): biggestFloat = if b == 0: break a *= a -proc parseBiggestFloat*(s: string, number: var biggestFloat, start = 0): int {. +proc parseBiggestFloat*(s: string, number: var BiggestFloat, start = 0): int {. rtl, extern: "npuParseBiggestFloat", noSideEffect.} = ## parses a float starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there occured a parsing @@ -319,7 +319,7 @@ proc parseFloat*(s: string, number: var float, start = 0): int {. ## parses a float starting at `start` and stores the value into `number`. ## Result is the number of processed chars or 0 if there occured a parsing ## error. - var bf: biggestFloat + var bf: BiggestFloat result = parseBiggestFloat(s, bf, start) number = bf diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index f5351c41c..2ae37e372 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -362,28 +362,28 @@ proc socketError*(socket: TSocket, err: int = -1, async = false) = else: SSLError("Unknown Error") if err == -1 and not (when defined(ssl): socket.isSSL else: false): - let lastError = OSLastError() + let lastError = osLastError() if async: when defined(windows): if lastError.int32 == WSAEWOULDBLOCK: return - else: OSError(lastError) + else: osError(lastError) else: if lastError.int32 == EAGAIN or lastError.int32 == EWOULDBLOCK: return else: OSError(lastError) - else: OSError(lastError) + else: osError(lastError) proc listen*(socket: TSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} = ## Marks ``socket`` as accepting connections. ## ``Backlog`` specifies the maximum length of the ## queue of pending connections. - if listen(socket.fd, cint(backlog)) < 0'i32: OSError(OSLastError()) + if listen(socket.fd, cint(backlog)) < 0'i32: osError(osLastError()) proc invalidIp4(s: string) {.noreturn, noinline.} = raise newException(EInvalidValue, "invalid ip4 address: " & s) -proc parseIp4*(s: string): biggestInt = +proc parseIp4*(s: string): BiggestInt = ## parses an IP version 4 in dotted decimal form like "a.b.c.d". ## ## This is equivalent to `inet_ntoa`:idx:. @@ -410,14 +410,14 @@ proc parseIp4*(s: string): biggestInt = if j <= 0: invalidIp4(s) inc(i, j) if s[i] != '\0': invalidIp4(s) - result = biggestInt(a shl 24 or b shl 16 or c shl 8 or d) + result = BiggestInt(a shl 24 or b shl 16 or c shl 8 or d) template gaiNim(a, p, h, list: expr): stmt = block: - var gaiResult = getAddrInfo(a, $p, addr(h), list) + var gaiResult = getaddrinfo(a, $p, addr(h), list) if gaiResult != 0'i32: when defined(windows): - OSError(OSLastError()) + osError(osLastError()) else: raise newException(EOS, $gai_strerror(gaiResult)) @@ -437,7 +437,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {. name.sin_addr.s_addr = sockets.htonl(INADDR_ANY) if bindSocket(socket.fd, cast[ptr TSockAddr](addr(name)), sizeof(name).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) else: var hints: TAddrInfo var aiList: ptr TAddrInfo = nil @@ -446,7 +446,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {. hints.ai_protocol = toInt(IPPROTO_TCP) gaiNim(address, port, hints, aiList) if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc getSockName*(socket: TSocket): TPort = ## returns the socket's associated port number. @@ -460,37 +460,37 @@ proc getSockName*(socket: TSocket): TPort = var namelen = sizeof(name).TSockLen if getsockname(socket.fd, cast[ptr TSockAddr](addr(name)), addr(namelen)) == -1'i32: - OSError(OSLastError()) + osError(osLastError()) result = TPort(sockets.ntohs(name.sin_port)) template acceptAddrPlain(noClientRet, successRet: expr, sslImplementation: stmt): stmt {.immediate.} = assert(client != nil) var sockAddress: Tsockaddr_in - var addrLen = sizeof(sockAddress).TSockLen + var addrLen = sizeof(sockAddress).Tsocklen var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen)) if sock == osInvalidSocket: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEINPROGRESS: - client = InvalidSocket + client = invalidSocket address = "" when noClientRet.int == -1: return else: return noClientRet - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: - client = InvalidSocket + client = invalidSocket address = "" when noClientRet.int == -1: return else: return noClientRet - else: OSError(err) + else: osError(err) else: client.fd = sock client.isBuffered = server.isBuffered @@ -669,7 +669,7 @@ proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} = result.port = TPort(s.s_port) result.proto = $s.s_proto -proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} = +proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} = ## This function will lookup the hostname of an IP Address. var myaddr: TInAddr myaddr.s_addr = inet_addr(ip) @@ -677,7 +677,7 @@ proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} = when defined(windows): var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint, cint(sockets.AF_INET)) - if s == nil: OSError(OSLastError()) + if s == nil: osError(osLastError()) else: var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).TSockLen, cint(posix.AF_INET)) @@ -698,13 +698,13 @@ proc getHostByAddr*(ip: string): THostEnt {.tags: [FReadIO].} = result.addrList = cstringArrayToSeq(s.h_addr_list) result.length = int(s.h_length) -proc getHostByName*(name: string): THostEnt {.tags: [FReadIO].} = +proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} = ## This function will lookup the IP address of a hostname. when defined(Windows): var s = winlean.gethostbyname(name) else: var s = posix.gethostbyname(name) - if s == nil: OSError(OSLastError()) + if s == nil: osError(osLastError()) result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) when defined(windows): @@ -726,7 +726,7 @@ proc getSockOptInt*(socket: TSocket, level, optname: int): int {. var size = sizeof(res).TSockLen if getsockopt(socket.fd, cint(level), cint(optname), addr(res), addr(size)) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) result = int(res) proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {. @@ -735,7 +735,7 @@ proc setSockOptInt*(socket: TSocket, level, optname, optval: int) {. var value = cint(optval) if setsockopt(socket.fd, cint(level), cint(optname), addr(value), sizeof(value).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc toCInt(opt: TSOBool): cint = case opt @@ -754,7 +754,7 @@ proc getSockOpt*(socket: TSocket, opt: TSOBool, level = SOL_SOCKET): bool {. var size = sizeof(res).TSockLen if getsockopt(socket.fd, cint(level), toCInt(opt), addr(res), addr(size)) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) result = res != 0 proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {. @@ -763,7 +763,7 @@ proc setSockOpt*(socket: TSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) var valuei = cint(if value: 1 else: 0) if setsockopt(socket.fd, cint(level), toCInt(opt), addr(valuei), sizeof(valuei).TSockLen) < 0'i32: - OSError(OSLastError()) + osError(osLastError()) proc connect*(socket: TSocket, address: string, port = TPort(0), af: TDomain = AF_INET) {.tags: [FReadIO].} = @@ -787,11 +787,11 @@ proc connect*(socket: TSocket, address: string, port = TPort(0), if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSockLen) == 0'i32: success = true break - else: lastError = OSLastError() + else: lastError = osLastError() it = it.ai_next freeaddrinfo(aiList) - if not success: OSError(lastError) + if not success: osError(lastError) when defined(ssl): if socket.isSSL: @@ -852,7 +852,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0), success = true break else: - lastError = OSLastError() + lastError = osLastError() when defined(windows): # Windows EINTR doesn't behave same as POSIX. if lastError.int32 == WSAEWOULDBLOCK: @@ -866,7 +866,7 @@ proc connectAsync*(socket: TSocket, name: string, port = TPort(0), it = it.ai_next freeaddrinfo(aiList) - if not success: OSError(lastError) + if not success: osError(lastError) when defined(ssl): if socket.isSSL: socket.sslNoHandshake = true @@ -912,7 +912,7 @@ when defined(ssl): else: SSLError("Socket is not an SSL socket.") -proc timeValFromMilliseconds(timeout = 500): TTimeVal = +proc timeValFromMilliseconds(timeout = 500): TTimeval = if timeout != -1: var seconds = timeout div 1000 result.tv_sec = seconds.int32 @@ -970,7 +970,7 @@ proc select*(readfds, writefds, exceptfds: var seq[TSocket], if buffersFilled > 0: return buffersFilled - var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout) + var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout) var rd, wr, ex: TFdSet var m = 0 @@ -993,7 +993,7 @@ proc select*(readfds, writefds: var seq[TSocket], let buffersFilled = checkBuffer(readfds) if buffersFilled > 0: return buffersFilled - var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout) + var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout) var rd, wr: TFdSet var m = 0 @@ -1017,7 +1017,7 @@ proc selectWrite*(writefds: var seq[TSocket], ## ## ``timeout`` is specified in miliseconds and ``-1`` can be specified for ## an unlimited time. - var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout) + var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout) var wr: TFdSet var m = 0 @@ -1035,7 +1035,7 @@ proc select*(readfds: var seq[TSocket], timeout = 500): int = let buffersFilled = checkBuffer(readfds) if buffersFilled > 0: return buffersFilled - var tv {.noInit.}: TTimeVal = timeValFromMilliseconds(timeout) + var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout) var rd: TFdSet var m = 0 @@ -1142,7 +1142,7 @@ proc waitFor(socket: TSocket, waited: var float, timeout, size: int, var s = @[socket] var startTime = epochTime() let selRet = select(s, timeout - int(waited * 1000.0)) - if selRet < 0: OSError(OSLastError()) + if selRet < 0: osError(osLastError()) if selRet != 1: raise newException(ETimeout, "Call to '" & funcName & "' timed out.") waited += (epochTime() - startTime) @@ -1180,7 +1180,7 @@ proc recv*(socket: TSocket, data: var string, size: int, timeout = -1): int = result = recv(socket, cstring(data), size, timeout) if result < 0: data.setLen(0) - socket.SocketError(result) + socket.socketError(result) data.setLen(result) proc recvAsync*(socket: TSocket, data: var string, size: int): int = @@ -1194,7 +1194,7 @@ proc recvAsync*(socket: TSocket, data: var string, size: int): int = result = recv(socket, cstring(data), size) if result < 0: data.setLen(0) - socket.SocketError(async = true) + socket.socketError(async = true) result = -1 data.setLen(result) @@ -1291,14 +1291,14 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {. var c: char discard waitFor(socket, waited, timeout, 1, "readLine") var n = recv(socket, addr(c), 1) - if n < 0: OSError(OSLastError()) + if n < 0: osError(osLastError()) elif n == 0: return if c == '\r': discard waitFor(socket, waited, timeout, 1, "readLine") n = peekChar(socket, c) if n > 0 and c == '\L': discard recv(socket, addr(c), 1) - elif n <= 0: OSError(OSLastError()) + elif n <= 0: osError(osLastError()) addNlIfEmpty() return elif c == '\L': @@ -1352,7 +1352,7 @@ proc readLineAsync*(socket: TSocket, setLen(line.string, 0) template errorOrNone = - socket.SocketError(async = true) + socket.socketError(async = true) return ReadNone while true: @@ -1385,7 +1385,7 @@ proc recv*(socket: TSocket): TaintedString {.tags: [FReadIO], deprecated.} = var pos = 0 while true: var bytesRead = recv(socket, addr(string(result)[pos]), bufSize-1) - if bytesRead == -1: OSError(OSLastError()) + if bytesRead == -1: osError(osLastError()) setLen(result.string, pos + bytesRead) if bytesRead != bufSize-1: break # increase capacity: @@ -1454,11 +1454,11 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {. else: SSLError("Unknown Error") if bytesRead == -1 and not (when defined(ssl): socket.isSSL else: false): - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEWOULDBLOCK: return False - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return False @@ -1489,7 +1489,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int, data.setLen(length) var sockAddress: Tsockaddr_in var addrLen = sizeof(sockAddress).TSockLen - result = recvFrom(socket.fd, cstring(data), length.cint, flags.cint, + result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint, cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen)) if result != -1: @@ -1497,7 +1497,7 @@ proc recvFrom*(socket: TSocket, data: var string, length: int, address = $inet_ntoa(sockAddress.sin_addr) port = ntohs(sockAddress.sin_port).TPort -proc recvFromAsync*(socket: TSocket, data: var String, length: int, +proc recvFromAsync*(socket: TSocket, data: var string, length: int, address: var string, port: var TPort, flags = 0'i32): bool {.tags: [FReadIO].} = ## Variant of ``recvFrom`` for non-blocking sockets. Unlike ``recvFrom``, @@ -1507,11 +1507,11 @@ proc recvFromAsync*(socket: TSocket, data: var String, length: int, result = true var callRes = recvFrom(socket, data, length, address, port, flags) if callRes < 0: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEWOULDBLOCK: return False - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return False @@ -1565,7 +1565,7 @@ proc send*(socket: TSocket, data: string) {.tags: [FWriteIO].} = if socket.isSSL: SSLError() - OSError(OSLastError()) + osError(osLastError()) if sent != data.len: raise newException(EOS, "Could not send all data.") @@ -1598,11 +1598,11 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [FWriteIO].} = else: return if result == -1: - let err = OSLastError() + let err = osLastError() when defined(windows): if err.int32 == WSAEINPROGRESS: return 0 - else: OSError(err) + else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: return 0 @@ -1633,7 +1633,7 @@ proc sendTo*(socket: TSocket, address: string, port: TPort, data: pointer, var success = false var it = aiList while it != nil: - result = sendTo(socket.fd, data, size.cint, flags.cint, it.ai_addr, + result = sendto(socket.fd, data, size.cint, flags.cint, it.ai_addr, it.ai_addrlen.TSockLen) if result != -1'i32: success = true @@ -1662,7 +1662,7 @@ proc setBlocking(s: TSocket, blocking: bool) = when defined(Windows): var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1: - OSError(OSLastError()) + osError(osLastError()) else: # BSD sockets var x: int = fcntl(s.fd, F_GETFL, 0) if x == -1: @@ -1709,7 +1709,7 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking ## Determines whether ``socket`` is blocking. when defined(Windows): - var wsa: TWSADATA - if WSAStartup(0x0101'i16, addr wsa) != 0: OSError(OSLastError()) + var wsa: TWSAData + if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError()) diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 764471b78..302742eb4 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -249,7 +249,7 @@ proc fsClose(s: PStream) = close(PFileStream(s).f) PFileStream(s).f = nil proc fsFlush(s: PStream) = flushFile(PFileStream(s).f) -proc fsAtEnd(s: PStream): bool = return EndOfFile(PFileStream(s).f) +proc fsAtEnd(s: PStream): bool = return endOfFile(PFileStream(s).f) proc fsSetPosition(s: PStream, pos: int) = setFilePos(PFileStream(s).f, pos) proc fsGetPosition(s: PStream): int = return int(getFilePos(PFileStream(s).f)) @@ -277,7 +277,7 @@ proc newFileStream*(filename: string, mode: TFileMode): PFileStream = ## If the file cannot be opened, nil is returned. See the `system ## `_ module for a list of available TFileMode enums. var f: TFile - if Open(f, filename, mode): result = newFileStream(f) + if open(f, filename, mode): result = newFileStream(f) when true: diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim index d8bc94176..7003acfcf 100644 --- a/lib/pure/strtabs.nim +++ b/lib/pure/strtabs.nim @@ -91,7 +91,7 @@ proc nextTry(h, maxHash: THash): THash {.inline.} = proc rawGet(t: PStringTable, key: string): int = var h: THash = myhash(t, key) and high(t.data) # start with real hash value while not isNil(t.data[h].key): - if mycmp(t, t.data[h].key, key): + if myCmp(t, t.data[h].key, key): return h h = nextTry(h, high(t.data)) result = - 1 @@ -100,7 +100,7 @@ proc `[]`*(t: PStringTable, key: string): string {.rtl, extern: "nstGet".} = ## retrieves the value at ``t[key]``. If `key` is not in `t`, "" is returned ## and no exception is raised. One can check with ``hasKey`` whether the key ## exists. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: result = "" @@ -108,7 +108,7 @@ proc mget*(t: PStringTable, key: string): var string {. rtl, extern: "nstTake".} = ## retrieves the location at ``t[key]``. If `key` is not in `t`, the ## ``EInvalidKey`` exception is raised. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key does not exist: " & key) @@ -127,17 +127,17 @@ proc enlarge(t: PStringTable) = var n: TKeyValuePairSeq newSeq(n, len(t.data) * growthFactor) for i in countup(0, high(t.data)): - if not isNil(t.data[i].key): RawInsert(t, n, t.data[i].key, t.data[i].val) + if not isNil(t.data[i].key): rawInsert(t, n, t.data[i].key, t.data[i].val) swap(t.data, n) proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} = ## puts a (key, value)-pair into `t`. - var index = RawGet(t, key) + var index = rawGet(t, key) if index >= 0: t.data[index].val = val else: - if mustRehash(len(t.data), t.counter): Enlarge(t) - RawInsert(t, t.data, key, val) + if mustRehash(len(t.data), t.counter): enlarge(t) + rawInsert(t, t.data, key, val) inc(t.counter) proc raiseFormatException(s: string) = @@ -184,7 +184,7 @@ proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]], ## var mytab = newStringTable({"key1": "val1", "key2": "val2"}, ## modeCaseInsensitive) result = newStringTable(mode) - for key, val in items(keyvaluePairs): result[key] = val + for key, val in items(keyValuePairs): result[key] = val proc `%`*(f: string, t: PStringTable, flags: set[TFormatFlag] = {}): string {. rtl, extern: "nstFormat".} = diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 388a76e71..b7e3de6cf 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -1,170 +1,170 @@ -# -# -# Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module contains various string utility routines. -## See the module `re `_ for regular expression support. -## See the module `pegs `_ for PEG support. - -import parseutils - -{.deadCodeElim: on.} - -{.push debugger:off .} # the user does not want to trace a part - # of the standard library! - -include "system/inclrtl" - -type - TCharSet* = set[char] # for compatibility with Nim - -const - Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} - ## All the characters that count as whitespace. - - Letters* = {'A'..'Z', 'a'..'z'} - ## the set of letters - - Digits* = {'0'..'9'} - ## the set of digits - - HexDigits* = {'0'..'9', 'A'..'F', 'a'..'f'} - ## the set of hexadecimal digits - - IdentChars* = {'a'..'z', 'A'..'Z', '0'..'9', '_'} - ## the set of characters an identifier can consist of - - IdentStartChars* = {'a'..'z', 'A'..'Z', '_'} - ## the set of characters an identifier can start with - - NewLines* = {'\13', '\10'} - ## the set of characters a newline terminator can start with - -proc toLower*(c: Char): Char {.noSideEffect, procvar, - rtl, extern: "nsuToLowerChar".} = - ## Converts `c` into lower case. This works only for the letters A-Z. - ## See `unicode.toLower` for a version that works for any Unicode character. - if c in {'A'..'Z'}: - result = chr(ord(c) + (ord('a') - ord('A'))) - else: - result = c - -proc toLower*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuToLowerStr".} = - ## Converts `s` into lower case. This works only for the letters A-Z. - ## See `unicode.toLower` for a version that works for any Unicode character. - result = newString(len(s)) - for i in 0..len(s) - 1: - result[i] = toLower(s[i]) - -proc toUpper*(c: Char): Char {.noSideEffect, procvar, - rtl, extern: "nsuToUpperChar".} = - ## Converts `c` into upper case. This works only for the letters a-z. - ## See `unicode.toUpper` for a version that works for any Unicode character. - if c in {'a'..'z'}: - result = Chr(Ord(c) - (Ord('a') - Ord('A'))) - else: - result = c - -proc toUpper*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuToUpperStr".} = - ## Converts `s` into upper case. This works only for the letters a-z. - ## See `unicode.toUpper` for a version that works for any Unicode character. - result = newString(len(s)) - for i in 0..len(s) - 1: - result[i] = toUpper(s[i]) - -proc capitalize*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuCapitalize".} = - ## Converts the first character of `s` into upper case. - ## This works only for the letters a-z. - result = toUpper(s[0]) & substr(s, 1) - -proc normalize*(s: string): string {.noSideEffect, procvar, - rtl, extern: "nsuNormalize".} = - ## Normalizes the string `s`. That means to convert it to lower case and - ## remove any '_'. This is needed for Nimrod identifiers for example. - result = newString(s.len) - var j = 0 - for i in 0..len(s) - 1: - if s[i] in {'A'..'Z'}: - result[j] = chr(ord(s[i]) + (ord('a') - ord('A'))) - inc j - elif s[i] != '_': - result[j] = s[i] - inc j - if j != s.len: setLen(result, j) - -proc cmpIgnoreCase*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuCmpIgnoreCase", procvar, operator: 4.} = - ## Compares two strings in a case insensitive manner. Returns: - ## - ## | 0 iff a == b - ## | < 0 iff a < b - ## | > 0 iff a > b - var i = 0 - var m = min(a.len, b.len) - while i < m: - result = ord(toLower(a[i])) - ord(toLower(b[i])) - if result != 0: return - inc(i) - result = a.len - b.len - -{.push checks: off, line_trace: off .} # this is a hot-spot in the compiler! - # thus we compile without checks here - -proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuCmpIgnoreStyle", procvar, operator: 3.} = - ## Compares two strings normalized (i.e. case and - ## underscores do not matter). Returns: - ## - ## | 0 iff a == b - ## | < 0 iff a < b - ## | > 0 iff a > b - var i = 0 - var j = 0 - while true: - while a[i] == '_': inc(i) - while b[j] == '_': inc(j) # BUGFIX: typo - var aa = toLower(a[i]) - var bb = toLower(b[j]) - result = ord(aa) - ord(bb) - if result != 0 or aa == '\0': break - inc(i) - inc(j) - -{.pop.} - -proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect, - rtl, extern: "nsuStrip", operator: 5.} = - ## Strips whitespace from `s` and returns the resulting string. - ## If `leading` is true, leading whitespace is stripped. - ## If `trailing` is true, trailing whitespace is stripped. - const - chars: set[Char] = Whitespace - var - first = 0 - last = len(s)-1 - if leading: - while s[first] in chars: inc(first) - if trailing: - while last >= 0 and s[last] in chars: dec(last) - result = substr(s, first, last) - -proc toOctal*(c: char): string {.noSideEffect, rtl, extern: "nsuToOctal".} = - ## Converts a character `c` to its octal representation. The resulting - ## string may not have a leading zero. Its length is always exactly 3. - result = newString(3) - var val = ord(c) - for i in countdown(2, 0): - result[i] = Chr(val mod 8 + ord('0')) - val = val div 8 - +# +# +# Nimrod's Runtime Library +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module contains various string utility routines. +## See the module `re `_ for regular expression support. +## See the module `pegs `_ for PEG support. + +import parseutils + +{.deadCodeElim: on.} + +{.push debugger:off .} # the user does not want to trace a part + # of the standard library! + +include "system/inclrtl" + +type + TCharSet* = set[char] # for compatibility with Nim + +const + Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'} + ## All the characters that count as whitespace. + + Letters* = {'A'..'Z', 'a'..'z'} + ## the set of letters + + Digits* = {'0'..'9'} + ## the set of digits + + HexDigits* = {'0'..'9', 'A'..'F', 'a'..'f'} + ## the set of hexadecimal digits + + IdentChars* = {'a'..'z', 'A'..'Z', '0'..'9', '_'} + ## the set of characters an identifier can consist of + + IdentStartChars* = {'a'..'z', 'A'..'Z', '_'} + ## the set of characters an identifier can start with + + NewLines* = {'\13', '\10'} + ## the set of characters a newline terminator can start with + +proc toLower*(c: char): char {.noSideEffect, procvar, + rtl, extern: "nsuToLowerChar".} = + ## Converts `c` into lower case. This works only for the letters A-Z. + ## See `unicode.toLower` for a version that works for any Unicode character. + if c in {'A'..'Z'}: + result = chr(ord(c) + (ord('a') - ord('A'))) + else: + result = c + +proc toLower*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuToLowerStr".} = + ## Converts `s` into lower case. This works only for the letters A-Z. + ## See `unicode.toLower` for a version that works for any Unicode character. + result = newString(len(s)) + for i in 0..len(s) - 1: + result[i] = toLower(s[i]) + +proc toUpper*(c: char): char {.noSideEffect, procvar, + rtl, extern: "nsuToUpperChar".} = + ## Converts `c` into upper case. This works only for the letters a-z. + ## See `unicode.toUpper` for a version that works for any Unicode character. + if c in {'a'..'z'}: + result = chr(ord(c) - (Ord('a') - Ord('A'))) + else: + result = c + +proc toUpper*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuToUpperStr".} = + ## Converts `s` into upper case. This works only for the letters a-z. + ## See `unicode.toUpper` for a version that works for any Unicode character. + result = newString(len(s)) + for i in 0..len(s) - 1: + result[i] = toUpper(s[i]) + +proc capitalize*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuCapitalize".} = + ## Converts the first character of `s` into upper case. + ## This works only for the letters a-z. + result = toUpper(s[0]) & substr(s, 1) + +proc normalize*(s: string): string {.noSideEffect, procvar, + rtl, extern: "nsuNormalize".} = + ## Normalizes the string `s`. That means to convert it to lower case and + ## remove any '_'. This is needed for Nimrod identifiers for example. + result = newString(s.len) + var j = 0 + for i in 0..len(s) - 1: + if s[i] in {'A'..'Z'}: + result[j] = chr(ord(s[i]) + (ord('a') - ord('A'))) + inc j + elif s[i] != '_': + result[j] = s[i] + inc j + if j != s.len: setLen(result, j) + +proc cmpIgnoreCase*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuCmpIgnoreCase", procvar, operator: 4.} = + ## Compares two strings in a case insensitive manner. Returns: + ## + ## | 0 iff a == b + ## | < 0 iff a < b + ## | > 0 iff a > b + var i = 0 + var m = min(a.len, b.len) + while i < m: + result = ord(toLower(a[i])) - ord(toLower(b[i])) + if result != 0: return + inc(i) + result = a.len - b.len + +{.push checks: off, line_trace: off .} # this is a hot-spot in the compiler! + # thus we compile without checks here + +proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuCmpIgnoreStyle", procvar, operator: 3.} = + ## Compares two strings normalized (i.e. case and + ## underscores do not matter). Returns: + ## + ## | 0 iff a == b + ## | < 0 iff a < b + ## | > 0 iff a > b + var i = 0 + var j = 0 + while true: + while a[i] == '_': inc(i) + while b[j] == '_': inc(j) # BUGFIX: typo + var aa = toLower(a[i]) + var bb = toLower(b[j]) + result = ord(aa) - ord(bb) + if result != 0 or aa == '\0': break + inc(i) + inc(j) + +{.pop.} + +proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect, + rtl, extern: "nsuStrip", operator: 5.} = + ## Strips whitespace from `s` and returns the resulting string. + ## If `leading` is true, leading whitespace is stripped. + ## If `trailing` is true, trailing whitespace is stripped. + const + chars: set[char] = Whitespace + var + first = 0 + last = len(s)-1 + if leading: + while s[first] in chars: inc(first) + if trailing: + while last >= 0 and s[last] in chars: dec(last) + result = substr(s, first, last) + +proc toOctal*(c: char): string {.noSideEffect, rtl, extern: "nsuToOctal".} = + ## Converts a character `c` to its octal representation. The resulting + ## string may not have a leading zero. Its length is always exactly 3. + result = newString(3) + var val = ord(c) + for i in countdown(2, 0): + result[i] = chr(val mod 8 + ord('0')) + val = val div 8 + iterator split*(s: string, seps: set[char] = Whitespace): string = ## Splits the string `s` into substrings using a group of separators. ## @@ -209,199 +209,199 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = ## "08" ## "08.398990" ## - var last = 0 - assert(not ('\0' in seps)) - while last < len(s): - while s[last] in seps: inc(last) - var first = last - while last < len(s) and s[last] not_in seps: inc(last) # BUGFIX! - if first <= last-1: - yield substr(s, first, last-1) - -iterator split*(s: string, sep: char): string = - ## Splits the string `s` into substrings using a single separator. - ## - ## Substrings are separated by the character `sep`. - ## Unlike the version of the iterator which accepts a set of separator - ## characters, this proc will not coalesce groups of the - ## separator, returning a string for each found character. The code: - ## - ## .. code-block:: nimrod - ## for word in split(";;this;is;an;;example;;;", ';'): - ## writeln(stdout, word) - ## - ## Results in: - ## - ## .. code-block:: - ## "" - ## "" - ## "this" - ## "is" - ## "an" - ## "" - ## "example" - ## "" - ## "" - ## "" - ## - var last = 0 - assert('\0' != sep) - if len(s) > 0: - # `<=` is correct here for the edge cases! - while last <= len(s): - var first = last - while last < len(s) and s[last] != sep: inc(last) - yield substr(s, first, last-1) - inc(last) - -iterator splitLines*(s: string): string = - ## Splits the string `s` into its containing lines. Every newline - ## combination (CR, LF, CR-LF) is supported. The result strings contain - ## no trailing ``\n``. - ## - ## Example: - ## - ## .. code-block:: nimrod - ## for line in splitLines("\nthis\nis\nan\n\nexample\n"): - ## writeln(stdout, line) - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "" - ## "this" - ## "is" - ## "an" - ## "" - ## "example" - ## "" - var first = 0 - var last = 0 - while true: - while s[last] notin {'\0', '\c', '\l'}: inc(last) - yield substr(s, first, last-1) - # skip newlines: - if s[last] == '\l': inc(last) - elif s[last] == '\c': - inc(last) - if s[last] == '\l': inc(last) - else: break # was '\0' - first = last - -proc splitLines*(s: string): seq[string] {.noSideEffect, - rtl, extern: "nsuSplitLines".} = - ## The same as the `splitLines` iterator, but is a proc that returns a - ## sequence of substrings. - accumulateResult(splitLines(s)) - -proc countLines*(s: string): int {.noSideEffect, - rtl, extern: "nsuCountLines".} = - ## same as ``len(splitLines(s))``, but much more efficient. - var i = 0 - while i < s.len: - case s[i] - of '\c': - if s[i+1] == '\l': inc i - inc result - of '\l': inc result - else: nil - inc i - -proc split*(s: string, seps: set[char] = Whitespace): seq[string] {. - noSideEffect, rtl, extern: "nsuSplitCharSet".} = - ## The same as the `split` iterator, but is a proc that returns a - ## sequence of substrings. - accumulateResult(split(s, seps)) - -proc split*(s: string, sep: char): seq[string] {.noSideEffect, - rtl, extern: "nsuSplitChar".} = - ## The same as the `split` iterator, but is a proc that returns a sequence - ## of substrings. - accumulateResult(split(s, sep)) - -proc toHex*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToHex".} = - ## Converts `x` to its hexadecimal representation. The resulting string - ## will be exactly `len` characters long. No prefix like ``0x`` - ## is generated. `x` is treated as an unsigned value. - const - HexChars = "0123456789ABCDEF" - var - shift: BiggestInt - result = newString(len) - for j in countdown(len-1, 0): - result[j] = HexChars[toU32(x shr shift) and 0xF'i32] - shift = shift + 4 - -proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect, - rtl, extern: "nsuIntToStr".} = - ## Converts `x` to its decimal representation. The resulting string - ## will be minimally `minchars` characters long. This is achieved by - ## adding leading zeros. - result = $abs(x) - for i in 1 .. minchars - len(result): - result = '0' & result - if x < 0: - result = '-' & result - -proc parseInt*(s: string): int {.noSideEffect, procvar, - rtl, extern: "nsuParseInt".} = - ## Parses a decimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. - var L = parseutils.parseInt(s, result, 0) - if L != s.len or L == 0: - raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseBiggestInt*(s: string): biggestInt {.noSideEffect, procvar, - rtl, extern: "nsuParseBiggestInt".} = - ## Parses a decimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. - var L = parseutils.parseBiggestInt(s, result, 0) - if L != s.len or L == 0: - raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseFloat*(s: string): float {.noSideEffect, procvar, - rtl, extern: "nsuParseFloat".} = - ## Parses a decimal floating point value contained in `s`. If `s` is not - ## a valid floating point number, `EInvalidValue` is raised. ``NAN``, - ## ``INF``, ``-INF`` are also supported (case insensitive comparison). - var L = parseutils.parseFloat(s, result, 0) - if L != s.len or L == 0: - raise newException(EInvalidValue, "invalid float: " & s) - -proc parseHexInt*(s: string): int {.noSideEffect, procvar, - rtl, extern: "nsuParseHexInt".} = - ## Parses a hexadecimal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. `s` can have one of the - ## following optional prefixes: ``0x``, ``0X``, ``#``. - ## Underscores within `s` are ignored. - var i = 0 - if s[i] == '0' and (s[i+1] == 'x' or s[i+1] == 'X'): inc(i, 2) - elif s[i] == '#': inc(i) - while true: - case s[i] - of '_': inc(i) - of '0'..'9': - result = result shl 4 or (ord(s[i]) - ord('0')) - inc(i) - of 'a'..'f': - result = result shl 4 or (ord(s[i]) - ord('a') + 10) - inc(i) - of 'A'..'F': - result = result shl 4 or (ord(s[i]) - ord('A') + 10) - inc(i) - of '\0': break - else: raise newException(EInvalidValue, "invalid integer: " & s) - -proc parseBool*(s: string): bool = - ## Parses a value into a `bool`. If ``s`` is one of the following values: - ## ``y, yes, true, 1, on``, then returns `true`. If ``s`` is one of the - ## following values: ``n, no, false, 0, off``, then returns `false`. - ## If ``s`` is something else a ``EInvalidValue`` exception is raised. - case normalize(s) - of "y", "yes", "true", "1", "on": result = true - of "n", "no", "false", "0", "off": result = false - else: raise newException(EInvalidValue, "cannot interpret as a bool: " & s) + var last = 0 + assert(not ('\0' in seps)) + while last < len(s): + while s[last] in seps: inc(last) + var first = last + while last < len(s) and s[last] not_in seps: inc(last) # BUGFIX! + if first <= last-1: + yield substr(s, first, last-1) + +iterator split*(s: string, sep: char): string = + ## Splits the string `s` into substrings using a single separator. + ## + ## Substrings are separated by the character `sep`. + ## Unlike the version of the iterator which accepts a set of separator + ## characters, this proc will not coalesce groups of the + ## separator, returning a string for each found character. The code: + ## + ## .. code-block:: nimrod + ## for word in split(";;this;is;an;;example;;;", ';'): + ## writeln(stdout, word) + ## + ## Results in: + ## + ## .. code-block:: + ## "" + ## "" + ## "this" + ## "is" + ## "an" + ## "" + ## "example" + ## "" + ## "" + ## "" + ## + var last = 0 + assert('\0' != sep) + if len(s) > 0: + # `<=` is correct here for the edge cases! + while last <= len(s): + var first = last + while last < len(s) and s[last] != sep: inc(last) + yield substr(s, first, last-1) + inc(last) + +iterator splitLines*(s: string): string = + ## Splits the string `s` into its containing lines. Every newline + ## combination (CR, LF, CR-LF) is supported. The result strings contain + ## no trailing ``\n``. + ## + ## Example: + ## + ## .. code-block:: nimrod + ## for line in splitLines("\nthis\nis\nan\n\nexample\n"): + ## writeln(stdout, line) + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "" + ## "this" + ## "is" + ## "an" + ## "" + ## "example" + ## "" + var first = 0 + var last = 0 + while true: + while s[last] notin {'\0', '\c', '\l'}: inc(last) + yield substr(s, first, last-1) + # skip newlines: + if s[last] == '\l': inc(last) + elif s[last] == '\c': + inc(last) + if s[last] == '\l': inc(last) + else: break # was '\0' + first = last + +proc splitLines*(s: string): seq[string] {.noSideEffect, + rtl, extern: "nsuSplitLines".} = + ## The same as the `splitLines` iterator, but is a proc that returns a + ## sequence of substrings. + accumulateResult(splitLines(s)) + +proc countLines*(s: string): int {.noSideEffect, + rtl, extern: "nsuCountLines".} = + ## same as ``len(splitLines(s))``, but much more efficient. + var i = 0 + while i < s.len: + case s[i] + of '\c': + if s[i+1] == '\l': inc i + inc result + of '\l': inc result + else: nil + inc i + +proc split*(s: string, seps: set[char] = Whitespace): seq[string] {. + noSideEffect, rtl, extern: "nsuSplitCharSet".} = + ## The same as the `split` iterator, but is a proc that returns a + ## sequence of substrings. + accumulateResult(split(s, seps)) + +proc split*(s: string, sep: char): seq[string] {.noSideEffect, + rtl, extern: "nsuSplitChar".} = + ## The same as the `split` iterator, but is a proc that returns a sequence + ## of substrings. + accumulateResult(split(s, sep)) + +proc toHex*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToHex".} = + ## Converts `x` to its hexadecimal representation. The resulting string + ## will be exactly `len` characters long. No prefix like ``0x`` + ## is generated. `x` is treated as an unsigned value. + const + HexChars = "0123456789ABCDEF" + var + shift: BiggestInt + result = newString(len) + for j in countdown(len-1, 0): + result[j] = HexChars[toU32(x shr shift) and 0xF'i32] + shift = shift + 4 + +proc intToStr*(x: int, minchars: int = 1): string {.noSideEffect, + rtl, extern: "nsuIntToStr".} = + ## Converts `x` to its decimal representation. The resulting string + ## will be minimally `minchars` characters long. This is achieved by + ## adding leading zeros. + result = $abs(x) + for i in 1 .. minchars - len(result): + result = '0' & result + if x < 0: + result = '-' & result + +proc parseInt*(s: string): int {.noSideEffect, procvar, + rtl, extern: "nsuParseInt".} = + ## Parses a decimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. + var L = parseutils.parseInt(s, result, 0) + if L != s.len or L == 0: + raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar, + rtl, extern: "nsuParseBiggestInt".} = + ## Parses a decimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. + var L = parseutils.parseBiggestInt(s, result, 0) + if L != s.len or L == 0: + raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseFloat*(s: string): float {.noSideEffect, procvar, + rtl, extern: "nsuParseFloat".} = + ## Parses a decimal floating point value contained in `s`. If `s` is not + ## a valid floating point number, `EInvalidValue` is raised. ``NAN``, + ## ``INF``, ``-INF`` are also supported (case insensitive comparison). + var L = parseutils.parseFloat(s, result, 0) + if L != s.len or L == 0: + raise newException(EInvalidValue, "invalid float: " & s) + +proc parseHexInt*(s: string): int {.noSideEffect, procvar, + rtl, extern: "nsuParseHexInt".} = + ## Parses a hexadecimal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. `s` can have one of the + ## following optional prefixes: ``0x``, ``0X``, ``#``. + ## Underscores within `s` are ignored. + var i = 0 + if s[i] == '0' and (s[i+1] == 'x' or s[i+1] == 'X'): inc(i, 2) + elif s[i] == '#': inc(i) + while true: + case s[i] + of '_': inc(i) + of '0'..'9': + result = result shl 4 or (ord(s[i]) - ord('0')) + inc(i) + of 'a'..'f': + result = result shl 4 or (ord(s[i]) - ord('a') + 10) + inc(i) + of 'A'..'F': + result = result shl 4 or (ord(s[i]) - ord('A') + 10) + inc(i) + of '\0': break + else: raise newException(EInvalidValue, "invalid integer: " & s) + +proc parseBool*(s: string): bool = + ## Parses a value into a `bool`. If ``s`` is one of the following values: + ## ``y, yes, true, 1, on``, then returns `true`. If ``s`` is one of the + ## following values: ``n, no, false, 0, off``, then returns `false`. + ## If ``s`` is something else a ``EInvalidValue`` exception is raised. + case normalize(s) + of "y", "yes", "true", "1", "on": result = true + of "n", "no", "false", "0", "off": result = false + else: raise newException(EInvalidValue, "cannot interpret as a bool: " & s) proc parseEnum*[T: enum](s: string): T = ## parses an enum ``T``. Raises ``EInvalidValue`` for an invalid value in @@ -418,30 +418,30 @@ proc parseEnum*[T: enum](s: string, default: T): T = if cmpIgnoreStyle(s, $e) == 0: return e result = default - -proc repeatChar*(count: int, c: Char = ' '): string {.noSideEffect, - rtl, extern: "nsuRepeatChar".} = - ## Returns a string of length `count` consisting only of - ## the character `c`. You can use this proc to left align strings. Example: - ## - ## .. code-block:: nimrod - ## let - ## width = 15 - ## text1 = "Hello user!" - ## text2 = "This is a very long string" - ## echo text1 & repeatChar(max(0, width - text1.len)) & "|" - ## echo text2 & repeatChar(max(0, width - text2.len)) & "|" - result = newString(count) - for i in 0..count-1: result[i] = c - -proc repeatStr*(count: int, s: string): string {.noSideEffect, - rtl, extern: "nsuRepeatStr".} = - ## Returns `s` concatenated `count` times. - result = newStringOfCap(count*s.len) - for i in 0..count-1: result.add(s) - -proc align*(s: string, count: int, padding = ' '): string {. - noSideEffect, rtl, extern: "nsuAlignString".} = + +proc repeatChar*(count: int, c: char = ' '): string {.noSideEffect, + rtl, extern: "nsuRepeatChar".} = + ## Returns a string of length `count` consisting only of + ## the character `c`. You can use this proc to left align strings. Example: + ## + ## .. code-block:: nimrod + ## let + ## width = 15 + ## text1 = "Hello user!" + ## text2 = "This is a very long string" + ## echo text1 & repeatChar(max(0, width - text1.len)) & "|" + ## echo text2 & repeatChar(max(0, width - text2.len)) & "|" + result = newString(count) + for i in 0..count-1: result[i] = c + +proc repeatStr*(count: int, s: string): string {.noSideEffect, + rtl, extern: "nsuRepeatStr".} = + ## Returns `s` concatenated `count` times. + result = newStringOfCap(count*s.len) + for i in 0..count-1: result.add(s) + +proc align*(s: string, count: int, padding = ' '): string {. + noSideEffect, rtl, extern: "nsuAlignString".} = ## Aligns a string `s` with `padding`, so that is of length `count`. ## `padding` characters (by default spaces) are added before `s` resulting in ## right alignment. If ``s.len >= count``, no spaces are added and `s` is @@ -453,247 +453,247 @@ proc align*(s: string, count: int, padding = ' '): string {. ## assert align("a", 0) == "a" ## assert align("1232", 6) == " 1232" ## assert align("1232", 6, '#') == "##1232" - if s.len < count: - result = newString(count) - let spaces = count - s.len - for i in 0..spaces-1: result[i] = padding - for i in spaces..count-1: result[i] = s[i-spaces] - else: - result = s - -iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ - token: string, isSep: bool] = - ## Tokenizes the string `s` into substrings. - ## - ## Substrings are separated by a substring containing only `seps`. - ## Examples: - ## - ## .. code-block:: nimrod - ## for word in tokenize(" this is an example "): - ## writeln(stdout, word) - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## (" ", true) - ## ("this", false) - ## (" ", true) - ## ("is", false) - ## (" ", true) - ## ("an", false) - ## (" ", true) - ## ("example", false) - ## (" ", true) - var i = 0 - while true: - var j = i - var isSep = s[j] in seps - while j < s.len and (s[j] in seps) == isSep: inc(j) - if j > i: - yield (substr(s, i, j-1), isSep) - else: - break - i = j - -proc wordWrap*(s: string, maxLineWidth = 80, - splitLongWords = true, - seps: set[char] = whitespace, - newLine = "\n"): string {. - noSideEffect, rtl, extern: "nsuWordWrap".} = - ## word wraps `s`. - result = newStringOfCap(s.len + s.len shr 6) - var SpaceLeft = maxLineWidth - for word, isSep in tokenize(s, seps): - if len(word) > SpaceLeft: - if splitLongWords and len(word) > maxLineWidth: - result.add(substr(word, 0, spaceLeft-1)) - var w = spaceLeft+1 - var wordLeft = len(word) - spaceLeft - while wordLeft > 0: - result.add(newLine) - var L = min(maxLineWidth, wordLeft) - SpaceLeft = maxLineWidth - L - result.add(substr(word, w, w+L-1)) - inc(w, L) - dec(wordLeft, L) - else: - SpaceLeft = maxLineWidth - len(Word) - result.add(newLine) - result.add(word) - else: - SpaceLeft = SpaceLeft - len(Word) - result.add(word) - -proc unindent*(s: string, eatAllIndent = false): string {. - noSideEffect, rtl, extern: "nsuUnindent".} = - ## unindents `s`. - result = newStringOfCap(s.len) - var i = 0 - var pattern = true - var indent = 0 - while s[i] == ' ': inc i - var level = if i == 0: -1 else: i - while i < s.len: - if s[i] == ' ': - if i > 0 and s[i-1] in {'\l', '\c'}: - pattern = true - indent = 0 - if pattern: - inc(indent) - if indent > level and not eatAllIndent: - result.add(s[i]) - if level < 0: level = indent - else: - # a space somewhere: do not delete - result.add(s[i]) - else: - pattern = false - result.add(s[i]) - inc i - -proc startsWith*(s, prefix: string): bool {.noSideEffect, - rtl, extern: "nsuStartsWith".} = - ## Returns true iff ``s`` starts with ``prefix``. - ## If ``prefix == ""`` true is returned. - var i = 0 - while true: - if prefix[i] == '\0': return true - if s[i] != prefix[i]: return false - inc(i) - -proc endsWith*(s, suffix: string): bool {.noSideEffect, - rtl, extern: "nsuEndsWith".} = - ## Returns true iff ``s`` ends with ``suffix``. - ## If ``suffix == ""`` true is returned. - var i = 0 - var j = len(s) - len(suffix) - while i+j <% s.len: - if s[i+j] != suffix[i]: return false - inc(i) - if suffix[i] == '\0': return true + if s.len < count: + result = newString(count) + let spaces = count - s.len + for i in 0..spaces-1: result[i] = padding + for i in spaces..count-1: result[i] = s[i-spaces] + else: + result = s + +iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[ + token: string, isSep: bool] = + ## Tokenizes the string `s` into substrings. + ## + ## Substrings are separated by a substring containing only `seps`. + ## Examples: + ## + ## .. code-block:: nimrod + ## for word in tokenize(" this is an example "): + ## writeln(stdout, word) + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## (" ", true) + ## ("this", false) + ## (" ", true) + ## ("is", false) + ## (" ", true) + ## ("an", false) + ## (" ", true) + ## ("example", false) + ## (" ", true) + var i = 0 + while true: + var j = i + var isSep = s[j] in seps + while j < s.len and (s[j] in seps) == isSep: inc(j) + if j > i: + yield (substr(s, i, j-1), isSep) + else: + break + i = j + +proc wordWrap*(s: string, maxLineWidth = 80, + splitLongWords = true, + seps: set[char] = whitespace, + newLine = "\n"): string {. + noSideEffect, rtl, extern: "nsuWordWrap".} = + ## word wraps `s`. + result = newStringOfCap(s.len + s.len shr 6) + var SpaceLeft = maxLineWidth + for word, isSep in tokenize(s, seps): + if len(word) > SpaceLeft: + if splitLongWords and len(word) > maxLineWidth: + result.add(substr(word, 0, SpaceLeft-1)) + var w = SpaceLeft+1 + var wordLeft = len(word) - SpaceLeft + while wordLeft > 0: + result.add(newLine) + var L = min(maxLineWidth, wordLeft) + SpaceLeft = maxLineWidth - L + result.add(substr(word, w, w+L-1)) + inc(w, L) + dec(wordLeft, L) + else: + SpaceLeft = maxLineWidth - len(word) + result.add(newLine) + result.add(word) + else: + SpaceLeft = SpaceLeft - len(word) + result.add(word) + +proc unindent*(s: string, eatAllIndent = false): string {. + noSideEffect, rtl, extern: "nsuUnindent".} = + ## unindents `s`. + result = newStringOfCap(s.len) + var i = 0 + var pattern = true + var indent = 0 + while s[i] == ' ': inc i + var level = if i == 0: -1 else: i + while i < s.len: + if s[i] == ' ': + if i > 0 and s[i-1] in {'\l', '\c'}: + pattern = true + indent = 0 + if pattern: + inc(indent) + if indent > level and not eatAllIndent: + result.add(s[i]) + if level < 0: level = indent + else: + # a space somewhere: do not delete + result.add(s[i]) + else: + pattern = false + result.add(s[i]) + inc i + +proc startsWith*(s, prefix: string): bool {.noSideEffect, + rtl, extern: "nsuStartsWith".} = + ## Returns true iff ``s`` starts with ``prefix``. + ## If ``prefix == ""`` true is returned. + var i = 0 + while true: + if prefix[i] == '\0': return true + if s[i] != prefix[i]: return false + inc(i) + +proc endsWith*(s, suffix: string): bool {.noSideEffect, + rtl, extern: "nsuEndsWith".} = + ## Returns true iff ``s`` ends with ``suffix``. + ## If ``suffix == ""`` true is returned. + var i = 0 + var j = len(s) - len(suffix) + while i+j <% s.len: + if s[i+j] != suffix[i]: return false + inc(i) + if suffix[i] == '\0': return true proc continuesWith*(s, substr: string, start: int): bool {.noSideEffect, rtl, extern: "nsuContinuesWith".} = - ## Returns true iff ``s`` continues with ``substr`` at position ``start``. - ## If ``substr == ""`` true is returned. - var i = 0 - while true: - if substr[i] == '\0': return true - if s[i+start] != substr[i]: return false - inc(i) - -proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect, - inline.} = - ## A shorthand for: - ## - ## .. code-block:: nimrod - ## if dest.len > startLen: add(dest, sep) - ## - ## This is often useful for generating some code where the items need to - ## be *separated* by `sep`. `sep` is only added if `dest` is longer than - ## `startLen`. The following example creates a string describing - ## an array of integers: - ## - ## .. code-block:: nimrod - ## var arr = "[" - ## for x in items([2, 3, 5, 7, 11]): - ## addSep(arr, startLen=len("[")) - ## add(arr, $x) - ## add(arr, "]") - if dest.len > startLen: add(dest, sep) - -proc allCharsInSet*(s: string, theSet: TCharSet): bool = - ## returns true iff each character of `s` is in the set `theSet`. - for c in items(s): - if c notin theSet: return false - return true - -proc abbrev*(s: string, possibilities: openarray[string]): int = - ## returns the index of the first item in `possibilities` if not - ## ambiguous; -1 if no item has been found; -2 if multiple items - ## match. - result = -1 # none found - for i in 0..possibilities.len-1: - if possibilities[i].startsWith(s): - if possibilities[i] == s: - # special case: exact match shouldn't be ambiguous - return i - if result >= 0: return -2 # ambiguous - result = i - -# --------------------------------------------------------------------------- - -proc join*(a: openArray[string], sep: string): string {. - noSideEffect, rtl, extern: "nsuJoinSep".} = - ## concatenates all strings in `a` separating them with `sep`. - if len(a) > 0: - var L = sep.len * (a.len-1) - for i in 0..high(a): inc(L, a[i].len) - result = newStringOfCap(L) - add(result, a[0]) - for i in 1..high(a): - add(result, sep) - add(result, a[i]) - else: - result = "" - -proc join*(a: openArray[string]): string {. - noSideEffect, rtl, extern: "nsuJoin".} = - ## concatenates all strings in `a`. - if len(a) > 0: - var L = 0 - for i in 0..high(a): inc(L, a[i].len) - result = newStringOfCap(L) - for i in 0..high(a): add(result, a[i]) - else: - result = "" - -type - TSkipTable = array[char, int] - -proc preprocessSub(sub: string, a: var TSkipTable) = - var m = len(sub) - for i in 0..0xff: a[chr(i)] = m+1 - for i in 0..m-1: a[sub[i]] = m-i - -proc findAux(s, sub: string, start: int, a: TSkipTable): int = - # fast "quick search" algorithm: - var - m = len(sub) - n = len(s) - # search: - var j = start - while j <= n - m: - block match: - for k in 0..m-1: - if sub[k] != s[k+j]: break match - return j - inc(j, a[s[j+m]]) - return -1 - -proc find*(s, sub: string, start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindStr", operator: 6.} = - ## Searches for `sub` in `s` starting at position `start`. Searching is - ## case-sensitive. If `sub` is not in `s`, -1 is returned. - var a {.noinit.}: TSkipTable - preprocessSub(sub, a) - result = findAux(s, sub, start, a) - -proc find*(s: string, sub: char, start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindChar".} = - ## Searches for `sub` in `s` starting at position `start`. Searching is - ## case-sensitive. If `sub` is not in `s`, -1 is returned. - for i in start..len(s)-1: - if sub == s[i]: return i - return -1 - -proc find*(s: string, chars: set[char], start: int = 0): int {.noSideEffect, - rtl, extern: "nsuFindCharSet".} = - ## Searches for `chars` in `s` starting at position `start`. If `s` contains - ## none of the characters in `chars`, -1 is returned. - for i in start..s.len-1: - if s[i] in chars: return i - return -1 + ## Returns true iff ``s`` continues with ``substr`` at position ``start``. + ## If ``substr == ""`` true is returned. + var i = 0 + while true: + if substr[i] == '\0': return true + if s[i+start] != substr[i]: return false + inc(i) + +proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect, + inline.} = + ## A shorthand for: + ## + ## .. code-block:: nimrod + ## if dest.len > startLen: add(dest, sep) + ## + ## This is often useful for generating some code where the items need to + ## be *separated* by `sep`. `sep` is only added if `dest` is longer than + ## `startLen`. The following example creates a string describing + ## an array of integers: + ## + ## .. code-block:: nimrod + ## var arr = "[" + ## for x in items([2, 3, 5, 7, 11]): + ## addSep(arr, startLen=len("[")) + ## add(arr, $x) + ## add(arr, "]") + if dest.len > startLen: add(dest, sep) + +proc allCharsInSet*(s: string, theSet: TCharSet): bool = + ## returns true iff each character of `s` is in the set `theSet`. + for c in items(s): + if c notin theSet: return false + return true + +proc abbrev*(s: string, possibilities: openArray[string]): int = + ## returns the index of the first item in `possibilities` if not + ## ambiguous; -1 if no item has been found; -2 if multiple items + ## match. + result = -1 # none found + for i in 0..possibilities.len-1: + if possibilities[i].startsWith(s): + if possibilities[i] == s: + # special case: exact match shouldn't be ambiguous + return i + if result >= 0: return -2 # ambiguous + result = i + +# --------------------------------------------------------------------------- + +proc join*(a: openArray[string], sep: string): string {. + noSideEffect, rtl, extern: "nsuJoinSep".} = + ## concatenates all strings in `a` separating them with `sep`. + if len(a) > 0: + var L = sep.len * (a.len-1) + for i in 0..high(a): inc(L, a[i].len) + result = newStringOfCap(L) + add(result, a[0]) + for i in 1..high(a): + add(result, sep) + add(result, a[i]) + else: + result = "" + +proc join*(a: openArray[string]): string {. + noSideEffect, rtl, extern: "nsuJoin".} = + ## concatenates all strings in `a`. + if len(a) > 0: + var L = 0 + for i in 0..high(a): inc(L, a[i].len) + result = newStringOfCap(L) + for i in 0..high(a): add(result, a[i]) + else: + result = "" + +type + TSkipTable = array[char, int] + +proc preprocessSub(sub: string, a: var TSkipTable) = + var m = len(sub) + for i in 0..0xff: a[chr(i)] = m+1 + for i in 0..m-1: a[sub[i]] = m-i + +proc findAux(s, sub: string, start: int, a: TSkipTable): int = + # fast "quick search" algorithm: + var + m = len(sub) + n = len(s) + # search: + var j = start + while j <= n - m: + block match: + for k in 0..m-1: + if sub[k] != s[k+j]: break match + return j + inc(j, a[s[j+m]]) + return -1 + +proc find*(s, sub: string, start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindStr", operator: 6.} = + ## Searches for `sub` in `s` starting at position `start`. Searching is + ## case-sensitive. If `sub` is not in `s`, -1 is returned. + var a {.noinit.}: TSkipTable + preprocessSub(sub, a) + result = findAux(s, sub, start, a) + +proc find*(s: string, sub: char, start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindChar".} = + ## Searches for `sub` in `s` starting at position `start`. Searching is + ## case-sensitive. If `sub` is not in `s`, -1 is returned. + for i in start..len(s)-1: + if sub == s[i]: return i + return -1 + +proc find*(s: string, chars: set[char], start: int = 0): int {.noSideEffect, + rtl, extern: "nsuFindCharSet".} = + ## Searches for `chars` in `s` starting at position `start`. If `s` contains + ## none of the characters in `chars`, -1 is returned. + for i in start..s.len-1: + if s[i] in chars: return i + return -1 proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} = ## Searches for `sub` in `s` in reverse, starting at `start` and going @@ -708,180 +708,180 @@ proc rfind*(s, sub: string, start: int = -1): int {.noSideEffect.} = break if result != -1: return return -1 - + proc quoteIfContainsWhite*(s: string): string {.deprecated.} = - ## returns ``'"' & s & '"'`` if `s` contains a space and does not - ## start with a quote, else returns `s` + ## returns ``'"' & s & '"'`` if `s` contains a space and does not + ## start with a quote, else returns `s` ## DEPRECATED as it was confused for shell quoting function. ## For this application use osproc.quoteShell. - if find(s, {' ', '\t'}) >= 0 and s[0] != '"': - result = '"' & s & '"' - else: - result = s - -proc contains*(s: string, c: char): bool {.noSideEffect.} = - ## Same as ``find(s, c) >= 0``. - return find(s, c) >= 0 - -proc contains*(s, sub: string): bool {.noSideEffect.} = - ## Same as ``find(s, sub) >= 0``. - return find(s, sub) >= 0 - -proc contains*(s: string, chars: set[char]): bool {.noSideEffect.} = - ## Same as ``find(s, chars) >= 0``. - return find(s, chars) >= 0 - -proc replace*(s, sub: string, by = ""): string {.noSideEffect, - rtl, extern: "nsuReplaceStr", operator: 1.} = - ## Replaces `sub` in `s` by the string `by`. - var a {.noinit.}: TSkipTable - result = "" - preprocessSub(sub, a) - var i = 0 - while true: - var j = findAux(s, sub, i, a) - if j < 0: break - add result, substr(s, i, j - 1) - add result, by - i = j + len(sub) - # copy the rest: - add result, substr(s, i) - -proc replace*(s: string, sub, by: char): string {.noSideEffect, - rtl, extern: "nsuReplaceChar".} = - ## optimized version for characters. - result = newString(s.len) - var i = 0 - while i < s.len: - if s[i] == sub: result[i] = by - else: result[i] = s[i] - inc(i) - -proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect, - rtl, extern: "nsuReplaceWord".} = - ## Replaces `sub` in `s` by the string `by`. Each occurance of `sub` - ## has to be surrounded by word boundaries (comparable to ``\\w`` in - ## regular expressions), otherwise it is not replaced. - const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} - var a {.noinit.}: TSkipTable - result = "" - preprocessSub(sub, a) - var i = 0 - while true: - var j = findAux(s, sub, i, a) - if j < 0: break - # word boundary? - if (j == 0 or s[j-1] notin wordChars) and - (j+sub.len >= s.len or s[j+sub.len] notin wordChars): - add result, substr(s, i, j - 1) - add result, by - i = j + len(sub) - else: - add result, substr(s, i, j) - i = j + 1 - # copy the rest: - add result, substr(s, i) - -proc delete*(s: var string, first, last: int) {.noSideEffect, - rtl, extern: "nsuDelete".} = - ## Deletes in `s` the characters at position `first` .. `last`. This modifies - ## `s` itself, it does not return a copy. - var i = first - var j = last+1 - var newLen = len(s)-j+i - while i < newLen: - s[i] = s[j] - inc(i) - inc(j) - setlen(s, newLen) - -proc parseOctInt*(s: string): int {.noSideEffect, - rtl, extern: "nsuParseOctInt".} = - ## Parses an octal integer value contained in `s`. If `s` is not - ## a valid integer, `EInvalidValue` is raised. `s` can have one of the - ## following optional prefixes: ``0o``, ``0O``. - ## Underscores within `s` are ignored. - var i = 0 - if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) - while true: - case s[i] - of '_': inc(i) - of '0'..'7': - result = result shl 3 or (ord(s[i]) - ord('0')) - inc(i) - of '\0': break - else: raise newException(EInvalidValue, "invalid integer: " & s) - -proc toOct*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToOct".} = - ## converts `x` into its octal representation. The resulting string is - ## always `len` characters long. No leading ``0o`` prefix is generated. - var - mask: BiggestInt = 7 - shift: BiggestInt = 0 - assert(len > 0) - result = newString(len) - for j in countdown(len-1, 0): - result[j] = chr(int((x and mask) shr shift) + ord('0')) - shift = shift + 3 - mask = mask shl 3 - -proc toBin*(x: BiggestInt, len: int): string {.noSideEffect, - rtl, extern: "nsuToBin".} = - ## converts `x` into its binary representation. The resulting string is - ## always `len` characters long. No leading ``0b`` prefix is generated. - var - mask: BiggestInt = 1 - shift: BiggestInt = 0 - assert(len > 0) - result = newString(len) - for j in countdown(len-1, 0): - result[j] = chr(int((x and mask) shr shift) + ord('0')) - shift = shift + 1 - mask = mask shl 1 - -proc insertSep*(s: string, sep = '_', digits = 3): string {.noSideEffect, - rtl, extern: "nsuInsertSep".} = - ## inserts the separator `sep` after `digits` digits from right to left. - ## Even though the algorithm works with any string `s`, it is only useful - ## if `s` contains a number. - ## Example: ``insertSep("1000000") == "1_000_000"`` - var L = (s.len-1) div digits + s.len - result = newString(L) - var j = 0 - dec(L) - for i in countdown(len(s)-1, 0): - if j == digits: - result[L] = sep - dec(L) - j = 0 - result[L] = s[i] - inc(j) - dec(L) - -proc escape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, - rtl, extern: "nsuEscape".} = - ## Escapes a string `s`. This does these operations (at the same time): - ## * replaces any ``\`` by ``\\`` - ## * replaces any ``'`` by ``\'`` - ## * replaces any ``"`` by ``\"`` - ## * replaces any other character in the set ``{'\0'..'\31', '\128'..'\255'}`` - ## by ``\xHH`` where ``HH`` is its hexadecimal value. - ## The procedure has been designed so that its output is usable for many - ## different common syntaxes. The resulting string is prefixed with - ## `prefix` and suffixed with `suffix`. Both may be empty strings. - result = newStringOfCap(s.len + s.len shr 2) - result.add(prefix) - for c in items(s): - case c - of '\0'..'\31', '\128'..'\255': - add(result, "\\x") - add(result, toHex(ord(c), 2)) - of '\\': add(result, "\\\\") - of '\'': add(result, "\\'") - of '\"': add(result, "\\\"") - else: add(result, c) - add(result, suffix) + if find(s, {' ', '\t'}) >= 0 and s[0] != '"': + result = '"' & s & '"' + else: + result = s + +proc contains*(s: string, c: char): bool {.noSideEffect.} = + ## Same as ``find(s, c) >= 0``. + return find(s, c) >= 0 + +proc contains*(s, sub: string): bool {.noSideEffect.} = + ## Same as ``find(s, sub) >= 0``. + return find(s, sub) >= 0 + +proc contains*(s: string, chars: set[char]): bool {.noSideEffect.} = + ## Same as ``find(s, chars) >= 0``. + return find(s, chars) >= 0 + +proc replace*(s, sub: string, by = ""): string {.noSideEffect, + rtl, extern: "nsuReplaceStr", operator: 1.} = + ## Replaces `sub` in `s` by the string `by`. + var a {.noinit.}: TSkipTable + result = "" + preprocessSub(sub, a) + var i = 0 + while true: + var j = findAux(s, sub, i, a) + if j < 0: break + add result, substr(s, i, j - 1) + add result, by + i = j + len(sub) + # copy the rest: + add result, substr(s, i) + +proc replace*(s: string, sub, by: char): string {.noSideEffect, + rtl, extern: "nsuReplaceChar".} = + ## optimized version for characters. + result = newString(s.len) + var i = 0 + while i < s.len: + if s[i] == sub: result[i] = by + else: result[i] = s[i] + inc(i) + +proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect, + rtl, extern: "nsuReplaceWord".} = + ## Replaces `sub` in `s` by the string `by`. Each occurance of `sub` + ## has to be surrounded by word boundaries (comparable to ``\\w`` in + ## regular expressions), otherwise it is not replaced. + const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} + var a {.noinit.}: TSkipTable + result = "" + preprocessSub(sub, a) + var i = 0 + while true: + var j = findAux(s, sub, i, a) + if j < 0: break + # word boundary? + if (j == 0 or s[j-1] notin wordChars) and + (j+sub.len >= s.len or s[j+sub.len] notin wordChars): + add result, substr(s, i, j - 1) + add result, by + i = j + len(sub) + else: + add result, substr(s, i, j) + i = j + 1 + # copy the rest: + add result, substr(s, i) + +proc delete*(s: var string, first, last: int) {.noSideEffect, + rtl, extern: "nsuDelete".} = + ## Deletes in `s` the characters at position `first` .. `last`. This modifies + ## `s` itself, it does not return a copy. + var i = first + var j = last+1 + var newLen = len(s)-j+i + while i < newLen: + s[i] = s[j] + inc(i) + inc(j) + setLen(s, newLen) + +proc parseOctInt*(s: string): int {.noSideEffect, + rtl, extern: "nsuParseOctInt".} = + ## Parses an octal integer value contained in `s`. If `s` is not + ## a valid integer, `EInvalidValue` is raised. `s` can have one of the + ## following optional prefixes: ``0o``, ``0O``. + ## Underscores within `s` are ignored. + var i = 0 + if s[i] == '0' and (s[i+1] == 'o' or s[i+1] == 'O'): inc(i, 2) + while true: + case s[i] + of '_': inc(i) + of '0'..'7': + result = result shl 3 or (ord(s[i]) - ord('0')) + inc(i) + of '\0': break + else: raise newException(EInvalidValue, "invalid integer: " & s) + +proc toOct*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToOct".} = + ## converts `x` into its octal representation. The resulting string is + ## always `len` characters long. No leading ``0o`` prefix is generated. + var + mask: BiggestInt = 7 + shift: BiggestInt = 0 + assert(len > 0) + result = newString(len) + for j in countdown(len-1, 0): + result[j] = chr(int((x and mask) shr shift) + ord('0')) + shift = shift + 3 + mask = mask shl 3 + +proc toBin*(x: BiggestInt, len: int): string {.noSideEffect, + rtl, extern: "nsuToBin".} = + ## converts `x` into its binary representation. The resulting string is + ## always `len` characters long. No leading ``0b`` prefix is generated. + var + mask: BiggestInt = 1 + shift: BiggestInt = 0 + assert(len > 0) + result = newString(len) + for j in countdown(len-1, 0): + result[j] = chr(int((x and mask) shr shift) + ord('0')) + shift = shift + 1 + mask = mask shl 1 + +proc insertSep*(s: string, sep = '_', digits = 3): string {.noSideEffect, + rtl, extern: "nsuInsertSep".} = + ## inserts the separator `sep` after `digits` digits from right to left. + ## Even though the algorithm works with any string `s`, it is only useful + ## if `s` contains a number. + ## Example: ``insertSep("1000000") == "1_000_000"`` + var L = (s.len-1) div digits + s.len + result = newString(L) + var j = 0 + dec(L) + for i in countdown(len(s)-1, 0): + if j == digits: + result[L] = sep + dec(L) + j = 0 + result[L] = s[i] + inc(j) + dec(L) + +proc escape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, + rtl, extern: "nsuEscape".} = + ## Escapes a string `s`. This does these operations (at the same time): + ## * replaces any ``\`` by ``\\`` + ## * replaces any ``'`` by ``\'`` + ## * replaces any ``"`` by ``\"`` + ## * replaces any other character in the set ``{'\0'..'\31', '\128'..'\255'}`` + ## by ``\xHH`` where ``HH`` is its hexadecimal value. + ## The procedure has been designed so that its output is usable for many + ## different common syntaxes. The resulting string is prefixed with + ## `prefix` and suffixed with `suffix`. Both may be empty strings. + result = newStringOfCap(s.len + s.len shr 2) + result.add(prefix) + for c in items(s): + case c + of '\0'..'\31', '\128'..'\255': + add(result, "\\x") + add(result, toHex(ord(c), 2)) + of '\\': add(result, "\\\\") + of '\'': add(result, "\\'") + of '\"': add(result, "\\\"") + else: add(result, c) + add(result, suffix) proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, rtl, extern: "nsuUnescape".} = @@ -920,323 +920,323 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect, if s[i .. -1] != suffix: raise newException(EInvalidValue, "String does not end with a suffix of: " & suffix) - -proc validIdentifier*(s: string): bool {.noSideEffect, - rtl, extern: "nsuValidIdentifier".} = - ## returns true if `s` is a valid identifier. A valid identifier starts - ## with a character of the set `IdentStartChars` and is followed by any - ## number of characters of the set `IdentChars`. - if s[0] in IdentStartChars: - for i in 1..s.len-1: - if s[i] notin IdentChars: return false - return true - -proc editDistance*(a, b: string): int {.noSideEffect, - rtl, extern: "nsuEditDistance".} = - ## returns the edit distance between `a` and `b`. This uses the - ## `Levenshtein`:idx: distance algorithm with only a linear memory overhead. - ## This implementation is highly optimized! - var len1 = a.len - var len2 = b.len - if len1 > len2: - # make `b` the longer string - return editDistance(b, a) - - # strip common prefix: - var s = 0 - while a[s] == b[s] and a[s] != '\0': - inc(s) - dec(len1) - dec(len2) - # strip common suffix: - while len1 > 0 and len2 > 0 and a[s+len1-1] == b[s+len2-1]: - dec(len1) - dec(len2) - # trivial cases: - if len1 == 0: return len2 - if len2 == 0: return len1 - - # another special case: - if len1 == 1: - for j in s..len2-1: - if a[s] == b[j]: return len2 - 1 - return len2 - - inc(len1) - inc(len2) - var half = len1 shr 1 - # initalize first row: - #var row = cast[ptr array[0..high(int) div 8, int]](alloc(len2*sizeof(int))) - var row: seq[int] - newSeq(row, len2) - var e = s + len2 - 1 # end marker - for i in 1..len2 - half - 1: row[i] = i - row[0] = len1 - half - 1 - for i in 1 .. len1 - 1: - var char1 = a[i + s - 1] - var char2p: int - var D, x: int - var p: int - if i >= len1 - half: - # skip the upper triangle: - var offset = i - len1 + half - char2p = offset - p = offset - var c3 = row[p] + ord(char1 != b[s + char2p]) - inc(p) - inc(char2p) - x = row[p] + 1 - D = x - if x > c3: x = c3 - row[p] = x - inc(p) - else: - p = 1 - char2p = 0 - D = i - x = i - if i <= half + 1: - # skip the lower triangle: - e = len2 + i - half - 2 - # main: - while p <= e: - dec(D) - var c3 = D + ord(char1 != b[char2p + s]) - inc(char2p) - inc(x) - if x > c3: x = c3 - D = row[p] + 1 - if x > D: x = D - row[p] = x - inc(p) - # lower triangle sentinel: - if i <= half: - dec(D) - var c3 = D + ord(char1 != b[char2p + s]) - inc(x) - if x > c3: x = c3 - row[p] = x - result = row[e] - #dealloc(row) - - -# floating point formating: - -proc c_sprintf(buf, frmt: CString) {.header: "", importc: "sprintf", - varargs, noSideEffect.} - -type - TFloatFormat* = enum ## the different modes of floating point formating - ffDefault, ## use the shorter floating point notation - ffDecimal, ## use decimal floating point notation - ffScientific ## use scientific notation (using ``e`` character) - -proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault, + +proc validIdentifier*(s: string): bool {.noSideEffect, + rtl, extern: "nsuValidIdentifier".} = + ## returns true if `s` is a valid identifier. A valid identifier starts + ## with a character of the set `IdentStartChars` and is followed by any + ## number of characters of the set `IdentChars`. + if s[0] in IdentStartChars: + for i in 1..s.len-1: + if s[i] notin IdentChars: return false + return true + +proc editDistance*(a, b: string): int {.noSideEffect, + rtl, extern: "nsuEditDistance".} = + ## returns the edit distance between `a` and `b`. This uses the + ## `Levenshtein`:idx: distance algorithm with only a linear memory overhead. + ## This implementation is highly optimized! + var len1 = a.len + var len2 = b.len + if len1 > len2: + # make `b` the longer string + return editDistance(b, a) + + # strip common prefix: + var s = 0 + while a[s] == b[s] and a[s] != '\0': + inc(s) + dec(len1) + dec(len2) + # strip common suffix: + while len1 > 0 and len2 > 0 and a[s+len1-1] == b[s+len2-1]: + dec(len1) + dec(len2) + # trivial cases: + if len1 == 0: return len2 + if len2 == 0: return len1 + + # another special case: + if len1 == 1: + for j in s..len2-1: + if a[s] == b[j]: return len2 - 1 + return len2 + + inc(len1) + inc(len2) + var half = len1 shr 1 + # initalize first row: + #var row = cast[ptr array[0..high(int) div 8, int]](alloc(len2*sizeof(int))) + var row: seq[int] + newSeq(row, len2) + var e = s + len2 - 1 # end marker + for i in 1..len2 - half - 1: row[i] = i + row[0] = len1 - half - 1 + for i in 1 .. len1 - 1: + var char1 = a[i + s - 1] + var char2p: int + var D, x: int + var p: int + if i >= len1 - half: + # skip the upper triangle: + var offset = i - len1 + half + char2p = offset + p = offset + var c3 = row[p] + ord(char1 != b[s + char2p]) + inc(p) + inc(char2p) + x = row[p] + 1 + D = x + if x > c3: x = c3 + row[p] = x + inc(p) + else: + p = 1 + char2p = 0 + D = i + x = i + if i <= half + 1: + # skip the lower triangle: + e = len2 + i - half - 2 + # main: + while p <= e: + dec(D) + var c3 = D + ord(char1 != b[char2p + s]) + inc(char2p) + inc(x) + if x > c3: x = c3 + D = row[p] + 1 + if x > D: x = D + row[p] = x + inc(p) + # lower triangle sentinel: + if i <= half: + dec(D) + var c3 = D + ord(char1 != b[char2p + s]) + inc(x) + if x > c3: x = c3 + row[p] = x + result = row[e] + #dealloc(row) + + +# floating point formating: + +proc c_sprintf(buf, frmt: cstring) {.header: "", importc: "sprintf", + varargs, noSideEffect.} + +type + TFloatFormat* = enum ## the different modes of floating point formating + ffDefault, ## use the shorter floating point notation + ffDecimal, ## use decimal floating point notation + ffScientific ## use scientific notation (using ``e`` character) + +proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault, precision: range[0..32] = 16): string {. - noSideEffect, operator: 2, rtl, extern: "nsu$1".} = - ## converts a floating point value `f` to a string. - ## - ## If ``format == ffDecimal`` then precision is the number of digits to - ## be printed after the decimal point. - ## If ``format == ffScientific`` then precision is the maximum number - ## of significant digits to be printed. - ## `precision`'s default value is the maximum number of meaningful digits + noSideEffect, operator: 2, rtl, extern: "nsu$1".} = + ## converts a floating point value `f` to a string. + ## + ## If ``format == ffDecimal`` then precision is the number of digits to + ## be printed after the decimal point. + ## If ``format == ffScientific`` then precision is the maximum number + ## of significant digits to be printed. + ## `precision`'s default value is the maximum number of meaningful digits ## after the decimal point for Nimrod's ``biggestFloat`` type. ## - ## If ``precision == 0``, it tries to format it nicely. - const floatFormatToChar: array[TFloatFormat, char] = ['g', 'f', 'e'] - var - frmtstr {.noinit.}: array[0..5, char] - buf {.noinit.}: array[0..2500, char] - frmtstr[0] = '%' - if precision > 0: - frmtstr[1] = '#' - frmtstr[2] = '.' - frmtstr[3] = '*' - frmtstr[4] = floatFormatToChar[format] - frmtstr[5] = '\0' - c_sprintf(buf, frmtstr, precision, f) - else: - frmtstr[1] = floatFormatToChar[format] - frmtstr[2] = '\0' - c_sprintf(buf, frmtstr, f) - result = $buf - -proc formatFloat*(f: float, format: TFloatFormat = ffDefault, + ## If ``precision == 0``, it tries to format it nicely. + const floatFormatToChar: array[TFloatFormat, char] = ['g', 'f', 'e'] + var + frmtstr {.noinit.}: array[0..5, char] + buf {.noinit.}: array[0..2500, char] + frmtstr[0] = '%' + if precision > 0: + frmtstr[1] = '#' + frmtstr[2] = '.' + frmtstr[3] = '*' + frmtstr[4] = floatFormatToChar[format] + frmtstr[5] = '\0' + c_sprintf(buf, frmtstr, precision, f) + else: + frmtstr[1] = floatFormatToChar[format] + frmtstr[2] = '\0' + c_sprintf(buf, frmtstr, f) + result = $buf + +proc formatFloat*(f: float, format: TFloatFormat = ffDefault, precision: range[0..32] = 16): string {. - noSideEffect, operator: 2, rtl, extern: "nsu$1".} = - ## converts a floating point value `f` to a string. - ## - ## If ``format == ffDecimal`` then precision is the number of digits to - ## be printed after the decimal point. - ## If ``format == ffScientific`` then precision is the maximum number - ## of significant digits to be printed. - ## `precision`'s default value is the maximum number of meaningful digits - ## after the decimal point for Nimrod's ``float`` type. - result = formatBiggestFloat(f, format, precision) - -proc formatSize*(bytes: biggestInt, decimalSep = '.'): string = - ## Rounds and formats `bytes`. Examples: - ## - ## .. code-block:: nimrod - ## - ## formatSize(1'i64 shl 31 + 300'i64) == "2.204GB" - ## formatSize(4096) == "4KB" - ## - template frmt(a, b, c: expr): expr = - let bs = $b - insertSep($a) & decimalSep & bs.substr(0, 2) & c - let gigabytes = bytes shr 30 - let megabytes = bytes shr 20 - let kilobytes = bytes shr 10 - if gigabytes != 0: - result = frmt(gigabytes, megabytes, "GB") - elif megabytes != 0: - result = frmt(megabytes, kilobytes, "MB") - elif kilobytes != 0: - result = frmt(kilobytes, bytes, "KB") - else: - result = insertSep($bytes) & "B" - -proc findNormalized(x: string, inArray: openarray[string]): int = - var i = 0 - while i < high(inArray): - if cmpIgnoreStyle(x, inArray[i]) == 0: return i - inc(i, 2) # incrementing by 1 would probably lead to a - # security hole... - return -1 - -proc invalidFormatString() {.noinline.} = - raise newException(EInvalidValue, "invalid format string") - -proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {. - noSideEffect, rtl, extern: "nsuAddf".} = - ## The same as ``add(s, formatstr % a)``, but more efficient. - const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} - var i = 0 - var num = 0 - while i < len(formatstr): - if formatstr[i] == '$': - case formatstr[i+1] # again we use the fact that strings - # are zero-terminated here - of '#': - if num >% a.high: invalidFormatString() - add s, a[num] - inc i, 2 - inc num - of '$': - add s, '$' - inc(i, 2) - of '1'..'9', '-': - var j = 0 - inc(i) # skip $ - var negative = formatstr[i] == '-' - if negative: inc i - while formatstr[i] in Digits: - j = j * 10 + ord(formatstr[i]) - ord('0') - inc(i) - let idx = if not negative: j-1 else: a.len-j - if idx >% a.high: invalidFormatString() - add s, a[idx] - of '{': - var j = i+1 - while formatstr[j] notin {'\0', '}'}: inc(j) - var x = findNormalized(substr(formatstr, i+2, j-1), a) - if x >= 0 and x < high(a): add s, a[x+1] - else: invalidFormatString() - i = j+1 - of 'a'..'z', 'A'..'Z', '\128'..'\255', '_': - var j = i+1 - while formatstr[j] in PatternChars: inc(j) - var x = findNormalized(substr(formatstr, i+1, j-1), a) - if x >= 0 and x < high(a): add s, a[x+1] - else: invalidFormatString() - i = j - else: - invalidFormatString() - else: - add s, formatstr[i] - inc(i) - -proc `%` *(formatstr: string, a: openarray[string]): string {.noSideEffect, - rtl, extern: "nsuFormatOpenArray".} = - ## The `substitution`:idx: operator performs string substitutions in - ## `formatstr` and returns a modified `formatstr`. This is often called - ## `string interpolation`:idx:. - ## - ## This is best explained by an example: - ## - ## .. code-block:: nimrod - ## "$1 eats $2." % ["The cat", "fish"] - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "The cat eats fish." - ## - ## The substitution variables (the thing after the ``$``) are enumerated - ## from 1 to ``a.len``. - ## To produce a verbatim ``$``, use ``$$``. - ## The notation ``$#`` can be used to refer to the next substitution - ## variable: - ## - ## .. code-block:: nimrod - ## "$# eats $#." % ["The cat", "fish"] - ## - ## Substitution variables can also be words (that is - ## ``[A-Za-z_]+[A-Za-z0-9_]*``) in which case the arguments in `a` with even - ## indices are keys and with odd indices are the corresponding values. - ## An example: - ## - ## .. code-block:: nimrod - ## "$animal eats $food." % ["animal", "The cat", "food", "fish"] - ## - ## Results in: - ## - ## .. code-block:: nimrod - ## "The cat eats fish." - ## - ## The variables are compared with `cmpIgnoreStyle`. `EInvalidValue` is - ## raised if an ill-formed format string has been passed to the `%` operator. - result = newStringOfCap(formatstr.len + a.len shl 4) - addf(result, formatstr, a) - -proc `%` *(formatstr, a: string): string {.noSideEffect, - rtl, extern: "nsuFormatSingleElem".} = - ## This is the same as ``formatstr % [a]``. - result = newStringOfCap(formatstr.len + a.len) - addf(result, formatstr, [a]) - -proc format*(formatstr: string, a: varargs[string, `$`]): string {.noSideEffect, - rtl, extern: "nsuFormatVarargs".} = + noSideEffect, operator: 2, rtl, extern: "nsu$1".} = + ## converts a floating point value `f` to a string. + ## + ## If ``format == ffDecimal`` then precision is the number of digits to + ## be printed after the decimal point. + ## If ``format == ffScientific`` then precision is the maximum number + ## of significant digits to be printed. + ## `precision`'s default value is the maximum number of meaningful digits + ## after the decimal point for Nimrod's ``float`` type. + result = formatBiggestFloat(f, format, precision) + +proc formatSize*(bytes: BiggestInt, decimalSep = '.'): string = + ## Rounds and formats `bytes`. Examples: + ## + ## .. code-block:: nimrod + ## + ## formatSize(1'i64 shl 31 + 300'i64) == "2.204GB" + ## formatSize(4096) == "4KB" + ## + template frmt(a, b, c: expr): expr = + let bs = $b + insertSep($a) & decimalSep & bs.substr(0, 2) & c + let gigabytes = bytes shr 30 + let megabytes = bytes shr 20 + let kilobytes = bytes shr 10 + if gigabytes != 0: + result = frmt(gigabytes, megabytes, "GB") + elif megabytes != 0: + result = frmt(megabytes, kilobytes, "MB") + elif kilobytes != 0: + result = frmt(kilobytes, bytes, "KB") + else: + result = insertSep($bytes) & "B" + +proc findNormalized(x: string, inArray: openArray[string]): int = + var i = 0 + while i < high(inArray): + if cmpIgnoreStyle(x, inArray[i]) == 0: return i + inc(i, 2) # incrementing by 1 would probably lead to a + # security hole... + return -1 + +proc invalidFormatString() {.noinline.} = + raise newException(EInvalidValue, "invalid format string") + +proc addf*(s: var string, formatstr: string, a: varargs[string, `$`]) {. + noSideEffect, rtl, extern: "nsuAddf".} = + ## The same as ``add(s, formatstr % a)``, but more efficient. + const PatternChars = {'a'..'z', 'A'..'Z', '0'..'9', '\128'..'\255', '_'} + var i = 0 + var num = 0 + while i < len(formatstr): + if formatstr[i] == '$': + case formatstr[i+1] # again we use the fact that strings + # are zero-terminated here + of '#': + if num >% a.high: invalidFormatString() + add s, a[num] + inc i, 2 + inc num + of '$': + add s, '$' + inc(i, 2) + of '1'..'9', '-': + var j = 0 + inc(i) # skip $ + var negative = formatstr[i] == '-' + if negative: inc i + while formatstr[i] in Digits: + j = j * 10 + ord(formatstr[i]) - ord('0') + inc(i) + let idx = if not negative: j-1 else: a.len-j + if idx >% a.high: invalidFormatString() + add s, a[idx] + of '{': + var j = i+1 + while formatstr[j] notin {'\0', '}'}: inc(j) + var x = findNormalized(substr(formatstr, i+2, j-1), a) + if x >= 0 and x < high(a): add s, a[x+1] + else: invalidFormatString() + i = j+1 + of 'a'..'z', 'A'..'Z', '\128'..'\255', '_': + var j = i+1 + while formatstr[j] in PatternChars: inc(j) + var x = findNormalized(substr(formatstr, i+1, j-1), a) + if x >= 0 and x < high(a): add s, a[x+1] + else: invalidFormatString() + i = j + else: + invalidFormatString() + else: + add s, formatstr[i] + inc(i) + +proc `%` *(formatstr: string, a: openArray[string]): string {.noSideEffect, + rtl, extern: "nsuFormatOpenArray".} = + ## The `substitution`:idx: operator performs string substitutions in + ## `formatstr` and returns a modified `formatstr`. This is often called + ## `string interpolation`:idx:. + ## + ## This is best explained by an example: + ## + ## .. code-block:: nimrod + ## "$1 eats $2." % ["The cat", "fish"] + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "The cat eats fish." + ## + ## The substitution variables (the thing after the ``$``) are enumerated + ## from 1 to ``a.len``. + ## To produce a verbatim ``$``, use ``$$``. + ## The notation ``$#`` can be used to refer to the next substitution + ## variable: + ## + ## .. code-block:: nimrod + ## "$# eats $#." % ["The cat", "fish"] + ## + ## Substitution variables can also be words (that is + ## ``[A-Za-z_]+[A-Za-z0-9_]*``) in which case the arguments in `a` with even + ## indices are keys and with odd indices are the corresponding values. + ## An example: + ## + ## .. code-block:: nimrod + ## "$animal eats $food." % ["animal", "The cat", "food", "fish"] + ## + ## Results in: + ## + ## .. code-block:: nimrod + ## "The cat eats fish." + ## + ## The variables are compared with `cmpIgnoreStyle`. `EInvalidValue` is + ## raised if an ill-formed format string has been passed to the `%` operator. + result = newStringOfCap(formatstr.len + a.len shl 4) + addf(result, formatstr, a) + +proc `%` *(formatstr, a: string): string {.noSideEffect, + rtl, extern: "nsuFormatSingleElem".} = + ## This is the same as ``formatstr % [a]``. + result = newStringOfCap(formatstr.len + a.len) + addf(result, formatstr, [a]) + +proc format*(formatstr: string, a: varargs[string, `$`]): string {.noSideEffect, + rtl, extern: "nsuFormatVarargs".} = ## This is the same as ``formatstr % a`` except that it supports - ## auto stringification. - result = newStringOfCap(formatstr.len + a.len) - addf(result, formatstr, a) - -{.pop.} - -when isMainModule: - doAssert align("abc", 4) == " abc" - doAssert align("a", 0) == "a" - doAssert align("1232", 6) == " 1232" - doAssert align("1232", 6, '#') == "##1232" - echo wordWrap(""" this is a long text -- muchlongerthan10chars and here - it goes""", 10, false) - doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001" - doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) == "1.0e-11" - - doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c" - echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB" - echo formatSize(1'i64 shl 31) - - doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] == - "The cat eats fish." - - doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz " - doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc" + ## auto stringification. + result = newStringOfCap(formatstr.len + a.len) + addf(result, formatstr, a) + +{.pop.} + +when isMainModule: + doAssert align("abc", 4) == " abc" + doAssert align("a", 0) == "a" + doAssert align("1232", 6) == " 1232" + doAssert align("1232", 6, '#') == "##1232" + echo wordWrap(""" this is a long text -- muchlongerthan10chars and here + it goes""", 10, false) + doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001" + doAssert formatBiggestFloat(0.00000000001, ffScientific, 1) == "1.0e-11" + + doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c" + echo formatSize(1'i64 shl 31 + 300'i64) # == "4,GB" + echo formatSize(1'i64 shl 31) + + doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] == + "The cat eats fish." + + doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz " + doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc" - type TMyEnum = enum enA, enB, enC, enuD, enE - doAssert parseEnum[TMyEnum]("enu_D") == enuD + type TMyEnum = enum enA, enB, enC, enuD, enE + doAssert parseEnum[TMyEnum]("enu_D") == enuD - doAssert parseEnum("invalid enum value", enC) == enC + doAssert parseEnum("invalid enum value", enC) == enC diff --git a/lib/pure/times.nim b/lib/pure/times.nim index a37091c52..6dfe80ca1 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -256,7 +256,7 @@ proc `+`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo = ## ## **Note:** This has been only briefly tested and it may not be ## very accurate. - let t = toSeconds(TimeInfoToTime(a)) + let t = toSeconds(timeInfoToTime(a)) let secs = toSeconds(a, interval) if a.tzname == "UTC": result = getGMTime(fromSeconds(t + secs)) @@ -268,7 +268,7 @@ proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo = ## ## **Note:** This has been only briefly tested, it is inaccurate especially ## when you subtract so much that you reach the Julian calendar. - let t = toSeconds(TimeInfoToTime(a)) + let t = toSeconds(timeInfoToTime(a)) let secs = toSeconds(a, interval) if a.tzname == "UTC": result = getGMTime(fromSeconds(t - secs)) @@ -319,11 +319,11 @@ when not defined(JS): importc: "gmtime", header: "", tags: [].} proc timec(timer: PTime): TTime {. importc: "time", header: "", tags: [].} - proc mktime(t: structTM): TTime {. + proc mktime(t: StructTM): TTime {. importc: "mktime", header: "", tags: [].} - proc asctime(tblock: structTM): CString {. + proc asctime(tblock: StructTM): cstring {. importc: "asctime", header: "", tags: [].} - proc ctime(time: PTime): CString {. + proc ctime(time: PTime): cstring {. importc: "ctime", header: "", tags: [].} # strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {. # importc: "strftime", header: "".} @@ -335,7 +335,7 @@ when not defined(JS): clocksPerSec {.importc: "CLOCKS_PER_SEC", nodecl.}: int # our own procs on top of that: - proc tmToTimeInfo(tm: structTM, local: bool): TTimeInfo = + proc tmToTimeInfo(tm: StructTM, local: bool): TTimeInfo = const weekDays: array [0..6, TWeekDay] = [ dSun, dMon, dTue, dWed, dThu, dFri, dSat] @@ -358,7 +358,7 @@ when not defined(JS): timezone: if local: getTimezone() else: 0 ) - proc timeInfoToTM(t: TTimeInfo): structTM = + proc timeInfoToTM(t: TTimeInfo): StructTM = const weekDays: array [TWeekDay, int8] = [1'i8,2'i8,3'i8,4'i8,5'i8,6'i8,0'i8] result.second = t.second @@ -453,7 +453,7 @@ when not defined(JS): result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001 elif defined(windows): var f: winlean.TFiletime - GetSystemTimeAsFileTime(f) + getSystemTimeAsFileTime(f) var i64 = rdFileTime(f) - epochDiff var secs = i64 div rateDiff var subsecs = i64 mod rateDiff diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index 1cf2816b4..b67341e89 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -109,7 +109,7 @@ proc runeAt*(s: string, i: int): TRune = proc toUTF8*(c: TRune): string {.rtl, extern: "nuc$1".} = ## converts a rune into its UTF8 representation - var i = irune(c) + var i = IRune(c) if i <=% 127: result = newString(1) result[0] = chr(i) @@ -1096,7 +1096,7 @@ const 0x01f1, 501, # 0x01f3, 499] # -proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int = +proc binarySearch(c: IRune, tab: openArray[IRune], len, stride: int): int = var n = len var t = 0 while n > 1: @@ -1114,29 +1114,29 @@ proc binarySearch(c: irune, tab: openArray[iRune], len, stride: int): int = proc toLower*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = ## Converts `c` into lower case. This works for any Unicode character. ## If possible, prefer `toLower` over `toUpper`. - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, tolowerRanges, len(toLowerRanges) div 3, 3) if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]: return TRune(c + tolowerRanges[p+2] - 500) p = binarySearch(c, toLowerSinglets, len(toLowerSinglets) div 2, 2) - if p >= 0 and c == toLowerSinglets[p]: - return TRune(c + toLowerSinglets[p+1] - 500) + if p >= 0 and c == tolowerSinglets[p]: + return TRune(c + tolowerSinglets[p+1] - 500) return TRune(c) proc toUpper*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = ## Converts `c` into upper case. This works for any Unicode character. ## If possible, prefer `toLower` over `toUpper`. - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, toUpperRanges, len(toUpperRanges) div 3, 3) - if p >= 0 and c >= toUpperRanges[p] and c <= toUpperRanges[p+1]: - return TRune(c + toUpperRanges[p+2] - 500) + if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]: + return TRune(c + toupperRanges[p+2] - 500) p = binarySearch(c, toUpperSinglets, len(toUpperSinglets) div 2, 2) - if p >= 0 and c == toUpperSinglets[p]: - return TRune(c + toUpperSinglets[p+1] - 500) + if p >= 0 and c == toupperSinglets[p]: + return TRune(c + toupperSinglets[p+1] - 500) return TRune(c) proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2) if p >= 0 and c == toTitleSinglets[p]: return TRune(c + toTitleSinglets[p+1] - 500) @@ -1145,32 +1145,32 @@ proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} = proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a lower case Unicode character ## If possible, prefer `isLower` over `isUpper`. - var c = irune(c) + var c = IRune(c) # Note: toUpperRanges is correct here! 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 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 proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a upper case Unicode character ## If possible, prefer `isLower` over `isUpper`. - var c = irune(c) + var c = IRune(c) # Note: toLowerRanges is correct here! 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 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 proc isAlpha*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is an *alpha* Unicode character (i.e. a letter) if isUpper(c) or isLower(c): return true - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2) if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]: return true @@ -1183,7 +1183,7 @@ proc isTitle*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = proc isWhiteSpace*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## returns true iff `c` is a Unicode whitespace character - var c = irune(c) + var c = IRune(c) var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2) if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]: return true @@ -1210,7 +1210,7 @@ proc cmpRunesIgnoreCase*(a, b: string): int {.rtl, extern: "nuc$1", procvar.} = # slow path: fastRuneAt(a, i, ar) fastRuneAt(b, j, br) - result = irune(toLower(ar)) - irune(toLower(br)) + result = IRune(toLower(ar)) - IRune(toLower(br)) if result != 0: return result = a.len - b.len diff --git a/lib/system.nim b/lib/system.nim index da3fee35a..7df4be4df 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -339,13 +339,13 @@ type TResult* = enum Failure, Success -proc sizeof*[T](x: T): natural {.magic: "SizeOf", noSideEffect.} +proc sizeof*[T](x: T): Natural {.magic: "SizeOf", noSideEffect.} ## returns the size of ``x`` in bytes. Since this is a low-level proc, ## its usage is discouraged - using ``new`` for the most cases suffices ## that one never needs to know ``x``'s size. As a special semantic rule, ## ``x`` may also be a type identifier (``sizeof(int)`` is valid). -proc `<`*[T](x: ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} +proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} ## unary ``<`` that can be used for nice looking excluding ranges: ## ## .. code-block:: nimrod @@ -353,22 +353,22 @@ proc `<`*[T](x: ordinal[T]): T {.magic: "UnaryLt", noSideEffect.} ## ## Semantically this is the same as ``pred``. -proc succ*[T](x: ordinal[T], y = 1): T {.magic: "Succ", noSideEffect.} +proc succ*[T](x: Ordinal[T], y = 1): T {.magic: "Succ", noSideEffect.} ## returns the ``y``-th successor of the value ``x``. ``T`` has to be ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised ## or a compile time error occurs. -proc pred*[T](x: ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.} +proc pred*[T](x: Ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.} ## returns the ``y``-th predecessor of the value ``x``. ``T`` has to be ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised ## or a compile time error occurs. -proc inc*[T](x: var ordinal[T], y = 1) {.magic: "Inc", noSideEffect.} +proc inc*[T](x: var Ordinal[T], y = 1) {.magic: "Inc", noSideEffect.} ## increments the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = succ(x, y)``. -proc dec*[T](x: var ordinal[T], y = 1) {.magic: "Dec", noSideEffect.} +proc dec*[T](x: var Ordinal[T], y = 1) {.magic: "Dec", noSideEffect.} ## decrements the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = pred(x, y)``. @@ -591,43 +591,43 @@ type IntMax32 = bool|int|int8|int16|int32 proc `+%` *(x, y: IntMax32): IntMax32 {.magic: "AddU", noSideEffect.} -proc `+%` *(x, y: Int64): Int64 {.magic: "AddU", noSideEffect.} +proc `+%` *(x, y: int64): int64 {.magic: "AddU", noSideEffect.} ## treats `x` and `y` as unsigned and adds them. The result is truncated to ## fit into the result. This implements modulo arithmetic. No overflow ## errors are possible. proc `-%` *(x, y: IntMax32): IntMax32 {.magic: "SubU", noSideEffect.} -proc `-%` *(x, y: Int64): Int64 {.magic: "SubU", noSideEffect.} +proc `-%` *(x, y: int64): int64 {.magic: "SubU", noSideEffect.} ## treats `x` and `y` as unsigned and subtracts them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `*%` *(x, y: IntMax32): IntMax32 {.magic: "MulU", noSideEffect.} -proc `*%` *(x, y: Int64): Int64 {.magic: "MulU", noSideEffect.} +proc `*%` *(x, y: int64): int64 {.magic: "MulU", noSideEffect.} ## treats `x` and `y` as unsigned and multiplies them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `/%` *(x, y: IntMax32): IntMax32 {.magic: "DivU", noSideEffect.} -proc `/%` *(x, y: Int64): Int64 {.magic: "DivU", noSideEffect.} +proc `/%` *(x, y: int64): int64 {.magic: "DivU", noSideEffect.} ## treats `x` and `y` as unsigned and divides them. The result is ## truncated to fit into the result. This implements modulo arithmetic. ## No overflow errors are possible. proc `%%` *(x, y: IntMax32): IntMax32 {.magic: "ModU", noSideEffect.} -proc `%%` *(x, y: Int64): Int64 {.magic: "ModU", noSideEffect.} +proc `%%` *(x, y: int64): int64 {.magic: "ModU", noSideEffect.} ## treats `x` and `y` as unsigned and compute the modulo of `x` and `y`. ## The result is truncated to fit into the result. ## This implements modulo arithmetic. ## No overflow errors are possible. proc `<=%` *(x, y: IntMax32): bool {.magic: "LeU", noSideEffect.} -proc `<=%` *(x, y: Int64): bool {.magic: "LeU64", noSideEffect.} +proc `<=%` *(x, y: int64): bool {.magic: "LeU64", noSideEffect.} ## treats `x` and `y` as unsigned and compares them. ## Returns true iff ``unsigned(x) <= unsigned(y)``. proc `<%` *(x, y: IntMax32): bool {.magic: "LtU", noSideEffect.} -proc `<%` *(x, y: Int64): bool {.magic: "LtU64", noSideEffect.} +proc `<%` *(x, y: int64): bool {.magic: "LtU64", noSideEffect.} ## treats `x` and `y` as unsigned and compares them. ## Returns true iff ``unsigned(x) < unsigned(y)``. @@ -1064,7 +1064,7 @@ proc toFloat*(i: int): float {. ## fails, `EInvalidValue` is raised. However, on most platforms the ## conversion cannot fail. -proc toBiggestFloat*(i: biggestint): biggestfloat {. +proc toBiggestFloat*(i: BiggestInt): BiggestFloat {. magic: "ToBiggestFloat", noSideEffect, importc: "toBiggestFloat".} ## converts an biggestint `i` into a ``biggestfloat``. If the conversion ## fails, `EInvalidValue` is raised. However, on most platforms the @@ -1076,7 +1076,7 @@ proc toInt*(f: float): int {. ## rounds `f` if it does not contain an integer value. If the conversion ## fails (because `f` is infinite for example), `EInvalidValue` is raised. -proc toBiggestInt*(f: biggestfloat): biggestint {. +proc toBiggestInt*(f: BiggestFloat): BiggestInt {. magic: "ToBiggestInt", noSideEffect, importc: "toBiggestInt".} ## converts a biggestfloat `f` into a ``biggestint``. Conversion ## rounds `f` if it does not contain an integer value. If the conversion @@ -1118,19 +1118,19 @@ proc substr*(s: string, first, last: int): string {. ## or `limit`:idx: a string's length. when not defined(nimrodVM): - proc zeroMem*(p: Pointer, size: int) {.importc, noDecl.} + proc zeroMem*(p: pointer, size: int) {.importc, noDecl.} ## overwrites the contents of the memory at ``p`` with the value 0. ## Exactly ``size`` bytes will be overwritten. Like any procedure ## dealing with raw memory this is *unsafe*. - proc copyMem*(dest, source: Pointer, size: int) {. + proc copyMem*(dest, source: pointer, size: int) {. importc: "memcpy", header: "".} ## copies the contents from the memory at ``source`` to the memory ## at ``dest``. Exactly ``size`` bytes will be copied. The memory ## regions may not overlap. Like any procedure dealing with raw ## memory this is *unsafe*. - proc moveMem*(dest, source: Pointer, size: int) {. + proc moveMem*(dest, source: pointer, size: int) {. importc: "memmove", header: "".} ## copies the contents from the memory at ``source`` to the memory ## at ``dest``. Exactly ``size`` bytes will be copied. The memory @@ -1138,7 +1138,7 @@ when not defined(nimrodVM): ## and is thus somewhat more safe than ``copyMem``. Like any procedure ## dealing with raw memory this is still *unsafe*, though. - proc equalMem*(a, b: Pointer, size: int): bool {. + proc equalMem*(a, b: pointer, size: int): bool {. importc: "equalMem", noDecl, noSideEffect.} ## compares the memory blocks ``a`` and ``b``. ``size`` bytes will ## be compared. If the blocks are equal, true is returned, false @@ -1160,7 +1160,7 @@ when not defined(nimrodVM): ## containing zero, so it is somewhat safer than ``alloc``. ## The allocated memory belongs to its allocating thread! ## Use `allocShared0` to allocate from a shared heap. - proc realloc*(p: Pointer, newsize: int): pointer {.noconv, rtl, tags: [].} + proc realloc*(p: pointer, newsize: int): pointer {.noconv, rtl, tags: [].} ## grows or shrinks a given memory block. If p is **nil** then a new ## memory block is returned. In either way the block has at least ## ``newsize`` bytes. If ``newsize == 0`` and p is not **nil** @@ -1168,7 +1168,7 @@ when not defined(nimrodVM): ## be freed with ``dealloc``. ## The allocated memory belongs to its allocating thread! ## Use `reallocShared` to reallocate from a shared heap. - proc dealloc*(p: Pointer) {.noconv, rtl, tags: [].} + proc dealloc*(p: pointer) {.noconv, rtl, tags: [].} ## frees the memory allocated with ``alloc``, ``alloc0`` or ## ``realloc``. This procedure is dangerous! If one forgets to ## free the memory a leak occurs; if one tries to access freed @@ -1189,13 +1189,13 @@ when not defined(nimrodVM): ## ``reallocShared(block, 0)`` or ``deallocShared(block)``. ## The block is initialized with all bytes ## containing zero, so it is somewhat safer than ``allocShared``. - proc reallocShared*(p: Pointer, newsize: int): pointer {.noconv, rtl.} + proc reallocShared*(p: pointer, newsize: int): pointer {.noconv, rtl.} ## grows or shrinks a given memory block on the heap. If p is **nil** ## then a new memory block is returned. In either way the block has at least ## ``newsize`` bytes. If ``newsize == 0`` and p is not **nil** ## ``reallocShared`` calls ``deallocShared(p)``. In other cases the ## block has to be freed with ``deallocShared``. - proc deallocShared*(p: Pointer) {.noconv, rtl.} + proc deallocShared*(p: pointer) {.noconv, rtl.} ## frees the memory allocated with ``allocShared``, ``allocShared0`` or ## ``reallocShared``. This procedure is dangerous! If one forgets to ## free the memory a leak occurs; if one tries to access freed @@ -1240,7 +1240,7 @@ proc `$` *(x: char): string {.magic: "CharToStr", noSideEffect.} ## The stingify operator for a character argument. Returns `x` ## converted to a string. -proc `$` *(x: Cstring): string {.magic: "CStrToStr", noSideEffect.} +proc `$` *(x: cstring): string {.magic: "CStrToStr", noSideEffect.} ## The stingify operator for a CString argument. Returns `x` ## converted to a string. @@ -1428,7 +1428,7 @@ iterator items*(E: typedesc[enum]): E = for v in low(E)..high(E): yield v -iterator pairs*[T](a: openarray[T]): tuple[key: int, val: T] {.inline.} = +iterator pairs*[T](a: openArray[T]): tuple[key: int, val: T] {.inline.} = ## iterates over each item of `a`. Yields ``(index, a[index])`` pairs. var i = 0 while i < len(a): @@ -1963,14 +1963,14 @@ when not defined(JS): #and not defined(NimrodVM): ## `useStdoutAsStdmsg` compile-time switch. proc open*(f: var TFile, filename: string, - mode: TFileMode = fmRead, bufSize: int = -1): Bool {.tags: [].} + mode: TFileMode = fmRead, bufSize: int = -1): bool {.tags: [].} ## Opens a file named `filename` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. ## This throws no exception if the file could not be opened. proc open*(f: var TFile, filehandle: TFileHandle, - mode: TFileMode = fmRead): Bool {.tags: [].} + mode: TFileMode = fmRead): bool {.tags: [].} ## Creates a ``TFile`` from a `filehandle` with given `mode`. ## ## Default mode is readonly. Returns true iff the file could be opened. @@ -1995,7 +1995,7 @@ when not defined(JS): #and not defined(NimrodVM): proc close*(f: TFile) {.importc: "fclose", header: "", tags: [].} ## Closes the file. - proc endOfFile*(f: TFile): Bool {.tags: [].} + proc endOfFile*(f: TFile): bool {.tags: [].} ## Returns true iff `f` is at the end. proc readChar*(f: TFile): char {. @@ -2021,10 +2021,10 @@ when not defined(JS): #and not defined(NimrodVM): proc write*(f: TFile, r: float32) {.tags: [FWriteIO].} proc write*(f: TFile, i: int) {.tags: [FWriteIO].} - proc write*(f: TFile, i: biggestInt) {.tags: [FWriteIO].} - proc write*(f: TFile, r: biggestFloat) {.tags: [FWriteIO].} + proc write*(f: TFile, i: BiggestInt) {.tags: [FWriteIO].} + proc write*(f: TFile, r: BiggestFloat) {.tags: [FWriteIO].} proc write*(f: TFile, s: string) {.tags: [FWriteIO].} - proc write*(f: TFile, b: Bool) {.tags: [FWriteIO].} + proc write*(f: TFile, b: bool) {.tags: [FWriteIO].} proc write*(f: TFile, c: char) {.tags: [FWriteIO].} proc write*(f: TFile, c: cstring) {.tags: [FWriteIO].} proc write*(f: TFile, a: varargs[string, `$`]) {.tags: [FWriteIO].} @@ -2050,13 +2050,13 @@ when not defined(JS): #and not defined(NimrodVM): proc getFileSize*(f: TFile): int64 {.tags: [FReadIO].} ## retrieves the file size (in bytes) of `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 {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than ## `len` (if not as many bytes are remaining), but not greater. - proc readChars*(f: TFile, a: var openarray[char], start, len: int): int {. + proc readChars*(f: TFile, a: var openArray[char], start, len: int): int {. tags: [FReadIO].} ## reads `len` bytes into the buffer `a` starting at ``a[start]``. Returns ## the actual number of bytes that have been read which may be less than @@ -2067,13 +2067,13 @@ when not defined(JS): #and not defined(NimrodVM): ## the actual number of bytes that have been read which may be less than ## `len` (if not as many bytes are remaining), but not greater. - proc writeBytes*(f: TFile, a: openarray[int8], start, len: int): int {. + proc writeBytes*(f: TFile, a: openArray[int8], start, len: int): int {. tags: [FWriteIO].} ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns ## the number of actual written bytes, which may be less than `len` in case ## of an error. - proc writeChars*(f: tFile, a: openarray[char], start, len: int): int {. + proc writeChars*(f: TFile, a: openArray[char], start, len: int): int {. tags: [FWriteIO].} ## writes the bytes of ``a[start..start+len-1]`` to the file `f`. Returns ## the number of actual written bytes, which may be less than `len` in case @@ -2195,7 +2195,7 @@ when not defined(JS): #and not defined(NimrodVM): const GenericSeqSize = (2 * sizeof(int)) - proc getDiscriminant(aa: Pointer, n: ptr TNimNode): int = + proc getDiscriminant(aa: pointer, n: ptr TNimNode): int = sysAssert(n.kind == nkCase, "getDiscriminant: node != nkCase") var d: int var a = cast[TAddress](aa) @@ -2206,7 +2206,7 @@ when not defined(JS): #and not defined(NimrodVM): else: sysAssert(false, "getDiscriminant: invalid n.typ.size") return d - proc selectBranch(aa: Pointer, n: ptr TNimNode): ptr TNimNode = + proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode = var discr = getDiscriminant(aa, n) if discr <% n.len: result = n.sons[discr] diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index e0f29a961..204d98a2c 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -109,7 +109,7 @@ type data: TTrunkBuckets type - TAlignType = biggestFloat + TAlignType = BiggestFloat TFreeCell {.final, pure.} = object next: ptr TFreeCell # next free cell in chunk (overlaid with refcount) zeroField: int # 0 means cell is not used (overlaid with typ field) @@ -260,7 +260,7 @@ proc intSetGet(t: TIntSet, key: int): PTrunk = result = nil proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = - result = IntSetGet(t, key) + result = intSetGet(t, key) if result == nil: result = cast[PTrunk](llAlloc(a, sizeof(result[]))) result.next = t.data[key and high(t.data)] @@ -268,7 +268,7 @@ proc intSetPut(a: var TMemRegion, t: var TIntSet, key: int): PTrunk = result.key = key proc contains(s: TIntSet, key: int): bool = - var t = IntSetGet(s, key shr TrunkShift) + var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask result = (t.bits[u shr IntShift] and (1 shl (u and IntMask))) != 0 @@ -276,12 +276,12 @@ proc contains(s: TIntSet, key: int): bool = result = false proc incl(a: var TMemRegion, s: var TIntSet, key: int) = - var t = IntSetPut(a, s, key shr TrunkShift) + var t = intSetPut(a, s, key shr TrunkShift) var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] or (1 shl (u and IntMask)) proc excl(s: var TIntSet, key: int) = - var t = IntSetGet(s, key shr TrunkShift) + var t = intSetGet(s, key shr TrunkShift) if t != nil: var u = key and TrunkMask t.bits[u shr IntShift] = t.bits[u shr IntShift] and not @@ -444,7 +444,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if isAccessible(a, ri) and chunkUnused(ri): sysAssert(not isSmallChunk(ri), "freeBigChunk 3") if not isSmallChunk(ri): - ListRemove(a.freeChunksList, cast[PBigChunk](ri)) + listRemove(a.freeChunksList, cast[PBigChunk](ri)) inc(c.size, ri.size) excl(a.chunkStarts, pageIndex(ri)) when coalescLeft: @@ -454,7 +454,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if isAccessible(a, le) and chunkUnused(le): sysAssert(not isSmallChunk(le), "freeBigChunk 5") if not isSmallChunk(le): - ListRemove(a.freeChunksList, cast[PBigChunk](le)) + listRemove(a.freeChunksList, cast[PBigChunk](le)) inc(le.size, c.size) excl(a.chunkStarts, pageIndex(c)) c = cast[PBigChunk](le) @@ -462,7 +462,7 @@ proc freeBigChunk(a: var TMemRegion, c: PBigChunk) = if c.size < ChunkOsReturn or weirdUnmap: incl(a, a.chunkStarts, pageIndex(c)) updatePrevSize(a, c, c.size) - ListAdd(a.freeChunksList, c) + listAdd(a.freeChunksList, c) c.used = false else: freeOsChunks(a, c, c.size) @@ -478,7 +478,7 @@ proc splitChunk(a: var TMemRegion, c: PBigChunk, size: int) = updatePrevSize(a, c, rest.size) c.size = size incl(a, a.chunkStarts, pageIndex(rest)) - ListAdd(a.freeChunksList, rest) + listAdd(a.freeChunksList, rest) proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = # use first fit for now: @@ -489,10 +489,10 @@ proc getBigChunk(a: var TMemRegion, size: int): PBigChunk = while result != nil: sysAssert chunkUnused(result), "getBigChunk 3" if result.size == size: - ListRemove(a.freeChunksList, result) + listRemove(a.freeChunksList, result) break search elif result.size > size: - ListRemove(a.freeChunksList, result) + listRemove(a.freeChunksList, result) splitChunk(a, result, size) break search result = result.next @@ -531,7 +531,7 @@ proc allocInv(a: TMemRegion): bool = while it != nil: if it.zeroField != 0: echo "[SYSASSERT] it.zeroField != 0" - cprintf("%ld %p\n", it.zeroField, it) + c_printf("%ld %p\n", it.zeroField, it) return false it = it.next c = c.next @@ -557,7 +557,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = c.free = SmallChunkSize - smallChunkOverhead() - size c.next = nil c.prev = nil - ListAdd(a.freeSmallChunks[s], c) + listAdd(a.freeSmallChunks[s], c) result = addr(c.data) sysAssert((cast[TAddress](result) and (MemAlign-1)) == 0, "rawAlloc 4") else: @@ -581,7 +581,7 @@ proc rawAlloc(a: var TMemRegion, requestedSize: int): pointer = sysAssert(allocInv(a), "rawAlloc: before c.free < size") if c.free < size: sysAssert(allocInv(a), "rawAlloc: before listRemove test") - ListRemove(a.freeSmallChunks[s], c) + listRemove(a.freeSmallChunks[s], c) sysAssert(allocInv(a), "rawAlloc: end listRemove test") sysAssert(((cast[TAddress](result) and PageMask) - smallChunkOverhead()) %% size == 0, "rawAlloc 21") @@ -628,12 +628,12 @@ proc rawDealloc(a: var TMemRegion, p: pointer) = # check if it is not in the freeSmallChunks[s] list: if c.free < s: # add it to the freeSmallChunks[s] array: - ListAdd(a.freeSmallChunks[s div memAlign], c) + listAdd(a.freeSmallChunks[s div memAlign], c) inc(c.free, s) else: inc(c.free, s) if c.free == SmallChunkSize-smallChunkOverhead(): - ListRemove(a.freeSmallChunks[s div memAlign], c) + listRemove(a.freeSmallChunks[s div memAlign], c) c.size = SmallChunkSize freeBigChunk(a, cast[PBigChunk](c)) sysAssert(((cast[TAddress](p) and PageMask) - smallChunkOverhead()) %% @@ -802,13 +802,13 @@ template instantiateForRegion(allocator: expr) = when hasThreadSupport: var sharedHeap: TMemRegion var heapLock: TSysLock - initSysLock(HeapLock) + initSysLock(heapLock) proc allocShared(size: int): pointer = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) result = alloc(sharedHeap, size) - releaseSys(HeapLock) + releaseSys(heapLock) else: result = alloc(size) @@ -818,17 +818,17 @@ template instantiateForRegion(allocator: expr) = proc deallocShared(p: pointer) = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) dealloc(sharedHeap, p) - releaseSys(HeapLock) + releaseSys(heapLock) else: dealloc(p) proc reallocShared(p: pointer, newsize: int): pointer = when hasThreadSupport: - acquireSys(HeapLock) + acquireSys(heapLock) result = realloc(sharedHeap, p, newsize) - releaseSys(HeapLock) + releaseSys(heapLock) else: result = realloc(p, newsize) diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index 064597df6..2d33965e3 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -28,8 +28,8 @@ type final, incompleteStruct.} = object C_BinaryFile {.importc: "FILE", header: "", final, incompleteStruct.} = object - C_TextFileStar = ptr CTextFile - C_BinaryFileStar = ptr CBinaryFile + C_TextFileStar = ptr C_TextFile + C_BinaryFileStar = ptr C_BinaryFile C_JmpBuf {.importc: "jmp_buf", header: "".} = object @@ -43,11 +43,11 @@ when not defined(SIGINT): when NoFakeVars: when defined(windows): const - SIGABRT = cint(22) - SIGFPE = cint(8) - SIGILL = cint(4) - SIGINT = cint(2) - SIGSEGV = cint(11) + SIGABRT = cint(22) + SIGFPE = cint(8) + SIGILL = cint(4) + SIGINT = cint(2) + SIGSEGV = cint(11) SIGTERM = cint(15) elif defined(macosx) or defined(linux): const diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 525822620..6b7ffaf7b 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -7,10 +7,10 @@ # distribution, for details about the copyright. # -proc genericResetAux(dest: Pointer, n: ptr TNimNode) +proc genericResetAux(dest: pointer, n: ptr TNimNode) -proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) -proc genericAssignAux(dest, src: Pointer, n: ptr TNimNode, shallow: bool) = +proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) +proc genericAssignAux(dest, src: pointer, n: ptr TNimNode, shallow: bool) = var d = cast[TAddress](dest) s = cast[TAddress](src) @@ -44,28 +44,28 @@ proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) = sysAssert(mt != nil, "genericAssignAux 2") case mt.Kind of tyString: - var x = cast[ppointer](dest) - var s2 = cast[ppointer](s)[] + var x = cast[PPointer](dest) + var s2 = cast[PPointer](s)[] if s2 == nil or shallow or ( cast[PGenericSeq](s2).reserved and seqShallowFlag) != 0: unsureAsgnRef(x, s2) else: unsureAsgnRef(x, copyString(cast[NimString](s2))) of tySequence: - var s2 = cast[ppointer](src)[] + var s2 = cast[PPointer](src)[] var seq = cast[PGenericSeq](s2) - var x = cast[ppointer](dest) + var x = cast[PPointer](dest) if s2 == nil or shallow or (seq.reserved and seqShallowFlag) != 0: # this can happen! nil sequences are allowed unsureAsgnRef(x, s2) return sysAssert(dest != nil, "genericAssignAux 3") unsureAsgnRef(x, newSeq(mt, seq.len)) - var dst = cast[taddress](cast[ppointer](dest)[]) + var dst = cast[TAddress](cast[PPointer](dest)[]) for i in 0..seq.len-1: genericAssignAux( cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize), - cast[pointer](cast[taddress](s2) +% i *% mt.base.size +% + cast[pointer](cast[TAddress](s2) +% i *% mt.base.size +% GenericSeqSize), mt.Base, shallow) of tyObject: @@ -83,16 +83,16 @@ proc genericAssignAux(dest, src: Pointer, mt: PNimType, shallow: bool) = genericAssignAux(cast[pointer](d +% i*% mt.base.size), cast[pointer](s +% i*% mt.base.size), mt.base, shallow) of tyRef: - unsureAsgnRef(cast[ppointer](dest), cast[ppointer](s)[]) + unsureAsgnRef(cast[PPointer](dest), cast[PPointer](s)[]) else: copyMem(dest, src, mt.size) # copy raw bits -proc genericAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = GC_disable() genericAssignAux(dest, src, mt, false) GC_enable() -proc genericShallowAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = GC_disable() genericAssignAux(dest, src, mt, true) GC_enable() @@ -126,7 +126,7 @@ when false: cprintf("%s %ld\n", k, t.size) debugNimType(t.base) -proc genericSeqAssign(dest, src: Pointer, mt: PNimType) {.compilerProc.} = +proc genericSeqAssign(dest, src: pointer, mt: PNimType) {.compilerProc.} = var src = src # ugly, but I like to stress the parser sometimes :-) genericAssign(dest, addr(src), mt) @@ -139,8 +139,8 @@ proc genericAssignOpenArray(dest, src: pointer, len: int, genericAssign(cast[pointer](d +% i*% mt.base.size), cast[pointer](s +% i*% mt.base.size), mt.base) -proc objectInit(dest: Pointer, typ: PNimType) {.compilerProc.} -proc objectInitAux(dest: Pointer, n: ptr TNimNode) = +proc objectInit(dest: pointer, typ: PNimType) {.compilerProc.} +proc objectInitAux(dest: pointer, n: ptr TNimNode) = var d = cast[TAddress](dest) case n.kind of nkNone: sysAssert(false, "objectInitAux") @@ -184,7 +184,7 @@ else: mixin destroy for i in countup(0, r.len - 1): destroy(r[i]) -proc genericReset(dest: Pointer, mt: PNimType) {.compilerProc.} +proc genericReset(dest: pointer, mt: PNimType) {.compilerProc.} proc genericResetAux(dest: Pointer, n: ptr TNimNode) = var d = cast[TAddress](dest) case n.kind @@ -202,7 +202,7 @@ proc genericReset(dest: Pointer, mt: PNimType) = sysAssert(mt != nil, "genericReset 2") case mt.Kind of tyString, tyRef, tySequence: - unsureAsgnRef(cast[ppointer](dest), nil) + unsureAsgnRef(cast[PPointer](dest), nil) of tyObject, tyTuple: # we don't need to reset m_type field for tyObject genericResetAux(dest, mt.node) diff --git a/lib/system/cellsets.nim b/lib/system/cellsets.nim index 85a24e856..9a22ed0c5 100644 --- a/lib/system/cellsets.nim +++ b/lib/system/cellsets.nim @@ -115,7 +115,7 @@ proc cellSetEnlarge(t: var TCellSet) = var oldMax = t.max t.max = ((t.max+1)*2)-1 var n = cast[PPageDescArray](alloc0((t.max + 1) * sizeof(PPageDesc))) - for i in 0 .. oldmax: + for i in 0 .. oldMax: if t.data[i] != nil: cellSetRawInsert(t, n, t.data[i]) dealloc(t.data) @@ -201,7 +201,7 @@ iterator elements(t: TCellSet): PCell {.inline.} = iterator elementsExcept(t, s: TCellSet): PCell {.inline.} = var r = t.head while r != nil: - let ss = CellSetGet(s, r.key) + let ss = cellSetGet(s, r.key) var i = 0 while i <= high(r.bits): var w = r.bits[i] diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index e78129483..eb1bf752e 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -9,7 +9,7 @@ # Implementation of some runtime checks. -proc raiseRangeError(val: biggestInt) {.compilerproc, noreturn, noinline.} = +proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} = when hostOs == "standalone": sysFatal(EOutOfRange, "value out of range") else: diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index e5f20f22a..5b00afc5b 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -17,7 +17,7 @@ var ## Unstable API. when not defined(windows) or not defined(guiapp): - proc writeToStdErr(msg: CString) = write(stdmsg, msg) + proc writeToStdErr(msg: cstring) = write(stdmsg, msg) else: proc MessageBoxA(hWnd: cint, lpText, lpCaption: cstring, uType: int): int32 {. @@ -240,7 +240,7 @@ proc raiseExceptionAux(e: ref E_Base) = showErrorMessage(buf) quitOrDebug() -proc raiseException(e: ref E_Base, ename: CString) {.compilerRtl.} = +proc raiseException(e: ref E_Base, ename: cstring) {.compilerRtl.} = e.name = ename when hasSomeStackTrace: e.trace = "" diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 2daa3eafa..2a137d7fb 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -154,7 +154,7 @@ proc collectCT(gch: var TGcHeap) proc isOnStack*(p: pointer): bool {.noinline.} proc forAllChildren(cell: PCell, op: TWalkOp) proc doOperation(p: pointer, op: TWalkOp) -proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp) +proc forAllChildrenAux(dest: pointer, mt: PNimType, op: TWalkOp) # we need the prototype here for debugging purposes when hasThreadSupport and hasSharedHeap: @@ -162,9 +162,9 @@ when hasThreadSupport and hasSharedHeap: template `++`(x: expr): stmt = discard atomicInc(x, rcIncrement) else: template `--`(x: expr): expr = - Dec(x, rcIncrement) + dec(x, rcIncrement) x <% rcIncrement - template `++`(x: expr): stmt = Inc(x, rcIncrement) + template `++`(x: expr): stmt = inc(x, rcIncrement) proc prepareDealloc(cell: PCell) = when useMarkForDebug: @@ -203,7 +203,7 @@ proc decRef(c: PCell) {.inline.} = gcAssert(c.refcount >=% rcIncrement, "decRef") if --c.refcount: rtlAddZCT(c) - elif canBeCycleRoot(c): + elif canbeCycleRoot(c): # unfortunately this is necessary here too, because a cycle might just # have been broken up and we could recycle it. rtlAddCycleRoot(c) @@ -214,7 +214,7 @@ proc incRef(c: PCell) {.inline.} = c.refcount = c.refCount +% rcIncrement # and not colorMask #writeCell("incRef", c) - if canBeCycleRoot(c): + if canbeCycleRoot(c): rtlAddCycleRoot(c) proc nimGCref(p: pointer) {.compilerProc, inline.} = incRef(usrToCell(p)) @@ -235,7 +235,7 @@ proc nimGCunrefNoCycle(p: pointer) {.compilerProc, inline.} = sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 2") sysAssert(allocInv(gch.region), "end nimGCunrefNoCycle 5") -proc asgnRef(dest: ppointer, src: pointer) {.compilerProc, inline.} = +proc asgnRef(dest: PPointer, src: pointer) {.compilerProc, inline.} = # the code generator calls this proc! gcAssert(not isOnStack(dest), "asgnRef") # BUGFIX: first incRef then decRef! @@ -243,7 +243,7 @@ proc asgnRef(dest: ppointer, src: pointer) {.compilerProc, inline.} = if dest[] != nil: decRef(usrToCell(dest[])) dest[] = src -proc asgnRefNoCycle(dest: ppointer, src: pointer) {.compilerProc, inline.} = +proc asgnRefNoCycle(dest: PPointer, src: pointer) {.compilerProc, inline.} = # the code generator calls this proc if it is known at compile time that no # cycle is possible. if src != nil: @@ -255,7 +255,7 @@ proc asgnRefNoCycle(dest: ppointer, src: pointer) {.compilerProc, inline.} = rtlAddZCT(c) dest[] = src -proc unsureAsgnRef(dest: ppointer, src: pointer) {.compilerProc.} = +proc unsureAsgnRef(dest: PPointer, src: pointer) {.compilerProc.} = # unsureAsgnRef updates the reference counters only if dest is not on the # stack. It is used by the code generator if it cannot decide wether a # reference is in the stack or not (this can happen for var parameters). @@ -318,7 +318,7 @@ proc forAllSlotsAux(dest: pointer, n: ptr TNimNode, op: TWalkOp) = # inlined for speed if n.sons[i].kind == nkSlot: if n.sons[i].typ.kind in {tyRef, tyString, tySequence}: - doOperation(cast[ppointer](d +% n.sons[i].offset)[], op) + doOperation(cast[PPointer](d +% n.sons[i].offset)[], op) else: forAllChildrenAux(cast[pointer](d +% n.sons[i].offset), n.sons[i].typ, op) @@ -335,7 +335,7 @@ proc forAllChildrenAux(dest: Pointer, mt: PNimType, op: TWalkOp) = if ntfNoRefs notin mt.flags: case mt.Kind of tyRef, tyString, tySequence: # leaf: - doOperation(cast[ppointer](d)[], op) + doOperation(cast[PPointer](d)[], op) of tyObject, tyTuple: forAllSlotsAux(dest, mt.node, op) of tyArray, tyArrayConstr, tyOpenArray: @@ -519,7 +519,7 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = d[j] = res break dec(j) - if canBeCycleRoot(ol): excl(gch.cycleRoots, ol) + if canbeCycleRoot(ol): excl(gch.cycleRoots, ol) when logGC: writeCell("growObj old cell", ol) writeCell("growObj new cell", res) @@ -869,7 +869,7 @@ else: sp = sp +% sizeof(pointer)*8 # last few entries: while sp <=% max: - gcMark(gch, cast[ppointer](sp)[]) + gcMark(gch, cast[PPointer](sp)[]) sp = sp +% sizeof(pointer) proc markStackAndRegisters(gch: var TGcHeap) {.noinline, cdecl.} = @@ -913,7 +913,7 @@ proc collectZCT(gch: var TGcHeap): bool = # In any case, it should be removed from the ZCT. But not # freed. **KEEP THIS IN MIND WHEN MAKING THIS INCREMENTAL!** when cycleGC: - if canBeCycleRoot(c): excl(gch.cycleRoots, c) + if canbeCycleRoot(c): excl(gch.cycleRoots, c) when logGC: writeCell("zct dealloc cell", c) gcTrace(c, csZctFreed) # We are about to free the object, call the finalizer BEFORE its diff --git a/lib/system/hti.nim b/lib/system/hti.nim index a2d132dbf..9d8ece7df 100644 --- a/lib/system/hti.nim +++ b/lib/system/hti.nim @@ -69,7 +69,7 @@ type kind: TNimNodeKind offset: int typ: ptr TNimType - name: Cstring + name: cstring len: int sons: ptr array [0..0x7fff, ptr TNimNode] diff --git a/lib/system/mmdisp.nim b/lib/system/mmdisp.nim index 942b6778e..a80fdad8f 100644 --- a/lib/system/mmdisp.nim +++ b/lib/system/mmdisp.nim @@ -33,7 +33,7 @@ const type PPointer = ptr pointer - TByteArray = array[0..1000_0000, byte] + TByteArray = array[0..1000_0000, Byte] PByte = ptr TByteArray PString = ptr string diff --git a/lib/system/repr.nim b/lib/system/repr.nim index f0d620952..aacf26653 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -96,7 +96,7 @@ proc reprSetAux(result: var string, p: pointer, typ: PNimType) = of 4: u = ze64(cast[ptr int32](p)[]) of 8: u = cast[ptr int64](p)[] else: - var a = cast[pbyteArray](p) + var a = cast[PByteArray](p) for i in 0 .. typ.size*8-1: if (ze(a[i div 8]) and (1 shl (i mod 8))) != 0: if elemCounter > 0: add result, ", " @@ -129,12 +129,12 @@ when not defined(useNimRtl): when hasThreadSupport and hasSharedHeap and defined(heapLock): AcquireSys(HeapLock) when defined(TCellSet): - Init(cl.marked) + init(cl.marked) cl.recdepth = -1 # default is to display everything! cl.indent = 0 proc deinitReprClosure(cl: var TReprClosure) = - when defined(TCellSet): Deinit(cl.marked) + when defined(TCellSet): deinit(cl.marked) when hasThreadSupport and hasSharedHeap and defined(heapLock): ReleaseSys(HeapLock) @@ -224,17 +224,17 @@ when not defined(useNimRtl): reprRecord(result, p, t, cl) of tyRef, tyPtr: sysAssert(p != nil, "reprAux") - if cast[ppointer](p)[] == nil: add result, "nil" - else: reprRef(result, cast[ppointer](p)[], typ, cl) + if cast[PPointer](p)[] == nil: add result, "nil" + else: reprRef(result, cast[PPointer](p)[], typ, cl) of tySequence: - reprSequence(result, cast[ppointer](p)[], typ, cl) + reprSequence(result, cast[PPointer](p)[], typ, cl) of tyInt: add result, $(cast[ptr int](p)[]) - of tyInt8: add result, $int(cast[ptr Int8](p)[]) - of tyInt16: add result, $int(cast[ptr Int16](p)[]) - of tyInt32: add result, $int(cast[ptr Int32](p)[]) - of tyInt64: add result, $(cast[ptr Int64](p)[]) - of tyUInt8: add result, $ze(cast[ptr Int8](p)[]) - of tyUInt16: add result, $ze(cast[ptr Int16](p)[]) + of tyInt8: add result, $int(cast[ptr int8](p)[]) + of tyInt16: add result, $int(cast[ptr int16](p)[]) + of tyInt32: add result, $int(cast[ptr int32](p)[]) + of tyInt64: add result, $(cast[ptr int64](p)[]) + of tyUInt8: add result, $ze(cast[ptr int8](p)[]) + of tyUInt16: add result, $ze(cast[ptr int16](p)[]) of tyFloat: add result, $(cast[ptr float](p)[]) of tyFloat32: add result, $(cast[ptr float32](p)[]) @@ -246,8 +246,8 @@ when not defined(useNimRtl): of tyCString: reprStrAux(result, $(cast[ptr cstring](p)[])) of tyRange: reprAux(result, p, typ.base, cl) of tyProc, tyPointer: - if cast[ppointer](p)[] == nil: add result, "nil" - else: add result, reprPointer(cast[ppointer](p)[]) + if cast[PPointer](p)[] == nil: add result, "nil" + else: add result, reprPointer(cast[PPointer](p)[]) else: add result, "(invalid data!)" inc(cl.recdepth) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 82b4b183a..9c0b0c589 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -24,16 +24,16 @@ proc fgetc(stream: TFile): cint {.importc: "fgetc", header: "", tags: [FReadIO].} proc ungetc(c: cint, f: TFile) {.importc: "ungetc", header: "", tags: [].} -proc putc(c: Char, stream: TFile) {.importc: "putc", header: "", +proc putc(c: char, stream: TFile) {.importc: "putc", header: "", tags: [FWriteIO].} -proc fprintf(f: TFile, frmt: CString) {.importc: "fprintf", +proc fprintf(f: TFile, frmt: cstring) {.importc: "fprintf", header: "", varargs, tags: [FWriteIO].} proc strlen(c: cstring): int {. importc: "strlen", header: "", tags: [].} # C routine that is used here: -proc fread(buf: Pointer, size, n: int, f: TFile): int {. +proc fread(buf: pointer, size, n: int, f: TFile): int {. importc: "fread", header: "", tags: [FReadIO].} proc fseek(f: TFile, offset: clong, whence: int): int {. importc: "fseek", header: "", tags: [].} @@ -48,7 +48,7 @@ proc write(f: TFile, c: cstring) = fputs(c, f) when NoFakeVars: when defined(windows): const - IOFBF = cint(0) + IOFBF = cint(0) IONBF = cint(4) elif defined(macosx) or defined(linux): const @@ -179,9 +179,9 @@ proc rawEchoNL() {.inline, compilerproc.} = write(stdout, "\n") when defined(windows) and not defined(useWinAnsi): include "system/widestrs" - proc wfopen(filename, mode: widecstring): pointer {. + proc wfopen(filename, mode: WideCString): pointer {. importc: "_wfopen", nodecl.} - proc wfreopen(filename, mode: widecstring, stream: TFile): TFile {. + proc wfreopen(filename, mode: WideCString, stream: TFile): TFile {. importc: "_wfreopen", nodecl.} proc fopen(filename, mode: cstring): pointer = diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index d62a987ff..bca14bb9d 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -63,14 +63,14 @@ proc copyStrLast(s: NimString, start, last: int): NimString {.compilerProc.} = proc copyStr(s: NimString, start: int): NimString {.compilerProc.} = result = copyStrLast(s, start, s.len-1) -proc toNimStr(str: CString, len: int): NimString {.compilerProc.} = +proc toNimStr(str: cstring, len: int): NimString {.compilerProc.} = result = rawNewString(len) result.len = len c_memcpy(result.data, str, (len+1) * sizeof(Char)) #result.data[len] = '\0' # readline relies on this! -proc cstrToNimstr(str: CString): NimString {.compilerRtl.} = - result = toNimstr(str, c_strlen(str)) +proc cstrToNimstr(str: cstring): NimString {.compilerRtl.} = + result = toNimStr(str, c_strlen(str)) proc copyString(src: NimString): NimString {.compilerRtl.} = if src != nil: @@ -98,8 +98,8 @@ proc hashString(s: string): int {.compilerproc.} = # the compiler needs exactly the same hash function! # this used to be used for efficient generation of string case statements var h = 0 - for i in 0..Len(s)-1: - h = h +% Ord(s[i]) + for i in 0..len(s)-1: + h = h +% ord(s[i]) h = h +% h shl 10 h = h xor (h shr 6) h = h +% h shl 3 @@ -150,10 +150,10 @@ proc addChar(s: NimString, c: char): NimString = # s = rawNewString(0); proc resizeString(dest: NimString, addlen: int): NimString {.compilerRtl.} = - if dest.len + addLen <= dest.space: + if dest.len + addlen <= dest.space: result = dest else: # slow path: - var sp = max(resize(dest.space), dest.len + addLen) + var sp = max(resize(dest.space), dest.len + addlen) result = cast[NimString](growObj(dest, sizeof(TGenericSeq) + sp + 1)) result.reserved = sp #result = rawNewString(sp) @@ -280,7 +280,7 @@ proc nimCharToStr(x: char): string {.compilerRtl.} = result = newString(1) result[0] = x -proc binaryStrSearch(x: openarray[string], y: string): int {.compilerproc.} = +proc binaryStrSearch(x: openArray[string], y: string): int {.compilerproc.} = var a = 0 b = len(x) diff --git a/lib/system/widestrs.nim b/lib/system/widestrs.nim index d856cc830..e2a5d87e9 100644 --- a/lib/system/widestrs.nim +++ b/lib/system/widestrs.nim @@ -1,153 +1,153 @@ -# -# -# Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## Nimrod support for C/C++'s `wide strings`:idx:. This is part of the system -## module! Do not import it directly! +# +# +# Nimrod's Runtime Library +# (c) Copyright 2012 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Nimrod support for C/C++'s `wide strings`:idx:. This is part of the system +## module! Do not import it directly! when not defined(NimString): {.error: "You must not import this module explicitly".} - -type - TUtf16Char* = distinct int16 - WideCString* = ref array[0.. 1_000_000, TUtf16Char] - -proc len*(w: WideCString): int = - ## returns the length of a widestring. This traverses the whole string to - ## find the binary zero end marker! - while int16(w[result]) != 0'i16: inc result - -const - UNI_REPLACEMENT_CHAR = TUtf16Char(0xFFFD'i16) - UNI_MAX_BMP = 0x0000FFFF - UNI_MAX_UTF16 = 0x0010FFFF - UNI_MAX_UTF32 = 0x7FFFFFFF - UNI_MAX_LEGAL_UTF32 = 0x0010FFFF - - halfShift = 10 - halfBase = 0x0010000 - halfMask = 0x3FF - - UNI_SUR_HIGH_START = 0xD800 - UNI_SUR_HIGH_END = 0xDBFF - UNI_SUR_LOW_START = 0xDC00 - UNI_SUR_LOW_END = 0xDFFF - -template ones(n: expr): expr = ((1 shl n)-1) - -template fastRuneAt(s: cstring, i: int, result: expr, doInc = true) = - ## Returns the unicode character ``s[i]`` in `result`. If ``doInc == true`` - ## `i` is incremented by the number of bytes that have been processed. - bind ones - - if ord(s[i]) <=% 127: - result = ord(s[i]) - when doInc: inc(i) - elif ord(s[i]) shr 5 == 0b110: - #assert(ord(s[i+1]) shr 6 == 0b10) - result = (ord(s[i]) and (ones(5))) shl 6 or (ord(s[i+1]) and ones(6)) - when doInc: inc(i, 2) - elif ord(s[i]) shr 4 == 0b1110: - #assert(ord(s[i+1]) shr 6 == 0b10) - #assert(ord(s[i+2]) shr 6 == 0b10) - result = (ord(s[i]) and ones(4)) shl 12 or - (ord(s[i+1]) and ones(6)) shl 6 or - (ord(s[i+2]) and ones(6)) - when doInc: inc(i, 3) - elif ord(s[i]) shr 3 == 0b11110: - #assert(ord(s[i+1]) shr 6 == 0b10) - #assert(ord(s[i+2]) shr 6 == 0b10) - #assert(ord(s[i+3]) shr 6 == 0b10) - result = (ord(s[i]) and ones(3)) shl 18 or - (ord(s[i+1]) and ones(6)) shl 12 or - (ord(s[i+2]) and ones(6)) shl 6 or - (ord(s[i+3]) and ones(6)) - when doInc: inc(i, 4) - else: - result = 0xFFFD - when doInc: inc(i) - -iterator runes(s: cstring): int = - var - i = 0 - result: int - while s[i] != '\0': - fastRuneAt(s, i, result, true) - yield result - -proc newWideCString*(source: cstring, L: int): WideCString = + +type + TUtf16Char* = distinct int16 + WideCString* = ref array[0.. 1_000_000, TUtf16Char] + +proc len*(w: WideCString): int = + ## returns the length of a widestring. This traverses the whole string to + ## find the binary zero end marker! + while int16(w[result]) != 0'i16: inc result + +const + UNI_REPLACEMENT_CHAR = TUtf16Char(0xFFFD'i16) + UNI_MAX_BMP = 0x0000FFFF + UNI_MAX_UTF16 = 0x0010FFFF + UNI_MAX_UTF32 = 0x7FFFFFFF + UNI_MAX_LEGAL_UTF32 = 0x0010FFFF + + halfShift = 10 + halfBase = 0x0010000 + halfMask = 0x3FF + + UNI_SUR_HIGH_START = 0xD800 + UNI_SUR_HIGH_END = 0xDBFF + UNI_SUR_LOW_START = 0xDC00 + UNI_SUR_LOW_END = 0xDFFF + +template ones(n: expr): expr = ((1 shl n)-1) + +template fastRuneAt(s: cstring, i: int, result: expr, doInc = true) = + ## Returns the unicode character ``s[i]`` in `result`. If ``doInc == true`` + ## `i` is incremented by the number of bytes that have been processed. + bind ones + + if ord(s[i]) <=% 127: + result = ord(s[i]) + when doInc: inc(i) + elif ord(s[i]) shr 5 == 0b110: + #assert(ord(s[i+1]) shr 6 == 0b10) + result = (ord(s[i]) and (ones(5))) shl 6 or (ord(s[i+1]) and ones(6)) + when doInc: inc(i, 2) + elif ord(s[i]) shr 4 == 0b1110: + #assert(ord(s[i+1]) shr 6 == 0b10) + #assert(ord(s[i+2]) shr 6 == 0b10) + result = (ord(s[i]) and ones(4)) shl 12 or + (ord(s[i+1]) and ones(6)) shl 6 or + (ord(s[i+2]) and ones(6)) + when doInc: inc(i, 3) + elif ord(s[i]) shr 3 == 0b11110: + #assert(ord(s[i+1]) shr 6 == 0b10) + #assert(ord(s[i+2]) shr 6 == 0b10) + #assert(ord(s[i+3]) shr 6 == 0b10) + result = (ord(s[i]) and ones(3)) shl 18 or + (ord(s[i+1]) and ones(6)) shl 12 or + (ord(s[i+2]) and ones(6)) shl 6 or + (ord(s[i+3]) and ones(6)) + when doInc: inc(i, 4) + else: + result = 0xFFFD + when doInc: inc(i) + +iterator runes(s: cstring): int = + var + i = 0 + result: int + while s[i] != '\0': + fastRuneAt(s, i, result, true) + yield result + +proc newWideCString*(source: cstring, L: int): WideCString = unsafeNew(result, L * 4 + 2) - #result = cast[wideCString](alloc(L * 4 + 2)) - var d = 0 - for ch in runes(source): - if ch <=% UNI_MAX_BMP: - if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_LOW_END: - result[d] = UNI_REPLACEMENT_CHAR - else: - result[d] = TUtf16Char(toU16(ch)) - elif ch >% UNI_MAX_UTF16: - result[d] = UNI_REPLACEMENT_CHAR - else: - let ch = ch -% halfBase - result[d] = TUtf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) - inc d - result[d] = TUtf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) - inc d - result[d] = TUtf16Char(0'i16) - -proc newWideCString*(s: cstring): WideCString = - if s.isNil: return nil - - when not defined(c_strlen): + #result = cast[wideCString](alloc(L * 4 + 2)) + var d = 0 + for ch in runes(source): + if ch <=% UNI_MAX_BMP: + if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_LOW_END: + result[d] = UNI_REPLACEMENT_CHAR + else: + result[d] = TUtf16Char(toU16(ch)) + elif ch >% UNI_MAX_UTF16: + result[d] = UNI_REPLACEMENT_CHAR + else: + let ch = ch -% halfBase + result[d] = TUtf16Char(toU16((ch shr halfShift) +% UNI_SUR_HIGH_START)) + inc d + result[d] = TUtf16Char(toU16((ch and halfMask) +% UNI_SUR_LOW_START)) + inc d + result[d] = TUtf16Char(0'i16) + +proc newWideCString*(s: cstring): WideCString = + if s.isNil: return nil + + when not defined(c_strlen): proc c_strlen(a: cstring): int {. - header: "", noSideEffect, importc: "strlen".} - - let L = cstrlen(s) - result = newWideCString(s, L) - -proc newWideCString*(s: string): WideCString = - result = newWideCString(s, s.len) - -proc `$`*(w: wideCString, estimate: int): string = - result = newStringOfCap(estimate + estimate shr 2) - - var i = 0 - while w[i].int16 != 0'i16: - var ch = w[i].int - inc i - if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_HIGH_END: - # If the 16 bits following the high surrogate are in the source buffer... - let ch2 = w[i].int - # If it's a low surrogate, convert to UTF32: - if ch2 >=% UNI_SUR_LOW_START and ch2 <=% UNI_SUR_LOW_END: - ch = ((ch -% UNI_SUR_HIGH_START) shr halfShift) +% - (ch2 -% UNI_SUR_LOW_START) +% halfBase - inc i - - if ch <=% 127: - result.add chr(ch) - elif ch <=% 0x07FF: - result.add chr((ch shr 6) or 0b110_00000) - result.add chr((ch and ones(6)) or 0b10_000000) - elif ch <=% 0xFFFF: - result.add chr(ch shr 12 or 0b1110_0000) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) - elif ch <=% 0x0010FFFF: - result.add chr(ch shr 18 or 0b1111_0000) - result.add chr(ch shr 12 and ones(6) or 0b10_0000_00) - result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) - result.add chr(ch and ones(6) or 0b10_0000_00) - else: - # replacement char: - result.add chr(0xFFFD shr 12 or 0b1110_0000) - result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) - result.add chr(0xFFFD and ones(6) or 0b10_0000_00) - -proc `$`*(s: WideCString): string = - result = s $ 80 + header: "", noSideEffect, importc: "strlen".} + + let L = c_strlen(s) + result = newWideCString(s, L) + +proc newWideCString*(s: string): WideCString = + result = newWideCString(s, s.len) + +proc `$`*(w: WideCString, estimate: int): string = + result = newStringOfCap(estimate + estimate shr 2) + + var i = 0 + while w[i].int16 != 0'i16: + var ch = w[i].int + inc i + if ch >=% UNI_SUR_HIGH_START and ch <=% UNI_SUR_HIGH_END: + # If the 16 bits following the high surrogate are in the source buffer... + let ch2 = w[i].int + # If it's a low surrogate, convert to UTF32: + if ch2 >=% UNI_SUR_LOW_START and ch2 <=% UNI_SUR_LOW_END: + ch = ((ch -% UNI_SUR_HIGH_START) shr halfShift) +% + (ch2 -% UNI_SUR_LOW_START) +% halfBase + inc i + + if ch <=% 127: + result.add chr(ch) + elif ch <=% 0x07FF: + result.add chr((ch shr 6) or 0b110_00000) + result.add chr((ch and ones(6)) or 0b10_000000) + elif ch <=% 0xFFFF: + result.add chr(ch shr 12 or 0b1110_0000) + result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) + result.add chr(ch and ones(6) or 0b10_0000_00) + elif ch <=% 0x0010FFFF: + result.add chr(ch shr 18 or 0b1111_0000) + result.add chr(ch shr 12 and ones(6) or 0b10_0000_00) + result.add chr(ch shr 6 and ones(6) or 0b10_0000_00) + result.add chr(ch and ones(6) or 0b10_0000_00) + else: + # replacement char: + result.add chr(0xFFFD shr 12 or 0b1110_0000) + result.add chr(0xFFFD shr 6 and ones(6) or 0b10_0000_00) + result.add chr(0xFFFD and ones(6) or 0b10_0000_00) + +proc `$`*(s: WideCString): string = + result = s $ 80 diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 481f61fda..e288910d7 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -42,13 +42,13 @@ type wShowWindow*: int16 cbReserved2*: int16 lpReserved2*: pointer - hStdInput*: THANDLE - hStdOutput*: THANDLE - hStdError*: THANDLE + hStdInput*: THandle + hStdOutput*: THandle + hStdError*: THandle TPROCESS_INFORMATION* {.final, pure.} = object - hProcess*: THANDLE - hThread*: THANDLE + hProcess*: THandle + hThread*: THandle dwProcessId*: int32 dwThreadId*: int32 @@ -96,7 +96,7 @@ const CREATE_UNICODE_ENVIRONMENT* = 1024'i32 -proc closeHandle*(hObject: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc closeHandle*(hObject: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "CloseHandle".} proc readFile*(hFile: THandle, Buffer: pointer, nNumberOfBytesToRead: int32, @@ -114,11 +114,11 @@ proc createPipe*(hReadPipe, hWritePipe: var THandle, stdcall, dynlib: "kernel32", importc: "CreatePipe".} when useWinUnicode: - proc createProcessW*(lpApplicationName, lpCommandLine: widecstring, + proc createProcessW*(lpApplicationName, lpCommandLine: WideCString, lpProcessAttributes: ptr TSECURITY_ATTRIBUTES, lpThreadAttributes: ptr TSECURITY_ATTRIBUTES, bInheritHandles: WINBOOL, dwCreationFlags: int32, - lpEnvironment, lpCurrentDirectory: widecstring, + lpEnvironment, lpCurrentDirectory: WideCString, lpStartupInfo: var TSTARTUPINFO, lpProcessInformation: var TPROCESS_INFORMATION): WINBOOL{. stdcall, dynlib: "kernel32", importc: "CreateProcessW".} @@ -134,25 +134,25 @@ else: stdcall, dynlib: "kernel32", importc: "CreateProcessA".} -proc suspendThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc suspendThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", importc: "SuspendThread".} -proc resumeThread*(hThread: THANDLE): int32 {.stdcall, dynlib: "kernel32", +proc resumeThread*(hThread: THandle): int32 {.stdcall, dynlib: "kernel32", importc: "ResumeThread".} -proc waitForSingleObject*(hHandle: THANDLE, dwMilliseconds: int32): int32 {. +proc waitForSingleObject*(hHandle: THandle, dwMilliseconds: int32): int32 {. stdcall, dynlib: "kernel32", importc: "WaitForSingleObject".} -proc terminateProcess*(hProcess: THANDLE, uExitCode: int): WINBOOL {.stdcall, +proc terminateProcess*(hProcess: THandle, uExitCode: int): WINBOOL {.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} -proc getExitCodeProcess*(hProcess: THANDLE, lpExitCode: var int32): WINBOOL {. +proc getExitCodeProcess*(hProcess: THandle, lpExitCode: var int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} -proc getStdHandle*(nStdHandle: int32): THANDLE {.stdcall, dynlib: "kernel32", +proc getStdHandle*(nStdHandle: int32): THandle {.stdcall, dynlib: "kernel32", importc: "GetStdHandle".} -proc setStdHandle*(nStdHandle: int32, hHandle: THANDLE): WINBOOL {.stdcall, +proc setStdHandle*(nStdHandle: int32, hHandle: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetStdHandle".} -proc flushFileBuffers*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc flushFileBuffers*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "FlushFileBuffers".} proc getLastError*(): int32 {.importc: "GetLastError", @@ -176,18 +176,18 @@ proc localFree*(p: pointer) {. when useWinUnicode: proc getCurrentDirectoryW*(nBufferLength: int32, - lpBuffer: widecstring): int32 {. + lpBuffer: WideCString): int32 {. importc: "GetCurrentDirectoryW", dynlib: "kernel32", stdcall.} - proc setCurrentDirectoryW*(lpPathName: widecstring): int32 {. + proc setCurrentDirectoryW*(lpPathName: WideCString): int32 {. importc: "SetCurrentDirectoryW", dynlib: "kernel32", stdcall.} - proc createDirectoryW*(pathName: widecstring, security: Pointer=nil): int32 {. + proc createDirectoryW*(pathName: WideCString, security: pointer=nil): int32 {. importc: "CreateDirectoryW", dynlib: "kernel32", stdcall.} - proc removeDirectoryW*(lpPathName: widecstring): int32 {. + proc removeDirectoryW*(lpPathName: WideCString): int32 {. importc: "RemoveDirectoryW", dynlib: "kernel32", stdcall.} - proc setEnvironmentVariableW*(lpName, lpValue: widecstring): int32 {. + proc setEnvironmentVariableW*(lpName, lpValue: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "SetEnvironmentVariableW".} - proc getModuleFileNameW*(handle: THandle, buf: wideCString, + proc getModuleFileNameW*(handle: THandle, buf: WideCString, size: int32): int32 {.importc: "GetModuleFileNameW", dynlib: "kernel32", stdcall.} else: @@ -230,10 +230,10 @@ type cAlternateFileName*: array[0..13, TWinChar] when useWinUnicode: - proc findFirstFileW*(lpFileName: widecstring, - lpFindFileData: var TWIN32_FIND_DATA): THANDLE {. + proc findFirstFileW*(lpFileName: WideCString, + lpFindFileData: var TWIN32_FIND_DATA): THandle {. stdcall, dynlib: "kernel32", importc: "FindFirstFileW".} - proc findNextFileW*(hFindFile: THANDLE, + proc findNextFileW*(hFindFile: THandle, lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileW".} else: @@ -244,32 +244,32 @@ else: lpFindFileData: var TWIN32_FIND_DATA): int32 {. stdcall, dynlib: "kernel32", importc: "FindNextFileA".} -proc findClose*(hFindFile: THANDLE) {.stdcall, dynlib: "kernel32", +proc findClose*(hFindFile: THandle) {.stdcall, dynlib: "kernel32", importc: "FindClose".} when useWinUnicode: - proc getFullPathNameW*(lpFileName: widecstring, nBufferLength: int32, - lpBuffer: widecstring, - lpFilePart: var widecstring): int32 {. + proc getFullPathNameW*(lpFileName: WideCString, nBufferLength: int32, + lpBuffer: WideCString, + lpFilePart: var WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "GetFullPathNameW".} - proc getFileAttributesW*(lpFileName: widecstring): int32 {. + proc getFileAttributesW*(lpFileName: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "GetFileAttributesW".} - proc setFileAttributesW*(lpFileName: widecstring, + proc setFileAttributesW*(lpFileName: WideCString, dwFileAttributes: int32): WINBOOL {. stdcall, dynlib: "kernel32", importc: "SetFileAttributesW".} - proc copyFileW*(lpExistingFileName, lpNewFileName: wideCString, + proc copyFileW*(lpExistingFileName, lpNewFileName: WideCString, bFailIfExists: cint): cint {. importc: "CopyFileW", stdcall, dynlib: "kernel32".} - proc getEnvironmentStringsW*(): widecstring {. + proc getEnvironmentStringsW*(): WideCString {. stdcall, dynlib: "kernel32", importc: "GetEnvironmentStringsW".} - proc freeEnvironmentStringsW*(para1: widecstring): int32 {. + proc freeEnvironmentStringsW*(para1: WideCString): int32 {. stdcall, dynlib: "kernel32", importc: "FreeEnvironmentStringsW".} - proc getCommandLineW*(): wideCString {.importc: "GetCommandLineW", + proc getCommandLineW*(): WideCString {.importc: "GetCommandLineW", stdcall, dynlib: "kernel32".} else: @@ -299,7 +299,7 @@ else: proc rdFileTime*(f: TFILETIME): int64 = result = ze64(f.dwLowDateTime) or (ze64(f.dwHighDateTime) shl 32) -proc rdFileSize*(f: TWin32FindData): int64 = +proc rdFileSize*(f: TWIN32_FIND_DATA): int64 = result = ze64(f.nFileSizeLow) or (ze64(f.nFileSizeHigh) shl 32) proc getSystemTimeAsFileTime*(lpSystemTimeAsFileTime: var TFILETIME) {. @@ -310,7 +310,7 @@ proc sleep*(dwMilliseconds: int32){.stdcall, dynlib: "kernel32", when useWinUnicode: proc shellExecuteW*(HWND: THandle, lpOperation, lpFile, - lpParameters, lpDirectory: widecstring, + lpParameters, lpDirectory: WideCString, nShowCmd: int32): THandle{. stdcall, dynlib: "shell32.dll", importc: "ShellExecuteW".} @@ -445,10 +445,10 @@ proc getservbyname*(name, proto: cstring): ptr TServent {. proc getservbyport*(port: cint, proto: cstring): ptr TServent {. stdcall, importc: "getservbyport", dynlib: ws2dll.} -proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr THostEnt {. +proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr Thostent {. stdcall, importc: "gethostbyaddr", dynlib: ws2dll.} -proc gethostbyname*(name: cstring): ptr THostEnt {. +proc gethostbyname*(name: cstring): ptr Thostent {. stdcall, importc: "gethostbyname", dynlib: ws2dll.} proc socket*(af, typ, protocol: cint): TSocketHandle {. @@ -457,20 +457,20 @@ proc socket*(af, typ, protocol: cint): TSocketHandle {. proc closesocket*(s: TSocketHandle): cint {. 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.} -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.} -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.} proc getsockname*(s: TSocketHandle, name: ptr TSockAddr, - namelen: ptr TSockLen): cint {. + namelen: ptr Tsocklen): cint {. stdcall, importc: "getsockname", dynlib: ws2dll.} proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: ptr TSockLen): cint {. + optlen: ptr Tsocklen): cint {. stdcall, importc: "getsockopt", dynlib: ws2dll.} proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: TSockLen): cint {. + optlen: Tsocklen): cint {. stdcall, importc: "setsockopt", dynlib: ws2dll.} proc listen*(s: TSocketHandle, backlog: cint): cint {. @@ -492,7 +492,7 @@ proc sendto*(s: TSocketHandle, buf: pointer, len, flags: cint, proc shutdown*(s: TSocketHandle, how: cint): cint {. 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, a6: Tsocklen, a7: cint): cint {. stdcall, importc: "getnameinfo", dynlib: ws2dll.} @@ -500,18 +500,18 @@ proc getnameinfo*(a1: ptr Tsockaddr, a2: Tsocklen, proc inet_addr*(cp: cstring): int32 {. stdcall, importc: "inet_addr", dynlib: ws2dll.} -proc WSAFDIsSet(s: TSocketHandle, FDSet: var TFDSet): bool {. +proc WSAFDIsSet(s: TSocketHandle, FDSet: var TFdSet): bool {. stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll.} -proc FD_ISSET*(Socket: TSocketHandle, FDSet: var TFDSet): cint = +proc FD_ISSET*(Socket: TSocketHandle, FDSet: var TFdSet): cint = result = if WSAFDIsSet(Socket, FDSet): 1'i32 else: 0'i32 -proc FD_SET*(Socket: TSocketHandle, FDSet: var TFDSet) = +proc FD_SET*(Socket: TSocketHandle, FDSet: var TFdSet) = if FDSet.fd_count < FD_SETSIZE: FDSet.fd_array[int(FDSet.fd_count)] = Socket inc(FDSet.fd_count) -proc FD_ZERO*(FDSet: var TFDSet) = +proc FD_ZERO*(FDSet: var TFdSet) = FDSet.fd_count = 0 proc WSAStartup*(wVersionRequired: int16, WSData: ptr TWSAData): cint {. @@ -531,7 +531,7 @@ const MAXIMUM_WAIT_OBJECTS* = 0x00000040 type - TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THANDLE] + TWOHandleArray* = array[0..MAXIMUM_WAIT_OBJECTS - 1, THandle] PWOHandleArray* = ptr TWOHandleArray proc waitForMultipleObjects*(nCount: DWORD, lpHandles: PWOHandleArray, @@ -566,12 +566,12 @@ const ERROR_ACCESS_DENIED* = 5 when useWinUnicode: - proc createFileW*(lpFileName: widecstring, dwDesiredAccess, dwShareMode: DWORD, + proc createFileW*(lpFileName: WideCString, dwDesiredAccess, dwShareMode: DWORD, lpSecurityAttributes: pointer, dwCreationDisposition, dwFlagsAndAttributes: DWORD, - hTemplateFile: THANDLE): THANDLE {. + hTemplateFile: THandle): THandle {. stdcall, dynlib: "kernel32", importc: "CreateFileW".} - proc deleteFileW*(pathName: widecstring): int32 {. + proc deleteFileW*(pathName: WideCString): int32 {. importc: "DeleteFileW", dynlib: "kernel32", stdcall.} else: proc createFileA*(lpFileName: cstring, dwDesiredAccess, dwShareMode: DWORD, @@ -582,28 +582,28 @@ else: proc deleteFileA*(pathName: cstring): int32 {. importc: "DeleteFileA", dynlib: "kernel32", stdcall.} -proc setEndOfFile*(hFile: THANDLE): WINBOOL {.stdcall, dynlib: "kernel32", +proc setEndOfFile*(hFile: THandle): WINBOOL {.stdcall, dynlib: "kernel32", importc: "SetEndOfFile".} -proc setFilePointer*(hFile: THANDLE, lDistanceToMove: LONG, +proc setFilePointer*(hFile: THandle, lDistanceToMove: LONG, lpDistanceToMoveHigh: ptr LONG, dwMoveMethod: DWORD): DWORD {. stdcall, dynlib: "kernel32", importc: "SetFilePointer".} -proc getFileSize*(hFile: THANDLE, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, +proc getFileSize*(hFile: THandle, lpFileSizeHigh: ptr DWORD): DWORD{.stdcall, dynlib: "kernel32", importc: "GetFileSize".} -proc mapViewOfFileEx*(hFileMappingObject: THANDLE, dwDesiredAccess: DWORD, +proc mapViewOfFileEx*(hFileMappingObject: THandle, dwDesiredAccess: DWORD, dwFileOffsetHigh, dwFileOffsetLow: DWORD, dwNumberOfBytesToMap: DWORD, lpBaseAddress: pointer): pointer{. stdcall, dynlib: "kernel32", importc: "MapViewOfFileEx".} -proc createFileMappingW*(hFile: THANDLE, +proc createFileMappingW*(hFile: THandle, lpFileMappingAttributes: pointer, flProtect, dwMaximumSizeHigh: DWORD, dwMaximumSizeLow: DWORD, - lpName: pointer): THANDLE {. + lpName: pointer): THandle {. stdcall, dynlib: "kernel32", importc: "CreateFileMappingW".} when not useWinUnicode: -- cgit 1.4.1-2-gfad0 From 438703f59e4d226f6e83e78c4f549a381526c6c2 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 29 Dec 2013 01:13:51 +0100 Subject: case consistency: next steps --- compiler/ast.nim | 14 ++-- compiler/astalgo.nim | 16 ++-- compiler/ccgexprs.nim | 16 ++-- compiler/ccgstmts.nim | 4 +- compiler/ccgtrav.nim | 2 +- compiler/ccgtypes.nim | 4 +- compiler/cgen.nim | 14 ++-- compiler/commands.nim | 16 ++-- compiler/condsyms.nim | 10 +-- compiler/crc.nim | 6 +- compiler/docgen.nim | 10 +-- compiler/evaltempl.nim | 2 +- compiler/filters.nim | 2 +- compiler/guards.nim | 4 +- compiler/hlo.nim | 2 +- compiler/idgen.nim | 2 +- compiler/jsgen.nim | 14 ++-- compiler/lambdalifting.nim | 6 +- compiler/lexer.nim | 2 +- compiler/llstream.nim | 4 +- compiler/magicsys.nim | 2 +- compiler/main.nim | 14 ++-- compiler/modules.nim | 2 +- compiler/msgs.nim | 14 ++-- compiler/nimconf.nim | 2 +- compiler/nimlexbase.nim | 2 +- compiler/nimrod.nim | 2 +- compiler/nimsets.nim | 4 +- compiler/options.nim | 12 +-- compiler/parampatterns.nim | 8 +- compiler/parser.nim | 20 ++--- compiler/pragmas.nim | 90 ++++++++++---------- compiler/pretty.nim | 7 +- compiler/renderer.nim | 60 +++++++------- compiler/rodread.nim | 12 +-- compiler/rodwrite.nim | 10 +-- compiler/ropes.nim | 8 +- compiler/sem.nim | 4 +- compiler/semcall.nim | 2 +- compiler/semdata.nim | 6 +- compiler/semexprs.nim | 16 ++-- compiler/seminst.nim | 2 +- compiler/semmagic.nim | 2 +- compiler/sempass2.nim | 10 +-- compiler/semstmts.nim | 12 +-- compiler/semtempl.nim | 4 +- compiler/semtypes.nim | 12 +-- compiler/semtypinst.nim | 2 +- compiler/service.nim | 2 +- compiler/sigmatch.nim | 14 ++-- compiler/suggest.nim | 4 +- compiler/syntaxes.nim | 4 +- compiler/transf.nim | 48 +++++------ compiler/treetab.nim | 4 +- compiler/types.nim | 26 +++--- compiler/vm.nim | 4 +- compiler/vmdef.nim | 2 +- compiler/vmgen.nim | 22 ++--- koch.nim | 4 +- lib/packages/docutils/highlite.nim | 2 +- lib/packages/docutils/rst.nim | 166 ++++++++++++++++++------------------- lib/packages/docutils/rstast.nim | 24 +++--- lib/packages/docutils/rstgen.nim | 28 +++---- lib/pure/json.nim | 12 +-- lib/pure/lexbase.nim | 2 +- lib/pure/os.nim | 68 +++++++-------- lib/pure/osproc.nim | 2 +- lib/pure/parseopt.nim | 2 +- lib/pure/sockets.nim | 20 ++--- lib/pure/strutils.nim | 2 +- lib/pure/unicode.nim | 16 ++-- lib/system.nim | 2 +- lib/system/assign.nim | 2 +- lib/system/chcks.nim | 2 +- lib/system/gc.nim | 14 ++-- lib/system/sysio.nim | 10 +-- lib/windows/winlean.nim | 28 +++---- 77 files changed, 513 insertions(+), 514 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/ast.nim b/compiler/ast.nim index 292283daf..a2f5fad17 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1167,30 +1167,30 @@ proc newSym(symKind: TSymKind, Name: PIdent, owner: PSym, proc initStrTable(x: var TStrTable) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc newStrTable*: TStrTable = initStrTable(result) proc initTable(x: var TTable) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc initIdTable(x: var TIdTable) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc initObjectSet(x: var TObjectSet) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc initIdNodeTable(x: var TIdNodeTable) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc initNodeTable(x: var TNodeTable) = x.counter = 0 - newSeq(x.data, startSize) + newSeq(x.data, StartSize) proc sonsLen(n: PType): int = if isNil(n.sons): result = 0 @@ -1402,7 +1402,7 @@ proc isGenericRoutine*(s: PSym): bool = else: discard proc skipGenericOwner*(s: PSym): PSym = - InternalAssert s.kind in skProcKinds + internalAssert s.kind in skProcKinds ## Generic instantiations are owned by their originating generic ## symbol. This proc skips such owners and goes straigh to the owner ## of the generic itself (the module or the enclosing proc). diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 83218b31d..35c306bcf 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -472,7 +472,7 @@ proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) = proc objectSetEnlarge(t: var TObjectSet) = var n: TObjectSeq - newSeq(n, len(t.data) * growthFactor) + newSeq(n, len(t.data) * GrowthFactor) for i in countup(0, high(t.data)): if t.data[i] != nil: objectSetRawInsert(n, t.data[i]) swap(t.data, n) @@ -535,7 +535,7 @@ proc tableRawInsert(data: var TPairSeq, key, val: PObject) = proc tableEnlarge(t: var TTable) = var n: TPairSeq - newSeq(n, len(t.data) * growthFactor) + newSeq(n, len(t.data) * GrowthFactor) for i in countup(0, high(t.data)): if t.data[i].key != nil: tableRawInsert(n, t.data[i].key, t.data[i].val) swap(t.data, n) @@ -583,7 +583,7 @@ proc symTabReplace*(t: var TStrTable, prevSym: PSym, newSym: PSym) = proc strTableEnlarge(t: var TStrTable) = var n: TSymSeq - newSeq(n, len(t.data) * growthFactor) + newSeq(n, len(t.data) * GrowthFactor) for i in countup(0, high(t.data)): if t.data[i] != nil: strTableRawInsert(n, t.data[i]) swap(t.data, n) @@ -742,7 +742,7 @@ proc idTablePut(t: var TIdTable, key: PIdObj, val: PObject) = t.data[index].val = val else: 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)): if t.data[i].key != nil: idTableRawInsert(n, t.data[i].key, t.data[i].val) @@ -792,7 +792,7 @@ proc idNodeTablePut(t: var TIdNodeTable, key: PIdObj, val: PNode) = else: if mustRehash(len(t.data), t.counter): var n: TIdNodePairSeq - newSeq(n, len(t.data) * growthFactor) + newSeq(n, len(t.data) * GrowthFactor) for i in countup(0, high(t.data)): if t.data[i].key != nil: 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) = x.counter = 0 - newSeq(x.data, startSize) - for i in countup(0, startSize - 1): x.data[i].key = InvalidKey + newSeq(x.data, StartSize) + for i in countup(0, StartSize - 1): x.data[i].key = InvalidKey proc iiTableRawGet(t: TIITable, key: int): int = var h: THash @@ -844,7 +844,7 @@ proc iiTablePut(t: var TIITable, key, val: int) = else: if mustRehash(len(t.data), t.counter): 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(t.data)): if t.data[i].key != InvalidKey: diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index b10d306a7..495c342ed 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -11,7 +11,7 @@ # -------------------------- constant expressions ------------------------ -proc intLiteral(i: biggestInt): PRope = +proc intLiteral(i: BiggestInt): PRope = if (i > low(int32)) and (i <= high(int32)): result = toRope(i) 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) = const - prc: array[mAddi..mModi64, string] = ["addInt", "subInt", "mulInt", + prc: array[mAddI..mModI64, string] = ["addInt", "subInt", "mulInt", "divInt", "modInt", "addInt64", "subInt64", "mulInt64", "divInt64", "modInt64"] - opr: array[mAddi..mModi64, string] = ["+", "-", "*", "/", "%", "+", "-", + opr: array[mAddI..mModI64, string] = ["+", "-", "*", "/", "%", "+", "-", "*", "/", "%"] var a, b: TLoc 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) tmp2.k = locTemp tmp2.t = field.loc.t - tmp2.s = onHeap + tmp2.s = OnHeap tmp2.heapRoot = tmp.r expr(p, it.sons[1], tmp2) if d.k == locNone: @@ -1196,7 +1196,7 @@ proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of tyOpenArray, tyVarargs: if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)") else: unaryExpr(p, e, d, "$1Len0") - of tyCstring: + of tyCString: if op == mHigh: unaryExpr(p, e, d, "(strlen($1)-1)") else: unaryExpr(p, e, d, "strlen($1)") of tyString, tySequence: @@ -1481,7 +1481,7 @@ proc genStrEquals(p: BProc, e: PNode, d: var TLoc) = binaryExpr(p, e, d, "#eqStrings($1, $2)") 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] = ["+", "-", "*", "/"] var a, b: TLoc 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))", toRope(opr[m]), rdLoc(a), rdLoc(b), getSimpleTypeDesc(p.module, e[1].typ))) - if optNanCheck in p.options: + if optNaNCheck in p.options: linefmt(p, cpsStmts, "#nanCheck($1);$n", rdLoc(d)) if optInfCheck in p.options: 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 mShrI..mXor: binaryArith(p, e, d, op) 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 mGetTypeInfo: genGetTypeInfo(p, e, d) of mSwap: genSwap(p, e, d) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index eb738b574..e9291edc5 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -920,7 +920,7 @@ proc genPragma(p: BProc, n: PNode) = case whichPragma(it) of wEmit: genEmit(p, it) of wBreakpoint: genBreakPoint(p, it) - of wWatchpoint: genWatchpoint(p, it) + of wWatchPoint: genWatchpoint(p, it) of wInjectStmt: var p = newProc(nil, p.module) p.options = p.options - {optLineTrace, optStackTrace} @@ -977,4 +977,4 @@ proc genAsgn(p: BProc, e: PNode, fastAsgn: bool) = proc genStmts(p: BProc, t: PNode) = var a: TLoc expr(p, t, a) - InternalAssert a.k in {locNone, locTemp, locLocalVar} + internalAssert a.k in {locNone, locTemp, locLocalVar} diff --git a/compiler/ccgtrav.nim b/compiler/ccgtrav.nim index 6de425cfd..ecf1eb152 100644 --- a/compiler/ccgtrav.nim +++ b/compiler/ccgtrav.nim @@ -111,7 +111,7 @@ proc genTraverseProc(m: BModule, typ: PType, reason: TTypeInfoReason): PRope = lineF(p, cpsInit, "a = ($1)p;$n", t) c.p = p - assert typ.kind != tyTypedesc + assert typ.kind != tyTypeDesc if typ.kind == tySequence: genTraverseProcSeq(c, "a".toRope, typ) else: diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index 9d3629085..f1e824e14 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -362,7 +362,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope = of tyString: discard cgsym(m, "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 tyChar: result = typeNameOrLiteral(typ, "NIM_CHAR") of tyNil: result = typeNameOrLiteral(typ, "0") @@ -559,7 +559,7 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = if not isImportedType(t): appf(m.s[cfsForwardTypes], getForwardStructFormat(), [result]) idTablePut(m.forwTypeCache, t, result) - assert(CacheGetType(m.typeCache, t) == nil) + assert(cacheGetType(m.typeCache, t) == nil) idTablePut(m.typeCache, t, con(result, "*")) if not isImportedType(t): if skipTypes(t.sons[0], typedescInst).kind != tyEmpty: diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 97177a0ec..97965def0 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -351,7 +351,7 @@ proc resetLoc(p: BProc, loc: var TLoc) = if not isComplexValueType(skipTypes(loc.t, abstractVarRange)): if containsGcRef: var nilLoc: TLoc - initLoc(nilLoc, locTemp, loc.t, onStack) + initLoc(nilLoc, locTemp, loc.t, OnStack) nilLoc.r = toRope("NIM_NIL") genRefAssign(p, loc, nilLoc, {afSrcIsNil}) else: @@ -665,7 +665,7 @@ proc symInDynamicLib(m: BModule, sym: PSym) = params, cstringLit(m, m.s[cfsDynLibInit], ropeToStr(extname))]) var last = lastSon(n) if last.kind == nkHiddenStdConv: last = last.sons[1] - InternalAssert(last.kind == nkStrLit) + internalAssert(last.kind == nkStrLit) let idx = last.strVal if idx.len == 0: app(m.initProc.s(cpsStmts), load) @@ -917,7 +917,7 @@ proc getCopyright(cfilenoext: string): PRope = "/* (c) 2012 Andreas Rumpf */$n" & "/* The generated code is subject to the original license. */$n", "; Generated by Nimrod Compiler v$1$n" & - "; (c) 2012 Andreas Rumpf$n", [toRope(versionAsString)]) + "; (c) 2012 Andreas Rumpf$n", [toRope(VersionAsString)]) else: result = ropeff("/* Generated by Nimrod Compiler v$1 */$n" & "/* (c) 2012 Andreas Rumpf */$n" & @@ -927,7 +927,7 @@ proc getCopyright(cfilenoext: string): PRope = "; Generated by Nimrod Compiler v$1$n" & "; (c) 2012 Andreas Rumpf$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.CPU[targetCPU].name), toRope(extccomp.CC[extccomp.ccompiler].name), @@ -992,8 +992,8 @@ proc genMainProc(m: BModule) = otherMain = WinCDllMain discard lists.IncludeStr(m.headerFiles, "") elif optGenDynLib in gGlobalOptions: - nimMain = posixNimDllMain - otherMain = posixCDllMain + nimMain = PosixNimDllMain + otherMain = PosixCDllMain elif platform.targetOS == osStandalone: nimMain = PosixNimMain otherMain = StandaloneCMain @@ -1202,7 +1202,7 @@ proc rawNewModule(module: PSym): BModule = proc newModule(module: PSym): BModule = # we should create only one cgen module for each module sym - InternalAssert getCgenModule(module) == nil + internalAssert getCgenModule(module) == nil result = rawNewModule(module) growCache gModules, module.position diff --git a/compiler/commands.nim b/compiler/commands.nim index acb9af8ac..96fa34ae0 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -27,7 +27,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) # implementation 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" const @@ -173,11 +173,11 @@ proc testCompileOption*(switch: string, info: TLineInfo): bool = of "linetrace": result = contains(gOptions, optLineTrace) of "debugger": result = contains(gOptions, optEndb) of "profiler": result = contains(gOptions, optProfiler) - of "checks", "x": result = gOptions * checksOptions == checksOptions + of "checks", "x": result = gOptions * ChecksOptions == ChecksOptions of "floatchecks": - result = gOptions * {optNanCheck, optInfCheck} == {optNanCheck, optInfCheck} + result = gOptions * {optNaNCheck, optInfCheck} == {optNaNCheck, 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 "fieldchecks": result = contains(gOptions, optFieldCheck) of "rangechecks": result = contains(gOptions, optRangeCheck) @@ -239,7 +239,7 @@ proc dynlibOverride(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = expectArg(switch, arg, pass, info) options.inclDynlibOverride(arg) -proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = +proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = var theOS: TSystemOS cpu: TSystemCPU @@ -335,11 +335,11 @@ proc processSwitch(switch, arg: string, pass: TCmdlinePass, info: TLineInfo) = processOnOffSwitch({optProfiler}, arg, pass, info) if optProfiler in gOptions: defineSymbol("profiler") else: undefSymbol("profiler") - of "checks", "x": processOnOffSwitch(checksOptions, arg, pass, info) + of "checks", "x": processOnOffSwitch(ChecksOptions, arg, pass, info) of "floatchecks": - processOnOffSwitch({optNanCheck, optInfCheck}, arg, pass, info) + processOnOffSwitch({optNaNCheck, 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 "fieldchecks": processOnOffSwitch({optFieldCheck}, arg, pass, info) of "rangechecks": processOnOffSwitch({optRangeCheck}, arg, pass, info) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index 575cda412..e74ab5853 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -55,12 +55,12 @@ proc initDefines*() = of cpuAmd64: defineSymbol("x8664") else: discard case targetOS - of osDOS: + of osDos: defineSymbol("msdos") of osWindows: defineSymbol("mswindows") defineSymbol("win32") - of osLinux, osMorphOS, osSkyOS, osIrix, osPalmOS, osQNX, osAtari, osAix, + of osLinux, osMorphos, osSkyos, osIrix, osPalmos, osQnx, osAtari, osAix, osHaiku: # these are all 'unix-like' defineSymbol("unix") @@ -69,13 +69,13 @@ proc initDefines*() = defineSymbol("sunos") defineSymbol("unix") defineSymbol("posix") - of osNetBSD, osFreeBSD, osOpenBSD: + of osNetbsd, osFreebsd, osOpenbsd: defineSymbol("unix") defineSymbol("bsd") defineSymbol("posix") - of osMacOS: + of osMacos: defineSymbol("macintosh") - of osMacOSX: + of osMacosx: defineSymbol("macintosh") defineSymbol("unix") defineSymbol("posix") diff --git a/compiler/crc.nim b/compiler/crc.nim index 3291ce7c0..ae1df3ff1 100644 --- a/compiler/crc.nim +++ b/compiler/crc.nim @@ -78,7 +78,7 @@ proc updateCrc32(val: int8, crc: TCrc32): TCrc32 = result = TCrc32(crc32table[(int(crc) xor (int(val) and 0x000000FF)) and 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) proc strCrc32(s: string): TCrc32 = @@ -93,7 +93,7 @@ type TByteArray = array[0..10000000, int8] PByteArray = ref TByteArray -proc crcFromBuf(buf: Pointer, length: int): TCrc32 = +proc crcFromBuf(buf: pointer, length: int): TCrc32 = var p = cast[PByteArray](buf) result = InitCrc32 for i in countup(0, length - 1): result = updateCrc32(p[i], result) @@ -106,7 +106,7 @@ proc crcFromFile(filename: string): TCrc32 = result = InitCrc32 if not open(bin, filename): return # not equal if file does not exist - var buf = alloc(BufSize) + var buf = alloc(bufSize) var p = cast[PByteArray](buf) while true: var readBytes = readBuffer(bin, buf, bufSize) diff --git a/compiler/docgen.nim b/compiler/docgen.nim index b38f53015..031b7d429 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -44,19 +44,19 @@ proc compilerMsgHandler(filename: string, line, col: int, proc parseRst(text, filename: string, line, column: int, hasToc: var bool, - rstOptions: TRstParseOptions): PRSTNode = + rstOptions: TRstParseOptions): PRstNode = result = rstParse(text, filename, line, column, hasToc, rstOptions, options.FindFile, compilerMsgHandler) proc newDocumentor*(filename: string, config: PStringTable): PDoc = new(result) - initRstGenerator(result[], (if gCmd != cmdRst2Tex: outHtml else: outLatex), + initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), options.gConfigVars, filename, {roSupportRawDirective}, options.FindFile, compilerMsgHandler) result.id = 100 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) 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()") result = "" -proc getRstName(n: PNode): PRSTNode = +proc getRstName(n: PNode): PRstNode = case n.kind of nkPostfix: result = getRstName(n.sons[1]) of nkPragmaExpr: result = getRstName(n.sons[0]) @@ -408,7 +408,7 @@ proc genOutFile(d: PDoc): PRope = proc generateIndex*(d: PDoc) = if optGenIndex in gGlobalOptions: 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) = var content = genOutFile(d) diff --git a/compiler/evaltempl.nim b/compiler/evaltempl.nim index 14202dbca..78cdbb45f 100644 --- a/compiler/evaltempl.nim +++ b/compiler/evaltempl.nim @@ -36,7 +36,7 @@ proc evalTemplateAux(templ, actual: PNode, c: var TemplCtx, result: PNode) = else: result.add copyTree(x) else: - InternalAssert sfGenSym in s.flags + internalAssert sfGenSym in s.flags var x = PSym(idTableGet(c.mapping, s)) if x == nil: x = copySym(s, false) diff --git a/compiler/filters.nim b/compiler/filters.nim index db8731d8c..ce0ffd196 100644 --- a/compiler/filters.nim +++ b/compiler/filters.nim @@ -35,7 +35,7 @@ proc getArg(n: PNode, name: string, pos: int): PNode = elif i == pos: 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) if x == nil: result = default elif x.kind == nkCharLit: result = chr(int(x.intVal)) diff --git a/compiler/guards.nim b/compiler/guards.nim index b35d9b872..3d27c85c9 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -254,7 +254,7 @@ proc valuesUnequal(a, b: PNode): bool = result = not sameValue(a, b) 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) dec result.intVal else: @@ -366,7 +366,7 @@ proc impliesIsNil(fact, eq: PNode): TImplication = else: discard proc impliesGe(fact, x, c: PNode): TImplication = - InternalAssert isLocation(x) + internalAssert isLocation(x) case fact.sons[0].sym.magic of someEq: if sameTree(fact.sons[1], x): diff --git a/compiler/hlo.nim b/compiler/hlo.nim index 7905761dd..e3f80ad36 100644 --- a/compiler/hlo.nim +++ b/compiler/hlo.nim @@ -12,7 +12,7 @@ proc hlo(c: PContext, n: 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 # aweful to semcheck before macro invocation, so we don't and treat # templates and macros as immediate in this context. diff --git a/compiler/idgen.nim b/compiler/idgen.nim index 5a1c90930..c4f5f2a9e 100644 --- a/compiler/idgen.nim +++ b/compiler/idgen.nim @@ -22,7 +22,7 @@ when debugIds: var usedIds = InitIntSet() proc registerID*(id: PIdObj) = - when debugIDs: + when debugIds: if id.id == -1 or containsOrIncl(usedIds, id.id): internalError("ID already used: " & $id.id) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 8fd72623a..1ba40f95d 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -111,7 +111,7 @@ proc mapType(typ: PType): TJSTypeKind = let t = skipTypes(typ, abstractInst) case t.kind of tyVar, tyRef, tyPtr: - if skipTypes(t.sons[0], abstractInst).kind in mappedToObject: + if skipTypes(t.sons[0], abstractInst).kind in MappedToObject: result = etyObject else: result = etyBaseIndex @@ -240,7 +240,7 @@ proc genOr(p: PProc, a, b: PNode, r: var TCompRes) = type 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 jsOps: TMagicOps = [ @@ -865,7 +865,7 @@ proc genFieldAddr(p: PProc, n: PNode, r: var TCompRes) = var f = b.sons[1].sym if f.loc.r == nil: f.loc.r = mangleName(f) r.res = makeJSString(ropeToStr(f.loc.r)) - InternalAssert a.typ != etyBaseIndex + internalAssert a.typ != etyBaseIndex r.address = a.res r.kind = resExpr @@ -894,7 +894,7 @@ proc genArrayAddr(p: PProc, n: PNode, r: var TCompRes) = r.typ = etyBaseIndex gen(p, n.sons[0], a) 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 var typ = skipTypes(n.sons[0].typ, abstractPtrs) 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 of mOr: genOr(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 mSwap: genSwap(p, n) of mUnaryLt: @@ -1416,7 +1416,7 @@ proc genObjConstr(p: PProc, n: PNode, r: var TCompRes) = for i in countup(1, sonsLen(n) - 1): if i > 0: app(r.res, ", ") var it = n.sons[i] - InternalAssert it.kind == nkExprColonExpr + internalAssert it.kind == nkExprColonExpr gen(p, it.sons[1], a) var f = it.sons[0].sym if f.loc.r == nil: f.loc.r = mangleName(f) @@ -1655,7 +1655,7 @@ proc genHeader(): PRope = "$nvar Globals = this;$n" & "var framePtr = null;$n" & "var excHandler = null;$n", - [toRope(versionAsString)]) + [toRope(VersionAsString)]) proc genModule(p: PProc, n: PNode) = if optStackTrace in p.options: diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index 558b2cfd3..9e42210c0 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -226,7 +226,7 @@ proc isInnerProc(s, outerProc: PSym): bool {.inline.} = #s.typ.callConv == ccClosure 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) cp.typ = newType(tyRef, i.fn) rawAddSon(cp.typ, e.tup) @@ -679,7 +679,7 @@ proc liftIterator*(iter: PSym, body: PNode): PNode = c.tup = newType(tyTuple, iter) 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) cp.typ = newType(tyRef, iter) rawAddSon(cp.typ, c.tup) @@ -758,7 +758,7 @@ proc liftForLoop*(body: PNode): PNode = ... """ 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] result = newNodeI(nkStmtList, body.info) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 17c971912..a258765cf 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -581,7 +581,7 @@ proc getCharacter(L: var TLexer, tok: var TToken) = inc(L.bufpos) # skip ' var c = L.buf[L.bufpos] case c - of '\0'..Pred(' '), '\'': lexMessage(L, errInvalidCharacterConstant) + of '\0'..pred(' '), '\'': lexMessage(L, errInvalidCharacterConstant) of '\\': getEscapedChar(L, tok) else: tok.literal = $c diff --git a/compiler/llstream.nim b/compiler/llstream.nim index 6eac08dbd..510880ffd 100644 --- a/compiler/llstream.nim +++ b/compiler/llstream.nim @@ -50,7 +50,7 @@ proc llStreamOpen(data: string): PLLStream = result.s = data result.kind = llsString -proc llStreamOpen(f: var tfile): PLLStream = +proc llStreamOpen(f: var TFile): PLLStream = new(result) result.f = f result.kind = llsFile @@ -179,7 +179,7 @@ proc llStreamWriteln(s: PLLStream, data: string) = llStreamWrite(s, data) llStreamWrite(s, "\n") -proc llStreamWrite(s: PLLStream, data: Char) = +proc llStreamWrite(s: PLLStream, data: char) = var c: char case s.kind of llsNone, llsStdIn: diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index f81347fae..281c642b7 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -79,7 +79,7 @@ proc getSysType(kind: TTypeKind): PType = of tyBool: result = sysTypeFromName("bool") of tyChar: result = sysTypeFromName("char") of tyString: result = sysTypeFromName("string") - of tyCstring: result = sysTypeFromName("cstring") + of tyCString: result = sysTypeFromName("cstring") of tyPointer: result = sysTypeFromName("pointer") of tyNil: result = newSysType(tyNil, ptrSize) else: internalError("request for typekind: " & $kind) diff --git a/compiler/main.nim b/compiler/main.nim index 275d65781..3571e6a4e 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -39,7 +39,7 @@ proc semanticPasses = proc commandGenDepend = semanticPasses() - registerPass(genDependPass) + registerPass(gendependPass) registerPass(cleanupPass) compileProject() generateDot(gProjectFull) @@ -127,7 +127,7 @@ proc commandCompileToJS = defineSymbol("ecmascript") # For backward compatibility defineSymbol("js") semanticPasses() - registerPass(jsgenPass) + registerPass(JSgenPass) compileProject() proc interactivePasses = @@ -177,7 +177,7 @@ proc commandPretty = pretty.overwriteFiles() proc commandScan = - var f = addFileExt(mainCommandArg(), nimExt) + var f = addFileExt(mainCommandArg(), NimExt) var stream = llStreamOpen(f, fmRead) if stream != nil: var @@ -224,7 +224,7 @@ proc wantMainModule = gProjectName = optMainModule gProjectFull = gProjectPath / gProjectName - gProjectMainIdx = addFileExt(gProjectFull, nimExt).fileInfoIdx + gProjectMainIdx = addFileExt(gProjectFull, NimExt).fileInfoIdx proc requireMainModuleOption = if optMainModule.len == 0: @@ -233,7 +233,7 @@ proc requireMainModuleOption = gProjectName = optMainModule gProjectFull = gProjectPath / gProjectName - gProjectMainIdx = addFileExt(gProjectFull, nimExt).fileInfoIdx + gProjectMainIdx = addFileExt(gProjectFull, NimExt).fileInfoIdx proc resetMemory = resetCompilationLists() @@ -334,7 +334,7 @@ proc mainCommand* = of "compiletollvm": gCmd = cmdCompileToLLVM wantMainModule() - when has_LLVM_Backend: + when hasLLVM_Backend: CommandCompileToLLVM() else: rawMessage(errInvalidCommandX, command) @@ -386,7 +386,7 @@ proc mainCommand* = for s in definedSymbolNames(): definedSymbols.elems.add(%s) var libpaths = newJArray() - for dir in itersearchpath(searchPaths): libpaths.elems.add(%dir) + for dir in iterSearchPath(searchPaths): libpaths.elems.add(%dir) var dumpdata = % [ (key: "version", val: %VersionAsString), diff --git a/compiler/modules.nim b/compiler/modules.nim index e1fc1ad95..1775599a9 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -41,7 +41,7 @@ template crc(x: PSym): expr = gMemCacheData[x.position].crc proc crcChanged(fileIdx: int32): bool = - InternalAssert fileIdx >= 0 and fileIdx < gMemCacheData.len + internalAssert fileIdx >= 0 and fileIdx < gMemCacheData.len template updateStatus = gMemCacheData[fileIdx].crcStatus = if result: crcHasChanged diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 7e851d1b2..cdfbc3ece 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -724,7 +724,7 @@ proc writeContext(lastinfo: TLineInfo) = var info = lastinfo for i in countup(0, len(msgContext) - 1): 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].col), getMessageStr(errInstantiationFrom, "")]) @@ -735,17 +735,17 @@ proc rawMessage*(msg: TMsgKind, args: openArray[string]) = case msg of errMin..errMax: writeContext(unknownLineInfo()) - frmt = rawErrorFormat + frmt = RawErrorFormat of warnMin..warnMax: if optWarns notin gOptions: return if msg notin gNotes: return writeContext(unknownLineInfo()) - frmt = rawWarningFormat + frmt = RawWarningFormat inc(gWarnCounter) of hintMin..hintMax: if optHints notin gOptions: return if msg notin gNotes: return - frmt = rawHintFormat + frmt = RawHintFormat inc(gHintCounter) let s = `%`(frmt, `%`(msgKindToString(msg), args)) msgWriteln(s) @@ -766,7 +766,7 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, case msg of errMin..errMax: writeContext(info) - frmt = posErrorFormat + frmt = PosErrorFormat # we try to filter error messages so that not two error message # in the same file and line are produced: #ignoreMsg = lastError == info and eh != doAbort @@ -774,11 +774,11 @@ proc liMessage(info: TLineInfo, msg: TMsgKind, arg: string, of warnMin..warnMax: ignoreMsg = optWarns notin gOptions or msg notin gNotes if not ignoreMsg: writeContext(info) - frmt = posWarningFormat + frmt = PosWarningFormat inc(gWarnCounter) of hintMin..hintMax: ignoreMsg = optHints notin gOptions or msg notin gNotes - frmt = posHintFormat + frmt = PosHintFormat inc(gHintCounter) let s = frmt % [toMsgFilename(info), coordToStr(info.line), coordToStr(info.col), getMessageStr(msg, arg)] diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index 50f24043b..fee96a54a 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -81,7 +81,7 @@ proc doElif(L: var TLexer, tok: var TToken) = proc jumpToDirective(L: var TLexer, tok: var TToken, dest: TJumpDest) = var nestedIfs = 0 - while True: + while true: if (tok.ident != nil) and (tok.ident.s == "@"): ppGetTok(L, tok) case whichKeyword(tok.ident) diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim index 1dcb927ce..e6dcd8ce7 100644 --- a/compiler/nimlexbase.nim +++ b/compiler/nimlexbase.nim @@ -107,7 +107,7 @@ proc fillBuffer(L: var TBaseLexer) = oldBufLen = L.BufLen L.bufLen = L.BufLen * 2 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]), oldBufLen * chrSize) div chrSize if charsRead < oldBufLen: diff --git a/compiler/nimrod.nim b/compiler/nimrod.nim index c4c4f887c..60124e335 100644 --- a/compiler/nimrod.nim +++ b/compiler/nimrod.nim @@ -71,7 +71,7 @@ proc handleCmdLine() = binPath = options.outFile.prependCurDir else: # Figure out ourselves a valid binary name. - binPath = changeFileExt(gProjectFull, exeExt).prependCurDir + binPath = changeFileExt(gProjectFull, ExeExt).prependCurDir var ex = quoteShell(binPath) execExternalProgram(ex & ' ' & service.arguments) diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index 8e5de4194..f24d3a356 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -98,13 +98,13 @@ proc toTreeSet(s: TBitSet, settype: PType, info: TLineInfo): PNode = result.typ = settype result.info = info e = 0 - while e < len(s) * elemSize: + while e < len(s) * ElemSize: if bitSetIn(s, e): a = e b = e while true: 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) if a == b: addSon(result, newIntTypeNode(nkIntLit, a + first, elemType)) diff --git a/compiler/options.nim b/compiler/options.nim index ae62af1c5..640f70f28 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -192,16 +192,16 @@ proc canonicalizePath*(path: string): string = proc shortenDir*(dir: string): string = ## returns the interesting part of a dir - var prefix = getPrefixDir() & dirSep + var prefix = getPrefixDir() & DirSep if startsWith(dir, prefix): return substr(dir, len(prefix)) - prefix = gProjectPath & dirSep + prefix = gProjectPath & DirSep if startsWith(dir, prefix): return substr(dir, len(prefix)) result = dir 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) else: result = path @@ -213,9 +213,9 @@ proc getGeneratedPath: string = proc getPackageName*(path: string): string = var q = 1 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): - if path[i] in {dirsep, altsep}: + if path[i] in {DirSep, AltSep}: if b == 0: b = i else: let x = path.substr(i+1, b-1) @@ -288,7 +288,7 @@ proc findFile*(f: string): string {.procvar.} = proc findModule*(modulename, currentModule: string): string = # returns path to module - let m = addFileExt(modulename, nimExt) + let m = addFileExt(modulename, NimExt) let currentPath = currentModule.splitFile.dir result = currentPath / m if not existsFile(result): diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim index 91c230ccb..be0f995b6 100644 --- a/compiler/parampatterns.nim +++ b/compiler/parampatterns.nim @@ -97,14 +97,14 @@ proc compileConstraints(p: PNode, result: var TPatternCode) = of "nosideeffect": result.add(ppNoSideEffect) else: # check all symkinds: - InternalAssert int(high(TSymKind)) < 255 + internalAssert int(high(TSymKind)) < 255 for i in low(TSymKind)..high(TSymKind): if cmpIgnoreStyle(($i).substr(2), spec) == 0: result.add(ppSymKind) result.add(chr(i.ord)) return # check all nodekinds: - InternalAssert int(high(TNodeKind)) < 255 + internalAssert int(high(TNodeKind)) < 255 for i in low(TNodeKind)..high(TNodeKind): if cmpIgnoreStyle($i, spec) == 0: result.add(ppNodeKind) @@ -124,7 +124,7 @@ proc semNodeKindConstraints*(p: PNode): PNode = if p.len >= 2: for i in 1.. maxStackSize-1: + if result.strVal.len > MaxStackSize-1: internalError(p.info, "parameter pattern too complex") else: patternError(p) @@ -221,7 +221,7 @@ proc isAssignable*(owner: PSym, n: PNode): TAssignableResult = proc matchNodeKinds*(p, n: PNode): bool = # matches the parameter constraint 'p' against the concrete AST 'n'. # Efficiency matters here. - var stack {.noinit.}: array[0..maxStackSize, bool] + var stack {.noinit.}: array[0..MaxStackSize, bool] # empty patterns are true: stack[0] = true var sp = 1 diff --git a/compiler/parser.nim b/compiler/parser.nim index 47e8e9a54..49fdd5703 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -211,7 +211,7 @@ proc getPrecedence(tok: TToken): int = of '?': result = 2 else: considerAsgn(2) 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 tkAnd: result = 4 of tkOr, tkXor: result = 3 @@ -455,7 +455,7 @@ proc simpleExpr(p: var TParser, mode = pmNormal): PNode proc semiStmtList(p: var TParser, result: PNode) = result.add(complexOrSimpleStmt(p)) - while p.tok.tokType == tkSemicolon: + while p.tok.tokType == tkSemiColon: getTok(p) optInd(p, result) 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; # tests/reject/tbind2 fails otherwise. semiStmtList(p, result) - elif p.tok.tokType == tkSemicolon: + elif p.tok.tokType == tkSemiColon: # '(;' enforces 'stmt' context: getTok(p) optInd(p, result) @@ -498,7 +498,7 @@ proc parsePar(p: var TParser): PNode = asgn.sons[0] = a asgn.sons[1] = b result.add(asgn) - elif p.tok.tokType == tkSemicolon: + elif p.tok.tokType == tkSemiColon: # stmt context: result.add(a) semiStmtList(p, result) @@ -798,7 +798,7 @@ proc parseTuple(p: var TParser, indentAllowed = false): PNode = while p.tok.tokType in {tkSymbol, tkAccent}: var a = parseIdentColonEquals(p, {}) addSon(result, a) - if p.tok.tokType notin {tkComma, tkSemicolon}: break + if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) @@ -840,7 +840,7 @@ proc parseParamList(p: var TParser, retColon = true): PNode = parMessage(p, errTokenExpected, ")") break addSon(result, a) - if p.tok.tokType notin {tkComma, tkSemicolon}: break + if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) @@ -1378,7 +1378,7 @@ proc parseGenericParamList(p: var TParser): PNode = while p.tok.tokType in {tkSymbol, tkAccent}: var a = parseGenericParam(p) addSon(result, a) - if p.tok.tokType notin {tkComma, tkSemicolon}: break + if p.tok.tokType notin {tkComma, tkSemiColon}: break getTok(p) skipComment(p, a) optPar(p) @@ -1810,7 +1810,7 @@ proc parseStmt(p: var TParser): PNode = while true: if p.tok.indent == p.currInd: nil - elif p.tok.tokType == tkSemicolon: + elif p.tok.tokType == tkSemiColon: getTok(p) if p.tok.indent < 0 or p.tok.indent == p.currInd: discard else: break @@ -1842,7 +1842,7 @@ proc parseStmt(p: var TParser): PNode = let a = simpleStmt(p) if a.kind == nkEmpty: parMessage(p, errExprExpected, p.tok) result.add(a) - if p.tok.tokType != tkSemicolon: break + if p.tok.tokType != tkSemiColon: break getTok(p) proc parseAll(p: var TParser): PNode = @@ -1866,7 +1866,7 @@ proc parseTopLevelStmt(p: var TParser): PNode = else: parMessage(p, errInvalidIndentation) p.firstTok = false case p.tok.tokType - of tkSemicolon: + of tkSemiColon: getTok(p) if p.tok.indent <= 0: discard else: parMessage(p, errInvalidIndentation) diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index 5c9247fed..b313e49f5 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -20,49 +20,49 @@ const const procPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl, - wMagic, wNosideEffect, wSideEffect, wNoreturn, wDynLib, wHeader, - wCompilerProc, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge, + wMagic, wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader, + wCompilerproc, wProcVar, wDeprecated, wVarargs, wCompileTime, wMerge, wBorrow, wExtern, wImportCompilerProc, wThread, wImportCpp, wImportObjC, wNoStackFrame, wError, wDiscardable, wNoInit, wDestructor, wCodegenDecl, - wGenSym, wInject, wRaises, wTags, wOperator, wDelegator} + wGensym, wInject, wRaises, wTags, wOperator, wDelegator} converterPragmas* = procPragmas methodPragmas* = procPragmas - templatePragmas* = {wImmediate, wDeprecated, wError, wGenSym, wInject, wDirty, + templatePragmas* = {wImmediate, wDeprecated, wError, wGensym, wInject, wDirty, wDelegator} macroPragmas* = {FirstCallConv..LastCallConv, wImmediate, wImportc, wExportc, - wNodecl, wMagic, wNosideEffect, wCompilerProc, wDeprecated, wExtern, - wImportcpp, wImportobjc, wError, wDiscardable, wGenSym, wInject, wDelegator} - iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideEffect, wSideEffect, + wNodecl, wMagic, wNosideeffect, wCompilerproc, wDeprecated, wExtern, + wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wDelegator} + iteratorPragmas* = {FirstCallConv..LastCallConv, wNosideeffect, wSideeffect, wImportc, wExportc, wNodecl, wMagic, wDeprecated, wBorrow, wExtern, - wImportcpp, wImportobjc, wError, wDiscardable, wGenSym, wInject, wRaises, + wImportCpp, wImportObjC, wError, wDiscardable, wGensym, wInject, wRaises, wTags, wOperator} exprPragmas* = {wLine} stmtPragmas* = {wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wLinedir, wStacktrace, wLinetrace, wOptimization, wHint, wWarning, wError, - wFatal, wDefine, wUndef, wCompile, wLink, wLinkSys, wPure, wPush, wPop, - wBreakpoint, wWatchpoint, wPassL, wPassC, wDeadCodeElim, wDeprecated, - wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll, + wFatal, wDefine, wUndef, wCompile, wLink, wLinksys, wPure, wPush, wPop, + wBreakpoint, wWatchPoint, wPassl, wPassc, wDeadCodeElim, wDeprecated, + wFloatchecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll, wLinearScanEnd, wPatterns, wEffects, wNoForward, wComputedGoto, wInjectStmt} lambdaPragmas* = {FirstCallConv..LastCallConv, wImportc, wExportc, wNodecl, - wNosideEffect, wSideEffect, wNoreturn, wDynLib, wHeader, - wDeprecated, wExtern, wThread, wImportcpp, wImportobjc, wNoStackFrame, + wNosideeffect, wSideeffect, wNoreturn, wDynlib, wHeader, + wDeprecated, wExtern, wThread, wImportCpp, wImportObjC, wNoStackFrame, wRaises, wTags} typePragmas* = {wImportc, wExportc, wDeprecated, wMagic, wAcyclic, wNodecl, - wPure, wHeader, wCompilerProc, wFinal, wSize, wExtern, wShallow, - wImportcpp, wImportobjc, wError, wIncompleteStruct, wByCopy, wByRef, - wInheritable, wGenSym, wInject, wRequiresInit} + wPure, wHeader, wCompilerproc, wFinal, wSize, wExtern, wShallow, + wImportCpp, wImportObjC, wError, wIncompleteStruct, wByCopy, wByRef, + wInheritable, wGensym, wInject, wRequiresInit} fieldPragmas* = {wImportc, wExportc, wDeprecated, wExtern, - wImportcpp, wImportobjc, wError} + wImportCpp, wImportObjC, wError} varPragmas* = {wImportc, wExportc, wVolatile, wRegister, wThreadVar, wNodecl, - wMagic, wHeader, wDeprecated, wCompilerProc, wDynLib, wExtern, - wImportcpp, wImportobjc, wError, wNoInit, wCompileTime, wGlobal, - wGenSym, wInject, wCodegenDecl} + wMagic, wHeader, wDeprecated, wCompilerproc, wDynlib, wExtern, + wImportCpp, wImportObjC, wError, wNoInit, wCompileTime, wGlobal, + wGensym, wInject, wCodegenDecl} constPragmas* = {wImportc, wExportc, wHeader, wDeprecated, wMagic, wNodecl, - wExtern, wImportcpp, wImportobjc, wError, wGenSym, wInject} + wExtern, wImportCpp, wImportObjC, wError, wGensym, wInject} letPragmas* = varPragmas - procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideEffect, + procTypePragmas* = {FirstCallConv..LastCallConv, wVarargs, wNosideeffect, wThread, wRaises, wTags} allRoutinePragmas* = procPragmas + iteratorPragmas + lambdaPragmas @@ -199,7 +199,7 @@ proc processCallConv(c: PContext, n: PNode) = if (n.kind == nkExprColonExpr) and (n.sons[1].kind == nkIdent): var sw = whichKeyword(n.sons[1].ident) case sw - of firstCallConv..lastCallConv: + of FirstCallConv..LastCallConv: POptionEntry(c.optionStack.tail).defaultCC = wordToCallConv(sw) else: localError(n.info, errCallConvExpected) 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 # a calling convention that doesn't introduce custom name mangling # 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 = ccCDecl @@ -284,27 +284,27 @@ proc processOption(c: PContext, n: PNode): bool = else: var sw = whichKeyword(n.sons[0].ident) case sw - of wChecks: onOff(c, n, checksOptions) + of wChecks: onOff(c, n, ChecksOptions) 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 wBoundchecks: onOff(c, n, {optBoundsCheck}) of wOverflowchecks: onOff(c, n, {optOverflowCheck}) of wNilchecks: onOff(c, n, {optNilCheck}) - of wFloatChecks: onOff(c, n, {optNanCheck, optInfCheck}) - of wNaNchecks: onOff(c, n, {optNanCheck}) + of wFloatchecks: onOff(c, n, {optNaNCheck, optInfCheck}) + of wNanChecks: onOff(c, n, {optNaNCheck}) of wInfChecks: onOff(c, n, {optInfCheck}) of wAssertions: onOff(c, n, {optAssert}) of wWarnings: onOff(c, n, {optWarns}) of wHints: onOff(c, n, {optHints}) - of wCallConv: processCallConv(c, n) + of wCallconv: processCallConv(c, n) of wLinedir: onOff(c, n, {optLineDir}) of wStacktrace: onOff(c, n, {optStackTrace}) of wLinetrace: onOff(c, n, {optLineTrace}) of wDebugger: onOff(c, n, {optEndb}) of wProfiler: onOff(c, n, {optProfiler}) of wByRef: onOff(c, n, {optByRef}) - of wDynLib: processDynLib(c, n, nil) + of wDynlib: processDynLib(c, n, nil) of wOptimization: if n.sons[1].kind != nkIdent: invalidPragma(n) @@ -591,23 +591,23 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, noVal(it) incl(sym.flags, sfNoSideEffect) if sym.typ != nil: incl(sym.typ.flags, tfNoSideEffect) - of wSideEffect: + of wSideeffect: noVal(it) incl(sym.flags, sfSideEffect) - of wNoReturn: + of wNoreturn: noVal(it) incl(sym.flags, sfNoReturn) - of wDynLib: + of wDynlib: processDynLib(c, it, sym) - of wCompilerProc: + of wCompilerproc: noVal(it) # compilerproc may not get a string! makeExternExport(sym, "$1") incl(sym.flags, sfCompilerProc) incl(sym.flags, sfUsed) # suppress all those stupid warnings registerCompilerProc(sym) - of wProcvar: + of wProcVar: noVal(it) - incl(sym.flags, sfProcVar) + incl(sym.flags, sfProcvar) of wDeprecated: noVal(it) if sym != nil: incl(sym.flags, sfDeprecated) @@ -638,7 +638,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wThread: noVal(it) incl(sym.flags, sfThread) - incl(sym.flags, sfProcVar) + incl(sym.flags, sfProcvar) if sym.typ != nil: incl(sym.typ.flags, tfThread) of wHint: message(it.info, hintUser, 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 wCompile: processCompile(c, it) of wLink: processCommonLink(c, it, linkNormal) - of wLinkSys: processCommonLink(c, it, linkSys) - of wPassL: extccomp.addLinkOption(expectStrLit(c, it)) - of wPassC: extccomp.addCompileOption(expectStrLit(c, it)) + of wLinksys: processCommonLink(c, it, linkSys) + of wPassl: extccomp.addLinkOption(expectStrLit(c, it)) + of wPassc: extccomp.addCompileOption(expectStrLit(c, it)) of wBreakpoint: pragmaBreakpoint(c, it) - of wWatchpoint: pragmaWatchpoint(c, it) + of wWatchPoint: pragmaWatchpoint(c, it) of wPush: processPush(c, n, i + 1) result = true @@ -679,13 +679,13 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wChecks, wObjChecks, wFieldChecks, wRangechecks, wBoundchecks, wOverflowchecks, wNilchecks, wAssertions, wWarnings, wHints, wLinedir, wStacktrace, wLinetrace, wOptimization, - wCallConv, - wDebugger, wProfiler, wFloatChecks, wNanChecks, wInfChecks, + wCallconv, + wDebugger, wProfiler, wFloatchecks, wNanChecks, wInfChecks, wPatterns: if processOption(c, it): # calling conventions (boring...): localError(it.info, errOptionExpected) - of firstCallConv..lastCallConv: + of FirstCallConv..LastCallConv: assert(sym != nil) if sym.typ == nil: invalidPragma(it) else: sym.typ.callConv = wordToCallConv(k) @@ -713,7 +713,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, noVal(it) if sym.kind != skType or sym.typ == nil: invalidPragma(it) else: incl(sym.typ.flags, tfByCopy) - of wInject, wGenSym: + of wInject, wGensym: # We check for errors, but do nothing with these pragmas otherwise # as they are handled directly in 'evalTemplate'. noVal(it) diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 704857f37..54d47393e 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -149,9 +149,8 @@ proc checkDef(c: PGen; n: PNode) = if {sfImportc, sfExportc} * s.flags == {} or c.checkExtern: checkStyle(n.info, s.name.s, s.kind) -proc checkUse*(n: PNode) = - if n.info.fileIndex < 0 or n.kind != nkSym: return - let s = n.sym +proc checkUse*(n: PNode, s: PSym) = + if n.info.fileIndex < 0: return # we simply convert it to what it looks like in the definition # for consistency @@ -267,7 +266,7 @@ when false: proc check(c: PGen, n: PNode) = case n.kind - of nkSym: checkUse(n) + of nkSym: checkUse(n, n.sym) of nkBlockStmt, nkBlockExpr, nkBlockType: checkDef(c, n[0]) check(c, n.sons[1]) diff --git a/compiler/renderer.nim b/compiler/renderer.nim index 79486da6b..99891df25 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -104,16 +104,16 @@ proc optNL(g: var TSrcGen) = optNL(g, g.indent) proc indentNL(g: var TSrcGen) = - inc(g.indent, indentWidth) + inc(g.indent, IndentWidth) g.pendingNL = g.indent g.lineLen = g.indent proc dedent(g: var TSrcGen) = - dec(g.indent, indentWidth) + dec(g.indent, IndentWidth) assert(g.indent >= 0) - if g.pendingNL > indentWidth: - dec(g.pendingNL, indentWidth) - dec(g.lineLen, indentWidth) + if g.pendingNL > IndentWidth: + dec(g.pendingNL, IndentWidth) + dec(g.lineLen, IndentWidth) proc put(g: var TSrcGen, kind: TTokType, s: string) = addPendingNL(g) @@ -269,7 +269,7 @@ proc gcom(g: var TSrcGen, n: PNode) = if (g.pendingNL < 0) and (len(g.buf) > 0) and (g.lineLen < LineCommentColumn): var ml = maxLineLength(n.comment) - if ml + LineCommentColumn <= maxLineLen: + if ml + LineCommentColumn <= MaxLineLen: put(g, tkSpaces, repeatChar(LineCommentColumn - g.lineLen)) 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 = # computes the length of a tree if isNil(n): return 0 - if n.comment != nil: return maxLineLen + 1 + if n.comment != nil: return MaxLineLen + 1 case n.kind of nkEmpty: result = 0 of nkTripleStrLit: - if containsNL(n.strVal): result = maxLineLen + 1 + if containsNL(n.strVal): result = MaxLineLen + 1 else: result = len(atom(n)) of succ(nkEmpty)..pred(nkTripleStrLit), succ(nkTripleStrLit)..nkNilLit: result = len(atom(n)) @@ -437,7 +437,7 @@ proc lsub(n: PNode): int = result = len("enum") of nkEnumFieldDef: result = lsons(n) + 3 of nkVarSection, nkLetSection: - if sonsLen(n) > 1: result = maxLineLen + 1 + if sonsLen(n) > 1: result = MaxLineLen + 1 else: result = lsons(n) + len("var_") of nkReturnStmt: result = lsub(n.sons[0]) + len("return_") 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 of nkExceptBranch: 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 = - result = x + g.lineLen <= maxLineLen + result = x + g.lineLen <= MaxLineLen type 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): var c = i < sonsLen(n) + theEnd 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 gsub(g, n.sons[i]) if c: @@ -514,21 +514,21 @@ proc gcomma(g: var TSrcGen, n: PNode, c: TContext, start: int = 0, theEnd: int = - 1) = var ind: int if rfInConstExpr in c.flags: - ind = g.indent + indentWidth + ind = g.indent + IndentWidth else: 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) proc gcomma(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) = 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) proc gsemicolon(g: var TSrcGen, n: PNode, start: int = 0, theEnd: int = - 1) = var ind = g.lineLen - if ind > maxLineLen div 2: ind = g.indent + longIndentWid - gcommaAux(g, n, ind, start, theEnd, tkSemicolon) + if ind > MaxLineLen div 2: ind = g.indent + longIndentWid + gcommaAux(g, n, ind, start, theEnd, tkSemiColon) proc gsons(g: var TSrcGen, n: PNode, c: TContext, start: int = 0, theEnd: int = - 1) = @@ -551,7 +551,7 @@ proc longMode(n: PNode, start: int = 0, theEnd: int = - 1): bool = if not result: # check further for i in countup(start, sonsLen(n) + theEnd): - if (lsub(n.sons[i]) > maxLineLen): + if (lsub(n.sons[i]) > MaxLineLen): result = true break @@ -576,7 +576,7 @@ proc gif(g: var TSrcGen, n: PNode) = gsub(g, n.sons[0].sons[0]) initContext(c) 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) gcoms(g) # a good place for comments gstmts(g, n.sons[0].sons[1], c) @@ -591,7 +591,7 @@ proc gwhile(g: var TSrcGen, n: PNode) = gsub(g, n.sons[0]) putWithSpace(g, tkColon, ":") 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) gcoms(g) # a good place for comments gstmts(g, n.sons[1], c) @@ -600,7 +600,7 @@ proc gpattern(g: var TSrcGen, n: PNode) = var c: TContext put(g, tkCurlyLe, "{") 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) gcoms(g) # a good place for comments gstmts(g, n.sons[0], c) @@ -611,7 +611,7 @@ proc gpragmaBlock(g: var TSrcGen, n: PNode) = gsub(g, n.sons[0]) putWithSpace(g, tkColon, ":") 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) gcoms(g) # a good place for comments gstmts(g, n.sons[1], c) @@ -621,7 +621,7 @@ proc gtry(g: var TSrcGen, n: PNode) = put(g, tkTry, "try") putWithSpace(g, tkColon, ":") 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) gcoms(g) # a good place for comments gstmts(g, n.sons[0], c) @@ -634,7 +634,7 @@ proc gfor(g: var TSrcGen, n: PNode) = initContext(c) if longMode(n) or (lsub(n.sons[length - 1]) + lsub(n.sons[length - 2]) + 6 + g.lineLen > - maxLineLen): + MaxLineLen): incl(c.flags, rfLongMode) gcomma(g, n, c, 0, - 3) put(g, tkSpaces, Space) @@ -649,7 +649,7 @@ proc gmacro(g: var TSrcGen, n: PNode) = initContext(c) gsub(g, n.sons[0]) 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) gcoms(g) gsons(g, n, c, 1) @@ -709,7 +709,7 @@ proc gblock(g: var TSrcGen, n: PNode) = else: put(g, tkBlock, "block") 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) gcoms(g) # 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, tkColon, ":") 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) gcoms(g) # a good place for comments gstmts(g, n.sons[0], c) @@ -816,7 +816,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) = put(g, tkParRi, ")") of nkStaticExpr: put(g, tkStatic, "static") - put(g, tkSpaces, space) + put(g, tkSpaces, Space) gsub(g, n.sons[0]) of nkBracketExpr: gsub(g, n.sons[0]) @@ -833,7 +833,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) = gcomma(g, n, 1) of nkCommand: gsub(g, n.sons[0]) - put(g, tkSpaces, space) + put(g, tkSpaces, Space) gcomma(g, n, 1) of nkExprEqExpr, nkAsgn, nkFastAsgn: gsub(g, n.sons[0]) @@ -940,7 +940,7 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) = of nkPrefix: gsub(g, n.sons[0]) if n.len > 1: - put(g, tkSpaces, space) + put(g, tkSpaces, Space) if n.sons[1].kind == nkInfix: put(g, tkParLe, "(") gsub(g, n.sons[1]) diff --git a/compiler/rodread.nim b/compiler/rodread.nim index eba876659..c3083852a 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -696,7 +696,7 @@ proc rrGetType(r: PRodReader, id: int, info: TLineInfo): PType = # load the type: var oldPos = r.pos var d = iiTableGet(r.index.tab, id) - if d == invalidKey: internalError(info, "rrGetType") + if d == InvalidKey: internalError(info, "rrGetType") r.pos = d + r.dataIdx result = decodeType(r, info) r.pos = oldPos @@ -726,7 +726,7 @@ proc findSomeWhere(id: int) = var rd = gMods[i].rd if rd != nil: var d = iiTableGet(rd.index.tab, id) - if d != invalidKey: + if d != InvalidKey: echo "found id ", id, " in ", gMods[i].filename proc getReader(moduleId: int): PRodReader = @@ -744,7 +744,7 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = if result == nil: # load the symbol: var d = iiTableGet(r.index.tab, id) - if d == invalidKey: + if d == InvalidKey: # import from other module: var moduleID = iiTableGet(r.imports.tab, id) if moduleID < 0: @@ -753,7 +753,7 @@ proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = internalError(info, "missing from both indexes: +" & x) var rd = getReader(moduleID) d = iiTableGet(rd.index.tab, id) - if d != invalidKey: + if d != InvalidKey: result = decodeSymSafePos(rd, d, info) else: var x = "" @@ -800,7 +800,7 @@ proc loadMethods(r: PRodReader) = if r.s[r.pos] == ' ': inc(r.pos) proc getCRC*(fileIdx: int32): TCrc32 = - InternalAssert fileIdx >= 0 and fileIdx < gMods.len + internalAssert fileIdx >= 0 and fileIdx < gMods.len if gMods[fileIdx].crcDone: return gMods[fileIdx].crc @@ -875,7 +875,7 @@ proc rawLoadStub(s: PSym) = var rd = gMods[s.position].rd var theId = s.id # used for later check 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()) if rs != s: #echo "rs: ", toHex(cast[int](rs.position), int.sizeof * 2), diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim index be55a5c17..c393ce1da 100644 --- a/compiler/rodwrite.nim +++ b/compiler/rodwrite.nim @@ -101,12 +101,12 @@ proc addInclDep(w: PRodWriter, dep: string) = proc pushType(w: PRodWriter, t: PType) = # 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) proc pushSym(w: PRodWriter, s: PSym) = # 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) proc encodeNode(w: PRodWriter, fInfo: TLineInfo, n: PNode, @@ -336,7 +336,7 @@ proc symStack(w: PRodWriter): int = if sfForward in s.flags: w.sstack[result] = s inc result - elif iiTableGet(w.index.tab, s.id) == invalidKey: + elif iiTableGet(w.index.tab, s.id) == InvalidKey: var m = getModule(s) if m == nil: internalError("symStack: module nil: " & s.name.s) 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 w.methods.len != 0: add(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) when debugWrittenIds: if not Contains(debugWritten, s.id): @@ -383,7 +383,7 @@ proc typeStack(w: PRodWriter): int = if t.kind == tyForward: w.tstack[result] = t inc result - elif iiTableGet(w.index.tab, t.id) == invalidKey: + elif iiTableGet(w.index.tab, t.id) == InvalidKey: var L = w.data.len addToIndex(w.index, t.id, L) encodeType(w, t, w.data) diff --git a/compiler/ropes.nim b/compiler/ropes.nim index f3c0a00e0..2be40524a 100644 --- a/compiler/ropes.nim +++ b/compiler/ropes.nim @@ -157,7 +157,7 @@ proc toRope(s: string): PRope = result = nil else: result = insertInCache(s) - assert(RopeInvariant(result)) + assert(ropeInvariant(result)) proc ropeSeqInsert(rs: var TRopeSeq, r: PRope, at: Natural) = var length = len(rs) @@ -280,7 +280,7 @@ proc ropef(frmt: TFormatStr, args: varargs[PRope]): PRope = else: break if i - 1 >= start: app(result, substr(frmt, start, i - 1)) - assert(RopeInvariant(result)) + assert(ropeInvariant(result)) {.push stack_trace: off, line_trace: off.} proc `~`*(r: expr[string]): PRope = @@ -313,7 +313,7 @@ proc ropeEqualsFile(r: PRope, f: string): bool = result = open(bin, f) if not result: return # not equal if file does not exist - var buf = alloc(BufSize) + var buf = alloc(bufSize) result = auxRopeEqualsFile(r, bin, buf) if result: 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) proc crcFromRope(r: PRope): TCrc32 = - result = newCrcFromRopeAux(r, initCrc32) + result = newCrcFromRopeAux(r, InitCrc32) proc writeRopeIfNotEqual(r: PRope, filename: string): bool = # returns true if overwritten diff --git a/compiler/sem.nim b/compiler/sem.nim index 123a813af..72b06da65 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -134,8 +134,8 @@ proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym = # like newSymS, but considers gensym'ed symbols if n.kind == nkSym: result = n.sym - InternalAssert sfGenSym in result.flags - InternalAssert result.kind == kind + internalAssert sfGenSym in result.flags + internalAssert result.kind == kind else: result = newSym(kind, considerAcc(n), getCurrOwner(), n.info) diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 38ff0f3be..bc4e8cd05 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -139,7 +139,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode, let overloadsState = result.state if overloadsState != csMatch: if nfDelegate in n.flags: - InternalAssert f.kind == nkIdent + internalAssert f.kind == nkIdent let calleeName = newStrNode(nkStrLit, f.ident.s) calleeName.info = n.info diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 15f0f71f0..8f00d91c6 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -198,15 +198,15 @@ proc addToLib(lib: PLib, sym: PSym) = proc makePtrType(c: PContext, baseType: PType): PType = result = newTypeS(tyPtr, c) - addSonSkipIntLit(result, baseType.AssertNotNil) + addSonSkipIntLit(result, baseType.assertNotNil) proc makeVarType(c: PContext, baseType: PType): PType = result = newTypeS(tyVar, c) - addSonSkipIntLit(result, baseType.AssertNotNil) + addSonSkipIntLit(result, baseType.assertNotNil) proc makeTypeDesc*(c: PContext, typ: PType): PType = result = newTypeS(tyTypeDesc, c) - result.addSonSkipIntLit(typ.AssertNotNil) + result.addSonSkipIntLit(typ.assertNotNil) proc makeTypeSymNode*(c: PContext, typ: PType, info: TLineInfo): PNode = let typedesc = makeTypeDesc(c, typ) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 43091aa74..46902e776 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -658,7 +658,7 @@ proc semStaticExpr(c: PContext, n: PNode): PNode = proc semOverloadedCallAnalyseEffects(c: PContext, n: PNode, nOrig: PNode, flags: TExprFlags): PNode = - if flags*{efInTypeOf, efWantIterator} != {}: + if flags*{efInTypeof, efWantIterator} != {}: # consider: 'for x in pReturningArray()' --> we don't want the restriction # to 'skIterator' anymore; skIterator is preferred in sigmatch already for # typeof support. @@ -702,7 +702,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = semOpAux(c, n) var t: PType = 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: # This is a proc variable, apply normal overload resolution var m: TCandidate @@ -964,10 +964,10 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = if f != nil: if fieldVisible(c, f): # 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[1] = newSymNode(f) # we now have the correct field n.typ = f.typ - markUsed(n, f) if check == nil: result = n else: @@ -977,11 +977,11 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = elif ty.kind == tyTuple and ty.n != nil: f = getSymFromList(ty.n, i) if f != nil: + markUsed(n.sons[1], f) n.sons[0] = makeDeref(n.sons[0]) n.sons[1] = newSymNode(f) n.typ = f.typ result = n - markUsed(n, f) proc dotTransformation(c: PContext, n: PNode): PNode = if isSymChoice(n.sons[1]): @@ -1164,7 +1164,7 @@ proc semAsgn(c: PContext, n: PNode): PNode = n.typ = enforceVoidContext if lhs.sym.typ.kind == tyGenericParam: if matchTypeClass(lhs.typ, rhs.typ): - InternalAssert c.p.resultSym != nil + internalAssert c.p.resultSym != nil lhs.typ = rhs.typ c.p.resultSym.typ = rhs.typ c.p.owner.typ.sons[0] = rhs.typ @@ -1356,7 +1356,7 @@ proc semUsing(c: PContext, n: PNode): PNode = of skProcKinds: addDeclAt(c.currentScope, usedSym.sym) continue - else: nil + else: discard localError(e.info, errUsingNoSymbol, e.renderTree) @@ -1372,7 +1372,7 @@ proc semExpandToAst(c: PContext, n: PNode): PNode = macroCall.sons[i] = semExprWithType(c, macroCall[i], {}) # 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 result = n @@ -1409,7 +1409,7 @@ proc processQuotations(n: var PNode, op: string, processQuotations(n.sons[i], op, quotes, ids) 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 # each interpolation. We'll pass this template to getAst. var diff --git a/compiler/seminst.nim b/compiler/seminst.nim index b03f20259..faf0aae11 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -132,7 +132,7 @@ proc sideEffectsCheck(c: PContext, s: PSym) = c.threadEntries.add(s) proc lateInstantiateGeneric(c: PContext, invocation: PType, info: TLineInfo): PType = - InternalAssert invocation.kind == tyGenericInvokation + internalAssert invocation.kind == tyGenericInvokation let cacheHit = searchInstTypes(invocation) if cacheHit != nil: diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim index e6c5fc574..9a2645f7e 100644 --- a/compiler/semmagic.nim +++ b/compiler/semmagic.nim @@ -26,7 +26,7 @@ proc semInstantiationInfo(c: PContext, n: PNode): PNode = let useFullPaths = expectIntLit(c, n.sons[2]) let info = getInfoContext(idx) 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)) line.intVal = toLinenumber(info) result.add(filename) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index efab8ddb6..c9d5036d8 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -305,7 +305,7 @@ proc notNilCheck(tracked: PEffects, n: PNode, paramType: PType) = if n.kind == nkAddr: # addr(x[]) can't be proven, but addr(x) can: 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: return 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) = let op = n.typ 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] let s = n.skipConv 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) = var effects = t.n.sons[0] - InternalAssert t.kind == tyProc and effects.kind == nkEffectList + internalAssert t.kind == tyProc and effects.kind == nkEffectList let raisesSpec = effectSpec(n, wRaises) tagsSpec = effectSpec(n, wTags) if not isNil(raisesSpec) or not isNil(tagsSpec): - InternalAssert effects.len == 0 + internalAssert effects.len == 0 newSeq(effects.sons, effectListLen) if not isNil(raisesSpec): effects.sons[exceptionEffects] = raisesSpec @@ -583,7 +583,7 @@ proc setEffectsForProcType*(t: PType, n: PNode) = proc trackProc*(s: PSym, body: PNode) = var effects = s.typ.n.sons[0] - InternalAssert effects.kind == nkEffectList + internalAssert effects.kind == nkEffectList # effects already computed? if sfForward in s.flags: return if effects.len == effectListLen: return diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index c89fb46a2..137f409b2 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -70,7 +70,7 @@ proc toCover(t: PType): BiggestInt = proc performProcvarCheck(c: PContext, n: PNode, s: PSym) = 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: localError(n.info, errXCannotBePassedToProcVar, s.name.s) @@ -788,8 +788,8 @@ proc typeSectionFinalPass(c: PContext, n: PNode) = # give anonymous object a dummy symbol: var st = s.typ if st.kind == tyGenericBody: st = st.lastSon - InternalAssert st.kind in {tyPtr, tyRef} - InternalAssert st.sons[0].sym == nil + internalAssert st.kind in {tyPtr, tyRef} + internalAssert st.sons[0].sym == nil st.sons[0].sym = newSym(skType, getIdent(s.name.s & ":ObjectType"), getCurrOwner(), s.info) @@ -887,7 +887,7 @@ proc semLambda(c: PContext, n: PNode, flags: TExprFlags): PNode = illFormedAst(n) # process parameters: if n.sons[paramsPos].kind != nkEmpty: var gp = newNodeI(nkGenericParams, n.info) - semParamList(c, n.sons[ParamsPos], gp, s) + semParamList(c, n.sons[paramsPos], gp, s) paramsTypeCheck(c, s.typ) else: s.typ = newTypeS(tyProc, c) @@ -939,7 +939,7 @@ type stepCompileBody proc isForwardDecl(s: PSym): bool = - InternalAssert s.kind == skProc + internalAssert s.kind == skProc result = s.ast[bodyPos].kind != nkEmpty 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) # process parameters: 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 n.sons[genericParamsPos].kind == nkEmpty: # we have a list of implicit type parameters: diff --git a/compiler/semtempl.nim b/compiler/semtempl.nim index f6c841e60..da38f8625 100644 --- a/compiler/semtempl.nim +++ b/compiler/semtempl.nim @@ -36,7 +36,7 @@ proc symBinding(n: PNode): TSymBinding = var key = if it.kind == nkExprColonExpr: it.sons[0] else: it if key.kind == nkIdent: case whichKeyword(key.ident) - of wGenSym: return spGenSym + of wGensym: return spGenSym of wInject: return spInject else: nil @@ -435,7 +435,7 @@ proc semTemplateDef(c: PContext, n: PNode): PNode = gp = newNodeI(nkGenericParams, n.info) # process parameters: 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 n.sons[genericParamsPos].kind == nkEmpty: # we have a list of implicit type parameters: diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 91bbb467e..69649a58c 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -50,13 +50,13 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType = of tyTuple: if sonsLen(v) == 2: 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 else: localError(strVal.info, errStringLiteralExpected) else: localError(v.info, errWrongNumberOfVariables) - of tyString, tyCstring: + of tyString, tyCString: strVal = v x = counter else: @@ -148,7 +148,7 @@ proc semDistinct(c: PContext, n: PNode, prev: PType): PType = result = newConstraint(c, tyDistinct) proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = - assert IsRange(n) + assert isRange(n) checkSonsLen(n, 3) result = newOrPrevType(tyRange, prev, c) 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) elif e.kind == nkSym and e.typ.kind == tyExpr: 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): localError(n[1].info, errOrdinalTypeExpected) 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 skLet: pragma(c, result, n.sons[1], letPragmas) of skConst: pragma(c, result, n.sons[1], constPragmas) - else: nil + else: discard else: result = semIdentVis(c, kind, n, allowed) @@ -970,7 +970,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = result = newOrPrevType(tyError, prev, c) elif s.kind == skParam and s.typ.kind == tyTypeDesc: assert s.typ.len > 0 - InternalAssert prev == nil + internalAssert prev == nil result = s.typ.sons[0] elif prev == nil: result = s.typ diff --git a/compiler/semtypinst.nim b/compiler/semtypinst.nim index 2afdeb5ae..6940af7b7 100644 --- a/compiler/semtypinst.nim +++ b/compiler/semtypinst.nim @@ -33,7 +33,7 @@ proc checkConstructedType*(info: TLineInfo, typ: PType) = proc searchInstTypes*(key: PType): PType = let genericTyp = key.sons[0] - InternalAssert genericTyp.kind == tyGenericBody and + internalAssert genericTyp.kind == tyGenericBody and key.sons[0] == genericTyp and genericTyp.sym != nil diff --git a/compiler/service.nim b/compiler/service.nim index 209ccd8e3..42c4aa9f4 100644 --- a/compiler/service.nim +++ b/compiler/service.nim @@ -36,7 +36,7 @@ proc processCmdLine*(pass: TCmdLinePass, cmd: string) = parseopt.next(p) case p.kind of cmdEnd: break - of cmdLongOption, cmdShortOption: + of cmdLongoption, cmdShortOption: # hint[X]:off is parsed as (p.key = "hint[X]", p.val = "off") # we fix this here var bracketLe = strutils.find(p.key, '[') diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 7a30dadc8..3b1f3e715 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -86,7 +86,7 @@ proc initCandidate*(c: var TCandidate, callee: PSym, binding: PNode, c.calleeScope = calleeScope initIdTable(c.bindings) c.errors = nil - if binding != nil and callee.kind in RoutineKinds: + if binding != nil and callee.kind in routineKinds: var typeParams = callee.ast[genericParamsPos] for i in 1..min(sonsLen(typeParams), sonsLen(binding)-1): 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: result = isGeneric else: - InternalAssert a.sons != nil and a.sons.len > 0 + internalAssert a.sons != nil and a.sons.len > 0 c.typedescMatched = true result = typeRel(c, f.sons[0], a.sons[0]) else: @@ -752,7 +752,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = else: result = isNone else: - InternalAssert prev.sonsLen == 1 + internalAssert prev.sonsLen == 1 let toMatch = if tfUnresolved in f.flags: a else: a.sons[0] 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) call.add(f.n.copyTree) call.add(arg.copyTree) - result = c.semOverloadedCall(c, call, call, RoutineKinds) + result = c.semOverloadedCall(c, call, call, routineKinds) if result != nil: # resulting type must be consistent with the other arguments: var r = typeRel(m, f.sons[0], result.typ) @@ -867,7 +867,7 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate, dummyName = param dummyType = a - InternalAssert dummyName.kind == nkIdent + internalAssert dummyName.kind == nkIdent var dummyParam = newSym(skType, dummyName.ident, f.sym, f.sym.info) dummyParam.typ = dummyType addDecl(c, dummyParam) @@ -904,7 +904,7 @@ proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, r = isGeneric else: if a.kind == tyExpr: - InternalAssert a.len > 0 + internalAssert a.len > 0 r = typeRel(m, f.lastSon, a.lastSon) else: let match = matchTypeClass(m.bindings, fMaybeExpr, a) @@ -1156,7 +1156,7 @@ proc matchesAux(c: PContext, n, nOrig: PNode, # unnamed param if f >= formalLen: # too many arguments? - if tfVarArgs in m.callee.flags: + if tfVarargs in m.callee.flags: # is ok... but don't increment any counters... # we have no formal here to snoop at: n.sons[a] = prepareOperand(c, n.sons[a]) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index 7e0a28afb..c88687f2c 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -203,7 +203,7 @@ const CallNodes = {nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit} 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 else: for i in 0.. 0 or n.sons[0].kind != nkEmpty: - result = n.ptransNode + result = n.PTransNode else: let labl = c.breakSyms[c.breakSyms.high] result = transformSons(c, n) @@ -292,11 +292,11 @@ proc transformYield(c: PTransf, n: PNode): PTransNode = add(result, c.transCon.forLoopBody) else: # 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 = result = transformSons(c, n) - var n = result.pnode + var n = result.PNode case n.sons[0].kind of nkObjUpConv, nkObjDownConv, nkChckRange, nkChckRangeF, nkChckRange64: 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 call.sons[0].typ.callConv == ccClosure or call.sons[0].sym.kind != skIterator: - n.sons[length-1] = transformLoopBody(c, n.sons[length-1]).pnode - return lambdalifting.liftForLoop(n).ptransNode + n.sons[length-1] = transformLoopBody(c, n.sons[length-1]).PNode + return lambdalifting.liftForLoop(n).PTransNode #InternalError(call.info, "transformFor") #echo "transforming: ", renderTree(n) @@ -446,7 +446,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode = var v = newNodeI(nkVarSection, n.info) for i in countup(0, length - 3): 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 # iterator! @@ -458,7 +458,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode = # generate access statements for the parameters (unless they are constant) pushTransCon(c, newC) 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 case putArgInto(arg, formal.typ) of paDirectMapping: @@ -467,7 +467,7 @@ proc transformFor(c: PTransf, n: PNode): PTransNode = # generate a temporary and produce an assignment statement: var temp = newTemp(c, formal.typ, formal.info) 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)) of paVarAsgn: assert(skipTypes(formal.typ, abstractInst).kind == tyVar) @@ -500,19 +500,19 @@ proc transformCase(c: PTransf, n: PNode): PTransNode = var e = transform(c, it) case it.kind of nkElifBranch: - if ifs.pnode == nil: + if ifs.PNode == nil: ifs = newTransNode(nkIfStmt, it.info, 0) ifs.add(e) of nkElse: - if ifs.pnode == nil: result.add(e) + if ifs.PNode == nil: result.add(e) else: ifs.add(e) else: result.add(e) - if ifs.pnode != nil: + if ifs.PNode != nil: var elseBranch = newTransNode(nkElse, n.info, 1) elseBranch[0] = ifs 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 {tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32}): # 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 = # 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: - result = n.ptransnode + result = n.PTransNode else: result = newTransNode(n) for i in 0 .. < n.len: @@ -563,24 +563,24 @@ proc transformCall(c: PTransf, n: PNode): PTransNode = add(result, transform(c, n.sons[0])) var j = 1 while j < sonsLen(n): - var a = transform(c, n.sons[j]).pnode + var a = transform(c, n.sons[j]).PNode inc(j) if isConstExpr(a): 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 a = evalOp(op.magic, n, a, b, nil) inc(j) - add(result, a.ptransnode) + add(result, a.PTransNode) if len(result) == 2: result = result[1] else: - let s = transformSons(c, n).pnode + let s = transformSons(c, n).PNode # bugfix: check after 'transformSons' if it's still a method call: # use the dispatcher for the call: if s.sons[0].kind == nkSym and s.sons[0].sym.kind == skMethod: - result = methodCall(s).ptransNode + result = methodCall(s).PTransNode else: - result = s.ptransNode + result = s.PTransNode proc dontInlineConstant(orig, cnst: PNode): bool {.inline.} = # symbols that expand to a complex constant (array, etc.) should not be @@ -683,7 +683,7 @@ proc transform(c: PTransf, n: PNode): PTransNode = # completely: result = PTransNode(newNode(nkCommentStmt)) of nkCommentStmt, nkTemplateDef: - return n.ptransNode + return n.PTransNode of nkConstSection: # do not replace ``const c = 3`` with ``const 3 = 3`` return transformConstSection(c, n) @@ -707,7 +707,7 @@ proc transform(c: PTransf, n: PNode): PTransNode = result = transformSons(c, n) # XXX comment handling really sucks: if importantComments(): - pnode(result).comment = n.comment + PNode(result).comment = n.comment else: result = transformSons(c, n) var cnst = getConstExpr(c.module, PNode(result)) diff --git a/compiler/treetab.nim b/compiler/treetab.nim index cccb1096a..ecb8fb083 100644 --- a/compiler/treetab.nim +++ b/compiler/treetab.nim @@ -83,7 +83,7 @@ proc nodeTablePut*(t: var TNodeTable, key: PNode, val: int) = t.data[index].val = val else: 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)): if t.data[i].key != nil: 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 else: 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)): if t.data[i].key != nil: nodeTableRawInsert(n, t.data[i].h, t.data[i].key, t.data[i].val) diff --git a/compiler/types.nim b/compiler/types.nim index 5870ccacd..a921c59ba 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -97,7 +97,7 @@ proc isPureObject(typ: PType): bool = while t.kind == tyObject and t.sons[0] != nil: t = t.sons[0] result = t.sym != nil and sfPure in t.sym.flags -proc getOrdValue(n: PNode): biggestInt = +proc getOrdValue(n: PNode): BiggestInt = case n.kind of nkCharLit..nkInt64Lit: result = n.intVal of nkNilLit: result = 0 @@ -526,7 +526,7 @@ proc resultType(t: PType): PType = proc base(t: PType): PType = result = t.sons[0] -proc firstOrd(t: PType): biggestInt = +proc firstOrd(t: PType): BiggestInt = case t.kind of tyBool, tyChar, tySequence, tyOpenArray, tyString, tyVarargs, tyProxy: result = 0 @@ -557,7 +557,7 @@ proc firstOrd(t: PType): biggestInt = internalError("invalid kind for first(" & $t.kind & ')') result = 0 -proc lastOrd(t: PType): biggestInt = +proc lastOrd(t: PType): BiggestInt = case t.kind of tyBool: result = 1 of tyChar: result = 255 @@ -591,7 +591,7 @@ proc lastOrd(t: PType): biggestInt = internalError("invalid kind for last(" & $t.kind & ')') result = 0 -proc lengthOrd(t: PType): biggestInt = +proc lengthOrd(t: PType): BiggestInt = case t.kind of tyInt64, tyInt32, tyInt: result = lastOrd(t) of tyDistinct, tyConst, tyMutable: result = lengthOrd(t.sons[0]) @@ -732,7 +732,7 @@ proc sameTuple(a, b: PType, c: var TSameTypeClosure): bool = result = false 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: result = a.id == b.id else: @@ -835,7 +835,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = result = exprStructuralEquivalent(a.n, b.n) and sameFlags(a, b) of tyObject: ifFastObjectTypeCheckFailed(a, b): - CycleCheck() + cycleCheck() result = sameObjectStructures(a, b, c) and sameFlags(a, b) of tyDistinct: cycleCheck() @@ -1133,7 +1133,7 @@ proc computeRecSizeAux(n: PNode, a, currOffset: var BiggestInt): BiggestInt = a = 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 if typ.size == - 2: # 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! if length + 1 < `shl`(1, 8): result = 1 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 a = result of tySet: @@ -1235,7 +1235,7 @@ proc computeSizeAux(typ: PType, a: var biggestInt): biggestInt = typ.size = result typ.align = int(a) -proc computeSize(typ: PType): biggestInt = +proc computeSize(typ: PType): BiggestInt = var a: BiggestInt = 1 result = computeSizeAux(typ, a) @@ -1244,7 +1244,7 @@ proc getReturnType*(s: PSym): PType = assert s.kind in {skProc, skTemplate, skMacro, skIterator} result = s.typ.sons[0] -proc getSize(typ: PType): biggestInt = +proc getSize(typ: PType): BiggestInt = result = computeSize(typ) if result < 0: internalError("getSize: " & $typ.kind) @@ -1289,8 +1289,8 @@ proc compatibleEffectsAux(se, re: PNode): bool = proc compatibleEffects*(formal, actual: PType): bool = # for proc type compatibility checking: assert formal.kind == tyProc and actual.kind == tyProc - InternalAssert formal.n.sons[0].kind == nkEffectList - InternalAssert actual.n.sons[0].kind == nkEffectList + internalAssert formal.n.sons[0].kind == nkEffectList + internalAssert actual.n.sons[0].kind == nkEffectList var spec = formal.n.sons[0] if spec.len != 0: @@ -1315,7 +1315,7 @@ proc compatibleEffects*(formal, actual: PType): bool = result = true proc isCompileTimeOnly*(t: PType): bool {.inline.} = - result = t.kind in {tyTypedesc, tyExpr} + result = t.kind in {tyTypeDesc, tyExpr} proc containsCompileTimeOnly*(t: PType): bool = if isCompileTimeOnly(t): return true diff --git a/compiler/vm.nim b/compiler/vm.nim index 3d76638bc..215b3486e 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -579,7 +579,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = of opcMinusSet: decodeBC(nkCurly) move(regs[ra].sons, nimsets.diffSets(regs[rb], regs[rc]).sons) - of opcSymDiffSet: + of opcSymdiffSet: decodeBC(nkCurly) move(regs[ra].sons, nimsets.symdiffSets(regs[rb], regs[rc]).sons) of opcConcatStr: @@ -982,7 +982,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): PNode = of opcNSetType: decodeB(nkMetaNode) 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 of opcNSetStrVal: decodeB(nkMetaNode) diff --git a/compiler/vmdef.nim b/compiler/vmdef.nim index b4b787798..480c7f31b 100644 --- a/compiler/vmdef.nim +++ b/compiler/vmdef.nim @@ -198,7 +198,7 @@ proc refresh*(c: PCtx, module: PSym) = const firstABxInstr* = opcTJmp largeInstrs* = { # instructions which use 2 int32s instead of 1: - opcSubstr, opcConv, opcCast, opcNewSeq, opcOf} + opcSubStr, opcConv, opcCast, opcNewSeq, opcOf} slotSomeTemp* = slotTempUnknown relativeJumps* = {opcTJmp, opcFJmp, opcJmp} diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index f686f10c2..563dbc6d1 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -85,7 +85,7 @@ proc genLabel(c: PCtx): TPosition = proc jmpBack(c: PCtx, n: PNode, opc: TOpcode, p = TPosition(0)) = 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) proc patch(c: PCtx, p: TPosition) = @@ -93,7 +93,7 @@ proc patch(c: PCtx, p: TPosition) = let p = p.int let diff = c.code.len - p #c.jumpTargets.incl(c.code.len) - InternalAssert(-0x7fff < diff and diff < 0x7fff) + internalAssert(-0x7fff < diff and diff < 0x7fff) let oldInstr = c.code[p] # opcode and regA stay the same: 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) = var d: TDest = dest gen(c, n, d) - InternalAssert d == dest + internalAssert d == dest proc gen(c: PCtx; n: PNode) = 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 = result = c.constants.len c.constants.add n - InternalAssert result < 0x7fff + internalAssert result < 0x7fff proc sameConstant*(a, b: PNode): bool = result = false @@ -678,8 +678,8 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = tmp2 = c.genx(n.sons[2]) tmp3 = c.getTemp(n.sons[2].typ) c.gABC(n, opcLenStr, tmp3, tmp1) - c.gABC(n, opcSubstr, dest, tmp1, tmp2) - c.gABC(n, opcSubstr, tmp3) + c.gABC(n, opcSubStr, dest, tmp1, tmp2) + c.gABC(n, opcSubStr, tmp3) c.freeTemp(tmp1) c.freeTemp(tmp2) c.freeTemp(tmp3) @@ -689,8 +689,8 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = tmp1 = c.genx(n.sons[1]) tmp2 = c.genx(n.sons[2]) tmp3 = c.genx(n.sons[3]) - c.gABC(n, opcSubstr, dest, tmp1, tmp2) - c.gABC(n, opcSubstr, tmp3) + c.gABC(n, opcSubStr, dest, tmp1, tmp2) + c.gABC(n, opcSubStr, tmp3) c.freeTemp(tmp1) c.freeTemp(tmp2) c.freeTemp(tmp3) @@ -922,7 +922,7 @@ proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) = gen(c, ri, tmp) c.gABx(le, whichAsgnOpc(le, opcWrGlobal), tmp, s.position) else: - InternalAssert s.position > 0 or (s.position == 0 and + internalAssert s.position > 0 or (s.position == 0 and s.kind in {skParam, skResult}) var dest: TRegister = s.position + ord(s.kind == skParam) 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)) c.gABx(n, opcLdConst, dest, lit) of skField: - InternalAssert dest < 0 + internalAssert dest < 0 if s.position > high(dest): internalError(n.info, "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) proc finalJumpTarget(c: PCtx; pc, diff: int) = - InternalAssert(-0x7fff < diff and diff < 0x7fff) + internalAssert(-0x7fff < diff and diff < 0x7fff) let oldInstr = c.code[pc] # opcode and regA stay the same: c.code[pc] = ((oldInstr.uint32 and 0xffff'u32).uint32 or diff --git a/koch.nim b/koch.nim index f09dcb044..2dac27fbf 100644 --- a/koch.nim +++ b/koch.nim @@ -115,7 +115,7 @@ proc findStartNimrod: string = if existsFile(dir / nimrod): return nimrod when defined(Posix): const buildScript = "build.sh" - if ExistsFile(buildScript): + if existsFile(buildScript): if tryExec("./" & buildScript): return "bin" / nimrod else: const buildScript = "build.bat" @@ -183,7 +183,7 @@ proc cleanAux(dir: string) = else: nil proc removePattern(pattern: string) = - for f in WalkFiles(pattern): + for f in walkFiles(pattern): echo "removing: ", f removeFile(f) diff --git a/lib/packages/docutils/highlite.nim b/lib/packages/docutils/highlite.nim index 737780a12..b41a37309 100644 --- a/lib/packages/docutils/highlite.nim +++ b/lib/packages/docutils/highlite.nim @@ -428,7 +428,7 @@ proc clikeNextToken(g: var TGeneralTokenizer, keywords: openArray[string], g.kind = gtOperator of 'a'..'z', 'A'..'Z', '_', '\x80'..'\xFF': var id = "" - while g.buf[pos] in SymChars: + while g.buf[pos] in symChars: add(id, g.buf[pos]) inc(pos) if isKeyword(keywords, id) >= 0: g.kind = gtKeyword diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim index 316476ce0..e6ffadcbd 100644 --- a/lib/packages/docutils/rst.nim +++ b/lib/packages/docutils/rst.nim @@ -58,10 +58,10 @@ const mwUnsupportedLanguage: "language '$1' not supported" ] -proc rstnodeToRefname*(n: PRSTNode): string -proc addNodes*(n: PRSTNode): string -proc getFieldValue*(n: PRSTNode, fieldname: string): string -proc getArgument*(n: PRSTNode): string +proc rstnodeToRefname*(n: PRstNode): string +proc addNodes*(n: PRstNode): string +proc getFieldValue*(n: PRstNode, fieldname: string): string +proc getArgument*(n: PRstNode): string # ----------------------------- scanner part -------------------------------- @@ -130,7 +130,7 @@ proc getThing(L: var TLexer, tok: var TToken, s: TCharSet) = tok.line = L.line tok.col = L.col var pos = L.bufpos - while True: + while true: add(tok.symbol, L.buf[pos]) inc(pos) if L.buf[pos] notin s: break @@ -143,7 +143,7 @@ proc getAdornment(L: var TLexer, tok: var TToken) = tok.col = L.col var pos = L.bufpos var c = L.buf[pos] - while True: + while true: add(tok.symbol, L.buf[pos]) inc(pos) if L.buf[pos] != c: break @@ -162,7 +162,7 @@ proc getIndentAux(L: var TLexer, start: int): int = if L.skipPounds: if buf[pos] == '#': inc(pos) if buf[pos] == '#': inc(pos) - while True: + while true: case buf[pos] of ' ', '\x0B', '\x0C': inc(pos) @@ -251,10 +251,10 @@ proc getTokens(buffer: string, skipPounds: bool, tokens: var TTokenSeq): int = tokens[0].kind = tkIndent type - TLevelMap = array[Char, int] + TLevelMap = array[char, int] TSubstitution{.final.} = object key*: string - value*: PRSTNode + value*: PRstNode TSharedState {.final.} = object options: TRstParseOptions # parsing options @@ -351,7 +351,7 @@ proc initParser(p: var TRstParser, sharedState: PSharedState) = p.line = 1 p.s = sharedState -proc addNodesAux(n: PRSTNode, result: var string) = +proc addNodesAux(n: PRstNode, result: var string) = if n.kind == rnLeaf: add(result, n.text) else: @@ -361,7 +361,7 @@ proc addNodes(n: PRstNode): string = 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: for i in countup(0, len(n.text) - 1): case n.text[i] @@ -391,7 +391,7 @@ proc rstnodeToRefname(n: PRstNode): string = var b = false rstnodeToRefnameAux(n, result, b) -proc findSub(p: var TRstParser, n: PRSTNode): int = +proc findSub(p: var TRstParser, n: PRstNode): int = var key = addNodes(n) # the spec says: if no exact match, try one without case distinction: for i in countup(0, high(p.s.subs)): @@ -402,7 +402,7 @@ proc findSub(p: var TRstParser, n: PRSTNode): int = return i 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) for i in countup(0, length - 1): 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].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) for i in countup(0, length - 1): 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].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)): if key == p.s.refs[i].key: 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) -proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode = +proc getReferenceName(p: var TRstParser, endStr: string): PRstNode = var res = newRstNode(rnInner) while true: case p.tok[p.idx].kind @@ -451,7 +451,7 @@ proc getReferenceName(p: var TRstParser, endStr: string): PRSTNode = inc(p.idx) result = res -proc untilEol(p: var TRstParser): PRSTNode = +proc untilEol(p: var TRstParser): PRstNode = result = newRstNode(rnInner) while not (p.tok[p.idx].kind in {tkIndent, tkEof}): add(result, newLeaf(p)) @@ -550,7 +550,7 @@ proc match(p: TRstParser, start: int, expr: string): bool = inc(i) result = true -proc fixupEmbeddedRef(n, a, b: PRSTNode) = +proc fixupEmbeddedRef(n, a, b: PRstNode) = var sep = - 1 for i in countdown(len(n) - 2, 0): 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(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 if isInlineMarkupEnd(p, "_"): inc(p.idx) @@ -613,7 +613,7 @@ proc matchVerbatim(p: TRstParser, start: int, expr: string): int = inc result 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 for key, val in items(Smilies): let m = matchVerbatim(p, p.idx, key) @@ -629,14 +629,14 @@ when false: '$', '(', ')', '~', '_', '?', '+', '-', '=', '\\', '.', '&', '\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 (p.tok[i+3].kind == tkWord) and (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 isURL(p, p.idx): + if isUrl(p, p.idx): var n = newRstNode(rnStandaloneHyperlink) while true: 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) add(father, n) -proc parseBackslash(p: var TRstParser, father: PRSTNode) = +proc parseBackslash(p: var TRstParser, father: PRstNode) = assert(p.tok[p.idx].kind == tkPunct) if p.tok[p.idx].symbol == "\\\\": add(father, newRstNode(rnLeaf, "\\")) @@ -692,7 +692,7 @@ when false: if p.tok[p.idx].symbol == "_": n = parsePostfix(p, n) add(father, n) -proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string, +proc parseUntil(p: var TRstParser, father: PRstNode, postfix: string, interpretBackslash: bool) = let line = p.tok[p.idx].line @@ -723,7 +723,7 @@ proc parseUntil(p: var TRstParser, father: PRSTNode, postfix: string, inc(p.idx) else: rstMessage(p, meExpected, postfix, line, col) -proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode = +proc parseMarkdownCodeblock(p: var TRstParser): PRstNode = var args = newRstNode(rnDirArg) if p.tok[p.idx].kind == tkWord: add(args, newLeaf(p)) @@ -753,7 +753,7 @@ proc parseMarkdownCodeblock(p: var TRstParser): PRSTNode = add(result, nil) add(result, lb) -proc parseInline(p: var TRstParser, father: PRSTNode) = +proc parseInline(p: var TRstParser, father: PRstNode) = case p.tok[p.idx].kind of tkPunct: if isInlineMarkupStart(p, "***"): @@ -797,7 +797,7 @@ proc parseInline(p: var TRstParser, father: PRSTNode) = if n != nil: add(father, n) return - parseURL(p, father) + parseUrl(p, father) of tkAdornment, tkOther, tkWhite: if roSupportSmilies in p.s.options: let n = parseSmiley(p) @@ -828,21 +828,21 @@ proc getDirective(p: var TRstParser): string = else: result = "" -proc parseComment(p: var TRstParser): PRSTNode = +proc parseComment(p: var TRstParser): PRstNode = case p.tok[p.idx].kind of tkIndent, tkEof: if p.tok[p.idx].kind != tkEof and p.tok[p.idx + 1].kind == tkIndent: inc(p.idx) # empty comment else: var indent = p.tok[p.idx].ival - while True: + while true: case p.tok[p.idx].kind of tkEof: break of tkIndent: if (p.tok[p.idx].ival < indent): break else: - nil + discard inc(p.idx) else: 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) else: result = dkNone -proc parseLine(p: var TRstParser, father: PRSTNode) = - while True: +proc parseLine(p: var TRstParser, father: PRstNode) = + while true: case p.tok[p.idx].kind of tkWhite, tkWord, tkOther, tkPunct: parseInline(p, father) else: break -proc parseUntilNewline(p: var TRstParser, father: PRSTNode) = - while True: +proc parseUntilNewline(p: var TRstParser, father: PRstNode) = + while true: case p.tok[p.idx].kind of tkWhite, tkWord, tkAdornment, tkOther, tkPunct: parseInline(p, father) of tkEof, tkIndent: break -proc parseSection(p: var TRstParser, result: PRSTNode) -proc parseField(p: var TRstParser): PRSTNode = +proc parseSection(p: var TRstParser, result: PRstNode) +proc parseField(p: var TRstParser): PRstNode = result = newRstNode(rnField) var col = p.tok[p.idx].col - var fieldname = newRstNode(rnFieldname) + var fieldname = newRstNode(rnFieldName) 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: var indent = p.tok[p.idx].ival @@ -892,7 +892,7 @@ proc parseField(p: var TRstParser): PRSTNode = add(result, fieldname) add(result, fieldbody) -proc parseFields(p: var TRstParser): PRSTNode = +proc parseFields(p: var TRstParser): PRstNode = result = nil 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 @@ -926,14 +926,14 @@ proc getArgument(n: PRstNode): string = if n.sons[0] == nil: result = "" else: result = addNodes(n.sons[0]) -proc parseDotDot(p: var TRstParser): PRSTNode -proc parseLiteralBlock(p: var TRstParser): PRSTNode = +proc parseDotDot(p: var TRstParser): PRstNode +proc parseLiteralBlock(p: var TRstParser): PRstNode = result = newRstNode(rnLiteralBlock) var n = newRstNode(rnLeaf, "") if p.tok[p.idx].kind == tkIndent: var indent = p.tok[p.idx].ival inc(p.idx) - while True: + while true: case p.tok[p.idx].kind of tkEof: break @@ -1032,7 +1032,7 @@ proc whichSection(p: TRstParser): TRstNodeKind = else: result = rnParagraph else: result = rnLeaf -proc parseLineBlock(p: var TRstParser): PRSTNode = +proc parseLineBlock(p: var TRstParser): PRstNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var col = p.tok[p.idx].col @@ -1051,8 +1051,8 @@ proc parseLineBlock(p: var TRstParser): PRSTNode = break popInd(p) -proc parseParagraph(p: var TRstParser, result: PRSTNode) = - while True: +proc parseParagraph(p: var TRstParser, result: PRstNode) = + while true: case p.tok[p.idx].kind of tkIndent: if p.tok[p.idx + 1].kind == tkIndent: @@ -1082,7 +1082,7 @@ proc parseParagraph(p: var TRstParser, result: PRSTNode) = parseInline(p, result) else: break -proc parseHeadline(p: var TRstParser): PRSTNode = +proc parseHeadline(p: var TRstParser): PRstNode = result = newRstNode(rnHeadline) parseUntilNewline(p, result) assert(p.tok[p.idx].kind == tkIndent) @@ -1112,16 +1112,16 @@ proc getColumns(p: var TRstParser, cols: var TIntSeq) = # last column has no limit: 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 cols: TIntSeq row: seq[string] i, last, line: int c: char q: TRstParser - a, b: PRSTNode + a, b: PRstNode result = newRstNode(rnTable) cols = @[] row = @[] @@ -1167,13 +1167,13 @@ proc parseSimpleTable(p: var TRstParser): PRSTNode = add(a, b) add(result, a) -proc parseTransition(p: var TRstParser): PRSTNode = +proc parseTransition(p: var TRstParser): PRstNode = result = newRstNode(rnTransition) 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] inc(p.idx, 2) result = newRstNode(rnOverline) @@ -1192,7 +1192,7 @@ proc parseOverline(p: var TRstParser): PRSTNode = inc(p.idx) # XXX: check? if p.tok[p.idx].kind == tkIndent: inc(p.idx) -proc parseBulletList(p: var TRstParser): PRSTNode = +proc parseBulletList(p: var TRstParser): PRstNode = result = nil if p.tok[p.idx + 1].kind == tkWhite: var bullet = p.tok[p.idx].symbol @@ -1212,7 +1212,7 @@ proc parseBulletList(p: var TRstParser): PRSTNode = break popInd(p) -proc parseOptionList(p: var TRstParser): PRSTNode = +proc parseOptionList(p: var TRstParser): PRstNode = result = newRstNode(rnOptionList) while true: if isOptionList(p): @@ -1241,7 +1241,7 @@ proc parseOptionList(p: var TRstParser): PRSTNode = else: break -proc parseDefinitionList(p: var TRstParser): PRSTNode = +proc parseDefinitionList(p: var TRstParser): PRstNode = result = nil var j = tokenAfterNewline(p) - 1 if (j >= 1) and (p.tok[j].kind == tkIndent) and @@ -1272,12 +1272,12 @@ proc parseDefinitionList(p: var TRstParser): PRSTNode = j = tokenAfterNewline(p) - 1 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: - nil + discard else: break if len(result) == 0: result = nil -proc parseEnumList(p: var TRstParser): PRSTNode = +proc parseEnumList(p: var TRstParser): PRstNode = const wildcards: array[0..2, string] = ["(e) ", "e) ", "e. "] wildpos: array[0..2, int] = [1, 0, 0] @@ -1307,7 +1307,7 @@ proc parseEnumList(p: var TRstParser): PRSTNode = dec(p.idx, wildpos[w] + 3) result = nil -proc sonKind(father: PRSTNode, i: int): TRstNodeKind = +proc sonKind(father: PRstNode, i: int): TRstNodeKind = result = rnLeaf if i < len(father): result = father.sons[i].kind @@ -1328,14 +1328,14 @@ proc parseSection(p: var TRstParser, result: PRstNode) = leave = true break if leave or p.tok[p.idx].kind == tkEof: break - var a: PRSTNode = nil + var a: PRstNode = nil var k = whichSection(p) case k of rnLiteralBlock: inc(p.idx) # skip '::' a = parseLiteralBlock(p) of rnBulletList: a = parseBulletList(p) - of rnLineblock: a = parseLineBlock(p) + of rnLineBlock: a = parseLineBlock(p) of rnDirective: a = parseDotDot(p) of rnEnumList: a = parseEnumList(p) 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: result.sons[0].kind = rnInner -proc parseSectionWrapper(p: var TRstParser): PRSTNode = +proc parseSectionWrapper(p: var TRstParser): PRstNode = result = newRstNode(rnInner) parseSection(p, result) while (result.kind == rnInner) and (len(result) == 1): @@ -1385,16 +1385,16 @@ type TDirFlag = enum hasArg, hasOptions, argIsFile, argIsWord 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) - var args: PRSTNode = nil - var options: PRSTNode = nil + var args: PRstNode = nil + var options: PRstNode = nil if hasArg in flags: args = newRstNode(rnDirArg) if argIsFile in flags: - while True: + while true: case p.tok[p.idx].kind of tkWord, tkOther, tkPunct, tkAdornment: 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) proc parseDirective(p: var TRstParser, flags: TDirFlags, - contentParser: TSectionParser): PRSTNode = + contentParser: TSectionParser): PRstNode = result = parseDirective(p, flags) if not isNil(contentParser) and indFollows(p): pushInd(p, p.tok[p.idx].ival) @@ -1430,13 +1430,13 @@ proc parseDirective(p: var TRstParser, flags: TDirFlags, else: add(result, nil) -proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRSTNode = +proc parseDirBody(p: var TRstParser, contentParser: TSectionParser): PRstNode = if indFollows(p): pushInd(p, p.tok[p.idx].ival) result = contentParser(p) popInd(p) -proc dirInclude(p: var TRstParser): PRSTNode = +proc dirInclude(p: var TRstParser): PRstNode = # #The following options are recognized: # @@ -1474,7 +1474,7 @@ proc dirInclude(p: var TRstParser): PRSTNode = # InternalError("Too many binary zeros in include file") result = parseDoc(q) -proc dirCodeBlock(p: var TRstParser): PRSTNode = +proc dirCodeBlock(p: var TRstParser): PRstNode = result = parseDirective(p, {hasArg, hasOptions}, parseLiteralBlock) var filename = strip(getFieldValue(result, "file")) if filename != "": @@ -1485,34 +1485,34 @@ proc dirCodeBlock(p: var TRstParser): PRSTNode = result.sons[2] = n result.kind = rnCodeBlock -proc dirContainer(p: var TRstParser): PRSTNode = +proc dirContainer(p: var TRstParser): PRstNode = result = parseDirective(p, {hasArg}, parseSectionWrapper) assert(result.kind == rnDirective) assert(len(result) == 3) result.kind = rnContainer -proc dirImage(p: var TRstParser): PRSTNode = +proc dirImage(p: var TRstParser): PRstNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, nil) result.kind = rnImage -proc dirFigure(p: var TRstParser): PRSTNode = +proc dirFigure(p: var TRstParser): PRstNode = result = parseDirective(p, {hasOptions, hasArg, argIsFile}, parseSectionWrapper) result.kind = rnFigure -proc dirTitle(p: var TRstParser): PRSTNode = +proc dirTitle(p: var TRstParser): PRstNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnTitle -proc dirContents(p: var TRstParser): PRSTNode = +proc dirContents(p: var TRstParser): PRstNode = result = parseDirective(p, {hasArg}, nil) result.kind = rnContents -proc dirIndex(p: var TRstParser): PRSTNode = +proc dirIndex(p: var TRstParser): PRstNode = result = parseDirective(p, {}, parseSectionWrapper) 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) = var filename = getFieldValue(result, "file") if filename.len > 0: @@ -1527,7 +1527,7 @@ proc dirRawAux(p: var TRstParser, result: var PRSTNode, kind: TRstNodeKind, result.kind = kind add(result, parseDirBody(p, contentParser)) -proc dirRaw(p: var TRstParser): PRSTNode = +proc dirRaw(p: var TRstParser): PRstNode = # #The following options are recognized: # @@ -1566,7 +1566,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = result = dirRaw(p) else: rstMessage(p, meInvalidDirective, d) - of dkCodeblock: result = dirCodeBlock(p) + of dkCodeBlock: result = dirCodeBlock(p) of dkIndex: result = dirIndex(p) else: rstMessage(p, meInvalidDirective, d) popInd(p) @@ -1581,7 +1581,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = # substitution definitions: inc(p.idx, 2) var a = getReferenceName(p, "|") - var b: PRSTNode + var b: PRstNode if p.tok[p.idx].kind == tkWhite: inc(p.idx) if cmpIgnoreStyle(p.tok[p.idx].symbol, "replace") == 0: inc(p.idx) @@ -1603,7 +1603,7 @@ proc parseDotDot(p: var TRstParser): PRstNode = else: result = parseComment(p) -proc resolveSubs(p: var TRstParser, n: PRSTNode): PRSTNode = +proc resolveSubs(p: var TRstParser, n: PRstNode): PRstNode = result = n if n == nil: return case n.kind @@ -1634,7 +1634,7 @@ proc rstParse*(text, filename: string, line, column: int, hasToc: var bool, options: TRstParseOptions, findFile: TFindFileHandler = nil, - msgHandler: TMsgHandler = nil): PRSTNode = + msgHandler: TMsgHandler = nil): PRstNode = var p: TRstParser initParser(p, newSharedState(options, findFile, msgHandler)) p.filename = filename diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim index bb0b61889..f5ef0f53d 100644 --- a/lib/packages/docutils/rstast.nim +++ b/lib/packages/docutils/rstast.nim @@ -62,34 +62,34 @@ type # leaf val - PRSTNode* = ref TRSTNode ## an RST node - TRstNodeSeq* = seq[PRSTNode] - TRSTNode* {.acyclic, final.} = object ## an RST node's description + PRstNode* = ref TRstNode ## an RST node + TRstNodeSeq* = seq[PRstNode] + TRstNode* {.acyclic, final.} = object ## an RST node's description kind*: TRstNodeKind ## the node's kind text*: string ## valid for leafs in the AST; and the title of ## the document or the section level*: int ## valid for some node kinds sons*: TRstNodeSeq ## the node's sons -proc len*(n: PRSTNode): int = +proc len*(n: PRstNode): int = result = len(n.sons) -proc newRstNode*(kind: TRstNodeKind): PRSTNode = +proc newRstNode*(kind: TRstNodeKind): PRstNode = new(result) result.sons = @[] result.kind = kind -proc newRstNode*(kind: TRstNodeKind, s: string): PRSTNode = +proc newRstNode*(kind: TRstNodeKind, s: string): PRstNode = result = newRstNode(kind) result.text = s -proc lastSon*(n: PRSTNode): PRSTNode = +proc lastSon*(n: PRstNode): PRstNode = result = n.sons[len(n.sons)-1] -proc add*(father, son: PRSTNode) = +proc add*(father, son: PRstNode) = add(father.sons, son) -proc addIfNotNil*(father, son: PRSTNode) = +proc addIfNotNil*(father, son: PRstNode) = if son != nil: add(father, son) @@ -98,9 +98,9 @@ type indent: 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): renderRstToRst(d, n.sons[i], result) @@ -281,7 +281,7 @@ proc renderRstToRst(d: var TRenderContext, n: PRstNode, result: var string) = else: 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`. var d: TRenderContext renderRstToRst(d, n, result) diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index f43c6e478..988338da1 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -32,7 +32,7 @@ type outLatex # output is Latex TTocEntry{.final.} = object - n*: PRSTNode + n*: PRstNode refname*, header*: string TMetaEnum* = enum @@ -196,7 +196,7 @@ proc dispA(target: TOutputTarget, dest: var string, if target != outLatex: addf(dest, xml, 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. ## ## 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) ## 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) -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 = "" for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp) if d.target != outLatex: @@ -232,7 +232,7 @@ proc setIndexTerm*(d: var TRstGenerator, id, term: string) = d.theIndex.add(id) d.theIndex.add("\n") -proc hash(n: PRSTNode): int = +proc hash(n: PRstNode): int = if n.kind == rnLeaf: result = hash(n.text) elif n.len > 0: @@ -241,7 +241,7 @@ proc hash(n: PRSTNode): int = result = result !& hash(n.sons[i]) 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)) var 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 = "" for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) var refname = rstnodeToRefname(n) @@ -336,7 +336,7 @@ proc renderHeadline(d: PDoc, n: PRSTNode, result: var string) = $n.level, refname, tmp, $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: for i in countup(0, len(n)-1): 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: result.add(tmp) -proc renderImage(d: PDoc, n: PRSTNode, result: var string) = +proc renderImage(d: PDoc, n: PRstNode, result: var string) = var options = "" var s = getFieldValue(n, "scale") 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]) 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, """""", "\\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 var m = n.sons[2].sons[0] assert m.kind == rnLeaf @@ -433,7 +433,7 @@ proc renderCodeBlock(d: PDoc, n: PRSTNode, result: var string) = deinitGeneralTokenizer(g) dispA(d.target, result, "", "\n\\end{rstpre}\n") -proc renderContainer(d: PDoc, n: PRSTNode, result: var string) = +proc renderContainer(d: PDoc, n: PRstNode, result: var string) = var tmp = "" renderRstToOut(d, n.sons[2], tmp) var arg = strip(getArgument(n)) @@ -442,11 +442,11 @@ proc renderContainer(d: PDoc, n: PRSTNode, result: var string) = else: dispA(d.target, result, "
$2
", "$2", [arg, tmp]) -proc texColumns(n: PRSTNode): string = +proc texColumns(n: PRstNode): string = result = "" 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 if d.target == outLatex: var fieldname = addNodes(n.sons[0]) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index f0d0aa0c0..c79e6e6da 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -645,7 +645,7 @@ proc hasKey*(node: PJsonNode, key: string): bool = ## Checks if `key` exists in `node`. assert(node.kind == JObject) 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) ## Deprecated for `hasKey` @@ -730,8 +730,8 @@ proc escapeJson*(s: string): string = result.add(toHex(r, 4)) result.add("\"") -proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = True, - lstArr = False, currIndent = 0) = +proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = true, + lstArr = false, currIndent = 0) = case node.kind of JObject: 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.add(escapeJson(node.fields[i].key)) result.add(": ") - toPretty(result, node.fields[i].val, indent, ml, False, + toPretty(result, node.fields[i].val, indent, ml, false, newIndent(currIndent, indent, ml)) result.nl(ml) 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.nl(ml) # New Line toPretty(result, node.elems[i], indent, ml, - True, newIndent(currIndent, indent, ml)) + true, newIndent(currIndent, indent, ml)) result.nl(ml) result.indent(currIndent) result.add("]") @@ -794,7 +794,7 @@ proc pretty*(node: PJsonNode, indent = 2): string = proc `$`*(node: PJsonNode): string = ## Converts `node` to its JSON Representation on one line. result = "" - toPretty(result, node, 1, False) + toPretty(result, node, 1, false) iterator items*(node: PJsonNode): PJsonNode = ## Iterator for the items of `node`. `node` has to be a JArray. diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 243c7dc4a..81f53b874 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -102,7 +102,7 @@ proc fillBuffer(L: var TBaseLexer) = oldBufLen = L.BufLen L.bufLen = L.BufLen * 2 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]), oldBufLen * chrSize) div chrSize if charsRead < oldBufLen: diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 202052bc6..c1b71c202 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -95,8 +95,8 @@ elif defined(macos): const CurDir* = ':' ParDir* = "::" - Dirsep* = ':' - Altsep* = Dirsep + DirSep* = ':' + AltSep* = Dirsep PathSep* = ',' FileSystemCaseSensitive* = false ExeExt* = "" @@ -123,10 +123,10 @@ elif defined(macos): # grandparent etc. elif doslike: const - Curdir* = '.' - Pardir* = ".." - Dirsep* = '\\' # seperator within paths - Altsep* = '/' + CurDir* = '.' + ParDir* = ".." + DirSep* = '\\' # seperator within paths + AltSep* = '/' PathSep* = ';' # seperator between paths FileSystemCaseSensitive* = false ExeExt* = "exe" @@ -134,19 +134,19 @@ elif doslike: DynlibFormat* = "$1.dll" elif defined(PalmOS) or defined(MorphOS): const - Dirsep* = '/' - Altsep* = Dirsep + DirSep* = '/' + AltSep* = Dirsep PathSep* = ';' - Pardir* = ".." + ParDir* = ".." FileSystemCaseSensitive* = false ExeExt* = "" ScriptExt* = "" DynlibFormat* = "$1.prc" elif defined(RISCOS): const - Dirsep* = '.' - Altsep* = '.' - Pardir* = ".." # is this correct? + DirSep* = '.' + AltSep* = '.' + ParDir* = ".." # is this correct? PathSep* = ',' FileSystemCaseSensitive* = true ExeExt* = "" @@ -154,10 +154,10 @@ elif defined(RISCOS): DynlibFormat* = "lib$1.so" else: # UNIX-like operating system const - Curdir* = '.' - Pardir* = ".." - Dirsep* = '/' - Altsep* = Dirsep + CurDir* = '.' + ParDir* = ".." + DirSep* = '/' + AltSep* = Dirsep PathSep* = ':' FileSystemCaseSensitive* = true ExeExt* = "" @@ -308,7 +308,7 @@ proc unixToNativePath*(path: string): string {. start = 1 elif path[0] == '.' and path[1] == '/': # current directory - result = $Curdir + result = $CurDir start = 2 else: result = "" @@ -538,7 +538,7 @@ proc splitPath*(path: string): tuple[head, tail: string] {. ## splitPath("") -> ("", "") var sepPos = -1 for i in countdown(len(path)-1, 0): - if path[i] in {Dirsep, Altsep}: + if path[i] in {DirSep, AltSep}: sepPos = i break if sepPos >= 0: @@ -550,9 +550,9 @@ proc splitPath*(path: string): tuple[head, tail: string] {. proc parentDirPos(path: string): int = 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): - if path[i] in {Dirsep, Altsep}: return i + if path[i] in {DirSep, AltSep}: return i result = -1 proc parentDir*(path: string): string {. @@ -593,8 +593,8 @@ iterator parentDirs*(path: string, fromRoot=false, inclusive=true): string = else: for i in countup(0, path.len - 2): # ignore the last / # deal with non-normalized paths such as /foo//bar//baz - if path[i] in {Dirsep, Altsep} and - (i == 0 or path[i-1] notin {Dirsep, Altsep}): + if path[i] in {DirSep, AltSep} and + (i == 0 or path[i-1] notin {DirSep, AltSep}): yield path.substr(0, i) if inclusive: yield path @@ -619,7 +619,7 @@ proc searchExtPos(s: string): int = if s[i] == ExtSep: result = i break - elif s[i] in {Dirsep, Altsep}: + elif s[i] in {DirSep, AltSep}: break # do not skip over path 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 directory component, `dir` is the empty string. ## 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, "", "") else: var sepPos = -1 @@ -647,8 +647,8 @@ proc splitFile*(path: string): tuple[dir, name, ext: string] {. for i in countdown(len(path)-1, 0): if path[i] == ExtSep: if dotPos == path.len and i > 0 and - path[i-1] notin {Dirsep, Altsep}: dotPos = i - elif path[i] in {Dirsep, Altsep}: + path[i-1] notin {DirSep, AltSep}: dotPos = i + elif path[i] in {DirSep, AltSep}: sepPos = i break result.dir = substr(path, 0, sepPos-1) @@ -659,7 +659,7 @@ proc extractFilename*(path: string): string {. noSideEffect, rtl, extern: "nos$1".} = ## Extracts the filename of a given `path`. This is the same as ## ``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 = "" else: result = splitPath(path).tail @@ -814,11 +814,11 @@ proc sameFileContent*(path1, path2: string): bool {.rtl, extern: "nos$1", if not open(b, path2): close(a) return false - var bufA = alloc(bufsize) - var bufB = alloc(bufsize) + var bufA = alloc(bufSize) + var bufB = alloc(bufSize) while true: - var readA = readBuffer(a, bufA, bufsize) - var readB = readBuffer(b, bufB, bufsize) + var readA = readBuffer(a, bufA, bufSize) + var readB = readBuffer(b, bufB, bufSize) if readA != readB: result = false break @@ -1159,7 +1159,7 @@ iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} = while true: if not skipFindData(f): yield splitFile(pattern).dir / extractFilename(getFilename(f)) - if findnextFile(res, f) == 0'i32: break + if findNextFile(res, f) == 0'i32: break findClose(res) else: # here we use glob var @@ -1214,7 +1214,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {. if (f.dwFileAttributes and FILE_ATTRIBUTE_DIRECTORY) != 0'i32: k = pcDir yield (k, dir / extractFilename(getFilename(f))) - if findnextFile(h, f) == 0'i32: break + if findNextFile(h, f) == 0'i32: break findClose(h) else: var d = openDir(dir) @@ -1308,7 +1308,7 @@ proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} = when defined(doslike): omitNext = isAbsolute(dir) for i in 1.. dir.len-1: - if dir[i] in {Dirsep, Altsep}: + if dir[i] in {DirSep, AltSep}: if omitNext: omitNext = false else: diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 49b4b6fab..1be30f006 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -396,7 +396,7 @@ when defined(Windows) and not defined(useNimRtl): proc startProcess(command: string, workingDir: string = "", - args: openarray[string] = [], + args: openArray[string] = [], env: PStringTable = nil, options: set[TProcessOption] = {poStdErrToStdOut}): PProcess = var diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim index 1be292af1..5076d72fd 100644 --- a/lib/pure/parseopt.nim +++ b/lib/pure/parseopt.nim @@ -105,7 +105,7 @@ proc next*(p: var TOptParser) {. of '-': inc(i) if p.cmd[i] == '-': - p.kind = cmdLongOption + p.kind = cmdLongoption inc(i) i = parseWord(p.cmd, i, p.key.string, {'\0', ' ', '\x09', ':', '='}) while p.cmd[i] in {'\x09', ' '}: inc(i) diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 2ae37e372..dee45cbd6 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -26,7 +26,7 @@ {.deadCodeElim: on.} -when hostos == "solaris": +when hostOS == "solaris": {.passl: "-lsocket -lnsl".} import os, parseutils @@ -467,7 +467,7 @@ template acceptAddrPlain(noClientRet, successRet: expr, sslImplementation: stmt): stmt {.immediate.} = assert(client != nil) var sockAddress: Tsockaddr_in - var addrLen = sizeof(sockAddress).Tsocklen + var addrLen = sizeof(sockAddress).TSockLen var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen)) @@ -1258,10 +1258,10 @@ proc recvLine*(socket: TSocket, line: var TaintedString, timeout = -1): bool {. if n > 0 and c == '\L': discard recv(socket, addr(c), 1) elif n <= 0: return false - addNlIfEmpty() + addNLIfEmpty() return true elif c == '\L': - addNlIfEmpty() + addNLIfEmpty() return true add(line.string, c) @@ -1299,10 +1299,10 @@ proc readLine*(socket: TSocket, line: var TaintedString, timeout = -1) {. if n > 0 and c == '\L': discard recv(socket, addr(c), 1) elif n <= 0: osError(osLastError()) - addNlIfEmpty() + addNLIfEmpty() return elif c == '\L': - addNlIfEmpty() + addNLIfEmpty() return add(line.string, c) @@ -1457,7 +1457,7 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {. let err = osLastError() when defined(windows): if err.int32 == WSAEWOULDBLOCK: - return False + return false else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: @@ -1469,7 +1469,7 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {. # increase capacity: setLen(s.string, s.string.len + bufSize) inc(pos, bytesRead) - result = True + result = true proc recvFrom*(socket: TSocket, data: var string, length: 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() when defined(windows): if err.int32 == WSAEWOULDBLOCK: - return False + return false else: osError(err) else: if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK: @@ -1710,6 +1710,6 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking when defined(Windows): var wsa: TWSAData - if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError()) + if wsaStartup(0x0101'i16, addr wsa) != 0: osError(osLastError()) diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 2a6d499a7..20109cfa2 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -214,7 +214,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string = while last < len(s): while s[last] in seps: inc(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: yield substr(s, first, last-1) diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim index b67341e89..37a64a8f3 100644 --- a/lib/pure/unicode.nim +++ b/lib/pure/unicode.nim @@ -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. ## If possible, prefer `toLower` over `toUpper`. 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]: 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]: return TRune(c + tolowerSinglets[p+1] - 500) 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. ## If possible, prefer `toLower` over `toUpper`. 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]: 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]: return TRune(c + toupperSinglets[p+1] - 500) return TRune(c) @@ -1147,10 +1147,10 @@ proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## If possible, prefer `isLower` over `isUpper`. var c = IRune(c) # 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]: 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]: return true @@ -1159,10 +1159,10 @@ proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} = ## If possible, prefer `isLower` over `isUpper`. var c = IRune(c) # 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]: 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]: return true diff --git a/lib/system.nim b/lib/system.nim index ebe722680..dddf77858 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1145,7 +1145,7 @@ when not defined(nimrodVM): ## otherwise. Like any procedure dealing with raw memory this is ## *unsafe*. - when hostOs != "standalone": + when hostOS != "standalone": proc alloc*(size: int): pointer {.noconv, rtl, tags: [].} ## allocates a new memory block with at least ``size`` bytes. The ## block has to be freed with ``realloc(block, 0)`` or diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 9e3930622..bed8820be 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -144,7 +144,7 @@ proc objectInitAux(dest: pointer, n: ptr TNimNode) = var d = cast[TAddress](dest) case n.kind 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: for i in 0..n.len-1: objectInitAux(dest, n.sons[i]) diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index eb1bf752e..f29e222e8 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -10,7 +10,7 @@ # Implementation of some runtime checks. proc raiseRangeError(val: BiggestInt) {.compilerproc, noreturn, noinline.} = - when hostOs == "standalone": + when hostOS == "standalone": sysFatal(EOutOfRange, "value out of range") else: sysFatal(EOutOfRange, "value out of range: ", $val) diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 376d1502c..6d6be33d0 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -573,7 +573,7 @@ proc scan(s: PCell) = proc collectWhite(s: PCell) = if s.color == rcWhite and s notin gch.cycleRoots: - s.setcolor(rcBlack) + s.setColor(rcBlack) forAllChildren(s, waCollectWhite) freeCyclicCell(gch, s) @@ -891,7 +891,7 @@ proc collectZCT(gch: var TGcHeap): bool = const workPackage = 100 var L = addr(gch.zct.len) - when withRealtime: + when withRealTime: var steps = workPackage var t0: TTicks if gch.maxPause > 0: t0 = getticks() @@ -904,7 +904,7 @@ proc collectZCT(gch: var TGcHeap): bool = c.refcount = c.refcount and not ZctFlag gch.zct.d[0] = gch.zct.d[L[] - 1] dec(L[]) - when withRealtime: dec steps + when withRealTime: dec steps if c.refcount <% rcIncrement: # 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 @@ -927,7 +927,7 @@ proc collectZCT(gch: var TGcHeap): bool = else: sysAssert(c.typ != nil, "collectZCT 2") zeroMem(c, sizeof(TCell)) - when withRealtime: + when withRealTime: if steps == 0: steps = workPackage if gch.maxPause > 0: @@ -952,7 +952,7 @@ proc unmarkStackAndRegisters(gch: var TGcHeap) = gch.decStack.len = 0 proc collectCTBody(gch: var TGcHeap) = - when withRealtime: + when withRealTime: let t0 = getticks() sysAssert(allocInv(gch.region), "collectCT: begin") @@ -975,7 +975,7 @@ proc collectCTBody(gch: var TGcHeap) = unmarkStackAndRegisters(gch) sysAssert(allocInv(gch.region), "collectCT: end") - when withRealtime: + when withRealTime: let duration = getticks() - t0 gch.stat.maxPause = max(gch.stat.maxPause, duration) when defined(reportMissedDeadlines): @@ -997,7 +997,7 @@ proc collectCT(gch: var TGcHeap) = markForDebug(gch) collectCTBody(gch) -when withRealtime: +when withRealTime: proc toNano(x: int): TNanos {.inline.} = result = x * 1000 diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 2b6ad8df1..56e6a9e5f 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -95,7 +95,7 @@ proc write(f: TFile, i: int) = fprintf(f, "%ld", i) proc write(f: TFile, i: BiggestInt) = - when sizeof(Biggestint) == 8: + when sizeof(BiggestInt) == 8: fprintf(f, "%lld", i) else: 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 = 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) -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) {.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) 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) result = writeBuffer(f, addr(x[start]), len) proc writeBuffer(f: TFile, buffer: pointer, len: int): int = diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index e288910d7..91c6495ce 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -92,7 +92,7 @@ const DETACHED_PROCESS* = 8'i32 SW_SHOWNORMAL* = 1'i32 - INVALID_HANDLE_VALUE* = THANDLE(-1) + INVALID_HANDLE_VALUE* = THandle(-1) CREATE_UNICODE_ENVIRONMENT* = 1024'i32 @@ -418,7 +418,7 @@ type ai_addr*: ptr TSockAddr ## Socket address of socket. ai_next*: ptr TAddrInfo ## Pointer to next in list. - Tsocklen* = cuint + TSockLen* = cuint var SOMAXCONN* {.importc, header: "Winsock2.h".}: cint @@ -457,20 +457,20 @@ proc socket*(af, typ, protocol: cint): TSocketHandle {. proc closesocket*(s: TSocketHandle): cint {. 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.} -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.} -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.} proc getsockname*(s: TSocketHandle, name: ptr TSockAddr, - namelen: ptr Tsocklen): cint {. + namelen: ptr TSockLen): cint {. stdcall, importc: "getsockname", dynlib: ws2dll.} proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: ptr Tsocklen): cint {. + optlen: ptr TSockLen): cint {. stdcall, importc: "getsockopt", dynlib: ws2dll.} proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer, - optlen: Tsocklen): cint {. + optlen: TSockLen): cint {. stdcall, importc: "setsockopt", dynlib: ws2dll.} 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 {. stdcall, importc: "recv", dynlib: ws2dll.} 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.} proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet, 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 {. stdcall, importc: "send", dynlib: ws2dll.} 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.} proc shutdown*(s: TSocketHandle, how: cint): cint {. stdcall, importc: "shutdown", dynlib: ws2dll.} -proc getnameinfo*(a1: ptr TSockAddr, a2: Tsocklen, - a3: cstring, a4: Tsocklen, a5: cstring, - a6: Tsocklen, a7: cint): cint {. +proc getnameinfo*(a1: ptr TSockAddr, a2: TSockLen, + a3: cstring, a4: TSockLen, a5: cstring, + a6: TSockLen, a7: cint): cint {. stdcall, importc: "getnameinfo", dynlib: ws2dll.} proc inet_addr*(cp: cstring): int32 {. @@ -514,7 +514,7 @@ proc FD_SET*(Socket: TSocketHandle, FDSet: var TFdSet) = proc FD_ZERO*(FDSet: var TFdSet) = 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.} proc getaddrinfo*(nodename, servname: cstring, hints: ptr TAddrInfo, -- cgit 1.4.1-2-gfad0 From b731e6ef1c4f10b9ba544c0a66ea1066b3c471a8 Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 29 Dec 2013 03:19:10 +0100 Subject: case consistency: cs:partial bootstraps on windows --- compiler/ast.nim | 18 +++++----- compiler/astalgo.nim | 8 ++--- compiler/babelcmd.nim | 4 +-- compiler/ccgexprs.nim | 36 +++++++++---------- compiler/ccgmerge.nim | 16 ++++----- compiler/ccgstmts.nim | 16 ++++----- compiler/ccgthreadvars.nim | 2 +- compiler/ccgtypes.nim | 12 +++---- compiler/cgen.nim | 44 +++++++++++------------ compiler/cgendata.nim | 8 ++--- compiler/commands.nim | 18 +++++----- compiler/condsyms.nim | 2 +- compiler/docgen.nim | 4 +-- compiler/extccomp.nim | 12 +++---- compiler/filter_tmpl.nim | 6 ++-- compiler/importer.nim | 14 ++++---- compiler/jsgen.nim | 24 ++++++------- compiler/jstypes.nim | 2 +- compiler/lexer.nim | 88 +++++++++++++++++++++++----------------------- compiler/lookups.nim | 14 ++++---- compiler/magicsys.nim | 2 +- compiler/main.nim | 4 +-- compiler/modules.nim | 4 +-- compiler/msgs.nim | 2 +- compiler/nimconf.nim | 6 ++-- compiler/nimlexbase.nim | 14 ++++---- compiler/nimrod.nim | 2 +- compiler/nimsets.nim | 2 +- compiler/options.nim | 8 ++--- compiler/parser.nim | 14 ++++---- compiler/pragmas.nim | 20 +++++------ compiler/pretty.nim | 18 +++++----- compiler/procfind.nim | 6 ++-- compiler/rodread.nim | 8 ++--- compiler/sem.nim | 16 ++++----- compiler/semcall.nim | 6 ++-- compiler/semdata.nim | 4 +-- compiler/semexprs.nim | 45 +++++++++++++----------- compiler/seminst.nim | 10 +++--- compiler/sempass2.nim | 2 +- compiler/semstmts.nim | 22 ++++++------ compiler/semtypes.nim | 20 ++++++----- compiler/semtypinst.nim | 2 +- compiler/sigmatch.nim | 16 ++++----- compiler/suggest.nim | 8 ++--- compiler/transf.nim | 4 +-- compiler/trees.nim | 4 +-- compiler/types.nim | 16 ++++----- compiler/vm.nim | 2 +- lib/pure/hashes.nim | 6 ++-- lib/pure/json.nim | 20 +++++------ lib/pure/lexbase.nim | 14 ++++---- lib/pure/os.nim | 4 +-- lib/pure/osproc.nim | 52 +++++++++++++-------------- lib/pure/parseopt.nim | 2 +- lib/pure/sockets.nim | 10 +++--- lib/pure/times.nim | 10 +++--- lib/system/gc.nim | 8 ++--- 58 files changed, 384 insertions(+), 377 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/ast.nim b/compiler/ast.nim index a2f5fad17..5a3af27e8 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -546,7 +546,7 @@ type typ*: PType info*: TLineInfo flags*: TNodeFlags - case Kind*: TNodeKind + case kind*: TNodeKind of nkCharLit..nkUInt64Lit: intVal*: BiggestInt of nkFloatLit..nkFloat128Lit: @@ -822,7 +822,7 @@ const # imported via 'importc: "fullname"' and no format string. # creator procs: -proc newSym*(symKind: TSymKind, Name: PIdent, owner: PSym, +proc newSym*(symKind: TSymKind, name: PIdent, owner: PSym, info: TLineInfo): PSym proc newType*(kind: TTypeKind, owner: PSym): PType proc newNode*(kind: TNodeKind): PNode @@ -1108,7 +1108,7 @@ proc assignType(dest, src: PType) = for i in countup(0, sonsLen(src) - 1): dest.sons[i] = src.sons[i] proc copyType(t: PType, owner: PSym, keepId: bool): PType = - result = newType(t.Kind, owner) + result = newType(t.kind, owner) assignType(result, t) if keepId: result.id = t.id @@ -1148,12 +1148,12 @@ proc createModuleAlias*(s: PSym, newIdent: PIdent, info: TLineInfo): PSym = # XXX once usedGenerics is used, ensure module aliases keep working! assert s.usedGenerics == nil -proc newSym(symKind: TSymKind, Name: PIdent, owner: PSym, +proc newSym(symKind: TSymKind, name: PIdent, owner: PSym, info: TLineInfo): PSym = # generates a symbol and initializes the hash field too new(result) - result.Name = Name - result.Kind = symKind + result.name = name + result.kind = symKind result.flags = {} result.info = info result.options = gOptions @@ -1270,7 +1270,7 @@ proc copyNode(src: PNode): PNode = when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id - case src.Kind + case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkSym: result.sym = src.sym @@ -1288,7 +1288,7 @@ proc shallowCopy*(src: PNode): PNode = when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id - case src.Kind + case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkSym: result.sym = src.sym @@ -1307,7 +1307,7 @@ proc copyTree(src: PNode): PNode = when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id - case src.Kind + case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkSym: result.sym = src.sym diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 35c306bcf..4b7348566 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -626,7 +626,7 @@ proc strTableGet(t: TStrTable, name: PIdent): PSym = proc initIdentIter(ti: var TIdentIter, tab: TStrTable, s: PIdent): PSym = ti.h = s.h ti.name = s - if tab.Counter == 0: result = nil + if tab.counter == 0: result = nil else: result = nextIdentIter(ti, tab) proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = @@ -635,7 +635,7 @@ proc nextIdentIter(ti: var TIdentIter, tab: TStrTable): PSym = start = h result = tab.data[h] while result != nil: - if result.Name.id == ti.name.id: break + if result.name.id == ti.name.id: break h = nextTry(h, high(tab.data)) if h == start: result = nil @@ -649,7 +649,7 @@ proc nextIdentExcluding*(ti: var TIdentIter, tab: TStrTable, var start = h result = tab.data[h] while result != nil: - if result.Name.id == ti.name.id and not contains(excluding, result.id): + if result.name.id == ti.name.id and not contains(excluding, result.id): break h = nextTry(h, high(tab.data)) if h == start: @@ -663,7 +663,7 @@ proc firstIdentExcluding*(ti: var TIdentIter, tab: TStrTable, s: PIdent, excluding: TIntSet): PSym = ti.h = s.h ti.name = s - if tab.Counter == 0: result = nil + if tab.counter == 0: result = nil else: result = nextIdentExcluding(ti, tab, excluding) proc initTabIter(ti: var TTabIter, tab: TStrTable): PSym = diff --git a/compiler/babelcmd.nim b/compiler/babelcmd.nim index 65a2fe545..7fa233732 100644 --- a/compiler/babelcmd.nim +++ b/compiler/babelcmd.nim @@ -13,7 +13,7 @@ import parseutils, strutils, strtabs, os, options, msgs, lists proc addPath*(path: string, info: TLineInfo) = if not contains(options.searchPaths, path): - lists.PrependStr(options.searchPaths, path) + lists.prependStr(options.searchPaths, path) proc versionSplitPos(s: string): int = result = s.len-2 @@ -61,7 +61,7 @@ iterator chosen(packages: PStringTable): string = proc addBabelPath(p: string, info: TLineInfo) = if not contains(options.searchPaths, p): if gVerbosity >= 1: message(info, hintPath, p) - lists.PrependStr(options.lazyPaths, p) + lists.prependStr(options.lazyPaths, p) proc addPathWithNimFiles(p: string, info: TLineInfo) = proc hasNimFile(dir: string): bool = diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 495c342ed..22a00cf29 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -436,7 +436,7 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = else: var storage: PRope var size = getSize(t) - if size < platform.IntSize: + if size < platform.intSize: storage = toRope("NI") else: storage = getTypeDesc(p.module, t) @@ -444,7 +444,7 @@ proc binaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = linefmt(p, cpsLocals, "$1 $2;$n", storage, tmp) lineCg(p, cpsStmts, "$1 = #$2($3, $4);$n", tmp, toRope(prc[m]), rdLoc(a), rdLoc(b)) - if size < platform.IntSize or t.kind in {tyRange, tyEnum, tySet}: + if size < platform.intSize or t.kind in {tyRange, tyEnum, tySet}: linefmt(p, cpsStmts, "if ($1 < $2 || $1 > $3) #raiseOverflow();$n", tmp, intLiteral(firstOrd(t)), intLiteral(lastOrd(t))) putIntoDest(p, d, e.typ, ropef("(NI$1)($2)", [toRope(getSize(t)*8), tmp])) @@ -838,7 +838,7 @@ proc genAndOr(p: BProc, e: PNode, d: var TLoc, m: TMagic) = proc genEcho(p: BProc, n: PNode) = # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)`` # is threadsafe. - discard lists.IncludeStr(p.module.headerFiles, "") + discard lists.includeStr(p.module.headerFiles, "") var args: PRope = nil var a: TLoc for i in countup(1, n.len-1): @@ -872,7 +872,7 @@ proc genStrConcat(p: BProc, e: PNode, d: var TLoc) = for i in countup(0, sonsLen(e) - 2): # compute the length expression: initLocExpr(p, e.sons[i + 1], a) - if skipTypes(e.sons[i + 1].Typ, abstractVarRange).kind == tyChar: + if skipTypes(e.sons[i + 1].typ, abstractVarRange).kind == tyChar: inc(L) app(appends, rfmt(p.module, "#appendChar($1, $2);$n", tmp.r, rdLoc(a))) else: @@ -910,7 +910,7 @@ proc genStrAppend(p: BProc, e: PNode, d: var TLoc) = for i in countup(0, sonsLen(e) - 3): # compute the length expression: initLocExpr(p, e.sons[i + 2], a) - if skipTypes(e.sons[i + 2].Typ, abstractVarRange).kind == tyChar: + if skipTypes(e.sons[i + 2].typ, abstractVarRange).kind == tyChar: inc(L) app(appends, rfmt(p.module, "#appendChar($1, $2);$n", rdLoc(dest), rdLoc(a))) @@ -940,7 +940,7 @@ proc genSeqElemAppend(p: BProc, e: PNode, d: var TLoc) = lineCg(p, cpsStmts, seqAppendPattern, [ rdLoc(a), getTypeDesc(p.module, skipTypes(e.sons[1].typ, abstractVar)), - getTypeDesc(p.module, skipTypes(e.sons[2].Typ, abstractVar))]) + getTypeDesc(p.module, skipTypes(e.sons[2].typ, abstractVar))]) keepAlive(p, a) initLoc(dest, locExpr, b.t, OnHeap) dest.r = rfmt(nil, "$1->data[$1->$2-1]", rdLoc(a), lenField()) @@ -1191,7 +1191,7 @@ proc genDollar(p: BProc, n: PNode, d: var TLoc, frmt: string) = proc genArrayLen(p: BProc, e: PNode, d: var TLoc, op: TMagic) = var a = e.sons[1] if a.kind == nkHiddenAddr: a = a.sons[0] - var typ = skipTypes(a.Typ, abstractVar) + var typ = skipTypes(a.typ, abstractVar) case typ.kind of tyOpenArray, tyVarargs: if op == mHigh: unaryExpr(p, e, d, "($1Len0-1)") @@ -1259,7 +1259,7 @@ proc fewCmps(s: PNode): bool = if s.kind != nkCurly: internalError(s.info, "fewCmps") if (getSize(s.typ) <= platform.intSize) and (nfAllConst in s.flags): result = false # it is better to emit the set generation code - elif elemType(s.typ).Kind in {tyInt, tyInt16..tyInt64}: + elif elemType(s.typ).kind in {tyInt, tyInt16..tyInt64}: result = true # better not emit the set if int is basetype! else: result = sonsLen(s) <= 8 # 8 seems to be a good value @@ -1284,7 +1284,7 @@ proc binaryStmtInExcl(p: BProc, e: PNode, d: var TLoc, frmt: string) = proc genInOp(p: BProc, e: PNode, d: var TLoc) = var a, b, x, y: TLoc - if (e.sons[1].Kind == nkCurly) and fewCmps(e.sons[1]): + if (e.sons[1].kind == nkCurly) and fewCmps(e.sons[1]): # a set constructor but not a constant set: # do not emit the set, but generate a bunch of comparisons; and if we do # so, we skip the unnecessary range check: This is a semantical extension @@ -1298,7 +1298,7 @@ proc genInOp(p: BProc, e: PNode, d: var TLoc) = b.r = toRope("(") var length = sonsLen(e.sons[1]) for i in countup(0, length - 1): - if e.sons[1].sons[i].Kind == nkRange: + if e.sons[1].sons[i].kind == nkRange: initLocExpr(p, e.sons[1].sons[i].sons[0], x) initLocExpr(p, e.sons[1].sons[i].sons[1], y) appf(b.r, "$1 >= $2 && $1 <= $3", @@ -1326,7 +1326,7 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = "if ($3) $3 = (memcmp($4, $5, $2) != 0);$n", "&", "|", "& ~", "^"] var a, b, i: TLoc - var setType = skipTypes(e.sons[1].Typ, abstractVar) + var setType = skipTypes(e.sons[1].typ, abstractVar) var size = int(getSize(setType)) case size of 1, 2, 4, 8: @@ -1512,25 +1512,25 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mGetTypeInfo: genGetTypeInfo(p, e, d) of mSwap: genSwap(p, e, d) of mUnaryLt: - if not (optOverflowCheck in p.Options): unaryExpr(p, e, d, "$1 - 1") + if not (optOverflowCheck in p.options): unaryExpr(p, e, d, "$1 - 1") else: unaryExpr(p, e, d, "#subInt($1, 1)") of mPred: # XXX: range checking? - if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 - $2") + if not (optOverflowCheck in p.options): binaryExpr(p, e, d, "$1 - $2") else: binaryExpr(p, e, d, "#subInt($1, $2)") of mSucc: # XXX: range checking? - if not (optOverflowCheck in p.Options): binaryExpr(p, e, d, "$1 + $2") + if not (optOverflowCheck in p.options): binaryExpr(p, e, d, "$1 + $2") else: binaryExpr(p, e, d, "#addInt($1, $2)") of mInc: - if not (optOverflowCheck in p.Options): + if not (optOverflowCheck in p.options): binaryStmt(p, e, d, "$1 += $2;$n") elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64: binaryStmt(p, e, d, "$1 = #addInt64($1, $2);$n") else: binaryStmt(p, e, d, "$1 = #addInt($1, $2);$n") of ast.mDec: - if not (optOverflowCheck in p.Options): + if not (optOverflowCheck in p.options): binaryStmt(p, e, d, "$1 -= $2;$n") elif skipTypes(e.sons[1].typ, abstractVar).kind == tyInt64: binaryStmt(p, e, d, "$1 = #subInt64($1, $2);$n") @@ -1778,7 +1778,7 @@ proc expr(p: BProc, n: PNode, d: var TLoc) = case n.kind of nkSym: var sym = n.sym - case sym.Kind + case sym.kind of skMethod: if sym.getBody.kind == nkEmpty or sfDispatcher in sym.flags: # we cannot produce code for the dispatcher yet: @@ -1990,7 +1990,7 @@ proc genConstSeq(p: BProc, n: PNode, t: PType): PRope = result = ropef("(($1)&$2)", [getTypeDesc(p.module, t), result]) proc genConstExpr(p: BProc, n: PNode): PRope = - case n.Kind + case n.kind of nkHiddenStdConv, nkHiddenSubConv: result = genConstExpr(p, n.sons[1]) of nkCurly: diff --git a/compiler/ccgmerge.nim b/compiler/ccgmerge.nim index 0ea30bd04..514b77b73 100644 --- a/compiler/ccgmerge.nim +++ b/compiler/ccgmerge.nim @@ -108,7 +108,7 @@ proc genMergeInfo*(m: BModule): PRope = s.add("labels:") encodeVInt(m.labels, s) s.add(" hasframe:") - encodeVInt(ord(m.FrameDeclared), s) + encodeVInt(ord(m.frameDeclared), s) s.add(tnl) s.add("*/") result = s.toRope @@ -119,8 +119,8 @@ proc skipWhite(L: var TBaseLexer) = var pos = L.bufpos while true: case ^pos - of CR: pos = nimlexbase.HandleCR(L, pos) - of LF: pos = nimlexbase.HandleLF(L, pos) + of CR: pos = nimlexbase.handleCR(L, pos) + of LF: pos = nimlexbase.handleLF(L, pos) of ' ': inc pos else: break L.bufpos = pos @@ -129,8 +129,8 @@ proc skipUntilCmd(L: var TBaseLexer) = var pos = L.bufpos while true: case ^pos - of CR: pos = nimlexbase.HandleCR(L, pos) - of LF: pos = nimlexbase.HandleLF(L, pos) + of CR: pos = nimlexbase.handleCR(L, pos) + of LF: pos = nimlexbase.handleLF(L, pos) of '\0': break of '/': if ^(pos+1) == '*' and ^(pos+2) == '\t': @@ -179,11 +179,11 @@ proc readVerbatimSection(L: var TBaseLexer): PRope = while true: case buf[pos] of CR: - pos = nimlexbase.HandleCR(L, pos) + pos = nimlexbase.handleCR(L, pos) buf = L.buf r.add(tnl) of LF: - pos = nimlexbase.HandleLF(L, pos) + pos = nimlexbase.handleLF(L, pos) buf = L.buf r.add(tnl) of '\0': @@ -249,7 +249,7 @@ proc processMergeInfo(L: var TBaseLexer, m: BModule) = of "declared": readIntSet(L, m.declaredThings) of "typeInfo": readIntSet(L, m.typeInfoMarker) of "labels": m.labels = decodeVInt(L.buf, L.bufpos) - of "hasframe": m.FrameDeclared = decodeVInt(L.buf, L.bufpos) != 0 + of "hasframe": m.frameDeclared = decodeVInt(L.buf, L.bufpos) != 0 else: internalError("ccgmerge: unkown key: " & k) when not defined(nimhygiene): diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index e9291edc5..af0d657f1 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -126,7 +126,7 @@ proc genGotoState(p: BProc, n: PNode) = var a: TLoc initLocExpr(p, n.sons[0], a) lineF(p, cpsStmts, "switch ($1) {$n", [rdLoc(a)]) - p.BeforeRetNeeded = true + p.beforeRetNeeded = true lineF(p, cpsStmts, "case -1: goto BeforeRet;$n", []) for i in 0 .. lastOrd(n.sons[0].typ): lineF(p, cpsStmts, "case $1: goto STATE$1;$n", [toRope(i)]) @@ -588,7 +588,7 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) = proc branchHasTooBigRange(b: PNode): bool = for i in countup(0, sonsLen(b)-2): # last son is block - if (b.sons[i].Kind == nkRange) and + if (b.sons[i].kind == nkRange) and b.sons[i].sons[1].intVal - b.sons[i].sons[0].intVal > RangeExpandLimit: return true @@ -706,7 +706,7 @@ proc genTryCpp(p: BProc, t: PNode, d: var TLoc) = expr(p, t.sons[0], d) length = sonsLen(t) endBlock(p, ropecg(p.module, "} catch (NimException& $1) {$n", [exc])) - if optStackTrace in p.Options: + if optStackTrace in p.options: linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n") inc p.inExceptBlock i = 1 @@ -779,7 +779,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) = # if not isEmptyType(t.typ) and d.k == locNone: getTemp(p, t.typ, d) - discard lists.IncludeStr(p.module.headerFiles, "") + discard lists.includeStr(p.module.headerFiles, "") genLineDir(p, t) var safePoint = getTempName() discard cgsym(p.module, "E_Base") @@ -794,7 +794,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) = endBlock(p) startBlock(p, "else {$n") linefmt(p, cpsStmts, "#popSafePoint();$n") - if optStackTrace in p.Options: + if optStackTrace in p.options: linefmt(p, cpsStmts, "#setFrame((TFrame*)&F);$n") inc p.inExceptBlock var i = 1 @@ -833,7 +833,7 @@ proc genTry(p: BProc, t: PNode, d: var TLoc) = proc genAsmOrEmitStmt(p: BProc, t: PNode, isAsmStmt=false): PRope = var res = "" for i in countup(0, sonsLen(t) - 1): - case t.sons[i].Kind + case t.sons[i].kind of nkStrLit..nkTripleStrLit: res.add(t.sons[i].strVal) of nkSym: @@ -892,7 +892,7 @@ var proc genBreakPoint(p: BProc, t: PNode) = var name: string - if optEndb in p.Options: + if optEndb in p.options: if t.kind == nkExprColonExpr: assert(t.sons[1].kind in {nkStrLit..nkTripleStrLit}) name = normalize(t.sons[1].strVal) @@ -906,7 +906,7 @@ proc genBreakPoint(p: BProc, t: PNode) = makeCString(name)]) proc genWatchpoint(p: BProc, n: PNode) = - if optEndb notin p.Options: return + if optEndb notin p.options: return var a: TLoc initLocExpr(p, n.sons[1], a) let typ = skipTypes(n.sons[1].typ, abstractVarRange) diff --git a/compiler/ccgthreadvars.nim b/compiler/ccgthreadvars.nim index ee01972fc..c00b931ef 100644 --- a/compiler/ccgthreadvars.nim +++ b/compiler/ccgthreadvars.nim @@ -16,7 +16,7 @@ proc emulatedThreadVars(): bool = result = {optThreads, optTlsEmulation} <= gGlobalOptions proc accessThreadLocalVar(p: BProc, s: PSym) = - if emulatedThreadVars() and not p.ThreadVarAccessed: + if emulatedThreadVars() and not p.threadVarAccessed: p.threadVarAccessed = true p.module.usesThreadVars = true appf(p.procSec(cpsLocals), "\tNimThreadVars* NimTV;$n") diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index f1e824e14..79f10b981 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -246,7 +246,7 @@ proc ccgIntroducedPtr(s: PSym): bool = assert skResult != s.kind if tfByRef in pt.flags: return true elif tfByCopy in pt.flags: return false - case pt.Kind + case pt.kind of tyObject: if (optByRef in s.options) or (getSize(pt) > platform.floatSize * 2): result = true # requested anyway @@ -305,7 +305,7 @@ proc genProcParams(m: BModule, t: PType, rettype, params: var PRope, var arr = param.typ if arr.kind == tyVar: arr = arr.sons[0] var j = 0 - while arr.Kind in {tyOpenArray, tyVarargs}: + while arr.kind in {tyOpenArray, tyVarargs}: # this fixes the 'sort' bug: if param.typ.kind == tyVar: param.loc.s = OnUnknown # need to pass hidden parameter: @@ -344,7 +344,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope = "NI", "NI8", "NI16", "NI32", "NI64", "NF", "NF32", "NF64", "NF128", "NU", "NU8", "NU16", "NU32", "NU64",] - case typ.Kind + case typ.kind of tyPointer: result = typeNameOrLiteral(typ, "void*") of tyEnum: @@ -367,7 +367,7 @@ proc getSimpleTypeDesc(m: BModule, typ: PType): PRope = of tyChar: result = typeNameOrLiteral(typ, "NIM_CHAR") of tyNil: result = typeNameOrLiteral(typ, "0") of tyInt..tyUInt64: - result = typeNameOrLiteral(typ, NumericalTypeToStr[typ.Kind]) + result = typeNameOrLiteral(typ, NumericalTypeToStr[typ.kind]) of tyRange: result = getSimpleTypeDesc(m, typ.sons[0]) else: result = nil @@ -509,14 +509,14 @@ proc getTypeDescAux(m: BModule, typ: PType, check: var TIntSet): PRope = # XXX: this BUG is hard to fix -> we need to introduce helper structs, # but determining when this needs to be done is hard. We should split # C type generation into an analysis and a code generation phase somehow. - case t.Kind + case t.kind of tyRef, tyPtr, tyVar: et = getUniqueType(t.sons[0]) if et.kind in {tyArrayConstr, tyArray, tyOpenArray, tyVarargs}: # this is correct! sets have no proper base type, so we treat # ``var set[char]`` in `getParamTypeDesc` et = getUniqueType(elemType(et)) - case et.Kind + case et.kind of tyObject, tyTuple: # no restriction! We have a forward declaration for structs name = getTypeForward(m, et) diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 97965def0..c74f0807d 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -75,12 +75,12 @@ proc isSimpleConst(typ: PType): bool = proc useStringh(m: BModule) = if not m.includesStringh: m.includesStringh = true - discard lists.IncludeStr(m.headerFiles, "") + discard lists.includeStr(m.headerFiles, "") proc useHeader(m: BModule, sym: PSym) = - if lfHeader in sym.loc.Flags: + if lfHeader in sym.loc.flags: assert(sym.annex != nil) - discard lists.IncludeStr(m.headerFiles, getStr(sym.annex.path)) + discard lists.includeStr(m.headerFiles, getStr(sym.annex.path)) proc cgsym(m: BModule, name: string): PRope @@ -279,11 +279,11 @@ proc genLineDir(p: BProc, t: PNode) = if optEmbedOrigSrc in gGlobalOptions: app(p.s(cpsStmts), con(~"//", t.info.sourceLine, rnl)) genCLineDir(p.s(cpsStmts), t.info.toFullPath, line) - if ({optStackTrace, optEndb} * p.Options == {optStackTrace, optEndb}) and + if ({optStackTrace, optEndb} * p.options == {optStackTrace, optEndb}) and (p.prc == nil or sfPure notin p.prc.flags): linefmt(p, cpsStmts, "#endb($1, $2);$n", line.toRope, makeCString(toFilename(t.info))) - elif ({optLineTrace, optStackTrace} * p.Options == + elif ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and (p.prc == nil or sfPure notin p.prc.flags): linefmt(p, cpsStmts, "nimln($1, $2);$n", @@ -724,7 +724,7 @@ proc generateHeaders(m: BModule) = appf(m.s[cfsHeaders], "$N#include \"$1\"$N", [toRope(it.data)]) else: appf(m.s[cfsHeaders], "$N#include $1$N", [toRope(it.data)]) - it = PStrEntry(it.Next) + it = PStrEntry(it.next) proc retIsNotVoid(s: PSym): bool = result = (s.typ.sons[0] != nil) and not isInvalidReturnType(s.typ.sons[0]) @@ -784,7 +784,7 @@ proc genProcAux(m: BModule, prc: PSym) = genStmts(p, prc.getBody) # modifies p.locals, p.init, etc. var generatedProc: PRope if sfPure in prc.flags: - if hasNakedDeclspec in extccomp.CC[extccomp.ccompiler].props: + if hasNakedDeclspec in extccomp.CC[extccomp.cCompiler].props: header = con("__declspec(naked) ", header) generatedProc = rfmt(nil, "$N$1 {$n$2$3$4}$N$N", header, p.s(cpsLocals), p.s(cpsInit), p.s(cpsStmts)) @@ -811,8 +811,8 @@ proc genProcAux(m: BModule, prc: PSym) = proc genProcPrototype(m: BModule, sym: PSym) = useHeader(m, sym) - if lfNoDecl in sym.loc.Flags: return - if lfDynamicLib in sym.loc.Flags: + if lfNoDecl in sym.loc.flags: return + if lfDynamicLib in sym.loc.flags: if getModule(sym).id != m.module.id and not containsOrIncl(m.declaredThings, sym.id): app(m.s[cfsVars], rfmt(nil, "extern $1 $2;$n", @@ -832,7 +832,7 @@ proc genProcNoForward(m: BModule, prc: PSym) = discard cgsym(m, prc.name.s) return genProcPrototype(m, prc) - if lfNoDecl in prc.loc.Flags: nil + if lfNoDecl in prc.loc.flags: nil elif prc.typ.callConv == ccInline: # We add inline procs to the calling module to enable C based inlining. # This also means that a check with ``q.declaredThings`` is wrong, we need @@ -854,7 +854,7 @@ proc requestConstImpl(p: BProc, sym: PSym) = useHeader(m, sym) if sym.loc.k == locNone: fillLoc(sym.loc, locData, sym.typ, mangleName(sym), OnUnknown) - if lfNoDecl in sym.loc.Flags: return + if lfNoDecl in sym.loc.flags: return # declare implementation: var q = findPendingModule(m, sym) if q != nil and not containsOrIncl(q.declaredThings, sym.id): @@ -879,7 +879,7 @@ proc genProc(m: BModule, prc: PSym) = else: genProcNoForward(m, prc) if {sfExportc, sfCompilerProc} * prc.flags == {sfExportc} and - generatedHeader != nil and lfNoDecl notin prc.loc.Flags: + generatedHeader != nil and lfNoDecl notin prc.loc.flags: genProcPrototype(generatedHeader, prc) if prc.typ.callConv == ccInline: if not containsOrIncl(generatedHeader.declaredThings, prc.id): @@ -889,7 +889,7 @@ proc genVarPrototypeAux(m: BModule, sym: PSym) = assert(sfGlobal in sym.flags) useHeader(m, sym) fillLoc(sym.loc, locGlobalVar, sym.typ, mangleName(sym), OnHeap) - if (lfNoDecl in sym.loc.Flags) or containsOrIncl(m.declaredThings, sym.id): + if (lfNoDecl in sym.loc.flags) or containsOrIncl(m.declaredThings, sym.id): return if sym.owner.id != m.module.id: # else we already have the symbol generated! @@ -930,7 +930,7 @@ proc getCopyright(cfilenoext: string): PRope = "; Command for LLVM compiler:$n $5$n", [toRope(VersionAsString), toRope(platform.OS[targetOS].name), toRope(platform.CPU[targetCPU].name), - toRope(extccomp.CC[extccomp.ccompiler].name), + toRope(extccomp.CC[extccomp.cCompiler].name), toRope(getCompileCFileCmd(cfilenoext))]) proc getFileHeader(cfilenoext: string): PRope = @@ -990,7 +990,7 @@ proc genMainProc(m: BModule) = else: nimMain = WinNimDllMain otherMain = WinCDllMain - discard lists.IncludeStr(m.headerFiles, "") + discard lists.includeStr(m.headerFiles, "") elif optGenDynLib in gGlobalOptions: nimMain = PosixNimDllMain otherMain = PosixCDllMain @@ -1053,11 +1053,11 @@ proc genInitCode(m: BModule) = app(prc, m.postInitProc.s(cpsLocals)) app(prc, genSectionEnd(cpsLocals)) - if optStackTrace in m.initProc.options and not m.FrameDeclared: + if optStackTrace in m.initProc.options and not m.frameDeclared: # BUT: the generated init code might depend on a current frame, so # declare it nevertheless: - m.FrameDeclared = true - if not m.PreventStackTrace: + m.frameDeclared = true + if not m.preventStackTrace: var procname = cstringLit(m.initProc, prc, m.module.name.s) app(prc, initFrame(m.initProc, procname, m.module.info.quotedFilename)) else: @@ -1074,7 +1074,7 @@ proc genInitCode(m: BModule) = app(prc, m.initProc.s(cpsStmts)) app(prc, m.postInitProc.s(cpsStmts)) app(prc, genSectionEnd(cpsStmts)) - if optStackTrace in m.initProc.options and not m.PreventStackTrace: + if optStackTrace in m.initProc.options and not m.preventStackTrace: app(prc, deinitFrame(m.initProc)) app(prc, deinitGCFrame(m.initProc)) appf(prc, "}$N$N") @@ -1148,7 +1148,7 @@ proc rawNewModule(module: PSym, filename: string): BModule = # no line tracing for the init sections of the system module so that we # don't generate a TFrame which can confuse the stack botton initialization: if sfSystemModule in module.flags: - result.PreventStackTrace = true + result.preventStackTrace = true excl(result.preInitProc.options, optStackTrace) excl(result.postInitProc.options, optStackTrace) @@ -1171,7 +1171,7 @@ proc resetModule*(m: var BModule) = m.forwardedProcs = @[] m.typeNodesName = getTempName() m.nimTypesName = getTempName() - m.PreventStackTrace = sfSystemModule in m.module.flags + m.preventStackTrace = sfSystemModule in m.module.flags nullify m.s m.usesThreadVars = false m.typeNodes = 0 @@ -1275,7 +1275,7 @@ proc shouldRecompile(code: PRope, cfile, cfilenoext: string): bool = if optForceFullMake notin gGlobalOptions: var objFile = toObjFile(cfilenoext) if writeRopeIfNotEqual(code, cfile): return - if existsFile(objFile) and os.FileNewer(objFile, cfile): result = false + if existsFile(objFile) and os.fileNewer(objFile, cfile): result = false else: writeRope(code, cfile) diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim index 58584552d..d72f9fa4d 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -61,8 +61,8 @@ type TCProc{.final.} = object # represents C proc that is currently generated prc*: PSym # the Nimrod proc that this C proc belongs to - BeforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed - ThreadVarAccessed*: bool # true if the proc already accessed some threadvar + beforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed + threadVarAccessed*: bool # true if the proc already accessed some threadvar nestedTryStmts*: seq[PNode] # in how many nested try statements we are # (the vars must be volatile then) inExceptBlock*: int # are we currently inside an except block? @@ -86,9 +86,9 @@ type module*: PSym filename*: string s*: TCFileSections # sections of the C file - PreventStackTrace*: bool # true if stack traces need to be prevented + preventStackTrace*: bool # true if stack traces need to be prevented usesThreadVars*: bool # true if the module uses a thread var - FrameDeclared*: bool # hack for ROD support so that we don't declare + frameDeclared*: bool # hack for ROD support so that we don't declare # a frame var twice in an init proc isHeaderFile*: bool # C source file is the header file includesStringh*: bool # C source file already includes ```` diff --git a/compiler/commands.nim b/compiler/commands.nim index 96fa34ae0..03c71ff5a 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -35,7 +35,7 @@ const AdvancedUsage = slurp"doc/advopt.txt".replace("//", "") proc getCommandLineDesc(): string = - result = (HelpMessage % [VersionAsString, platform.os[platform.hostOS].name, + result = (HelpMessage % [VersionAsString, platform.OS[platform.hostOS].name, CPU[platform.hostCPU].name]) & Usage proc helpOnError(pass: TCmdLinePass) = @@ -46,14 +46,14 @@ proc helpOnError(pass: TCmdLinePass) = proc writeAdvancedUsage(pass: TCmdLinePass) = if pass == passCmd1: msgWriteln(`%`(HelpMessage, [VersionAsString, - platform.os[platform.hostOS].name, + platform.OS[platform.hostOS].name, CPU[platform.hostCPU].name]) & AdvancedUsage) quit(0) proc writeVersionInfo(pass: TCmdLinePass) = if pass == passCmd1: msgWriteln(`%`(HelpMessage, [VersionAsString, - platform.os[platform.hostOS].name, + platform.OS[platform.hostOS].name, CPU[platform.hostCPU].name])) quit(0) @@ -256,8 +256,8 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "excludepath": expectArg(switch, arg, pass, info) let path = processPath(arg) - lists.ExcludeStr(options.searchPaths, path) - lists.ExcludeStr(options.lazyPaths, path) + lists.excludeStr(options.searchPaths, path) + lists.excludeStr(options.lazyPaths, path) of "nimcache": expectArg(switch, arg, pass, info) options.nimcacheDir = processPath(arg) @@ -425,19 +425,19 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "os": expectArg(switch, arg, pass, info) if pass in {passCmd1, passPP}: - theOS = platform.NameToOS(arg) + theOS = platform.nameToOS(arg) if theOS == osNone: localError(info, errUnknownOS, arg) elif theOS != platform.hostOS: setTarget(theOS, targetCPU) - condsyms.InitDefines() + condsyms.initDefines() of "cpu": expectArg(switch, arg, pass, info) if pass in {passCmd1, passPP}: - cpu = platform.NameToCPU(arg) + cpu = platform.nameToCPU(arg) if cpu == cpuNone: localError(info, errUnknownCPU, arg) elif cpu != platform.hostCPU: setTarget(targetOS, cpu) - condsyms.InitDefines() + condsyms.initDefines() of "run", "r": expectNoArg(switch, arg, pass, info) incl(gGlobalOptions, optRun) diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index e74ab5853..c79fda13e 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -83,6 +83,6 @@ proc initDefines*() = defineSymbol("cpu" & $CPU[targetCPU].bit) defineSymbol(normalize(EndianToStr[CPU[targetCPU].endian])) defineSymbol(CPU[targetCPU].name) - defineSymbol(platform.os[targetOS].name) + defineSymbol(platform.OS[targetOS].name) if platform.OS[targetOS].props.contains(ospLacksThreadVars): defineSymbol("emulatedthreadvars") diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 031b7d429..343f415b3 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -46,13 +46,13 @@ proc parseRst(text, filename: string, line, column: int, hasToc: var bool, rstOptions: TRstParseOptions): PRstNode = result = rstParse(text, filename, line, column, hasToc, rstOptions, - options.FindFile, compilerMsgHandler) + options.findFile, compilerMsgHandler) proc newDocumentor*(filename: string, config: PStringTable): PDoc = new(result) initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), options.gConfigVars, filename, {roSupportRawDirective}, - options.FindFile, compilerMsgHandler) + options.findFile, compilerMsgHandler) result.id = 100 proc dispA(dest: var PRope, xml, tex: string, args: openArray[PRope]) = diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim index afcba8b4b..95778941e 100644 --- a/compiler/extccomp.nim +++ b/compiler/extccomp.nim @@ -335,8 +335,8 @@ proc getConfigVar(c: TSystemCC, suffix: string): string = # for niminst support if (platform.hostOS != targetOS or platform.hostCPU != targetCPU) and optCompileOnly notin gGlobalOptions: - let fullCCname = platform.cpu[targetCPU].name & '.' & - platform.os[targetOS].name & '.' & + let fullCCname = platform.CPU[targetCPU].name & '.' & + platform.OS[targetOS].name & '.' & CC[c].name & suffix result = getConfigVar(fullCCname) if result.len == 0: @@ -406,7 +406,7 @@ proc execExternalProgram*(cmd: string) = proc generateScript(projectFile: string, script: PRope) = let (dir, name, ext) = splitFile(projectFile) writeRope(script, dir / addFileExt("compile_" & name, - platform.os[targetOS].scriptExt)) + platform.OS[targetOS].scriptExt)) proc getOptSpeed(c: TSystemCC): string = result = getConfigVar(c, ".options.speed") @@ -517,7 +517,7 @@ proc footprint(filename: string): TCrc32 = result = crcFromFile(filename) >< platform.OS[targetOS].name >< platform.CPU[targetCPU].name >< - extccomp.CC[extccomp.ccompiler].name >< + extccomp.CC[extccomp.cCompiler].name >< getCompileCFileCmd(filename, true) proc externalFileChanged(filename: string): bool = @@ -608,10 +608,10 @@ proc callCCompiler*(projectfile: string) = else: buildgui = "" var exefile: string if optGenDynLib in gGlobalOptions: - exefile = platform.os[targetOS].dllFrmt % splitFile(projectfile).name + exefile = platform.OS[targetOS].dllFrmt % splitFile(projectfile).name builddll = CC[c].buildDll else: - exefile = splitFile(projectfile).name & platform.os[targetOS].exeExt + exefile = splitFile(projectfile).name & platform.OS[targetOS].exeExt builddll = "" if options.outFile.len > 0: exefile = options.outFile diff --git a/compiler/filter_tmpl.nim b/compiler/filter_tmpl.nim index 749d38b34..806754122 100644 --- a/compiler/filter_tmpl.nim +++ b/compiler/filter_tmpl.nim @@ -27,7 +27,7 @@ type indent, emitPar: int x: string # the current input line outp: PLLStream # the ouput will be parsed by pnimsyn - subsChar, NimDirective: char + subsChar, nimDirective: char emit, conc, toStr: string curly, bracket, par: int pendingExprLine: bool @@ -67,9 +67,9 @@ proc parseLine(p: var TTmplParser) = keyw: string j = 0 while p.x[j] == ' ': inc(j) - if (p.x[0] == p.NimDirective) and (p.x[0 + 1] == '!'): + if (p.x[0] == p.nimDirective) and (p.x[0 + 1] == '!'): newLine(p) - elif (p.x[j] == p.NimDirective): + elif (p.x[j] == p.nimDirective): newLine(p) inc(j) while p.x[j] == ' ': inc(j) diff --git a/compiler/importer.nim b/compiler/importer.nim index 24779f2ae..078a90c98 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -63,8 +63,8 @@ proc rawImportSymbol(c: PContext, s: PSym) = if check != nil and check.id != s.id: if s.kind notin OverloadableSyms: # s and check need to be qualified: - incl(c.AmbiguousSymbols, s.id) - incl(c.AmbiguousSymbols, check.id) + incl(c.ambiguousSymbols, s.id) + incl(c.ambiguousSymbols, check.id) # thanks to 'export' feature, it could be we import the same symbol from # multiple sources, so we need to call 'StrTableAdd' here: strTableAdd(c.importTable.symbols, s) @@ -73,7 +73,7 @@ proc rawImportSymbol(c: PContext, s: PSym) = if etyp.kind in {tyBool, tyEnum} and sfPure notin s.flags: for j in countup(0, sonsLen(etyp.n) - 1): var e = etyp.n.sons[j].sym - if e.Kind != skEnumField: + if e.kind != skEnumField: internalError(s.info, "rawImportSymbol") # BUGFIX: because of aliases for enums the symbol may already # have been put into the symbol table @@ -99,16 +99,16 @@ proc importSymbol(c: PContext, n: PNode, fromMod: PSym) = localError(n.info, errUndeclaredIdentifier, ident.s) else: if s.kind == skStub: loadStub(s) - if s.Kind notin ExportableSymKinds: + if s.kind notin ExportableSymKinds: internalError(n.info, "importSymbol: 2") # for an enumeration we have to add all identifiers - case s.Kind + case s.kind of skProc, skMethod, skIterator, skMacro, skTemplate, skConverter: # for a overloadable syms add all overloaded routines var it: TIdentIter var e = initIdentIter(it, fromMod.tab, s.name) while e != nil: - if e.name.id != s.Name.id: internalError(n.info, "importSymbol: 3") + if e.name.id != s.name.id: internalError(n.info, "importSymbol: 3") rawImportSymbol(c, e) e = nextIdentIter(it, fromMod.tab) else: rawImportSymbol(c, s) @@ -119,7 +119,7 @@ proc importAllSymbolsExcept(c: PContext, fromMod: PSym, exceptSet: TIntSet) = while s != nil: if s.kind != skModule: if s.kind != skEnumField: - if s.Kind notin ExportableSymKinds: + if s.kind notin ExportableSymKinds: internalError(s.info, "importAllSymbols: " & $s.kind) if exceptSet.empty or s.name.id notin exceptSet: rawImportSymbol(c, s) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 1ba40f95d..c6b0b194f 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -64,7 +64,7 @@ type options: TOptions module: BModule g: PGlobals - BeforeRetNeeded: bool + beforeRetNeeded: bool target: TTarget # duplicated here for faster dispatching unique: int # for temp identifier generation blocks: seq[TBlock] @@ -485,14 +485,14 @@ proc arith(p: PProc, n: PNode, r: var TCompRes, op: TMagic) = proc genLineDir(p: PProc, n: PNode) = let line = toLinenumber(n.info) - if optLineDir in p.Options: + if optLineDir in p.options: appf(p.body, "// line $2 \"$1\"$n" | "-- line $2 \"$1\"$n", [toRope(toFilename(n.info)), toRope(line)]) - if {optStackTrace, optEndb} * p.Options == {optStackTrace, optEndb} and + if {optStackTrace, optEndb} * p.options == {optStackTrace, optEndb} and ((p.prc == nil) or sfPure notin p.prc.flags): useMagic(p, "endb") appf(p.body, "endb($1);$n", [toRope(line)]) - elif ({optLineTrace, optStackTrace} * p.Options == + elif ({optLineTrace, optStackTrace} * p.options == {optLineTrace, optStackTrace}) and ((p.prc == nil) or not (sfPure in p.prc.flags)): appf(p.body, "F.line = $1;$n", [toRope(line)]) @@ -555,7 +555,7 @@ proc genTry(p: PProc, n: PNode, r: var TCompRes) = "var $1 = {prev: excHandler, exc: null};$nexcHandler = $1;$n" | "local $1 = pcall(", [safePoint]) - if optStackTrace in p.Options: app(p.body, "framePtr = F;" & tnl) + if optStackTrace in p.options: app(p.body, "framePtr = F;" & tnl) appf(p.body, "try {$n" | "function()$n") var length = sonsLen(n) var a: TCompRes @@ -747,7 +747,7 @@ proc genAsmStmt(p: PProc, n: PNode) = genLineDir(p, n) assert(n.kind == nkAsmStmt) for i in countup(0, sonsLen(n) - 1): - case n.sons[i].Kind + case n.sons[i].kind of nkStrLit..nkTripleStrLit: app(p.body, n.sons[i].strVal) of nkSym: app(p.body, mangleName(n.sons[i].sym)) else: internalError(n.sons[i].info, "jsgen: genAsmStmt()") @@ -1298,15 +1298,15 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) = of mSwap: genSwap(p, n) of mUnaryLt: # XXX: range checking? - if not (optOverflowCheck in p.Options): unaryExpr(p, n, r, "", "$1 - 1") + if not (optOverflowCheck in p.options): unaryExpr(p, n, r, "", "$1 - 1") else: unaryExpr(p, n, r, "subInt", "subInt($1, 1)") of mPred: # XXX: range checking? - if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 - $2") + if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 - $2") else: binaryExpr(p, n, r, "subInt", "subInt($1, $2)") of mSucc: # XXX: range checking? - if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 - $2") + if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 - $2") else: binaryExpr(p, n, r, "addInt", "addInt($1, $2)") of mAppendStrCh: binaryExpr(p, n, r, "addChar", "addChar($1, $2)") of mAppendStrStr: @@ -1335,10 +1335,10 @@ proc genMagic(p: PProc, n: PNode, r: var TCompRes) = else: unaryExpr(p, n, r, "", "($1.length-1)") of mInc: - if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 += $2") + if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 += $2") else: binaryExpr(p, n, r, "addInt", "$1 = addInt($1, $2)") of ast.mDec: - if not (optOverflowCheck in p.Options): binaryExpr(p, n, r, "", "$1 -= $2") + if not (optOverflowCheck in p.options): binaryExpr(p, n, r, "", "$1 -= $2") else: binaryExpr(p, n, r, "subInt", "$1 = subInt($1, $2)") of mSetLengthStr: binaryExpr(p, n, r, "", "$1.length = ($2)-1") of mSetLengthSeq: binaryExpr(p, n, r, "", "$1.length = $2") @@ -1470,7 +1470,7 @@ proc convCStrToStr(p: PProc, n: PNode, r: var TCompRes) = proc genReturnStmt(p: PProc, n: PNode) = if p.procDef == nil: internalError(n.info, "genReturnStmt") - p.BeforeRetNeeded = true + p.beforeRetNeeded = true if (n.sons[0].kind != nkEmpty): genStmt(p, n.sons[0]) else: diff --git a/compiler/jstypes.nim b/compiler/jstypes.nim index cbe87bbc1..6d14076e1 100644 --- a/compiler/jstypes.nim +++ b/compiler/jstypes.nim @@ -119,7 +119,7 @@ proc genTypeInfo(p: PProc, typ: PType): PRope = var t = typ if t.kind == tyGenericInst: t = lastSon(t) result = ropef("NTI$1", [toRope(t.id)]) - if containsOrIncl(p.g.TypeInfoGenerated, t.id): return + if containsOrIncl(p.g.typeInfoGenerated, t.id): return case t.kind of tyDistinct: result = genTypeInfo(p, typ.sons[0]) diff --git a/compiler/lexer.nim b/compiler/lexer.nim index a258765cf..93aea7f61 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -180,18 +180,18 @@ proc printTok*(tok: TToken) = var dummyIdent: PIdent proc initToken*(L: var TToken) = - L.TokType = tkInvalid + L.tokType = tkInvalid L.iNumber = 0 - L.Indent = 0 + L.indent = 0 L.literal = "" L.fNumber = 0.0 L.base = base10 L.ident = dummyIdent proc fillToken(L: var TToken) = - L.TokType = tkInvalid + L.tokType = tkInvalid L.iNumber = 0 - L.Indent = 0 + L.indent = 0 setLen(L.literal, 0) L.fNumber = 0.0 L.base = base10 @@ -201,24 +201,24 @@ proc openLexer(lex: var TLexer, fileIdx: int32, inputstream: PLLStream) = openBaseLexer(lex, inputstream) lex.fileIdx = fileidx lex.indentAhead = - 1 - inc(lex.Linenumber, inputstream.lineOffset) + inc(lex.lineNumber, inputstream.lineOffset) proc closeLexer(lex: var TLexer) = - inc(gLinesCompiled, lex.LineNumber) + inc(gLinesCompiled, lex.lineNumber) closeBaseLexer(lex) proc getColumn(L: TLexer): int = - result = getColNumber(L, L.bufPos) + result = getColNumber(L, L.bufpos) proc getLineInfo(L: TLexer): TLineInfo = - result = newLineInfo(L.fileIdx, L.linenumber, getColNumber(L, L.bufpos)) + result = newLineInfo(L.fileIdx, L.lineNumber, getColNumber(L, L.bufpos)) proc lexMessage(L: TLexer, msg: TMsgKind, arg = "") = - msgs.Message(getLineInfo(L), msg, arg) + msgs.message(getLineInfo(L), msg, arg) proc lexMessagePos(L: var TLexer, msg: TMsgKind, pos: int, arg = "") = - var info = newLineInfo(L.fileIdx, L.linenumber, pos - L.lineStart) - msgs.Message(info, msg, arg) + var info = newLineInfo(L.fileIdx, L.lineNumber, pos - L.lineStart) + msgs.message(info, msg, arg) proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) = var pos = L.bufpos # use registers for pos, buf @@ -235,7 +235,7 @@ proc matchUnderscoreChars(L: var TLexer, tok: var TToken, chars: TCharSet) = break add(tok.literal, '_') inc(pos) - L.bufPos = pos + L.bufpos = pos proc matchTwoChars(L: TLexer, first: char, second: TCharSet): bool = result = (L.buf[L.bufpos] == first) and (L.buf[L.bufpos + 1] in second) @@ -408,7 +408,7 @@ proc getNumber(L: var TLexer): TToken = else: internalError(getLineInfo(L), "getNumber") elif isFloatLiteral(result.literal) or (result.tokType == tkFloat32Lit) or (result.tokType == tkFloat64Lit): - result.fnumber = parseFloat(result.literal) + result.fNumber = parseFloat(result.literal) if result.tokType == tkIntLit: result.tokType = tkFloatLit else: result.iNumber = parseBiggestInt(result.literal) @@ -445,7 +445,7 @@ proc getEscapedChar(L: var TLexer, tok: var TToken) = inc(L.bufpos) # skip '\' case L.buf[L.bufpos] of 'n', 'N': - if tok.toktype == tkCharLit: lexMessage(L, errNnotAllowedInCharacter) + if tok.tokType == tkCharLit: lexMessage(L, errNnotAllowedInCharacter) add(tok.literal, tnl) inc(L.bufpos) of 'r', 'R', 'c', 'C': @@ -514,16 +514,16 @@ proc handleCRLF(L: var TLexer, pos: int): int = case L.buf[pos] of CR: registerLine() - result = nimlexbase.HandleCR(L, pos) + result = nimlexbase.handleCR(L, pos) of LF: registerLine() - result = nimlexbase.HandleLF(L, pos) + result = nimlexbase.handleLF(L, pos) else: result = pos proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = - var pos = L.bufPos + 1 # skip " + var pos = L.bufpos + 1 # skip " var buf = L.buf # put `buf` in a register - var line = L.linenumber # save linenumber for better error message + var line = L.lineNumber # save linenumber for better error message if buf[pos] == '\"' and buf[pos+1] == '\"': tok.tokType = tkTripleStrLit # long string literal: inc(pos, 2) # skip "" @@ -544,10 +544,10 @@ proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = buf = L.buf add(tok.literal, tnl) of nimlexbase.EndOfFile: - var line2 = L.linenumber - L.LineNumber = line + var line2 = L.lineNumber + L.lineNumber = line lexMessagePos(L, errClosingTripleQuoteExpected, L.lineStart) - L.LineNumber = line2 + L.lineNumber = line2 break else: add(tok.literal, buf[pos]) @@ -569,9 +569,9 @@ proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = lexMessage(L, errClosingQuoteExpected) break elif (c == '\\') and not rawMode: - L.bufPos = pos + L.bufpos = pos getEscapedChar(L, tok) - pos = L.bufPos + pos = L.bufpos else: add(tok.literal, c) inc(pos) @@ -707,7 +707,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = tok.indent = -1 skip(L, tok) var c = L.buf[L.bufpos] - tok.line = L.linenumber + tok.line = L.lineNumber tok.col = getColNumber(L, L.bufpos) if c in SymStartChars - {'r', 'R', 'l'}: getSymbol(L, tok) @@ -724,7 +724,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = else: getOperator(L, tok) of ',': - tok.toktype = tkComma + tok.tokType = tkComma inc(L.bufpos) of 'l': # if we parsed exactly one character and its a small L (l), this @@ -733,55 +733,55 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = lexMessage(L, warnSmallLshouldNotBeUsed) getSymbol(L, tok) of 'r', 'R': - if L.buf[L.bufPos + 1] == '\"': - inc(L.bufPos) + if L.buf[L.bufpos + 1] == '\"': + inc(L.bufpos) getString(L, tok, true) else: getSymbol(L, tok) of '(': inc(L.bufpos) - if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': - tok.toktype = tkParDotLe + if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.': + tok.tokType = tkParDotLe inc(L.bufpos) else: - tok.toktype = tkParLe + tok.tokType = tkParLe of ')': - tok.toktype = tkParRi + tok.tokType = tkParRi inc(L.bufpos) of '[': inc(L.bufpos) - if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': - tok.toktype = tkBracketDotLe + if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.': + tok.tokType = tkBracketDotLe inc(L.bufpos) else: - tok.toktype = tkBracketLe + tok.tokType = tkBracketLe of ']': - tok.toktype = tkBracketRi + tok.tokType = tkBracketRi inc(L.bufpos) of '.': - if L.buf[L.bufPos+1] == ']': + if L.buf[L.bufpos+1] == ']': tok.tokType = tkBracketDotRi inc(L.bufpos, 2) - elif L.buf[L.bufPos+1] == '}': + elif L.buf[L.bufpos+1] == '}': tok.tokType = tkCurlyDotRi inc(L.bufpos, 2) - elif L.buf[L.bufPos+1] == ')': + elif L.buf[L.bufpos+1] == ')': tok.tokType = tkParDotRi inc(L.bufpos, 2) else: getOperator(L, tok) of '{': inc(L.bufpos) - if L.buf[L.bufPos] == '.' and L.buf[L.bufPos+1] != '.': - tok.toktype = tkCurlyDotLe + if L.buf[L.bufpos] == '.' and L.buf[L.bufpos+1] != '.': + tok.tokType = tkCurlyDotLe inc(L.bufpos) else: - tok.toktype = tkCurlyLe + tok.tokType = tkCurlyLe of '}': - tok.toktype = tkCurlyRi + tok.tokType = tkCurlyRi inc(L.bufpos) of ';': - tok.toktype = tkSemiColon + tok.tokType = tkSemiColon inc(L.bufpos) of '`': tok.tokType = tkAccent @@ -804,7 +804,7 @@ proc rawGetTok(L: var TLexer, tok: var TToken) = if c in OpChars: getOperator(L, tok) elif c == nimlexbase.EndOfFile: - tok.toktype = tkEof + tok.tokType = tkEof tok.indent = 0 else: tok.literal = $c diff --git a/compiler/lookups.nim b/compiler/lookups.nim index 379e00b0e..57c420d3b 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -135,14 +135,14 @@ proc wrongRedefinition*(info: TLineInfo, s: string) = proc addDecl*(c: PContext, sym: PSym) = if c.currentScope.addUniqueSym(sym) == Failure: - wrongRedefinition(sym.info, sym.Name.s) + wrongRedefinition(sym.info, sym.name.s) proc addPrelimDecl*(c: PContext, sym: PSym) = discard c.currentScope.addUniqueSym(sym) proc addDeclAt*(scope: PScope, sym: PSym) = if scope.addUniqueSym(sym) == Failure: - wrongRedefinition(sym.info, sym.Name.s) + wrongRedefinition(sym.info, sym.name.s) proc addInterfaceDeclAux(c: PContext, sym: PSym) = if sfExported in sym.flags: @@ -159,8 +159,8 @@ proc addOverloadableSymAt*(scope: PScope, fn: PSym) = internalError(fn.info, "addOverloadableSymAt") return var check = strTableGet(scope.symbols, fn.name) - if check != nil and check.Kind notin OverloadableSyms: - wrongRedefinition(fn.info, fn.Name.s) + if check != nil and check.kind notin OverloadableSyms: + wrongRedefinition(fn.info, fn.name.s) else: scope.addSym(fn) @@ -193,7 +193,7 @@ proc lookUp*(c: PContext, n: PNode): PSym = else: internalError(n.info, "lookUp") return - if contains(c.AmbiguousSymbols, result.id): + if contains(c.ambiguousSymbols, result.id): localError(n.info, errUseQualifier, result.name.s) if result.kind == skStub: loadStub(result) @@ -210,11 +210,11 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = localError(n.info, errUndeclaredIdentifier, ident.s) result = errorSym(c, n) elif checkAmbiguity in flags and result != nil and - contains(c.AmbiguousSymbols, result.id): + contains(c.ambiguousSymbols, result.id): localError(n.info, errUseQualifier, ident.s) of nkSym: result = n.sym - if checkAmbiguity in flags and contains(c.AmbiguousSymbols, result.id): + if checkAmbiguity in flags and contains(c.ambiguousSymbols, result.id): localError(n.info, errUseQualifier, n.sym.name.s) of nkDotExpr: result = nil diff --git a/compiler/magicsys.nim b/compiler/magicsys.nim index 281c642b7..b4f6e043d 100644 --- a/compiler/magicsys.nim +++ b/compiler/magicsys.nim @@ -134,7 +134,7 @@ proc addSonSkipIntLit*(father, son: PType) = proc setIntLitType*(result: PNode) = let i = result.intVal - case platform.IntSize + case platform.intSize of 8: result.typ = getIntLitType(result) of 4: if i >= low(int32) and i <= high(int32): diff --git a/compiler/main.nim b/compiler/main.nim index 3571e6a4e..4cea24f9d 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -18,7 +18,7 @@ import tables, docgen2, service, parser, modules, ccgutils, sigmatch, ropes, lists, pretty -from magicsys import SystemModule, resetSysTypes +from magicsys import systemModule, resetSysTypes const hasLLVM_Backend = false @@ -73,7 +73,7 @@ proc commandCompileToC = compileProject() cgenWriteModules() if gCmd != cmdRun: - extccomp.CallCCompiler(changeFileExt(gProjectFull, "")) + extccomp.callCCompiler(changeFileExt(gProjectFull, "")) if isServing: # caas will keep track only of the compilation commands diff --git a/compiler/modules.nim b/compiler/modules.nim index 1775599a9..6a1491682 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -164,7 +164,7 @@ proc importModule*(s: PSym, fileIdx: int32): PSym {.procvar.} = result = compileModule(fileIdx, {}) if optCaasEnabled in gGlobalOptions: addDep(s, fileIdx) if sfSystemModule in result.flags: - localError(result.info, errAttemptToRedefine, result.Name.s) + localError(result.info, errAttemptToRedefine, result.name.s) proc includeModule*(s: PSym, fileIdx: int32): PNode {.procvar.} = result = syntaxes.parseFile(fileIdx) @@ -180,7 +180,7 @@ proc `==^`(a, b: string): bool = result = false proc compileSystemModule* = - if magicsys.SystemModule == nil: + if magicsys.systemModule == nil: systemFileIdx = fileInfoIdx(options.libpath/"system.nim") discard compileModule(systemFileIdx, {sfSystemModule}) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index cdfbc3ece..cc76f857d 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -845,7 +845,7 @@ proc quotedFilename*(i: TLineInfo): PRope = internalAssert i.fileIndex >= 0 result = fileInfos[i.fileIndex].quotedName -ropes.ErrorHandler = proc (err: TRopesError, msg: string, useWarning: bool) = +ropes.errorHandler = proc (err: TRopesError, msg: string, useWarning: bool) = case err of rInvalidFormatStr: internalError("ropes: invalid format string: " & msg) diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim index fee96a54a..2bdfbe0b8 100644 --- a/compiler/nimconf.nim +++ b/compiler/nimconf.nim @@ -121,7 +121,7 @@ proc parseDirective(L: var TLexer, tok: var TToken) = of wEnd: doEnd(L, tok) of wWrite: ppGetTok(L, tok) - msgs.MsgWriteln(tokToStr(tok)) + msgs.msgWriteln(tokToStr(tok)) ppGetTok(L, tok) else: case tok.ident.s.normalize @@ -135,13 +135,13 @@ proc parseDirective(L: var TLexer, tok: var TToken) = ppGetTok(L, tok) var key = tokToStr(tok) ppGetTok(L, tok) - os.putEnv(key, tokToStr(tok) & os.getenv(key)) + os.putEnv(key, tokToStr(tok) & os.getEnv(key)) ppGetTok(L, tok) of "appendenv": ppGetTok(L, tok) var key = tokToStr(tok) ppGetTok(L, tok) - os.putEnv(key, os.getenv(key) & tokToStr(tok)) + os.putEnv(key, os.getEnv(key) & tokToStr(tok)) ppGetTok(L, tok) else: lexMessage(L, errInvalidDirectiveX, tokToStr(tok)) diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim index e6dcd8ce7..038573c35 100644 --- a/compiler/nimlexbase.nim +++ b/compiler/nimlexbase.nim @@ -42,7 +42,7 @@ type buf*: cstring bufLen*: int # length of buffer in characters stream*: PLLStream # we read from this stream - LineNumber*: int # the current line number + lineNumber*: int # the current line number # private data: sentinel*: int lineStart*: int # index of last line start in buffer @@ -80,7 +80,7 @@ proc fillBuffer(L: var TBaseLexer) = # we know here that pos == L.sentinel, but not if this proc # is called the first time by initBaseLexer() assert(L.sentinel < L.bufLen) - toCopy = L.BufLen - L.sentinel - 1 + toCopy = L.bufLen - L.sentinel - 1 assert(toCopy >= 0) if toCopy > 0: moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) @@ -104,8 +104,8 @@ proc fillBuffer(L: var TBaseLexer) = else: # rather than to give up here because the line is too long, # double the buffer's size and try again: - oldBufLen = L.BufLen - L.bufLen = L.BufLen * 2 + oldBufLen = L.bufLen + L.bufLen = L.bufLen * 2 L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) assert(L.bufLen - oldBufLen == oldBufLen) charsRead = llStreamRead(L.stream, addr(L.buf[oldBufLen]), @@ -128,14 +128,14 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int = proc handleCR(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == CR) - inc(L.linenumber) + inc(L.lineNumber) result = fillBaseLexer(L, pos) if L.buf[result] == LF: result = fillBaseLexer(L, result) proc handleLF(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == LF) - inc(L.linenumber) + inc(L.lineNumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; proc skipUTF8BOM(L: var TBaseLexer) = @@ -150,7 +150,7 @@ proc openBaseLexer(L: var TBaseLexer, inputstream: PLLStream, bufLen = 8192) = L.buf = cast[cstring](alloc(bufLen * chrSize)) L.sentinel = bufLen - 1 L.lineStart = 0 - L.linenumber = 1 # lines start at 1 + L.lineNumber = 1 # lines start at 1 L.stream = inputstream fillBuffer(L) skipUTF8BOM(L) diff --git a/compiler/nimrod.nim b/compiler/nimrod.nim index 60124e335..38d440ade 100644 --- a/compiler/nimrod.nim +++ b/compiler/nimrod.nim @@ -81,7 +81,7 @@ when defined(GC_setMaxPause): when compileOption("gc", "v2") or compileOption("gc", "refc"): # the new correct mark&sweet collector is too slow :-/ GC_disableMarkAndSweep() -condsyms.InitDefines() +condsyms.initDefines() when not defined(selftest): handleCmdLine() diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim index f24d3a356..d65618e0a 100644 --- a/compiler/nimsets.nim +++ b/compiler/nimsets.nim @@ -58,7 +58,7 @@ proc overlap(a, b: PNode): bool = else: result = sameValue(a, b) -proc SomeInSet(s: PNode, a, b: PNode): bool = +proc someInSet(s: PNode, a, b: PNode): bool = # checks if some element of a..b is in the set s if s.kind != nkCurly: internalError(s.info, "SomeInSet") diff --git a/compiler/options.nim b/compiler/options.nim index 640f70f28..f184deb69 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -254,11 +254,11 @@ proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = result = joinPath(subdir, tail) #echo "completeGeneratedFilePath(", f, ") = ", result -iterator iterSearchPath*(SearchPaths: TLinkedList): string = - var it = PStrEntry(SearchPaths.head) +iterator iterSearchPath*(searchPaths: TLinkedList): string = + var it = PStrEntry(searchPaths.head) while it != nil: yield it.data - it = PStrEntry(it.Next) + it = PStrEntry(it.next) proc rawFindFile(f: string): string = for it in iterSearchPath(searchPaths): @@ -274,7 +274,7 @@ proc rawFindFile2(f: string): string = if existsFile(result): bringToFront(lazyPaths, it) return result.canonicalizePath - it = PStrEntry(it.Next) + it = PStrEntry(it.next) result = "" proc findFile*(f: string): string {.procvar.} = diff --git a/compiler/parser.nim b/compiler/parser.nim index 49fdd5703..b3a4e6963 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -61,7 +61,7 @@ proc newIdentNodeP*(ident: PIdent, p: TParser): PNode proc expectIdentOrKeyw*(p: TParser) proc expectIdent*(p: TParser) proc parLineInfo*(p: TParser): TLineInfo -proc eat*(p: var TParser, TokType: TTokType) +proc eat*(p: var TParser, tokType: TTokType) proc skipInd*(p: var TParser) proc optPar*(p: var TParser) proc optInd*(p: var TParser, n: PNode) @@ -139,9 +139,9 @@ proc expectIdent(p: TParser) = if p.tok.tokType != tkSymbol: lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok)) -proc eat(p: var TParser, TokType: TTokType) = - if p.tok.TokType == TokType: getTok(p) - else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[TokType]) +proc eat(p: var TParser, tokType: TTokType) = + if p.tok.tokType == tokType: getTok(p) + else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType]) proc parLineInfo(p: TParser): TLineInfo = result = getLineInfo(p.lex, p.tok) @@ -1060,7 +1060,7 @@ proc parseExprStmt(p: var TParser): PNode = result = makeCall(result) getTok(p) skipComment(p, result) - if p.tok.TokType notin {tkOf, tkElif, tkElse, tkExcept}: + if p.tok.tokType notin {tkOf, tkElif, tkElse, tkExcept}: let body = parseStmt(p) addSon(result, newProcNode(nkDo, body.info, body)) while sameInd(p): @@ -1638,7 +1638,7 @@ proc parseTypeClass(p: var TParser): PNode = var args = newNode(nkArgList) addSon(result, args) addSon(args, p.parseTypeClassParam) - while p.tok.TokType == tkComma: + while p.tok.tokType == tkComma: getTok(p) addSon(args, p.parseTypeClassParam) if p.tok.tokType == tkCurlyDotLe and p.validInd: @@ -1818,7 +1818,7 @@ proc parseStmt(p: var TParser): PNode = if p.tok.indent > p.currInd: parMessage(p, errInvalidIndentation) break - if p.tok.toktype in {tkCurlyRi, tkParRi, tkCurlyDotRi, tkBracketRi}: + if p.tok.tokType in {tkCurlyRi, tkParRi, tkCurlyDotRi, tkBracketRi}: # XXX this ensures tnamedparamanonproc still compiles; # deprecate this syntax later break diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index b313e49f5..d9ed50cfe 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -209,13 +209,13 @@ proc getLib(c: PContext, kind: TLibKind, path: PNode): PLib = var it = PLib(c.libs.head) while it != nil: if it.kind == kind: - if trees.ExprStructuralEquivalent(it.path, path): return it + if trees.exprStructuralEquivalent(it.path, path): return it it = PLib(it.next) result = newLib(kind) result.path = path append(c.libs, result) if path.kind in {nkStrLit..nkTripleStrLit}: - result.isOverriden = options.isDynLibOverride(path.strVal) + result.isOverriden = options.isDynlibOverride(path.strVal) proc expectDynlibNode(c: PContext, n: PNode): PNode = if n.kind != nkExprColonExpr: @@ -505,11 +505,11 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, if key.kind == nkIdent: var userPragma = strTableGet(c.userPragmas, key.ident) if userPragma != nil: - inc c.InstCounter - if c.InstCounter > 100: + inc c.instCounter + if c.instCounter > 100: globalError(it.info, errRecursiveDependencyX, userPragma.name.s) pragma(c, sym, userPragma.ast, validPragmas) - dec c.InstCounter + dec c.instCounter else: var k = whichKeyword(key.ident) if k in validPragmas: @@ -547,7 +547,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, sym.typ.size = size of wNodecl: noVal(it) - incl(sym.loc.Flags, lfNoDecl) + incl(sym.loc.flags, lfNoDecl) of wPure, wNoStackFrame: noVal(it) if sym != nil: incl(sym.flags, sfPure) @@ -566,7 +566,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, of wCompileTime: noVal(it) incl(sym.flags, sfCompileTime) - incl(sym.loc.Flags, lfNoDecl) + incl(sym.loc.flags, lfNoDecl) of wGlobal: noVal(it) incl(sym.flags, sfGlobal) @@ -579,7 +579,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, addToLib(lib, sym) incl(sym.flags, sfImportc) incl(sym.loc.flags, lfHeader) - incl(sym.loc.Flags, lfNoDecl) + incl(sym.loc.flags, lfNoDecl) # implies nodecl, because otherwise header would not make sense if sym.loc.r == nil: sym.loc.r = toRope(sym.name.s) of wDestructor: @@ -735,7 +735,7 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, proc implictPragmas*(c: PContext, sym: PSym, n: PNode, validPragmas: TSpecialWords) = if sym != nil and sym.kind != skModule: - var it = POptionEntry(c.optionstack.head) + var it = POptionEntry(c.optionStack.head) while it != nil: let o = it.otherPragmas if not o.isNil: @@ -746,7 +746,7 @@ proc implictPragmas*(c: PContext, sym: PSym, n: PNode, if lfExportLib in sym.loc.flags and sfExportc notin sym.flags: localError(n.info, errDynlibRequiresExportc) - var lib = POptionEntry(c.optionstack.tail).dynlib + var lib = POptionEntry(c.optionStack.tail).dynlib if {lfDynamicLib, lfHeader} * sym.loc.flags == {} and sfImportc in sym.flags and lib != nil: incl(sym.loc.flags, lfDynamicLib) diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 54d47393e..3a5bfe197 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -20,7 +20,6 @@ const type TGen = object of TPassContext module*: PSym - checkExtern: bool PGen = ref TGen TSourceFile = object @@ -30,6 +29,7 @@ type var gSourceFiles: seq[TSourceFile] = @[] + gCheckExtern: bool rules: PStringTable proc loadFile(info: TLineInfo) = @@ -118,8 +118,7 @@ proc beautifyName(s: string, k: TSymKind): string = proc checkStyle*(info: TLineInfo, s: string, k: TSymKind) = let beau = beautifyName(s, k) if s != beau: - message(info, errGenerated, - "name does not adhere to naming convention; should be: " & beau) + message(info, errGenerated, "name should be: " & beau) const Letters = {'a'..'z', 'A'..'Z', '0'..'9', '\x80'..'\xFF', '_'} @@ -138,17 +137,18 @@ proc differ(line: string, a, b: int, x: string): bool = inc j return false -proc checkDef(c: PGen; n: PNode) = - if n.kind != nkSym: return - let s = n.sym - +proc checkDef*(n: PNode; s: PSym) = # operators stay as they are: if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return - if {sfImportc, sfExportc} * s.flags == {} or c.checkExtern: + if {sfImportc, sfExportc} * s.flags == {} or gCheckExtern: checkStyle(n.info, s.name.s, s.kind) +proc checkDef(c: PGen; n: PNode) = + if n.kind != nkSym: return + checkDef(n, n.sym) + proc checkUse*(n: PNode, s: PSym) = if n.info.fileIndex < 0: return # we simply convert it to what it looks like in the definition @@ -306,7 +306,7 @@ proc myOpen(module: PSym): PPassContext = var g: PGen new(g) g.module = module - g.checkExtern = options.getConfigVar("pretty.checkextern").normalize == "on" + gCheckExtern = options.getConfigVar("pretty.checkextern").normalize == "on" result = g if rules.isNil: rules = newStringTable(modeStyleInsensitive) diff --git a/compiler/procfind.nim b/compiler/procfind.nim index a59df1178..51bd7b937 100644 --- a/compiler/procfind.nim +++ b/compiler/procfind.nim @@ -35,13 +35,13 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym = # in the symbol table. If the parameter lists are exactly # the same the sym in the symbol table is returned, else nil. var it: TIdentIter - result = initIdentIter(it, scope.symbols, fn.Name) + result = initIdentIter(it, scope.symbols, fn.name) if isGenericRoutine(fn): # we simply check the AST; this is imprecise but nearly the best what # can be done; this doesn't work either though as type constraints are # not kept in the AST .. while result != nil: - if result.Kind == fn.kind and isGenericRoutine(result): + if result.kind == fn.kind and isGenericRoutine(result): let genR = result.ast.sons[genericParamsPos] let genF = fn.ast.sons[genericParamsPos] if exprStructuralEquivalent(genR, genF) and @@ -52,7 +52,7 @@ proc searchForProc*(c: PContext, scope: PScope, fn: PSym): PSym = result = nextIdentIter(it, scope.symbols) else: while result != nil: - if result.Kind == fn.kind and not isGenericRoutine(result): + if result.kind == fn.kind and not isGenericRoutine(result): case equalParams(result.typ.n, fn.typ.n) of paramsEqual: return diff --git a/compiler/rodread.nim b/compiler/rodread.nim index c3083852a..7a35f0c84 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -658,7 +658,7 @@ proc newRodReader(modfilename: string, crc: TCrc32, readerIndex: int): PRodReader = new(result) try: - result.memFile = memfiles.open(modfilename) + result.memfile = memfiles.open(modfilename) except EOS: return nil result.files = @[] @@ -673,7 +673,7 @@ proc newRodReader(modfilename: string, crc: TCrc32, initIdTable(r.syms) # we terminate the file explicitely with ``\0``, so the cast to `cstring` # is safe: - r.s = cast[cstring](r.memFile.mem) + r.s = cast[cstring](r.memfile.mem) if startsWith(r.s, "NIM:"): initIiTable(r.index.tab) initIiTable(r.imports.tab) # looks like a ROD file @@ -736,7 +736,7 @@ proc getReader(moduleId: int): PRodReader = # problems: for i in 0 .. 0: # quick error message for performance of 'compiles' built-in: - globalError(n.Info, errGenerated, "ambiguous call") + globalError(n.info, errGenerated, "ambiguous call") elif gErrorCounter == 0: # don't cascade errors var args = "(" @@ -178,7 +178,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode, add(args, typeToString(n.sons[i].typ)) add(args, ")") - localError(n.Info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [ + localError(n.info, errGenerated, msgKindToString(errAmbiguousCallXYZ) % [ getProcHeader(result.calleeSym), getProcHeader(alt.calleeSym), args]) diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 8f00d91c6..924224fee 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -160,7 +160,7 @@ proc newOptionEntry(): POptionEntry = proc newContext(module: PSym): PContext = new(result) - result.AmbiguousSymbols = initIntSet() + result.ambiguousSymbols = initIntSet() initLinkedList(result.optionStack) initLinkedList(result.libs) append(result.optionStack, newOptionEntry()) @@ -172,7 +172,7 @@ proc newContext(module: PSym): PContext = result.includedFiles = initIntSet() initStrTable(result.userPragmas) result.generics = @[] - result.UnknownIdents = initIntSet() + result.unknownIdents = initIntSet() proc inclSym(sq: var TSymSeq, s: PSym) = var L = len(sq) diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 46902e776..082ee7583 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -151,15 +151,15 @@ proc checkConvertible(castDest, src: PType): TConvStatus = return var d = skipTypes(castDest, abstractVar) var s = skipTypes(src, abstractVar-{tyTypeDesc}) - while (d != nil) and (d.Kind in {tyPtr, tyRef}) and (d.Kind == s.Kind): + while (d != nil) and (d.kind in {tyPtr, tyRef}) and (d.kind == s.kind): d = base(d) s = base(s) if d == nil: result = convNotLegal - elif d.Kind == tyObject and s.Kind == tyObject: + elif d.kind == tyObject and s.kind == tyObject: result = checkConversionBetweenObjects(d, s) - elif (skipTypes(castDest, abstractVarRange).Kind in IntegralTypes) and - (skipTypes(src, abstractVarRange-{tyTypeDesc}).Kind in IntegralTypes): + elif (skipTypes(castDest, abstractVarRange).kind in IntegralTypes) and + (skipTypes(src, abstractVarRange-{tyTypeDesc}).kind in IntegralTypes): # accept conversion between integral types else: # we use d, s here to speed up that operation a bit: @@ -228,9 +228,9 @@ proc semCast(c: PContext, n: PNode): PNode = result.typ = semTypeNode(c, n.sons[0], nil) addSon(result, copyTree(n.sons[0])) addSon(result, semExprWithType(c, n.sons[1])) - if not isCastable(result.typ, result.sons[1].Typ): + if not isCastable(result.typ, result.sons[1].typ): localError(result.info, errExprCannotBeCastedToX, - typeToString(result.Typ)) + typeToString(result.typ)) proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode = const @@ -240,7 +240,7 @@ proc semLowHigh(c: PContext, n: PNode, m: TMagic): PNode = else: n.sons[1] = semExprWithType(c, n.sons[1], {efDetermineType}) var typ = skipTypes(n.sons[1].typ, abstractVarRange) - case typ.Kind + case typ.kind of tySequence, tyString, tyOpenArray, tyVarargs: n.typ = getSysType(tyInt) of tyArrayConstr, tyArray: @@ -711,7 +711,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = if m.state != csMatch: if c.inCompilesContext > 0: # speed up error generation: - globalError(n.Info, errTypeMismatch, "") + globalError(n.info, errTypeMismatch, "") return emptyNode else: var hasErrorType = false @@ -726,7 +726,7 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = if not hasErrorType: add(msg, ")\n" & msgKindToString(errButExpected) & "\n" & typeToString(n.sons[0].typ)) - localError(n.Info, errGenerated, msg) + localError(n.info, errGenerated, msg) return errorNode(c, n) result = nil else: @@ -771,7 +771,7 @@ proc afterCallActions(c: PContext; n, orig: PNode, flags: TExprFlags): PNode = analyseIfAddressTakenInCall(c, result) if callee.magic != mNone: result = magicsAfterOverloadResolution(c, result, flags) - if c.InTypeClass == 0: + if c.inTypeClass == 0: result = evalAtCompileTime(c, result) proc semDirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = @@ -810,7 +810,7 @@ proc semEcho(c: PContext, n: PNode): PNode = proc buildEchoStmt(c: PContext, n: PNode): PNode = # we MUST not check 'n' for semantics again here! result = newNodeI(nkCall, n.info) - var e = strTableGet(magicsys.systemModule.Tab, getIdent"echo") + var e = strTableGet(magicsys.systemModule.tab, getIdent"echo") if e != nil: addSon(result, newSymNode(e)) else: @@ -908,6 +908,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) if s != nil: + markUsed(n.sons[1], s) return semSym(c, n, s, flags) n.sons[0] = semExprWithType(c, n.sons[0], flags+{efDetermineType}) @@ -950,7 +951,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = return # XXX: This is probably not relevant any more # reset to prevent 'nil' bug: see "tests/reject/tenumitems.nim": - ty = n.sons[0].Typ + ty = n.sons[0].typ ty = skipTypes(ty, {tyGenericInst, tyVar, tyPtr, tyRef}) var check: PNode = nil @@ -1446,7 +1447,7 @@ proc tryExpr(c: PContext, n: PNode, # watch out, hacks ahead: let oldErrorCount = msgs.gErrorCounter let oldErrorMax = msgs.gErrorMax - inc c.InCompilesContext + inc c.inCompilesContext # do not halt after first error: msgs.gErrorMax = high(int) @@ -1459,9 +1460,9 @@ proc tryExpr(c: PContext, n: PNode, errorOutputs = if bufferErrors: {eInMemory} else: {} let oldContextLen = msgs.getInfoContextLen() - let oldInGenericContext = c.InGenericContext - let oldInUnrolledContext = c.InUnrolledContext - let oldInGenericInst = c.InGenericInst + let oldInGenericContext = c.inGenericContext + let oldInUnrolledContext = c.inUnrolledContext + let oldInGenericInst = c.inGenericInst let oldProcCon = c.p c.generics = @[] try: @@ -1471,14 +1472,14 @@ proc tryExpr(c: PContext, n: PNode, nil # undo symbol table changes (as far as it's possible): c.generics = oldGenerics - c.InGenericContext = oldInGenericContext - c.InUnrolledContext = oldInUnrolledContext - c.InGenericInst = oldInGenericInst + c.inGenericContext = oldInGenericContext + c.inUnrolledContext = oldInUnrolledContext + c.inGenericInst = oldInGenericInst c.p = oldProcCon msgs.setInfoContextLen(oldContextLen) setLen(gOwners, oldOwnerLen) c.currentScope = oldScope - dec c.InCompilesContext + dec c.inCompilesContext errorOutputs = oldErrorOutputs msgs.gErrorCounter = oldErrorCount msgs.gErrorMax = oldErrorMax @@ -1893,6 +1894,8 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = let mode = if nfDelegate in n.flags: {} else: {checkUndeclared} var s = qualifiedLookUp(c, n.sons[0], mode) if s != nil: + if gCmd == cmdPretty and n.sons[0].kind == nkDotExpr: + pretty.checkUse(n.sons[0].sons[1], s) case s.kind of skMacro: if sfImmediate notin s.flags: @@ -1912,7 +1915,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = result = semConv(c, n) elif n.len == 1: result = semObjConstr(c, n, flags) - elif contains(c.AmbiguousSymbols, s.id): + elif contains(c.ambiguousSymbols, s.id): localError(n.info, errUseQualifier, s.name.s) elif s.magic == mNone: result = semDirectOp(c, n, flags) else: result = semMagic(c, n, s, flags) diff --git a/compiler/seminst.nim b/compiler/seminst.nim index faf0aae11..1025457fd 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -88,7 +88,7 @@ proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) proc instantiateBody(c: PContext, n: PNode, result: PSym) = if n.sons[bodyPos].kind != nkEmpty: - inc c.InGenericInst + inc c.inGenericInst # add it here, so that recursive generic procs are possible: addDecl(c, result) pushProcCon(c, result) @@ -109,7 +109,7 @@ proc instantiateBody(c: PContext, n: PNode, result: PSym) = #echo "code instantiated ", result.name.s excl(result.flags, sfForward) popProcCon(c) - dec c.InGenericInst + dec c.inGenericInst proc fixupInstantiatedSymbols(c: PContext, s: PSym) = for i in countup(0, c.generics.len - 1): @@ -265,8 +265,8 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, if fn.kind in {skTemplate, skMacro}: return fn # generates an instantiated proc - if c.InstCounter > 1000: internalError(fn.ast.info, "nesting too deep") - inc(c.InstCounter) + if c.instCounter > 1000: internalError(fn.ast.info, "nesting too deep") + inc(c.instCounter) # careful! we copy the whole AST including the possibly nil body! var n = copyTree(fn.ast) # NOTE: for access of private fields within generics from a different module @@ -309,5 +309,5 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, popOwner() #c.currentScope = oldScope c.friendModule = oldFriend - dec(c.InstCounter) + dec(c.instCounter) if result.kind == skMethod: finishMethod(c, result) diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index c9d5036d8..fb266ae3a 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -367,7 +367,7 @@ proc trackCase(tracked: PEffects, n: PNode) = for i in oldState.. 0 and result.typ.kind == tyBool: + elif c.inTypeClass > 0 and result.typ.kind == tyBool: let verdict = semConstExpr(c, result) if verdict.intVal == 0: localError(result.info, "type class predicate failed.") @@ -193,7 +193,7 @@ proc semCase(c: PContext, n: PNode): PNode = var covered: BiggestInt = 0 var typ = commonTypeBegin var hasElse = false - case skipTypes(n.sons[0].Typ, abstractVarRange-{tyTypeDesc}).Kind + case skipTypes(n.sons[0].typ, abstractVarRange-{tyTypeDesc}).kind of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32: chckCovered = true of tyFloat..tyFloat128, tyString, tyError: @@ -375,7 +375,7 @@ proc semVarOrLet(c: PContext, n: PNode, symkind: TSymKind): PNode = var v = semIdentDef(c, a.sons[j], symkind) if sfGenSym notin v.flags: addInterfaceDecl(c, v) when oKeepVariableNames: - if c.InUnrolledContext > 0: v.flags.incl(sfShadowed) + if c.inUnrolledContext > 0: v.flags.incl(sfShadowed) else: let shadowed = findShadowedVar(c, v) if shadowed != nil: @@ -496,10 +496,10 @@ proc semForObjectFields(c: TFieldsCtx, typ, forLoop, father: PNode) = fc.field = typ.sym fc.replaceByFieldName = c.m == mFieldPairs openScope(c.c) - inc c.c.InUnrolledContext + inc c.c.inUnrolledContext let body = instFieldLoopBody(fc, lastSon(forLoop), forLoop) father.add(semStmt(c.c, body)) - dec c.c.InUnrolledContext + dec c.c.inUnrolledContext closeScope(c.c) of nkNilLit: discard of nkRecCase: @@ -535,7 +535,7 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = # so that 'break' etc. work as expected, we produce # a 'while true: stmt; break' loop ... result = newNodeI(nkWhileStmt, n.info, 2) - var trueSymbol = strTableGet(magicsys.systemModule.Tab, getIdent"true") + var trueSymbol = strTableGet(magicsys.systemModule.tab, getIdent"true") if trueSymbol == nil: localError(n.info, errSystemNeeds, "true") trueSymbol = newSym(skUnknown, getIdent"true", getCurrOwner(), n.info) @@ -570,9 +570,9 @@ proc semForFields(c: PContext, n: PNode, m: TMagic): PNode = fc.tupleIndex = i fc.replaceByFieldName = m == mFieldPairs var body = instFieldLoopBody(fc, loopBody, n) - inc c.InUnrolledContext + inc c.inUnrolledContext stmts.add(semStmt(c, body)) - dec c.InUnrolledContext + dec c.inUnrolledContext closeScope(c) else: var fc: TFieldsCtx @@ -744,9 +744,9 @@ proc typeSectionRightSidePass(c: PContext, n: PNode) = var body: PType = nil s.typScope = c.currentScope.parent else: - inc c.InGenericContext + inc c.inGenericContext var body = semTypeNode(c, a.sons[2], nil) - dec c.InGenericContext + dec c.inGenericContext if body != nil: body.sym = s body.size = -1 # could not be computed properly @@ -1267,7 +1267,7 @@ proc semStmtList(c: PContext, n: PNode): PNode = # "Last expression must be explicitly returned if it " & # "is discardable or discarded") -proc SemStmt(c: PContext, n: PNode): PNode = +proc semStmt(c: PContext, n: PNode): PNode = # now: simply an alias: result = semExprNoType(c, n) diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 69649a58c..4fdd84841 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -153,7 +153,7 @@ proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = result = newOrPrevType(tyRange, prev, c) result.n = newNodeI(nkRange, n.info) if (n[1].kind == nkEmpty) or (n[2].kind == nkEmpty): - localError(n.Info, errRangeIsEmpty) + localError(n.info, errRangeIsEmpty) var a = semConstExpr(c, n[1]) var b = semConstExpr(c, n[2]) if not sameType(a.typ, b.typ): @@ -163,7 +163,7 @@ proc semRangeAux(c: PContext, n: PNode, prev: PType): PType = localError(n.info, errOrdinalTypeExpected) elif enumHasHoles(a.typ): localError(n.info, errEnumXHasHoles, a.typ.sym.name.s) - elif not leValue(a, b): localError(n.Info, errRangeIsEmpty) + elif not leValue(a, b): localError(n.info, errRangeIsEmpty) addSon(result.n, a) addSon(result.n, b) addSonSkipIntLit(result, b.typ) @@ -198,7 +198,7 @@ proc semArray(c: PContext, n: PNode, prev: PType): PType = indx = makeRangeType(c, 0, e.intVal-1, n.info, e.typ) elif e.kind == nkSym and e.typ.kind == tyExpr: 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): localError(n[1].info, errOrdinalTypeExpected) indx = e.typ @@ -240,7 +240,7 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = # This is a typedesc param. is it already bound? # it's not bound when it's used multiple times in the # proc signature for example - if c.InGenericInst > 0: + if c.inGenericInst > 0: let bound = result.typ.sons[0].sym if bound != nil: return bound return result @@ -300,6 +300,7 @@ proc semTuple(c: PContext, n: PNode, prev: PType): PType = else: addSon(result.n, newSymNode(field)) addSonSkipIntLit(result, typ) + if gCmd == cmdPretty: checkDef(a.sons[j], field) proc semIdentVis(c: PContext, kind: TSymKind, n: PNode, allowed: TSymFlags): PSym = @@ -334,6 +335,7 @@ proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode, else: discard else: result = semIdentVis(c, kind, n, allowed) + if gCmd == cmdPretty: checkDef(n, result) proc checkForOverlap(c: PContext, t: PNode, currentEx, branchIndex: int) = let ex = t[branchIndex][currentEx].skipConv @@ -412,7 +414,7 @@ proc semRecordCase(c: PContext, n: PNode, check: var TIntSet, pos: var int, return incl(a.sons[0].sym.flags, sfDiscriminant) var covered: BiggestInt = 0 - var typ = skipTypes(a.sons[0].Typ, abstractVar-{tyTypeDesc}) + var typ = skipTypes(a.sons[0].typ, abstractVar-{tyTypeDesc}) if not isOrdinalType(typ): localError(n.info, errSelectorMustBeOrdinal) elif firstOrd(typ) < 0: @@ -450,7 +452,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, case it.kind of nkElifBranch: checkSonsLen(it, 2) - if c.InGenericContext == 0: + if c.inGenericContext == 0: var e = semConstBoolExpr(c, it.sons[0]) if e.kind != nkIntLit: internalError(e.info, "semRecordNodeAux") elif e.intVal != 0 and branch == nil: branch = it.sons[1] @@ -461,7 +463,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, if branch == nil: branch = it.sons[0] idx = 0 else: illFormedAst(n) - if c.InGenericContext > 0: + if c.inGenericContext > 0: # use a new check intset here for each branch: var newCheck: TIntSet assign(newCheck, check) @@ -469,7 +471,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, var newf = newNodeI(nkRecList, n.info) semRecordNodeAux(c, it.sons[idx], newCheck, newPos, newf, rectype) it.sons[idx] = if newf.len == 1: newf[0] else: newf - if c.InGenericContext > 0: + if c.inGenericContext > 0: addSon(father, n) elif branch != nil: semRecordNodeAux(c, branch, check, pos, father, rectype) @@ -761,6 +763,8 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode, addSon(result.n, newSymNode(arg)) rawAddSon(result, finalType) addParamOrResult(c, arg, kind) + if gCmd == cmdPretty: checkDef(a.sons[j], arg) + if n.sons[0].kind != nkEmpty: var r = semTypeNode(c, n.sons[0], nil) diff --git a/compiler/semtypinst.nim b/compiler/semtypinst.nim index 6940af7b7..2e2d54b5b 100644 --- a/compiler/semtypinst.nim +++ b/compiler/semtypinst.nim @@ -226,7 +226,7 @@ proc replaceTypeVarsT*(cl: var TReplTypeVars, t: PType): PType = for i in countup(0, sonsLen(result) - 1): result.sons[i] = replaceTypeVarsT(cl, result.sons[i]) result.n = replaceTypeVarsN(cl, result.n) - if result.Kind in GenericTypes: + if result.kind in GenericTypes: localError(cl.info, errCannotInstantiateX, typeToString(t, preferName)) if result.kind == tyProc and result.sons[0] != nil: if result.sons[0].kind == tyEmpty: diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 3b1f3e715..201f61dec 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -354,9 +354,9 @@ proc procTypeRel(c: var TCandidate, f, a: PType): TTypeRelation = return isNone elif f.flags * {tfIterator} != a.flags * {tfIterator}: return isNone - elif f.callconv != a.callconv: + elif f.callConv != a.callConv: # valid to pass a 'nimcall' thingie to 'closure': - if f.callconv == ccClosure and a.callconv == ccDefault: + if f.callConv == ccClosure and a.callConv == ccDefault: result = isConvertible else: return isNone @@ -509,7 +509,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = elif lengthOrd(fRange) != lengthOrd(a): result = isNone else: nil of tyOpenArray, tyVarargs: - case a.Kind + case a.kind of tyOpenArray, tyVarargs: result = typeRel(c, base(f), base(a)) if result < isGeneric: result = isNone @@ -530,7 +530,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = result = isConvertible else: nil of tySequence: - case a.Kind + case a.kind of tySequence: if (f.sons[0].kind != tyGenericParam) and (a.sons[0].kind == tyEmpty): result = isSubtype @@ -620,7 +620,7 @@ proc typeRel(c: var TCandidate, f, a: PType, doBind = true): TTypeRelation = else: nil of tyCString: # conversion from string to cstring is automatic: - case a.Kind + case a.kind of tyCString: if tfNotNil in f.flags and tfNotNil notin a.flags: result = isNilConversion @@ -849,10 +849,10 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate, # pushInfoContext(arg.info) openScope(c) - inc c.InTypeClass + inc c.inTypeClass finally: - dec c.InTypeClass + dec c.inTypeClass closeScope(c) for param in f.n[0]: @@ -894,7 +894,7 @@ proc paramTypesMatchAux(c: PContext, m: var TCandidate, f, argType: PType, arg = argSemantized let - a = if c.InTypeClass > 0: argType.skipTypes({tyTypeDesc}) + a = if c.inTypeClass > 0: argType.skipTypes({tyTypeDesc}) else: argType fMaybeExpr = f.skipTypes({tyDistinct}) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index c88687f2c..06d1b28d2 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -151,7 +151,7 @@ proc suggestEverything(c: PContext, n: PNode, outputs: var int) = proc suggestFieldAccess(c: PContext, n: PNode, outputs: var int) = # special code that deals with ``myObj.``. `n` is NOT the nkDotExpr-node, but # ``myObj``. - var typ = n.Typ + var typ = n.typ if typ == nil: # a module symbol has no type for example: if n.kind == nkSym and n.sym.kind == skModule: @@ -338,8 +338,8 @@ proc suggestExpr*(c: PContext, node: PNode) = if cp == cpNone: return var outputs = 0 # This keeps semExpr() from coming here recursively: - if c.InCompilesContext > 0: return - inc(c.InCompilesContext) + if c.inCompilesContext > 0: return + inc(c.inCompilesContext) if optSuggest in gGlobalOptions: var n = findClosestDot(node) @@ -369,7 +369,7 @@ proc suggestExpr*(c: PContext, node: PNode) = addSon(a, x) suggestCall(c, a, n, outputs) - dec(c.InCompilesContext) + dec(c.inCompilesContext) if outputs > 0 and optUsages notin gGlobalOptions: suggestQuit() proc suggestStmt*(c: PContext, n: PNode) = diff --git a/compiler/transf.nim b/compiler/transf.nim index 936cf89ae..2332d0b48 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -513,7 +513,7 @@ proc transformCase(c: PTransf, n: PNode): PTransNode = elseBranch[0] = ifs result.add(elseBranch) 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}): # fix a stupid code gen bug by normalizing: var elseBranch = newTransNode(nkElse, n.info, 1) @@ -533,7 +533,7 @@ proc getMergeOp(n: PNode): PSym = case n.kind of nkCall, nkHiddenCallConv, nkCommand, nkInfix, nkPrefix, nkPostfix, nkCallStrLit: - if (n.sons[0].Kind == nkSym) and (n.sons[0].sym.kind == skProc) and + if (n.sons[0].kind == nkSym) and (n.sons[0].sym.kind == skProc) and (sfMerge in n.sons[0].sym.flags): result = n.sons[0].sym else: nil diff --git a/compiler/trees.nim b/compiler/trees.nim index ea2f8fbf1..35e9334cc 100644 --- a/compiler/trees.nim +++ b/compiler/trees.nim @@ -88,13 +88,13 @@ proc getOpSym*(op: PNode): PSym = result = nil else: if sonsLen(op) <= 0: internalError(op.info, "getOpSym") - elif op.sons[0].Kind == nkSym: result = op.sons[0].sym + elif op.sons[0].kind == nkSym: result = op.sons[0].sym else: result = nil proc getMagic*(op: PNode): TMagic = case op.kind of nkCallKinds: - case op.sons[0].Kind + case op.sons[0].kind of nkSym: result = op.sons[0].sym.magic else: result = mNone else: result = mNone diff --git a/compiler/types.nim b/compiler/types.nim index a921c59ba..779a649a7 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -155,14 +155,14 @@ proc skipTypes(t: PType, kinds: TTypeKinds): PType = proc isOrdinalType(t: PType): bool = assert(t != nil) # caution: uint, uint64 are no ordinal types! - result = t.Kind in {tyChar,tyInt..tyInt64,tyUInt8..tyUInt32,tyBool,tyEnum} or - (t.Kind in {tyRange, tyOrdinal, tyConst, tyMutable, tyGenericInst}) and + result = t.kind in {tyChar,tyInt..tyInt64,tyUInt8..tyUInt32,tyBool,tyEnum} or + (t.kind in {tyRange, tyOrdinal, tyConst, tyMutable, tyGenericInst}) and isOrdinalType(t.sons[0]) proc enumHasHoles(t: PType): bool = var b = t while b.kind in {tyConst, tyMutable, tyRange, tyGenericInst}: b = b.sons[0] - result = b.Kind == tyEnum and tfEnumHasHoles in b.flags + result = b.kind == tyEnum and tfEnumHasHoles in b.flags proc iterOverTypeAux(marker: var TIntSet, t: PType, iter: TTypeIter, closure: PObject): bool @@ -429,9 +429,9 @@ proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string = if t == nil: return if prefer == preferName and t.sym != nil and sfAnon notin t.sym.flags: if t.kind == tyInt and isIntLit(t): - return t.sym.Name.s & " literal(" & $t.n.intVal & ")" - return t.sym.Name.s - case t.Kind + return t.sym.name.s & " literal(" & $t.n.intVal & ")" + return t.sym.name.s + case t.kind of tyInt: if not isIntLit(t) or prefer == preferExported: result = typeToStr[t.kind] @@ -746,7 +746,7 @@ template ifFastObjectTypeCheckFailed(a, b: PType, body: stmt) {.immediate.} = # TA[T] = object # TB[T] = object # --> TA[int] != TB[int] - if tfFromGeneric in a.flags * b.flags and a.sym.Id == b.sym.Id: + if tfFromGeneric in a.flags * b.flags and a.sym.id == b.sym.id: # ok, we need the expensive structural check body @@ -827,7 +827,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = of dcEqOrDistinctOf: while a.kind == tyDistinct: a = a.sons[0] if a.kind != b.kind: return false - case a.Kind + case a.kind of tyEmpty, tyChar, tyBool, tyNil, tyPointer, tyString, tyCString, tyInt..tyBigNum, tyStmt: result = sameFlags(a, b) diff --git a/compiler/vm.nim b/compiler/vm.nim index 215b3486e..0a1ee0a1a 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -144,7 +144,7 @@ proc copyValue(src: PNode): PNode = when defined(useNodeIds): if result.id == nodeIdToDebug: echo "COMES FROM ", src.id - case src.Kind + case src.kind of nkCharLit..nkUInt64Lit: result.intVal = src.intVal of nkFloatLit..nkFloat128Lit: result.floatVal = src.floatVal of nkSym: result.sym = src.sym diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 1c0c59a7c..ee05ad7e2 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -32,16 +32,16 @@ proc `!$`*(h: THash): THash {.inline.} = result = result xor (result shr 11) result = result +% result shl 15 -proc hashData*(Data: pointer, Size: int): THash = +proc hashData*(data: pointer, size: int): THash = ## hashes an array of bytes of size `size` var h: THash = 0 when defined(js): var p: cstring asm """`p` = `Data`;""" else: - var p = cast[cstring](Data) + var p = cast[cstring](data) var i = 0 - var s = Size + var s = size while s > 0: h = h !& ord(p[i]) inc(i) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index c79e6e6da..360a3a5e7 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -151,11 +151,11 @@ proc kind*(my: TJsonParser): TJsonEventKind {.inline.} = proc getColumn*(my: TJsonParser): int {.inline.} = ## get the current column the parser has arrived at. - result = getColNumber(my, my.bufPos) + result = getColNumber(my, my.bufpos) proc getLine*(my: TJsonParser): int {.inline.} = ## get the current line the parser has arrived at. - result = my.linenumber + result = my.lineNumber proc getFilename*(my: TJsonParser): string {.inline.} = ## get the filename of the file that the parser processes. @@ -227,11 +227,11 @@ proc parseString(my: var TJsonParser): TTokKind = add(my.a, buf[pos]) inc(pos) of '\c': - pos = lexbase.HandleCR(my, pos) + pos = lexbase.handleCR(my, pos) buf = my.buf add(my.a, '\c') of '\L': - pos = lexbase.HandleLF(my, pos) + pos = lexbase.handleLF(my, pos) buf = my.buf add(my.a, '\L') else: @@ -253,11 +253,11 @@ proc skip(my: var TJsonParser) = of '\0': break of '\c': - pos = lexbase.HandleCR(my, pos) + pos = lexbase.handleCR(my, pos) buf = my.buf break of '\L': - pos = lexbase.HandleLF(my, pos) + pos = lexbase.handleLF(my, pos) buf = my.buf break else: @@ -271,10 +271,10 @@ proc skip(my: var TJsonParser) = my.err = errEOC_Expected break of '\c': - pos = lexbase.HandleCR(my, pos) + pos = lexbase.handleCR(my, pos) buf = my.buf of '\L': - pos = lexbase.HandleLF(my, pos) + pos = lexbase.handleLF(my, pos) buf = my.buf of '*': inc(pos) @@ -288,10 +288,10 @@ proc skip(my: var TJsonParser) = of ' ', '\t': inc(pos) of '\c': - pos = lexbase.HandleCR(my, pos) + pos = lexbase.handleCR(my, pos) buf = my.buf of '\L': - pos = lexbase.HandleLF(my, pos) + pos = lexbase.handleLF(my, pos) buf = my.buf else: break diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim index 81f53b874..eee95e2e6 100644 --- a/lib/pure/lexbase.nim +++ b/lib/pure/lexbase.nim @@ -31,7 +31,7 @@ type buf*: cstring ## the buffer itself bufLen*: int ## length of buffer in characters input: PStream ## the input stream - LineNumber*: int ## the current line number + lineNumber*: int ## the current line number sentinel: int lineStart: int # index of last line start in buffer fileOpened: bool @@ -75,7 +75,7 @@ proc fillBuffer(L: var TBaseLexer) = # we know here that pos == L.sentinel, but not if this proc # is called the first time by initBaseLexer() assert(L.sentinel < L.bufLen) - toCopy = L.BufLen - L.sentinel - 1 + toCopy = L.bufLen - L.sentinel - 1 assert(toCopy >= 0) if toCopy > 0: moveMem(L.buf, addr(L.buf[L.sentinel + 1]), toCopy * chrSize) @@ -99,8 +99,8 @@ proc fillBuffer(L: var TBaseLexer) = else: # rather than to give up here because the line is too long, # double the buffer's size and try again: - oldBufLen = L.BufLen - L.bufLen = L.BufLen * 2 + oldBufLen = L.bufLen + L.bufLen = L.bufLen * 2 L.buf = cast[cstring](realloc(L.buf, L.bufLen * chrSize)) assert(L.bufLen - oldBufLen == oldBufLen) charsRead = readData(L.input, addr(L.buf[oldBufLen]), @@ -123,14 +123,14 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int = proc handleCR(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == '\c') - inc(L.linenumber) + inc(L.lineNumber) result = fillBaseLexer(L, pos) if L.buf[result] == '\L': result = fillBaseLexer(L, result) proc handleLF(L: var TBaseLexer, pos: int): int = assert(L.buf[pos] == '\L') - inc(L.linenumber) + inc(L.lineNumber) result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result; proc skipUtf8Bom(L: var TBaseLexer) = @@ -147,7 +147,7 @@ proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) = L.buf = cast[cstring](alloc(bufLen * chrSize)) L.sentinel = bufLen - 1 L.lineStart = 0 - L.linenumber = 1 # lines start at 1 + L.lineNumber = 1 # lines start at 1 fillBuffer(L) skipUtf8Bom(L) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index c1b71c202..9b08fea6f 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -356,8 +356,8 @@ when defined(windows): proc skipFindData(f: TWIN32_FIND_DATA): bool {.inline.} = const dot = ord('.') - result = f.cFilename[0].int == dot and(f.cFilename[1].int == 0 or - f.cFilename[1].int == dot and f.cFilename[2].int == 0) + result = f.cFileName[0].int == dot and(f.cFileName[1].int == 0 or + f.cFileName[1].int == dot and f.cFileName[2].int == 0) proc existsFile*(filename: string): bool {.rtl, extern: "nos$1", tags: [FReadDir].} = diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 1be30f006..76765ff8e 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -23,7 +23,7 @@ else: type TProcess = object of TObject when defined(windows): - FProcessHandle: THandle + fProcessHandle: THandle inHandle, outHandle, errHandle: TFileHandle id: THandle else: @@ -336,7 +336,7 @@ when defined(Windows) and not defined(useNimRtl): var s = PFileHandleStream(s) if s.atTheEnd: return 0 var br: int32 - var a = winlean.ReadFile(s.handle, buffer, bufLen.cint, br, nil) + var a = winlean.readFile(s.handle, buffer, bufLen.cint, br, nil) # TRUE and zero bytes returned (EOF). # TRUE and n (>0) bytes returned (good data). # FALSE and bytes returned undefined (system error). @@ -383,12 +383,12 @@ when defined(Windows) and not defined(useNimRtl): # O_WRONLY {.importc: "_O_WRONLY", header: "".}: int # O_RDONLY {.importc: "_O_RDONLY", header: "".}: int - proc createPipeHandles(Rdhandle, WrHandle: var THandle) = + proc createPipeHandles(rdHandle, wrHandle: var THandle) = var piInheritablePipe: TSECURITY_ATTRIBUTES - piInheritablePipe.nlength = sizeof(TSECURITY_ATTRIBUTES).cint + piInheritablePipe.nLength = sizeof(TSECURITY_ATTRIBUTES).cint piInheritablePipe.lpSecurityDescriptor = nil - piInheritablePipe.Binherithandle = 1 - if createPipe(Rdhandle, WrHandle, piInheritablePipe, 1024) == 0'i32: + piInheritablePipe.bInheritHandle = 1 + if createPipe(rdHandle, wrHandle, piInheritablePipe, 1024) == 0'i32: osError(osLastError()) proc fileClose(h: THandle) {.inline.} = @@ -440,11 +440,11 @@ when defined(Windows) and not defined(useNimRtl): var tmp = newWideCString(cmdl) var ee = newWideCString(e) var wwd = newWideCString(wd) - success = winlean.CreateProcessW(nil, + success = winlean.createProcessW(nil, tmp, nil, nil, 1, NORMAL_PRIORITY_CLASS or CREATE_UNICODE_ENVIRONMENT, ee, wwd, si, procInfo) else: - success = winlean.CreateProcessA(nil, + success = winlean.createProcessA(nil, cmdl, nil, nil, 1, NORMAL_PRIORITY_CLASS, e, wd, SI, ProcInfo) let lastError = osLastError() @@ -459,45 +459,45 @@ when defined(Windows) and not defined(useNimRtl): if success == 0: osError(lastError) # Close the handle now so anyone waiting is woken: discard closeHandle(procInfo.hThread) - result.FProcessHandle = procInfo.hProcess - result.id = procInfo.dwProcessID + result.fProcessHandle = procInfo.hProcess + result.id = procInfo.dwProcessId proc close(p: PProcess) = when false: # somehow this does not work on Windows: - discard CloseHandle(p.inHandle) - discard CloseHandle(p.outHandle) - discard CloseHandle(p.errHandle) - discard CloseHandle(p.FProcessHandle) + discard closeHandle(p.inHandle) + discard closeHandle(p.outHandle) + discard closeHandle(p.errHandle) + discard closeHandle(p.FProcessHandle) proc suspend(p: PProcess) = - discard suspendThread(p.FProcessHandle) + discard suspendThread(p.fProcessHandle) proc resume(p: PProcess) = - discard resumeThread(p.FProcessHandle) + discard resumeThread(p.fProcessHandle) proc running(p: PProcess): bool = - var x = waitForSingleObject(p.FProcessHandle, 50) + var x = waitForSingleObject(p.fProcessHandle, 50) return x == WAIT_TIMEOUT proc terminate(p: PProcess) = if running(p): - discard terminateProcess(p.FProcessHandle, 0) + discard terminateProcess(p.fProcessHandle, 0) proc waitForExit(p: PProcess, timeout: int = -1): int = - discard waitForSingleObject(p.FProcessHandle, timeout.int32) + discard waitForSingleObject(p.fProcessHandle, timeout.int32) var res: int32 - discard getExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.fProcessHandle, res) result = res - discard closeHandle(p.FProcessHandle) + discard closeHandle(p.fProcessHandle) proc peekExitCode(p: PProcess): int = - var b = waitForSingleObject(p.FProcessHandle, 50) == WAIT_TIMEOUT + var b = waitForSingleObject(p.fProcessHandle, 50) == WAIT_TIMEOUT if b: result = -1 else: var res: int32 - discard getExitCodeProcess(p.FProcessHandle, res) + discard getExitCodeProcess(p.fProcessHandle, res) return res proc inputStream(p: PProcess): PStream = @@ -521,10 +521,10 @@ when defined(Windows) and not defined(useNimRtl): si.hStdOutput = getStdHandle(STD_OUTPUT_HANDLE) when useWinUnicode: var c = newWideCString(command) - var res = winlean.CreateProcessW(nil, c, nil, nil, 0, + var res = winlean.createProcessW(nil, c, nil, nil, 0, NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo) else: - var res = winlean.CreateProcessA(nil, command, nil, nil, 0, + var res = winlean.createProcessA(nil, command, nil, nil, 0, NORMAL_PRIORITY_CLASS, nil, nil, SI, ProcInfo) if res == 0: osError(osLastError()) @@ -542,7 +542,7 @@ when defined(Windows) and not defined(useNimRtl): assert readfds.len <= MAXIMUM_WAIT_OBJECTS var rfds: TWOHandleArray for i in 0..readfds.len()-1: - rfds[i] = readfds[i].FProcessHandle + rfds[i] = readfds[i].fProcessHandle var ret = waitForMultipleObjects(readfds.len.int32, addr(rfds), 0'i32, timeout.int32) diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim index 5076d72fd..6b2ee6282 100644 --- a/lib/pure/parseopt.nim +++ b/lib/pure/parseopt.nim @@ -37,7 +37,7 @@ type ## or the argument, ``value`` is not "" if ## the option was given a value -when defined(os.ParamCount): +when defined(os.paramCount): # we cannot provide this for NimRtl creation on Posix, because we can't # access the command line arguments then! diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index dee45cbd6..61df82640 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -445,7 +445,7 @@ proc bindAddr*(socket: TSocket, port = TPort(0), address = "") {. hints.ai_socktype = toInt(SOCK_STREAM) hints.ai_protocol = toInt(IPPROTO_TCP) gaiNim(address, port, hints, aiList) - if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrLen.TSockLen) < 0'i32: + if bindSocket(socket.fd, aiList.ai_addr, aiList.ai_addrlen.TSockLen) < 0'i32: osError(osLastError()) proc getSockName*(socket: TSocket): TPort = @@ -628,7 +628,7 @@ proc accept*(server: TSocket): TSocket {.deprecated, tags: [FReadIO].} = proc close*(socket: TSocket) = ## closes a socket. when defined(windows): - discard winlean.closeSocket(socket.fd) + discard winlean.closesocket(socket.fd) else: discard posix.close(socket.fd) # TODO: These values should not be discarded. An EOS should be raised. @@ -687,7 +687,7 @@ proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} = result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) when defined(windows): - result.addrType = TDomain(s.h_addrtype) + result.addrtype = TDomain(s.h_addrtype) else: if s.h_addrtype == posix.AF_INET: result.addrType = AF_INET @@ -708,7 +708,7 @@ proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} = result.name = $s.h_name result.aliases = cstringArrayToSeq(s.h_aliases) when defined(windows): - result.addrType = TDomain(s.h_addrtype) + result.addrtype = TDomain(s.h_addrtype) else: if s.h_addrtype == posix.AF_INET: result.addrType = AF_INET @@ -1058,7 +1058,7 @@ proc readIntoBuf(socket: TSocket, flags: int32): int = else: result = recv(socket.fd, addr(socket.buffer), cint(socket.buffer.high), flags) if result <= 0: - socket.buflen = 0 + socket.bufLen = 0 socket.currPos = 0 return result socket.bufLen = result diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 246126828..be3e5d6da 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -345,11 +345,11 @@ when not defined(JS): monthday: int(tm.monthday), month: TMonth(tm.month), year: tm.year + 1900'i32, - weekday: weekDays[int(tm.weekDay)], + weekday: weekDays[int(tm.weekday)], yearday: int(tm.yearday), - isDST: tm.isDST > 0, + isDST: tm.isdst > 0, tzname: if local: - if tm.isDST > 0: + if tm.isdst > 0: getTzname().DST else: getTzname().nonDST @@ -367,7 +367,7 @@ when not defined(JS): result.monthday = t.monthday result.month = ord(t.month) result.year = t.year - 1900 - result.weekday = weekDays[t.weekDay] + result.weekday = weekDays[t.weekday] result.yearday = t.yearday result.isdst = if t.isDST: 1 else: 0 @@ -532,7 +532,7 @@ proc getDateStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} = ## gets the current date as a string of the format ``YYYY-MM-DD``. var ti = getLocalTime(getTime()) result = $ti.year & '-' & intToStr(ord(ti.month)+1, 2) & - '-' & intToStr(ti.monthDay, 2) + '-' & intToStr(ti.monthday, 2) proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [FTime].} = ## gets the current clock time as a string of the format ``HH:MM:SS``. diff --git a/lib/system/gc.nim b/lib/system/gc.nim index 6d6be33d0..0fb9bb482 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -132,9 +132,9 @@ when BitsPerPage mod (sizeof(int)*8) != 0: template color(c): expr = c.refCount and colorMask template setColor(c, col) = when col == rcBlack: - c.refcount = c.refCount and not colorMask + c.refcount = c.refcount and not colorMask else: - c.refcount = c.refCount and not colorMask or col + c.refcount = c.refcount and not colorMask or col proc writeCell(msg: cstring, c: PCell) = var kind = -1 @@ -211,7 +211,7 @@ proc decRef(c: PCell) {.inline.} = proc incRef(c: PCell) {.inline.} = gcAssert(isAllocatedPtr(gch.region, c), "incRef: interiorPtr") - c.refcount = c.refCount +% rcIncrement + c.refcount = c.refcount +% rcIncrement # and not colorMask #writeCell("incRef", c) if canbeCycleRoot(c): @@ -582,7 +582,7 @@ proc markRoots(gch: var TGcHeap) = for s in elements(gch.cycleRoots): #writeCell("markRoot", s) inc tabSize - if s.color == rcPurple and s.refCount >=% rcIncrement: + if s.color == rcPurple and s.refcount >=% rcIncrement: markGray(s) else: excl(gch.cycleRoots, s) -- cgit 1.4.1-2-gfad0 From a59939d29500f7a00cfd45b4990c5e34a9548add Mon Sep 17 00:00:00 2001 From: Araq Date: Sun, 19 Jan 2014 01:25:48 +0100 Subject: it's the year 2014 --- compiler/astalgo.nim | 14 +++++++------- compiler/cgen.nim | 8 ++++---- compiler/commands.nim | 2 +- compiler/jsgen.nim | 4 ++-- compiler/main.nim | 2 +- compiler/semgnrc.nim | 6 +++--- compiler/semthreads.nim | 4 ++-- todo.txt | 6 ++---- 8 files changed, 22 insertions(+), 24 deletions(-) (limited to 'compiler/commands.nim') diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index 110ee191f..2505bc687 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -455,18 +455,18 @@ proc nextTry(h, maxHash: THash): THash = # generates each int in range(maxHash) exactly once (see any text on # random-number generation for proof). -proc objectSetContains(t: TObjectSet, obj: PObject): bool = +proc objectSetContains(t: TObjectSet, obj: PObject): bool = # returns true whether n is in t var h: THash = hashNode(obj) and high(t.data) # start with real hash value - while t.data[h] != nil: - if (t.data[h] == obj): + while t.data[h] != nil: + if t.data[h] == obj: return true h = nextTry(h, high(t.data)) result = false -proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) = +proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) = var h: THash = hashNode(obj) and high(data) - while data[h] != nil: + while data[h] != nil: assert(data[h] != obj) h = nextTry(h, high(data)) assert(data[h] == nil) @@ -475,7 +475,7 @@ proc objectSetRawInsert(data: var TObjectSeq, obj: PObject) = proc objectSetEnlarge(t: var TObjectSet) = var n: TObjectSeq 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]) swap(t.data, n) @@ -699,7 +699,7 @@ proc idTableRawGet(t: TIdTable, key: int): int = var h: THash h = key and high(t.data) # start with real hash value while t.data[h].key != nil: - if (t.data[h].key.id == key): + if t.data[h].key.id == key: return h h = nextTry(h, high(t.data)) result = - 1 diff --git a/compiler/cgen.nim b/compiler/cgen.nim index b08647512..c7de1091b 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -914,18 +914,18 @@ proc addIntTypes(result: var PRope) {.inline.} = proc getCopyright(cfilenoext: string): PRope = if optCompileOnly in gGlobalOptions: result = ropeff("/* Generated by Nimrod Compiler v$1 */$n" & - "/* (c) 2012 Andreas Rumpf */$n" & + "/* (c) 2014 Andreas Rumpf */$n" & "/* The generated code is subject to the original license. */$n", "; Generated by Nimrod Compiler v$1$n" & "; (c) 2012 Andreas Rumpf$n", [toRope(VersionAsString)]) else: result = ropeff("/* Generated by Nimrod Compiler v$1 */$n" & - "/* (c) 2012 Andreas Rumpf */$n" & + "/* (c) 2014 Andreas Rumpf */$n" & "/* The generated code is subject to the original license. */$n" & "/* Compiled for: $2, $3, $4 */$n" & "/* Command for C compiler:$n $5 */$n", "; Generated by Nimrod Compiler v$1$n" & - "; (c) 2012 Andreas Rumpf$n" & + "; (c) 2014 Andreas Rumpf$n" & "; Compiled for: $2, $3, $4$n" & "; Command for LLVM compiler:$n $5$n", [toRope(VersionAsString), toRope(platform.OS[targetOS].name), diff --git a/compiler/commands.nim b/compiler/commands.nim index 7179b07c1..18bdb54d3 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -28,7 +28,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) const HelpMessage = "Nimrod Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" & - "Copyright (c) 2004-2013 by Andreas Rumpf\n" + "Copyright (c) 2006-2014 by Andreas Rumpf\n" const Usage = slurp"doc/basicopt.txt".replace("//", "") diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index b4e696d0a..dd06b0235 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -1652,7 +1652,7 @@ proc newModule(module: PSym): BModule = proc genHeader(): PRope = result = ropef("/* Generated by the Nimrod Compiler v$1 */$n" & - "/* (c) 2013 Andreas Rumpf */$n$n" & + "/* (c) 2014 Andreas Rumpf */$n$n" & "$nvar Globals = this;$n" & "var framePtr = null;$n" & "var excHandler = null;$n", diff --git a/compiler/main.nim b/compiler/main.nim index 4cea24f9d..cdea7b5ca 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index b40e86cbf..89a167b96 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -103,7 +103,7 @@ proc semGenericStmt(c: PContext, n: PNode, # not work. Copying the symbol does not work either because we're already # the owner of the symbol! What we need to do is to copy the symbol # in the generic instantiation process... - nil + discard of nkBind: result = semGenericStmt(c, n.sons[0], flags+{withinBind}, ctx) of nkMixinStmt: @@ -271,7 +271,7 @@ proc semGenericStmt(c: PContext, n: PNode, else: illFormedAst(n) addDecl(c, newSymS(skUnknown, getIdentNode(a.sons[i]), c)) of nkObjectTy, nkTupleTy: - nil + discard of nkFormalParams: checkMinSonsLen(n, 1) if n.sons[0].kind != nkEmpty: @@ -304,7 +304,7 @@ proc semGenericStmt(c: PContext, n: PNode, else: body = n.sons[bodyPos] n.sons[bodyPos] = semGenericStmtScope(c, body, flags, ctx) closeScope(c) - of nkPragma, nkPragmaExpr: nil + of nkPragma, nkPragmaExpr: discard of nkExprColonExpr, nkExprEqExpr: checkMinSonsLen(n, 2) result.sons[1] = semGenericStmt(c, n.sons[1], flags, ctx) diff --git a/compiler/semthreads.nim b/compiler/semthreads.nim index c96acf2f1..f7322db80 100644 --- a/compiler/semthreads.nim +++ b/compiler/semthreads.nim @@ -160,7 +160,7 @@ proc writeAccess(c: PProcCtx, n: PNode, owner: TThreadOwner) = # we could not backtrack to a concrete symbol, but that's fine: var lastOwner = analyse(c, n) case lastOwner - of toNil: nil # fine, toNil can be overwritten + of toNil: discard # fine, toNil can be overwritten of toVoid, toUndefined: internalError(n.info, "writeAccess") of toTheirs: message(n.info, warnWriteToForeignHeap) of toMine: @@ -369,7 +369,7 @@ proc analyse(c: PProcCtx, n: PNode): TThreadOwner = result = toMine of nkAsmStmt, nkPragma, nkIteratorDef, nkProcDef, nkMethodDef, nkConverterDef, nkMacroDef, nkTemplateDef, - nkGotoState, nkState, nkBreakState, nkType: + nkGotoState, nkState, nkBreakState, nkType, nkIdent: result = toVoid of nkExprColonExpr: result = analyse(c, n.sons[1]) diff --git a/todo.txt b/todo.txt index c29638e29..067c376ad 100644 --- a/todo.txt +++ b/todo.txt @@ -1,13 +1,12 @@ version 0.9.4 ============= +- test&finish first class iterators: + * nested iterators - ``--gc:none`` should complain about when you use the GC - ensure (ref T)(a, b) works as a type conversion and type constructor -- Aporia doesn't compile under devel - document new templating symbol binding rules - make '--implicitStatic:on' the default -- test&finish first class iterators: - * nested iterators - special rule for ``[]=`` - ``=`` should be overloadable; requires specialization for ``=``; general @@ -34,7 +33,6 @@ Bugs - blocks can "export" an identifier but the CCG generates {} for them ... - osproc execProcesses can deadlock if all processes fail (as experienced in c++ mode) -- result = result shr 8 for the "system()" wrapper version 0.9.x -- cgit 1.4.1-2-gfad0 From 3e25d5f24747c324a5a0f0deb555611166c96209 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 8 Apr 2014 01:19:15 +0200 Subject: merged better html links #850 --- compiler/commands.nim | 3 + compiler/docgen.nim | 168 ++++++++++++++++++++++++++++++++++++--- compiler/options.nim | 2 + compiler/renderer.nim | 28 ++++--- compiler/typesrenderer.nim | 113 ++++++++++++++++++++++++++ config/nimdoc.cfg | 35 +++++++- doc/advopt.txt | 2 + doc/docgen.txt | 133 +++++++++++++++++++++++++++++-- lib/core/macros.nim | 4 +- lib/packages/docutils/rstgen.nim | 90 ++++++++++++++++++--- lib/pure/cgi.nim | 2 +- tools/nimweb.nim | 33 +++++--- tools/website.tmpl | 2 +- 13 files changed, 559 insertions(+), 56 deletions(-) create mode 100644 compiler/typesrenderer.nim (limited to 'compiler/commands.nim') diff --git a/compiler/commands.nim b/compiler/commands.nim index 18bdb54d3..8339219ed 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -267,6 +267,9 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "out", "o": expectArg(switch, arg, pass, info) options.outFile = arg + of "docseesrcurl": + expectArg(switch, arg, pass, info) + options.docSeeSrcUrl = arg of "mainmodule", "m": expectArg(switch, arg, pass, info) optMainModule = arg diff --git a/compiler/docgen.nim b/compiler/docgen.nim index d8c439c9c..6948c4979 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -14,7 +14,7 @@ import ast, strutils, strtabs, options, msgs, os, ropes, idents, wordrecg, syntaxes, renderer, lexer, rstast, rst, rstgen, times, highlite, - importer, sempass2, json + importer, sempass2, json, xmltree, cgi, typesrenderer type TSections = array[TSymKind, PRope] @@ -23,8 +23,9 @@ type id: int # for generating IDs toc, section: TSections indexValFilename: string + seenSymbols: PStringTable # avoids duplicate symbol generation for HTML. - PDoc* = ref TDocumentor + PDoc* = ref TDocumentor ## Alias to type less. proc compilerMsgHandler(filename: string, line, col: int, msgKind: rst.TMsgKind, arg: string) {.procvar.} = @@ -59,6 +60,7 @@ proc newDocumentor*(filename: string, config: PStringTable): PDoc = initRstGenerator(result[], (if gCmd != cmdRst2tex: outHtml else: outLatex), options.gConfigVars, filename, {roSupportRawDirective}, docgenFindFile, compilerMsgHandler) + result.seenSymbols = newStringTable(modeCaseInsensitive) result.id = 100 proc dispA(dest: var PRope, xml, tex: string, args: openArray[PRope]) = @@ -144,6 +146,23 @@ proc genRecComment(d: PDoc, n: PNode): PRope = else: n.comment = nil +proc getPlainDocstring(n: PNode): string = + ## Gets the plain text docstring of a node non destructively. + ## + ## You need to call this before genRecComment, whose side effects are removal + ## of comments from the tree. The proc will recursively scan and return all + ## the concatenated ``##`` comments of the node. + result = "" + if n == nil: return + if n.comment != nil and startsWith(n.comment, "##"): + result = n.comment + if result.len < 1: + if n.kind notin {nkEmpty..nkNilLit}: + for i in countup(0, len(n)-1): + result = getPlainDocstring(n.sons[i]) + if result.len > 0: return + + proc findDocComment(n: PNode): PNode = if n == nil: return nil if not isNil(n.comment) and startsWith(n.comment, "##"): return n @@ -205,14 +224,111 @@ proc getRstName(n: PNode): PRstNode = internalError(n.info, "getRstName()") result = nil +proc newUniquePlainSymbol(d: PDoc, original: string): string = + ## Returns a new unique plain symbol made up from the original. + ## + ## When a collision is found in the seenSymbols table, new numerical variants + ## with underscore + number will be generated. + if not d.seenSymbols.hasKey(original): + result = original + d.seenSymbols[original] = "" + return + + # Iterate over possible numeric variants of the original name. + var count = 2 + + while true: + result = original & "_" & $count + if not d.seenSymbols.hasKey(result): + d.seenSymbols[result] = "" + break + count += 1 + + +proc complexName(k: TSymKind, n: PNode, baseName: string): string = + ## Builds a complex unique href name for the node. + ## + ## Pass as ``baseName`` the plain symbol obtained from the nodeName. The + ## format of the returned symbol will be ``baseName(.callable type)?,(param + ## type)?(,param type)*``. The callable type part will be added only if the + ## node is not a proc, as those are the common ones. The suffix will be a dot + ## and a single letter representing the type of the callable. The parameter + ## types will be added with a preceeding dash. Return types won't be added. + ## + ## If you modify the output of this proc, please update the anchor generation + ## section of ``doc/docgen.txt``. + result = baseName + case k: + of skProc: result.add(defaultParamSeparator) + of skMacro: result.add(".m" & defaultParamSeparator) + of skMethod: result.add(".e" & defaultParamSeparator) + of skIterator: result.add(".i" & defaultParamSeparator) + of skTemplate: result.add(".t" & defaultParamSeparator) + of skConverter: result.add(".c" & defaultParamSeparator) + else: discard + + if len(n) > paramsPos and n[paramsPos].kind == nkFormalParams: + result.add(renderParamTypes(n[paramsPos])) + + +proc isCallable(n: PNode): bool = + ## Returns true if `n` contains a callable node. + case n.kind + of nkProcDef, nkMethodDef, nkIteratorDef, nkMacroDef, nkTemplateDef, + nkConverterDef: result = true + else: + result = false + + +proc docstringSummary(rstText: string): string = + ## Returns just the first line or a brief chunk of text from a rst string. + ## + ## Most docstrings will contain a one liner summary, so stripping at the + ## first newline is usually fine. If after that the content is still too big, + ## it is stripped at the first comma, colon or dot, usual english sentence + ## separators. + ## + ## No guarantees are made on the size of the output, but it should be small. + ## Also, we hope to not break the rst, but maybe we do. If there is any + ## trimming done, an ellipsis unicode char is added. + const maxDocstringChars = 100 + assert (rstText.len < 2 or (rstText[0] == '#' and rstText[1] == '#')) + result = rstText.substr(2).strip + var pos = result.find('\L') + if pos > 0: + result.delete(pos, result.len - 1) + result.add("…") + if pos < maxDocstringChars: + return + # Try to keep trimming at other natural boundaries. + pos = result.find({'.', ',', ':'}) + let last = result.len - 1 + if pos > 0 and pos < last: + result.delete(pos, last) + result.add("…") + + proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) = if not isVisible(nameNode): return - var name = toRope(getName(d, nameNode)) + let + name = getName(d, nameNode) + nameRope = name.toRope + plainDocstring = getPlainDocstring(n) # call here before genRecComment! var result: PRope = nil - var literal = "" + var literal, plainName = "" var kind = tkEof var comm = genRecComment(d, n) # call this here for the side-effect! var r: TSrcGen + # Obtain the plain rendered string for hyperlink titles. + initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments, + renderNoPragmas, renderNoProcDefs}) + while true: + getNextTok(r, kind, literal) + if kind == tkEof: + break + plainName.add(literal) + + # Render the HTML hyperlink. initTokRender(r, n, {renderNoBody, renderNoComments, renderDocComments}) while true: getNextTok(r, kind, literal) @@ -253,13 +369,47 @@ proc genItem(d: PDoc, n, nameNode: PNode, k: TSymKind) = dispA(result, "$1", "\\spanOther{$1}", [toRope(esc(d.target, literal))]) inc(d.id) + let + plainNameRope = toRope(xmltree.escape(plainName.strip)) + cleanPlainSymbol = renderPlainSymbolName(nameNode) + complexSymbol = complexName(k, n, cleanPlainSymbol) + plainSymbolRope = toRope(cleanPlainSymbol) + plainSymbolEncRope = toRope(URLEncode(cleanPlainSymbol)) + itemIDRope = toRope(d.id) + symbolOrId = d.newUniquePlainSymbol(complexSymbol) + symbolOrIdRope = symbolOrId.toRope + symbolOrIdEncRope = URLEncode(symbolOrId).toRope + + var seeSrcRope: PRope = nil + let docItemSeeSrc = getConfigVar("doc.item.seesrc") + if docItemSeeSrc.len > 0 and options.docSeeSrcUrl.len > 0: + let urlRope = ropeFormatNamedVars(options.docSeeSrcUrl, + ["path", "line"], [n.info.toFilename.toRope, toRope($n.info.line)]) + dispA(seeSrcRope, "$1", "", [ropeFormatNamedVars(docItemSeeSrc, + ["path", "line", "url"], [n.info.toFilename.toRope, + toRope($n.info.line), urlRope])]) + app(d.section[k], ropeFormatNamedVars(getConfigVar("doc.item"), - ["name", "header", "desc", "itemID"], - [name, result, comm, toRope(d.id)])) + ["name", "header", "desc", "itemID", "header_plain", "itemSym", + "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc", "seeSrc"], + [nameRope, result, comm, itemIDRope, plainNameRope, plainSymbolRope, + symbolOrIdRope, plainSymbolEncRope, symbolOrIdEncRope, seeSrcRope])) app(d.toc[k], ropeFormatNamedVars(getConfigVar("doc.item.toc"), - ["name", "header", "desc", "itemID"], [ - toRope(getName(d, nameNode, d.splitAfter)), result, comm, toRope(d.id)])) - setIndexTerm(d[], $d.id, getName(d, nameNode)) + ["name", "header", "desc", "itemID", "header_plain", "itemSym", + "itemSymOrID", "itemSymEnc", "itemSymOrIDEnc"], + [toRope(getName(d, nameNode, d.splitAfter)), result, comm, + itemIDRope, plainNameRope, plainSymbolRope, symbolOrIdRope, + plainSymbolEncRope, symbolOrIdEncRope])) + + # Ironically for types the complexSymbol is *cleaner* than the plainName + # because it doesn't include object fields or documentation comments. So we + # use the plain one for callable elements, and the complex for the rest. + var linkTitle = changeFileExt(extractFilename(d.filename), "") & " : " + if n.isCallable: linkTitle.add(xmltree.escape(plainName.strip)) + else: linkTitle.add(xmltree.escape(complexSymbol.strip)) + + setIndexTerm(d[], symbolOrId, name, linkTitle, + xmltree.escape(plainDocstring.docstringSummary)) proc genJSONItem(d: PDoc, n, nameNode: PNode, k: TSymKind): PJsonNode = if not isVisible(nameNode): return diff --git a/compiler/options.nim b/compiler/options.nim index 102ebc386..fa8b77ead 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -100,6 +100,8 @@ var gSelectedGC* = gcRefc # the selected GC searchPaths*, lazyPaths*: TLinkedList outFile*: string = "" + docSeeSrcUrl*: string = "" # if empty, no seeSrc will be generated. \ + # The string uses the formatting variables `path` and `line`. headerFile*: string = "" gVerbosity* = 1 # how verbose the compiler is gNumberOfProcessors*: int # number of processors diff --git a/compiler/renderer.nim b/compiler/renderer.nim index 2d2310914..fa119eba9 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -15,7 +15,7 @@ import type TRenderFlag* = enum renderNone, renderNoBody, renderNoComments, renderDocComments, - renderNoPragmas, renderIds + renderNoPragmas, renderIds, renderNoProcDefs TRenderFlags* = set[TRenderFlag] TRenderTok*{.final.} = object kind*: TTokType @@ -51,10 +51,17 @@ proc isKeyword*(s: string): bool = (i.id <= ord(tokKeywordHigh) - ord(tkSymbol)): result = true -proc renderDefinitionName*(s: PSym): string = +proc renderDefinitionName*(s: PSym, noQuotes = false): string = + ## Returns the definition name of the symbol. + ## + ## If noQuotes is false the symbol may be returned in backticks. This will + ## happen if the name happens to be a keyword or the first character is not + ## part of the SymStartChars set. let x = s.name.s - if x[0] in SymStartChars and not renderer.isKeyword(x): result = x - else: result = '`' & x & '`' + if noQuotes or (x[0] in SymStartChars and not renderer.isKeyword(x)): + result = x + else: + result = '`' & x & '`' const IndentWidth = 2 @@ -1119,22 +1126,22 @@ proc gsub(g: var TSrcGen, n: PNode, c: TContext) = of nkStaticStmt: gstaticStmt(g, n) of nkAsmStmt: gasm(g, n) of nkProcDef: - putWithSpace(g, tkProc, "proc") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkProc, "proc") gproc(g, n) of nkConverterDef: - putWithSpace(g, tkConverter, "converter") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkConverter, "converter") gproc(g, n) of nkMethodDef: - putWithSpace(g, tkMethod, "method") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkMethod, "method") gproc(g, n) of nkIteratorDef: - putWithSpace(g, tkIterator, "iterator") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkIterator, "iterator") gproc(g, n) of nkMacroDef: - putWithSpace(g, tkMacro, "macro") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkMacro, "macro") gproc(g, n) of nkTemplateDef: - putWithSpace(g, tkTemplate, "template") + if renderNoProcDefs notin g.flags: putWithSpace(g, tkTemplate, "template") gproc(g, n) of nkTypeSection: gsection(g, n, emptyContext, tkType, "type") @@ -1336,4 +1343,3 @@ proc getNextTok(r: var TSrcGen, kind: var TTokType, literal: var string) = inc(r.idx) else: kind = tkEof - diff --git a/compiler/typesrenderer.nim b/compiler/typesrenderer.nim new file mode 100644 index 000000000..ebb9b7e15 --- /dev/null +++ b/compiler/typesrenderer.nim @@ -0,0 +1,113 @@ +import renderer, strutils, ast, msgs, types + +const defaultParamSeparator* = "," + +proc renderPlainSymbolName*(n: PNode): string = + ## Returns the first non '*' nkIdent node from the tree. + ## + ## Use this on documentation name nodes to extract the *raw* symbol name, + ## without decorations, parameters, or anything. That can be used as the base + ## for the HTML hyperlinks. + result = "" + case n.kind + of nkPostfix: + for i in 0 .. 0: + return + of nkIdent: + if n.ident.s != "*": + result = n.ident.s + of nkSym: + result = n.sym.renderDefinitionName(noQuotes = true) + of nkPragmaExpr: + result = renderPlainSymbolName(n[0]) + of nkAccQuoted: + result = renderPlainSymbolName(n[ 1 + let params = n[0] + assert params.kind == nkFormalParams + assert len(params) > 0 + result = "proc(" + for i in 1 .. = 3 + let typePos = len(n) - 2 + let typeStr = renderType(n[typePos]) + result = typeStr + for i in 1 .. 0 + result = "tuple[" + for i in 0 .. = 2 + result = renderType(n[0]) & '[' + for i in 1 .. 0 + var typeStr = renderType(n[typePos]) + if typeStr.len < 1: + # Try with the last node, maybe its a default value. + assert n[typePos+1].kind != nkEmpty + let typ = n[typePos+1].typ + if not typ.isNil: typeStr = typeToString(typ, preferExported) + if typeStr.len < 1: + return + for i in 0 .. 0: + result = found.join(sep) diff --git a/config/nimdoc.cfg b/config/nimdoc.cfg index 63a3c30c4..dc241db50 100644 --- a/config/nimdoc.cfg +++ b/config/nimdoc.cfg @@ -1,6 +1,7 @@ # This is the config file for the documentation generator. # (c) 2012 Andreas Rumpf -# Feel free to edit the templates as you need. +# Feel free to edit the templates as you need. If you modify this file, it +# might be worth updating the hardcoded values in packages/docutils/rstgen.ni split.item.toc = "20" # too long entries in the table of contents wrap around @@ -23,17 +24,45 @@ doc.section.toc = """ """ +# Chunk of HTML emmited for each entry in the HTML table of contents. +# Available variables are: +# * $desc: the actual docstring of the item. +# * $header: the full version of name, including types, pragmas, tags, etc. +# * $header_plain: like header but without HTML, for attribute embedding. +# * $itemID: numerical unique entry of the item in the HTML. +# * $itemSym: short symbolic name of the item for easier hyperlinking. +# * $itemSymEnc: quoted version for URLs or attributes. +# * $itemSymOrID: the symbolic name or the ID if that is not unique. +# * $itemSymOrIDEnc: quoted version for URLs or attributes. +# * $name: reduced name of the item. +# * $seeSrc: generated HTML from doc.item.seesrc (if some switches are used). + doc.item = """ -
$header
+
$header
$desc +$seeSrc
""" +# Chunk of HTML emmited for each entry in the HTML table of contents. +# See doc.item for available substitution variables. doc.item.toc = """ -
  • $name
  • +
  • $name
  • """ +# HTML rendered for doc.item's seeSrc variable. Note that this will render to +# the empty string if you don't pass anything through --docSeeSrcURL. Available +# substitutaion variables here are: +# * $path: relative path to the file being processed. +# * $line: line of the item in the original source file. +# * $url: whatever you did pass through the --docSeeSrcUrl switch (which also +# gets variables path/line replaced!) +doc.item.seesrc = """See source""" + doc.toc = """