From 9a1be7a9f3d8a6bd0c9b8ce5b37ad41c89250a56 Mon Sep 17 00:00:00 2001 From: dumndummer Date: Mon, 2 Feb 2015 17:57:31 +0000 Subject: Update macros.nim minor doc comment spelling correction --- lib/core/macros.nim | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) (limited to 'lib/core/macros.nim') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 3e0da79be..22b9c4907 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -238,7 +238,7 @@ proc genSym*(kind: TNimrodSymKind = nskLet; ident = ""): PNimrodNode {. ## needs to occur in a declaration context. proc callsite*(): PNimrodNode {.magic: "NCallSite", gcsafe.} - ## returns the AST if the invokation expression that invoked this macro. + ## returns the AST of the invocation expression that invoked this macro. proc toStrLit*(n: PNimrodNode): PNimrodNode {.compileTime.} = ## converts the AST `n` to the concrete Nimrod code and wraps that -- cgit 1.4.1-2-gfad0 From 10335fd7264560e9b5a6ca4b2b5fe8e28e78209b Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 11 Feb 2015 17:42:28 +0100 Subject: fixed minor bugs; cleaned up tests --- compiler/sempass2.nim | 3 +- lib/core/macros.nim | 20 +- lib/pure/collections/tables.nim | 2 +- lib/pure/math.nim | 8 +- lib/pure/net.nim | 9 +- lib/pure/os.nim | 6 +- lib/pure/times.nim | 102 ++++----- lib/system.nim | 38 ++-- lib/system/repr.nim | 6 +- tests/collections/tindexby.nim | 22 ++ tests/collections/ttableconstr.nim | 16 ++ tests/collections/ttables.nim | 148 ++++++++++-- tests/collections/ttables2.nim | 20 ++ tests/collections/ttablesref.nim | 137 +++++++++++ tests/collections/ttablesref2.nim | 20 ++ tests/stdlib/tircbot.nim | 453 ------------------------------------- tests/stdlib/tmitems.nim | 2 +- tests/table/ptables.nim | 137 ----------- tests/table/ptables2.nim | 20 -- tests/table/ttableconstr.nim | 16 -- tests/table/ttables.nim | 128 ----------- tests/table/ttables2.nim | 20 -- todo.txt | 1 - 23 files changed, 438 insertions(+), 896 deletions(-) create mode 100644 tests/collections/tindexby.nim create mode 100644 tests/collections/ttableconstr.nim create mode 100644 tests/collections/ttables2.nim create mode 100644 tests/collections/ttablesref.nim create mode 100644 tests/collections/ttablesref2.nim delete mode 100644 tests/stdlib/tircbot.nim delete mode 100644 tests/table/ptables.nim delete mode 100644 tests/table/ptables2.nim delete mode 100644 tests/table/ttableconstr.nim delete mode 100644 tests/table/ttables.nim delete mode 100644 tests/table/ttables2.nim (limited to 'lib/core/macros.nim') diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index ede556a70..6fa7c756e 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -859,7 +859,8 @@ proc trackProc*(s: PSym, body: PNode) = if s.typ.lockLevel == UnspecifiedLockLevel: s.typ.lockLevel = t.maxLockLevel elif t.maxLockLevel > s.typ.lockLevel: - localError(s.info, + #localError(s.info, + message(s.info, warnLockLevel, "declared lock level is $1, but real lock level is $2" % [$s.typ.lockLevel, $t.maxLockLevel]) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 22b9c4907..4c561df70 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -136,12 +136,12 @@ proc len*(n: PNimrodNode): int {.magic: "NLen", noSideEffect.} ## returns the number of children of `n`. proc add*(father, child: PNimrodNode): PNimrodNode {.magic: "NAdd", discardable, - noSideEffect.} + noSideEffect, locks: 0.} ## Adds the `child` to the `father` node. Returns the ## father node so that calls can be nested. proc add*(father: PNimrodNode, children: varargs[PNimrodNode]): PNimrodNode {. - magic: "NAddMultiple", discardable, noSideEffect.} + magic: "NAddMultiple", discardable, noSideEffect, locks: 0.} ## Adds each child of `children` to the `father` node. ## Returns the `father` node so that calls can be nested. @@ -177,13 +177,13 @@ proc newNimNode*(kind: TNimrodNodeKind, proc copyNimNode*(n: PNimrodNode): PNimrodNode {.magic: "NCopyNimNode", noSideEffect.} proc copyNimTree*(n: PNimrodNode): PNimrodNode {.magic: "NCopyNimTree", noSideEffect.} -proc error*(msg: string) {.magic: "NError", gcsafe.} +proc error*(msg: string) {.magic: "NError", benign.} ## writes an error message at compile time -proc warning*(msg: string) {.magic: "NWarning", gcsafe.} +proc warning*(msg: string) {.magic: "NWarning", benign.} ## writes a warning message at compile time -proc hint*(msg: string) {.magic: "NHint", gcsafe.} +proc hint*(msg: string) {.magic: "NHint", benign.} ## writes a hint message at compile time proc newStrLitNode*(s: string): PNimrodNode {.compileTime, noSideEffect.} = @@ -237,7 +237,7 @@ proc genSym*(kind: TNimrodSymKind = nskLet; ident = ""): PNimrodNode {. ## generates a fresh symbol that is guaranteed to be unique. The symbol ## needs to occur in a declaration context. -proc callsite*(): PNimrodNode {.magic: "NCallSite", gcsafe.} +proc callsite*(): PNimrodNode {.magic: "NCallSite", benign.} ## returns the AST of the invocation expression that invoked this macro. proc toStrLit*(n: PNimrodNode): PNimrodNode {.compileTime.} = @@ -387,11 +387,11 @@ proc nestList*(theProc: TNimrodIdent, # This could easily user code and so should be fixed in evals.nim somehow. result = newCall(theProc, x[i], copyNimTree(result)) -proc treeRepr*(n: PNimrodNode): string {.compileTime.} = +proc treeRepr*(n: PNimrodNode): string {.compileTime, benign.} = ## Convert the AST `n` to a human-readable tree-like string. ## ## See also `repr` and `lispRepr`. - proc traverse(res: var string, level: int, n: PNimrodNode) = + proc traverse(res: var string, level: int, n: PNimrodNode) {.benign.} = for i in 0..level-1: res.add " " res.add(($n.kind).substr(3)) @@ -412,7 +412,7 @@ proc treeRepr*(n: PNimrodNode): string {.compileTime.} = result = "" traverse(result, 0, n) -proc lispRepr*(n: PNimrodNode): string {.compileTime.} = +proc lispRepr*(n: PNimrodNode): string {.compileTime, benign.} = ## Convert the AST `n` to a human-readable lisp-like string, ## ## See also `repr` and `treeRepr`. @@ -651,7 +651,7 @@ proc `body=`*(someProc: PNimrodNode, val: PNimrodNode) {.compileTime.} = else: badNodeKind someProc.kind, "body=" -proc basename*(a: PNimrodNode): PNimrodNode {.compiletime.} +proc basename*(a: PNimrodNode): PNimrodNode {.compiletime, benign.} proc `$`*(node: PNimrodNode): string {.compileTime.} = diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index 9dcc97148..671f767cf 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -347,7 +347,7 @@ proc `$`*[A, B](t: TableRef[A, B]): string = proc `==`*[A, B](s, t: TableRef[A, B]): bool = if isNil(s): result = isNil(t) elif isNil(t): result = false - else: result = equalsImpl() + else: equalsImpl() proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B] = ## Index the collection with the proc provided. diff --git a/lib/pure/math.nim b/lib/pure/math.nim index b9e057e78..1690377ff 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -129,25 +129,25 @@ proc variance*(x: openArray[float]): float {.noSideEffect.} = result = result + diff*diff result = result / toFloat(len(x)) -proc random*(max: int): int {.gcsafe.} +proc random*(max: int): int {.benign.} ## returns a random number in the range 0..max-1. The sequence of ## random number is always the same, unless `randomize` is called ## which initializes the random number generator with a "random" ## number, i.e. a tickcount. -proc random*(max: float): float {.gcsafe.} +proc random*(max: float): float {.benign.} ## returns a random number in the range 0.. 2..4 +# test table constructor: +ignoreExpr({:}) +ignoreExpr({2: 3, "key": "value"}) + +# NEW: +assert 56 in 50..100 + +assert 56 in ..60 + diff --git a/tests/collections/ttables.nim b/tests/collections/ttables.nim index f374d5504..de4aaed5e 100644 --- a/tests/collections/ttables.nim +++ b/tests/collections/ttables.nim @@ -1,22 +1,128 @@ -import tables - -doAssert indexBy(newSeq[int](), proc(x: int):int = x) == initTable[int, int](), "empty int table" - -var tbl1 = initTable[int, int]() -tbl1.add(1,1) -tbl1.add(2,2) -doAssert indexBy(@[1,2], proc(x: int):int = x) == tbl1, "int table" - -type - TElem = object - foo: int - bar: string - -let - elem1 = TElem(foo: 1, bar: "bar") - elem2 = TElem(foo: 2, bar: "baz") +discard """ + output: '''true''' +""" + +import hashes, tables + +const + data = { + "34": 123456, "12": 789, + "90": 343, "0": 34404, + "1": 344004, "2": 344774, + "3": 342244, "4": 3412344, + "5": 341232144, "6": 34214544, + "7": 3434544, "8": 344544, + "9": 34435644, "---00": 346677844, + "10": 34484, "11": 34474, "19": 34464, + "20": 34454, "30": 34141244, "40": 344114, + "50": 344490, "60": 344491, "70": 344492, + "80": 344497} + + sorteddata = { + "---00": 346677844, + "0": 34404, + "1": 344004, + "10": 34484, + "11": 34474, + "12": 789, + "19": 34464, + "2": 344774, "20": 34454, + "3": 342244, "30": 34141244, + "34": 123456, + "4": 3412344, "40": 344114, + "5": 341232144, "50": 344490, + "6": 34214544, "60": 344491, + "7": 3434544, "70": 344492, + "8": 344544, "80": 344497, + "9": 34435644, + "90": 343} + +block tableTest1: + var t = initTable[tuple[x, y: int], string]() + t[(0,0)] = "00" + t[(1,0)] = "10" + t[(0,1)] = "01" + t[(1,1)] = "11" + for x in 0..1: + for y in 0..1: + assert t[(x,y)] == $x & $y + assert($t == + "{(x: 0, y: 0): 00, (x: 0, y: 1): 01, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") + +block tableTest2: + var t = initTable[string, float]() + t["test"] = 1.2345 + t["111"] = 1.000043 + t["123"] = 1.23 + t.del("111") -var tbl2 = initTable[string, TElem]() -tbl2.add("bar", elem1) -tbl2.add("baz", elem2) -doAssert indexBy(@[elem1,elem2], proc(x: TElem): string = x.bar) == tbl2, "element table" + t["012"] = 67.9 + t["123"] = 1.5 # test overwriting + + assert t["123"] == 1.5 + assert t["111"] == 0.0 # deleted + assert(not hasKey(t, "111")) + + for key, val in items(data): t[key] = val.toFloat + for key, val in items(data): assert t[key] == val.toFloat + + +block orderedTableTest1: + var t = initOrderedTable[string, int](2) + for key, val in items(data): t[key] = val + for key, val in items(data): assert t[key] == val + var i = 0 + # `pairs` needs to yield in insertion order: + for key, val in pairs(t): + assert key == data[i][0] + assert val == data[i][1] + inc(i) + + for key, val in mpairs(t): val = 99 + for val in mvalues(t): assert val == 99 + +block countTableTest1: + var s = data.toTable + var t = initCountTable[string]() + for k in s.keys: t.inc(k) + for k in t.keys: assert t[k] == 1 + t.inc("90", 3) + t.inc("12", 2) + t.inc("34", 1) + assert t.largest()[0] == "90" + + t.sort() + var i = 0 + for k, v in t.pairs: + case i + of 0: assert k == "90" and v == 4 + of 1: assert k == "12" and v == 3 + of 2: assert k == "34" and v == 2 + else: break + inc i + +block SyntaxTest: + var x = toTable[int, string]({:}) + +proc orderedTableSortTest() = + var t = initOrderedTable[string, int](2) + for key, val in items(data): t[key] = val + for key, val in items(data): assert t[key] == val + t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)) + var i = 0 + # `pairs` needs to yield in sorted order: + for key, val in pairs(t): + doAssert key == sorteddata[i][0] + doAssert val == sorteddata[i][1] + inc(i) + + # check that lookup still works: + for key, val in pairs(t): + doAssert val == t[key] + # check that insert still works: + t["newKeyHere"] = 80 + + +orderedTableSortTest() +echo "true" + diff --git a/tests/collections/ttables2.nim b/tests/collections/ttables2.nim new file mode 100644 index 000000000..611f3f8ec --- /dev/null +++ b/tests/collections/ttables2.nim @@ -0,0 +1,20 @@ +discard """ + output: '''true''' +""" + +import tables + +proc TestHashIntInt() = + var tab = initTable[int,int]() + for i in 1..1_000_000: + tab[i] = i + for i in 1..1_000_000: + var x = tab[i] + if x != i : echo "not found ", i + +proc run1() = # occupied Memory stays constant, but + for i in 1 .. 50: # aborts at run: 44 on win32 with 3.2GB with out of memory + TestHashIntInt() + +run1() +echo "true" diff --git a/tests/collections/ttablesref.nim b/tests/collections/ttablesref.nim new file mode 100644 index 000000000..e666c7852 --- /dev/null +++ b/tests/collections/ttablesref.nim @@ -0,0 +1,137 @@ +discard """ + output: '''true''' +""" + +import hashes, tables + +const + data = { + "34": 123456, "12": 789, + "90": 343, "0": 34404, + "1": 344004, "2": 344774, + "3": 342244, "4": 3412344, + "5": 341232144, "6": 34214544, + "7": 3434544, "8": 344544, + "9": 34435644, "---00": 346677844, + "10": 34484, "11": 34474, "19": 34464, + "20": 34454, "30": 34141244, "40": 344114, + "50": 344490, "60": 344491, "70": 344492, + "80": 344497} + + sorteddata = { + "---00": 346677844, + "0": 34404, + "1": 344004, + "10": 34484, + "11": 34474, + "12": 789, + "19": 34464, + "2": 344774, "20": 34454, + "3": 342244, "30": 34141244, + "34": 123456, + "4": 3412344, "40": 344114, + "5": 341232144, "50": 344490, + "6": 34214544, "60": 344491, + "7": 3434544, "70": 344492, + "8": 344544, "80": 344497, + "9": 34435644, + "90": 343} + +block tableTest1: + var t = newTable[tuple[x, y: int], string]() + t[(0,0)] = "00" + t[(1,0)] = "10" + t[(0,1)] = "01" + t[(1,1)] = "11" + for x in 0..1: + for y in 0..1: + assert t[(x,y)] == $x & $y + assert($t == + "{(x: 0, y: 0): 00, (x: 0, y: 1): 01, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") + +block tableTest2: + var t = newTable[string, float]() + t["test"] = 1.2345 + t["111"] = 1.000043 + t["123"] = 1.23 + t.del("111") + + t["012"] = 67.9 + t["123"] = 1.5 # test overwriting + + assert t["123"] == 1.5 + assert t["111"] == 0.0 # deleted + assert(not hasKey(t, "111")) + + for key, val in items(data): t[key] = val.toFloat + for key, val in items(data): assert t[key] == val.toFloat + + +block orderedTableTest1: + var t = newOrderedTable[string, int](2) + for key, val in items(data): t[key] = val + for key, val in items(data): assert t[key] == val + var i = 0 + # `pairs` needs to yield in insertion order: + for key, val in pairs(t): + assert key == data[i][0] + assert val == data[i][1] + inc(i) + + for key, val in mpairs(t): val = 99 + for val in mvalues(t): assert val == 99 + +block countTableTest1: + var s = data.toTable + var t = newCountTable[string]() + for k in s.keys: t.inc(k) + for k in t.keys: assert t[k] == 1 + t.inc("90", 3) + t.inc("12", 2) + t.inc("34", 1) + assert t.largest()[0] == "90" + + t.sort() + var i = 0 + for k, v in t.pairs: + case i + of 0: assert k == "90" and v == 4 + of 1: assert k == "12" and v == 3 + of 2: assert k == "34" and v == 2 + else: break + inc i + +block SyntaxTest: + var x = newTable[int, string]({:}) + +block nilTest: + var i, j: PTable[int, int] = nil + assert i == j + j = newTable[int, int]() + assert i != j + assert j != i + i = newTable[int, int]() + assert i == j + +proc orderedTableSortTest() = + var t = newOrderedTable[string, int](2) + for key, val in items(data): t[key] = val + for key, val in items(data): assert t[key] == val + t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)) + var i = 0 + # `pairs` needs to yield in sorted order: + for key, val in pairs(t): + doAssert key == sorteddata[i][0] + doAssert val == sorteddata[i][1] + inc(i) + + # check that lookup still works: + for key, val in pairs(t): + doAssert val == t[key] + # check that insert still works: + t["newKeyHere"] = 80 + + +orderedTableSortTest() +echo "true" + diff --git a/tests/collections/ttablesref2.nim b/tests/collections/ttablesref2.nim new file mode 100644 index 000000000..939de2b84 --- /dev/null +++ b/tests/collections/ttablesref2.nim @@ -0,0 +1,20 @@ +discard """ + output: '''true''' +""" + +import tables + +proc TestHashIntInt() = + var tab = newTable[int,int]() + for i in 1..1_000_000: + tab[i] = i + for i in 1..1_000_000: + var x = tab[i] + if x != i : echo "not found ", i + +proc run1() = # occupied Memory stays constant, but + for i in 1 .. 50: # aborts at run: 44 on win32 with 3.2GB with out of memory + TestHashIntInt() + +run1() +echo "true" diff --git a/tests/stdlib/tircbot.nim b/tests/stdlib/tircbot.nim deleted file mode 100644 index 6b209dce3..000000000 --- a/tests/stdlib/tircbot.nim +++ /dev/null @@ -1,453 +0,0 @@ -import irc, sockets, asyncio, json, os, strutils, times, redis - -type - TDb* = object - r*: Redis - lastPing: float - - TBuildResult* = enum - bUnknown, bFail, bSuccess - - TTestResult* = enum - tUnknown, tFail, tSuccess - - TEntry* = tuple[c: TCommit, p: seq[TPlatform]] - - TCommit* = object - commitMsg*, username*, hash*: string - date*: Time - - TPlatform* = object - buildResult*: TBuildResult - testResult*: TTestResult - failReason*, platform*: string - total*, passed*, skipped*, failed*: BiggestInt - csources*: bool - -const - listName = "commits" - failOnExisting = false - -proc open*(host = "localhost", port: Port): TDb = - result.r = redis.open(host, port) - result.lastPing = epochTime() - -discard """proc customHSet(database: TDb, name, field, value: string) = - if database.r.hSet(name, field, value).int == 0: - if failOnExisting: - assert(false) - else: - echo("[Warning:REDIS] ", field, " already exists in ", name)""" - -proc updateProperty*(database: TDb, commitHash, platform, property, - value: string) = - var name = platform & ":" & commitHash - if database.r.hSet(name, property, value).int == 0: - echo("[INFO:REDIS] '$1' field updated in hash" % [property]) - else: - echo("[INFO:REDIS] '$1' new field added to hash" % [property]) - -proc globalProperty*(database: TDb, commitHash, property, value: string) = - if database.r.hSet(commitHash, property, value).int == 0: - echo("[INFO:REDIS] '$1' field updated in hash" % [property]) - else: - echo("[INFO:REDIS] '$1' new field added to hash" % [property]) - -proc addCommit*(database: TDb, commitHash, commitMsg, user: string) = - # Add the commit hash to the `commits` list. - discard database.r.lPush(listName, commitHash) - # Add the commit message, current date and username as a property - globalProperty(database, commitHash, "commitMsg", commitMsg) - globalProperty(database, commitHash, "date", $int(getTime())) - globalProperty(database, commitHash, "username", user) - -proc keepAlive*(database: var TDb) = - ## Keep the connection alive. Ping redis in this case. This functions does - ## not guarantee that redis will be pinged. - var t = epochTime() - if t - database.lastPing >= 60.0: - echo("PING -> redis") - assert(database.r.ping() == "PONG") - database.lastPing = t - -proc getCommits*(database: TDb, - plStr: var seq[string]): seq[TEntry] = - result = @[] - var commitsRaw = database.r.lrange("commits", 0, -1) - for c in items(commitsRaw): - var commit: TCommit - commit.hash = c - for key, value in database.r.hPairs(c): - case normalize(key) - of "commitmsg": commit.commitMsg = value - of "date": commit.date = Time(parseInt(value)) - of "username": commit.username = value - else: - echo(key) - assert(false) - - var platformsRaw = database.r.lrange(c & ":platforms", 0, -1) - var platforms: seq[TPlatform] = @[] - for p in items(platformsRaw): - var platform: TPlatform - for key, value in database.r.hPairs(p & ":" & c): - case normalize(key) - of "buildresult": - platform.buildResult = parseInt(value).TBuildResult - of "testresult": - platform.testResult = parseInt(value).TTestResult - of "failreason": - platform.failReason = value - of "total": - platform.total = parseBiggestInt(value) - of "passed": - platform.passed = parseBiggestInt(value) - of "skipped": - platform.skipped = parseBiggestInt(value) - of "failed": - platform.failed = parseBiggestInt(value) - of "csources": - platform.csources = if value == "t": true else: false - else: - echo(normalize(key)) - assert(false) - - platform.platform = p - - platforms.add(platform) - if p notin plStr: - plStr.add(p) - result.add((commit, platforms)) - -proc commitExists*(database: TDb, commit: string, starts = false): bool = - # TODO: Consider making the 'commits' list a set. - for c in items(database.r.lrange("commits", 0, -1)): - if starts: - if c.startsWith(commit): return true - else: - if c == commit: return true - return false - -proc platformExists*(database: TDb, commit: string, platform: string): bool = - for p in items(database.r.lrange(commit & ":" & "platforms", 0, -1)): - if p == platform: return true - -proc expandHash*(database: TDb, commit: string): string = - for c in items(database.r.lrange("commits", 0, -1)): - if c.startsWith(commit): return c - assert false - -proc isNewest*(database: TDb, commit: string): bool = - return database.r.lIndex("commits", 0) == commit - -proc getNewest*(database: TDb): string = - return database.r.lIndex("commits", 0) - -proc addPlatform*(database: TDb, commit: string, platform: string) = - assert database.commitExists(commit) - assert (not database.platformExists(commit, platform)) - var name = platform & ":" & commit - if database.r.exists(name): - if failOnExisting: quit("[FAIL] " & name & " already exists!", 1) - else: echo("[Warning] " & name & " already exists!") - - discard database.r.lPush(commit & ":" & "platforms", platform) - -proc `[]`*(p: seq[TPlatform], name: string): TPlatform = - for platform in items(p): - if platform.platform == name: - return platform - raise newException(ValueError, name & " platforms not found in commits.") - -proc contains*(p: seq[TPlatform], s: string): bool = - for i in items(p): - if i.platform == s: - return true - - -type - PState = ref TState - TState = object of RootObj - dispatcher: Dispatcher - sock: AsyncSocket - ircClient: PAsyncIRC - hubPort: Port - database: TDb - dbConnected: bool - - TSeenType = enum - PSeenJoin, PSeenPart, PSeenMsg, PSeenNick, PSeenQuit - - TSeen = object - nick: string - channel: string - timestamp: Time - case kind*: TSeenType - of PSeenJoin: nil - of PSeenPart, PSeenQuit, PSeenMsg: - msg: string - of PSeenNick: - newNick: string - -const - ircServer = "irc.freenode.net" - joinChans = @["#nim"] - botNickname = "NimBot" - -proc setSeen(d: TDb, s: TSeen) = - discard d.r.del("seen:" & s.nick) - - var hashToSet = @[("type", $s.kind.int), ("channel", s.channel), - ("timestamp", $s.timestamp.int)] - case s.kind - of PSeenJoin: discard - of PSeenPart, PSeenMsg, PSeenQuit: - hashToSet.add(("msg", s.msg)) - of PSeenNick: - hashToSet.add(("newnick", s.newNick)) - - d.r.hMSet("seen:" & s.nick, hashToSet) - -proc getSeen(d: TDb, nick: string, s: var TSeen): bool = - if d.r.exists("seen:" & nick): - result = true - s.nick = nick - # Get the type first - s.kind = d.r.hGet("seen:" & nick, "type").parseInt.TSeenType - - for key, value in d.r.hPairs("seen:" & nick): - case normalize(key) - of "type": - discard - #s.kind = value.parseInt.TSeenType - of "channel": - s.channel = value - of "timestamp": - s.timestamp = Time(value.parseInt) - of "msg": - s.msg = value - of "newnick": - s.newNick = value - -template createSeen(typ: TSeenType, n, c: string): stmt {.immediate, dirty.} = - var seenNick: TSeen - seenNick.kind = typ - seenNick.nick = n - seenNick.channel = c - seenNick.timestamp = getTime() - -proc parseReply(line: string, expect: string): bool = - var jsonDoc = parseJson(line) - return jsonDoc["reply"].str == expect - -proc limitCommitMsg(m: string): string = - ## Limits the message to 300 chars and adds ellipsis. - var m1 = m - if NewLines in m1: - m1 = m1.splitLines()[0] - - if m1.len >= 300: - m1 = m1[0..300] - - if m1.len >= 300 or NewLines in m: m1.add("... ") - - if NewLines in m: m1.add($m.splitLines().len & " more lines") - - return m1 - -proc handleWebMessage(state: PState, line: string) = - echo("Got message from hub: " & line) - var json = parseJson(line) - if json.hasKey("payload"): - for i in 0..min(4, json["payload"]["commits"].len-1): - var commit = json["payload"]["commits"][i] - # Create the message - var message = "" - message.add(json["payload"]["repository"]["owner"]["name"].str & "/" & - json["payload"]["repository"]["name"].str & " ") - message.add(commit["id"].str[0..6] & " ") - message.add(commit["author"]["name"].str & " ") - message.add("[+" & $commit["added"].len & " ") - message.add("±" & $commit["modified"].len & " ") - message.add("-" & $commit["removed"].len & "]: ") - message.add(limitCommitMsg(commit["message"].str)) - - # Send message to #nim. - discard state.ircClient.privmsg(joinChans[0], message) - elif json.hasKey("redisinfo"): - assert json["redisinfo"].hasKey("port") - #let redisPort = json["redisinfo"]["port"].num - state.dbConnected = true - -proc hubConnect(state: PState) -proc handleConnect(s: AsyncSocket, state: PState) = - try: - # Send greeting - var obj = newJObject() - obj["name"] = newJString("irc") - obj["platform"] = newJString("?") - state.sock.send($obj & "\c\L") - - # Wait for reply. - var line = "" - sleep(1500) - if state.sock.recvLine(line): - assert(line != "") - doAssert parseReply(line, "OK") - echo("The hub accepted me!") - else: - raise newException(ValueError, - "Hub didn't accept me. Waited 1.5 seconds.") - - # ask for the redis info - var riobj = newJObject() - riobj["do"] = newJString("redisinfo") - state.sock.send($riobj & "\c\L") - - except OsError: - echo(getCurrentExceptionMsg()) - s.close() - echo("Waiting 5 seconds...") - sleep(5000) - state.hubConnect() - -proc handleRead(s: AsyncSocket, state: PState) = - var line = "" - if state.sock.recvLine(line): - if line != "": - # Handle the message - state.handleWebMessage(line) - else: - echo("Disconnected from hub: ", osErrorMsg()) - s.close() - echo("Reconnecting...") - state.hubConnect() - else: - echo(osErrorMsg()) - -proc hubConnect(state: PState) = - state.sock = asyncSocket() - state.sock.connect("127.0.0.1", state.hubPort) - state.sock.handleConnect = - proc (s: AsyncSocket) = - handleConnect(s, state) - state.sock.handleRead = - proc (s: AsyncSocket) = - handleRead(s, state) - - state.dispatcher.register(state.sock) - -proc handleIrc(irc: PAsyncIRC, event: TIRCEvent, state: PState) = - case event.typ - of EvConnected: discard - of EvDisconnected: - while not state.ircClient.isConnected: - try: - state.ircClient.connect() - except: - echo("Error reconnecting: ", getCurrentExceptionMsg()) - - echo("Waiting 5 seconds...") - sleep(5000) - echo("Reconnected successfully!") - of EvMsg: - echo("< ", event.raw) - case event.cmd - of MPrivMsg: - let msg = event.params[event.params.len-1] - let words = msg.split(' ') - template pm(msg: string): stmt = - state.ircClient.privmsg(event.origin, msg) - case words[0] - of "!ping": pm("pong") - of "!lag": - if state.ircClient.getLag != -1.0: - var lag = state.ircClient.getLag - lag = lag * 1000.0 - pm($int(lag) & "ms between me and the server.") - else: - pm("Unknown.") - of "!seen": - if words.len > 1: - let nick = words[1] - if nick == botNickname: - pm("Yes, I see myself.") - echo(nick) - var seenInfo: TSeen - if state.database.getSeen(nick, seenInfo): - #var mSend = "" - case seenInfo.kind - of PSeenMsg: - pm("$1 was last seen on $2 in $3 saying: $4" % - [seenInfo.nick, $seenInfo.timestamp, - seenInfo.channel, seenInfo.msg]) - of PSeenJoin: - pm("$1 was last seen on $2 joining $3" % - [seenInfo.nick, $seenInfo.timestamp, seenInfo.channel]) - of PSeenPart: - pm("$1 was last seen on $2 leaving $3 with message: $4" % - [seenInfo.nick, $seenInfo.timestamp, seenInfo.channel, - seenInfo.msg]) - of PSeenQuit: - pm("$1 was last seen on $2 quitting with message: $3" % - [seenInfo.nick, $seenInfo.timestamp, seenInfo.msg]) - of PSeenNick: - pm("$1 was last seen on $2 changing nick to $3" % - [seenInfo.nick, $seenInfo.timestamp, seenInfo.newNick]) - - else: - pm("I have not seen " & nick) - else: - pm("Syntax: !seen ") - - # TODO: ... commands - - # -- Seen - # Log this as activity. - createSeen(PSeenMsg, event.nick, event.origin) - seenNick.msg = msg - state.database.setSeen(seenNick) - of MJoin: - createSeen(PSeenJoin, event.nick, event.origin) - state.database.setSeen(seenNick) - of MPart: - createSeen(PSeenPart, event.nick, event.origin) - let msg = event.params[event.params.high] - seenNick.msg = msg - state.database.setSeen(seenNick) - of MQuit: - createSeen(PSeenQuit, event.nick, event.origin) - let msg = event.params[event.params.high] - seenNick.msg = msg - state.database.setSeen(seenNick) - of MNick: - createSeen(PSeenNick, event.nick, "#nim") - seenNick.newNick = event.params[0] - state.database.setSeen(seenNick) - else: - discard # TODO: ? - -proc open(port: Port = Port(5123)): PState = - var res: PState - new(res) - res.dispatcher = newDispatcher() - - res.hubPort = port - res.hubConnect() - let hirc = - proc (a: PAsyncIRC, ev: TIRCEvent) = - handleIrc(a, ev, res) - # Connect to the irc server. - res.ircClient = AsyncIrc(ircServer, nick = botNickname, user = botNickname, - joinChans = joinChans, ircEvent = hirc) - res.ircClient.connect() - res.dispatcher.register(res.ircClient) - - res.dbConnected = false - result = res - -var state = tircbot.open() # Connect to the website and the IRC server. - -while state.dispatcher.poll(): - if state.dbConnected: - state.database.keepAlive() diff --git a/tests/stdlib/tmitems.nim b/tests/stdlib/tmitems.nim index bf67d2b7b..2c0a0392a 100644 --- a/tests/stdlib/tmitems.nim +++ b/tests/stdlib/tmitems.nim @@ -11,7 +11,7 @@ fpqeew [11, 12, 13] [11, 12, 13] [11, 12, 13] -{ "key1": 11, "key2": 12, "key3": 13} +{"key1": 11, "key2": 12, "key3": 13} [11, 12, 13] diff --git a/tests/table/ptables.nim b/tests/table/ptables.nim deleted file mode 100644 index 79a9aab17..000000000 --- a/tests/table/ptables.nim +++ /dev/null @@ -1,137 +0,0 @@ -discard """ - output: '''true''' -""" - -import hashes, tables - -const - data = { - "34": 123456, "12": 789, - "90": 343, "0": 34404, - "1": 344004, "2": 344774, - "3": 342244, "4": 3412344, - "5": 341232144, "6": 34214544, - "7": 3434544, "8": 344544, - "9": 34435644, "---00": 346677844, - "10": 34484, "11": 34474, "19": 34464, - "20": 34454, "30": 34141244, "40": 344114, - "50": 344490, "60": 344491, "70": 344492, - "80": 344497} - - sorteddata = { - "---00": 346677844, - "0": 34404, - "1": 344004, - "10": 34484, - "11": 34474, - "12": 789, - "19": 34464, - "2": 344774, "20": 34454, - "3": 342244, "30": 34141244, - "34": 123456, - "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, - "6": 34214544, "60": 344491, - "7": 3434544, "70": 344492, - "8": 344544, "80": 344497, - "9": 34435644, - "90": 343} - -block tableTest1: - var t = newTable[tuple[x, y: int], string]() - t[(0,0)] = "00" - t[(1,0)] = "10" - t[(0,1)] = "01" - t[(1,1)] = "11" - for x in 0..1: - for y in 0..1: - assert t[(x,y)] == $x & $y - assert($t == - "{(x: 0, y: 0): 00, (x: 0, y: 1): 01, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") - -block tableTest2: - var t = newTable[string, float]() - t["test"] = 1.2345 - t["111"] = 1.000043 - t["123"] = 1.23 - t.del("111") - - t["012"] = 67.9 - t["123"] = 1.5 # test overwriting - - assert t["123"] == 1.5 - assert t["111"] == 0.0 # deleted - assert(not hasKey(t, "111")) - - for key, val in items(data): t[key] = val.toFloat - for key, val in items(data): assert t[key] == val.toFloat - - -block orderedTableTest1: - var t = newOrderedTable[string, int](2) - for key, val in items(data): t[key] = val - for key, val in items(data): assert t[key] == val - var i = 0 - # `pairs` needs to yield in insertion order: - for key, val in pairs(t): - assert key == data[i][0] - assert val == data[i][1] - inc(i) - - for key, val in mpairs(t): val = 99 - for val in mvalues(t): assert val == 99 - -block countTableTest1: - var s = data.toTable - var t = newCountTable[string]() - for k in s.Keys: t.inc(k) - for k in t.keys: assert t[k] == 1 - t.inc("90", 3) - t.inc("12", 2) - t.inc("34", 1) - assert t.largest()[0] == "90" - - t.sort() - var i = 0 - for k, v in t.pairs: - case i - of 0: assert k == "90" and v == 4 - of 1: assert k == "12" and v == 3 - of 2: assert k == "34" and v == 2 - else: break - inc i - -block SyntaxTest: - var x = newTable[int, string]({:}) - -block nilTest: - var i, j: PTable[int, int] = nil - assert i == j - j = newTable[int, int]() - assert i != j - assert j != i - i = newTable[int, int]() - assert i == j - -proc orderedTableSortTest() = - var t = newOrderedTable[string, int](2) - for key, val in items(data): t[key] = val - for key, val in items(data): assert t[key] == val - t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)) - var i = 0 - # `pairs` needs to yield in sorted order: - for key, val in pairs(t): - doAssert key == sorteddata[i][0] - doAssert val == sorteddata[i][1] - inc(i) - - # check that lookup still works: - for key, val in pairs(t): - doAssert val == t[key] - # check that insert still works: - t["newKeyHere"] = 80 - - -orderedTableSortTest() -echo "true" - diff --git a/tests/table/ptables2.nim b/tests/table/ptables2.nim deleted file mode 100644 index 939de2b84..000000000 --- a/tests/table/ptables2.nim +++ /dev/null @@ -1,20 +0,0 @@ -discard """ - output: '''true''' -""" - -import tables - -proc TestHashIntInt() = - var tab = newTable[int,int]() - for i in 1..1_000_000: - tab[i] = i - for i in 1..1_000_000: - var x = tab[i] - if x != i : echo "not found ", i - -proc run1() = # occupied Memory stays constant, but - for i in 1 .. 50: # aborts at run: 44 on win32 with 3.2GB with out of memory - TestHashIntInt() - -run1() -echo "true" diff --git a/tests/table/ttableconstr.nim b/tests/table/ttableconstr.nim deleted file mode 100644 index 1a21a18d1..000000000 --- a/tests/table/ttableconstr.nim +++ /dev/null @@ -1,16 +0,0 @@ -# Test if the new table constructor syntax works: - -template ignoreExpr(e: expr): stmt {.immediate.} = - discard - -# test first class '..' syntactical citizen: -ignoreExpr x <> 2..4 -# test table constructor: -ignoreExpr({:}) -ignoreExpr({2: 3, "key": "value"}) - -# NEW: -assert 56 in 50..100 - -assert 56 in ..60 - diff --git a/tests/table/ttables.nim b/tests/table/ttables.nim deleted file mode 100644 index de4aaed5e..000000000 --- a/tests/table/ttables.nim +++ /dev/null @@ -1,128 +0,0 @@ -discard """ - output: '''true''' -""" - -import hashes, tables - -const - data = { - "34": 123456, "12": 789, - "90": 343, "0": 34404, - "1": 344004, "2": 344774, - "3": 342244, "4": 3412344, - "5": 341232144, "6": 34214544, - "7": 3434544, "8": 344544, - "9": 34435644, "---00": 346677844, - "10": 34484, "11": 34474, "19": 34464, - "20": 34454, "30": 34141244, "40": 344114, - "50": 344490, "60": 344491, "70": 344492, - "80": 344497} - - sorteddata = { - "---00": 346677844, - "0": 34404, - "1": 344004, - "10": 34484, - "11": 34474, - "12": 789, - "19": 34464, - "2": 344774, "20": 34454, - "3": 342244, "30": 34141244, - "34": 123456, - "4": 3412344, "40": 344114, - "5": 341232144, "50": 344490, - "6": 34214544, "60": 344491, - "7": 3434544, "70": 344492, - "8": 344544, "80": 344497, - "9": 34435644, - "90": 343} - -block tableTest1: - var t = initTable[tuple[x, y: int], string]() - t[(0,0)] = "00" - t[(1,0)] = "10" - t[(0,1)] = "01" - t[(1,1)] = "11" - for x in 0..1: - for y in 0..1: - assert t[(x,y)] == $x & $y - assert($t == - "{(x: 0, y: 0): 00, (x: 0, y: 1): 01, (x: 1, y: 0): 10, (x: 1, y: 1): 11}") - -block tableTest2: - var t = initTable[string, float]() - t["test"] = 1.2345 - t["111"] = 1.000043 - t["123"] = 1.23 - t.del("111") - - t["012"] = 67.9 - t["123"] = 1.5 # test overwriting - - assert t["123"] == 1.5 - assert t["111"] == 0.0 # deleted - assert(not hasKey(t, "111")) - - for key, val in items(data): t[key] = val.toFloat - for key, val in items(data): assert t[key] == val.toFloat - - -block orderedTableTest1: - var t = initOrderedTable[string, int](2) - for key, val in items(data): t[key] = val - for key, val in items(data): assert t[key] == val - var i = 0 - # `pairs` needs to yield in insertion order: - for key, val in pairs(t): - assert key == data[i][0] - assert val == data[i][1] - inc(i) - - for key, val in mpairs(t): val = 99 - for val in mvalues(t): assert val == 99 - -block countTableTest1: - var s = data.toTable - var t = initCountTable[string]() - for k in s.keys: t.inc(k) - for k in t.keys: assert t[k] == 1 - t.inc("90", 3) - t.inc("12", 2) - t.inc("34", 1) - assert t.largest()[0] == "90" - - t.sort() - var i = 0 - for k, v in t.pairs: - case i - of 0: assert k == "90" and v == 4 - of 1: assert k == "12" and v == 3 - of 2: assert k == "34" and v == 2 - else: break - inc i - -block SyntaxTest: - var x = toTable[int, string]({:}) - -proc orderedTableSortTest() = - var t = initOrderedTable[string, int](2) - for key, val in items(data): t[key] = val - for key, val in items(data): assert t[key] == val - t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)) - var i = 0 - # `pairs` needs to yield in sorted order: - for key, val in pairs(t): - doAssert key == sorteddata[i][0] - doAssert val == sorteddata[i][1] - inc(i) - - # check that lookup still works: - for key, val in pairs(t): - doAssert val == t[key] - # check that insert still works: - t["newKeyHere"] = 80 - - -orderedTableSortTest() -echo "true" - diff --git a/tests/table/ttables2.nim b/tests/table/ttables2.nim deleted file mode 100644 index 611f3f8ec..000000000 --- a/tests/table/ttables2.nim +++ /dev/null @@ -1,20 +0,0 @@ -discard """ - output: '''true''' -""" - -import tables - -proc TestHashIntInt() = - var tab = initTable[int,int]() - for i in 1..1_000_000: - tab[i] = i - for i in 1..1_000_000: - var x = tab[i] - if x != i : echo "not found ", i - -proc run1() = # occupied Memory stays constant, but - for i in 1 .. 50: # aborts at run: 44 on win32 with 3.2GB with out of memory - TestHashIntInt() - -run1() -echo "true" diff --git a/todo.txt b/todo.txt index 706954f65..57cfea017 100644 --- a/todo.txt +++ b/todo.txt @@ -41,7 +41,6 @@ Misc - make tuple unpacking work in a non-var/let context - built-in 'getImpl' - prevent 'alloc(TypeWithGCedMemory)' -- some table related tests are wrong (memory usage checks) Bugs -- cgit 1.4.1-2-gfad0 From c95f6f117a665bc6d3d64ae8703459759973f63f Mon Sep 17 00:00:00 2001 From: Federico Ceratto Date: Sun, 15 Feb 2015 16:06:06 +0000 Subject: Fix typos --- compiler/ast.nim | 6 +++--- compiler/canonicalizer.nim | 4 ++-- compiler/ccgexprs.nim | 2 +- compiler/ccgmerge.nim | 2 +- compiler/ccgutils.nim | 2 +- compiler/docgen.nim | 4 ++-- compiler/jsgen.nim | 2 +- compiler/lambdalifting.nim | 4 ++-- compiler/msgs.nim | 8 ++++---- compiler/rodread.nim | 2 +- compiler/semasgn.nim | 2 +- compiler/semdestruct.nim | 2 +- compiler/semexprs.nim | 4 ++-- compiler/seminst.nim | 2 +- compiler/sempass2.nim | 2 +- compiler/semstmts.nim | 6 +++--- compiler/semtempl.nim | 4 ++-- compiler/semtypes.nim | 20 ++++++++++---------- compiler/semtypinst.nim | 14 +++++++------- compiler/sigmatch.nim | 16 ++++++++-------- compiler/types.nim | 10 +++++----- doc/advopt.txt | 2 +- doc/idetools.txt | 6 +++--- doc/intern.txt | 2 +- koch.nim | 4 ++-- lib/core/macros.nim | 2 +- lib/pure/collections/sequtils.nim | 20 ++++++++++---------- lib/pure/colors.nim | 2 +- lib/pure/htmlparser.nim | 4 ++-- lib/pure/json.nim | 2 +- lib/pure/net.nim | 2 +- lib/pure/os.nim | 6 +++--- lib/pure/osproc.nim | 2 +- lib/pure/parsecfg.nim | 2 +- lib/pure/parseutils.nim | 2 +- lib/pure/parsexml.nim | 2 +- lib/pure/sockets.nim | 4 ++-- lib/pure/streams.nim | 20 ++++++++++---------- lib/pure/xmlparser.nim | 4 ++-- lib/system.nim | 4 ++-- lib/system/hti.nim | 2 +- lib/wrappers/libffi/msvc/win32.c | 2 +- lib/wrappers/mysql.nim | 2 +- lib/wrappers/readline/history.nim | 2 +- lib/wrappers/readline/tweaked/history.h | 2 +- .../keineschweine/dependencies/chipmunk/chipmunk.nim | 2 +- tests/manyloc/keineschweine/lib/zlib_helpers.nim | 4 ++-- tests/types/tforwty2.nim | 2 +- tinyc/tccgen.c | 2 +- 49 files changed, 115 insertions(+), 115 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/compiler/ast.nim b/compiler/ast.nim index 1a5ae8aab..18b6e6b37 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -314,7 +314,7 @@ type # XXX put this into an include file to avoid this issue! tyNone, tyBool, tyChar, tyEmpty, tyArrayConstr, tyNil, tyExpr, tyStmt, tyTypeDesc, - tyGenericInvokation, # ``T[a, b]`` for types to invoke + tyGenericInvocation, # ``T[a, b]`` for types to invoke tyGenericBody, # ``T[a, b, body]`` last parameter is the body tyGenericInst, # ``T[a, b, realInstance]`` instantiated generic type # realInstance will be a concrete type like tyObject @@ -859,7 +859,7 @@ const OverloadableSyms* = {skProc, skMethod, skIterator, skClosureIterator, skConverter, skModule, skTemplate, skMacro} - GenericTypes*: TTypeKinds = {tyGenericInvokation, tyGenericBody, + GenericTypes*: TTypeKinds = {tyGenericInvocation, tyGenericBody, tyGenericParam} StructuralEquivTypes*: TTypeKinds = {tyArrayConstr, tyNil, tyTuple, tyArray, @@ -1350,7 +1350,7 @@ proc propagateToOwner*(owner, elem: PType) = const HaveTheirOwnEmpty = {tySequence, tySet} owner.flags = owner.flags + (elem.flags * {tfHasMeta}) if tfNotNil in elem.flags: - if owner.kind in {tyGenericInst, tyGenericBody, tyGenericInvokation}: + if owner.kind in {tyGenericInst, tyGenericBody, tyGenericInvocation}: owner.flags.incl tfNotNil elif owner.kind notin HaveTheirOwnEmpty: owner.flags.incl tfNeedsInit diff --git a/compiler/canonicalizer.nim b/compiler/canonicalizer.nim index 02010961d..50d3fd017 100644 --- a/compiler/canonicalizer.nim +++ b/compiler/canonicalizer.nim @@ -119,8 +119,8 @@ proc hashType(c: var MD5Context, t: PType) = c.hashSym(t.sym) case t.kind - of tyGenericBody, tyGenericInst, tyGenericInvokation: - for i in countup(0, sonsLen(t) -1 -ord(t.kind != tyGenericInvokation)): + of tyGenericBody, tyGenericInst, tyGenericInvocation: + for i in countup(0, sonsLen(t) -1 -ord(t.kind != tyGenericInvocation)): c.hashType t.sons[i] of tyUserTypeClass: internalAssert t.sym != nil and t.sym.owner != nil diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 6ed4d361c..3bc0d8afb 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -1390,7 +1390,7 @@ proc genSwap(p: BProc, e: PNode, d: var TLoc) = genAssignment(p, b, tmp, {}) proc rdSetElemLoc(a: TLoc, setType: PType): PRope = - # read a location of an set element; it may need a substraction operation + # read a location of an set element; it may need a subtraction operation # before the set operation result = rdCharLoc(a) assert(setType.kind == tySet) diff --git a/compiler/ccgmerge.nim b/compiler/ccgmerge.nim index 36da68d23..f4f837834 100644 --- a/compiler/ccgmerge.nim +++ b/compiler/ccgmerge.nim @@ -223,7 +223,7 @@ 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: unknown key: " & k) when not defined(nimhygiene): {.pragma: inject.} diff --git a/compiler/ccgutils.nim b/compiler/ccgutils.nim index 1e1fcd6fb..e4ce0aa6c 100644 --- a/compiler/ccgutils.nim +++ b/compiler/ccgutils.nim @@ -96,7 +96,7 @@ proc getUniqueType*(key: PType): PType = #if obj.sym != nil and obj.sym.name.s == "TOption": # echo "for ", typeToString(key), " I returned " # debug result - of tyArrayConstr, tyGenericInvokation, tyGenericBody, + of tyArrayConstr, tyGenericInvocation, tyGenericBody, tyOpenArray, tyArray, tySet, tyRange, tyTuple, tyPtr, tyRef, tySequence, tyForward, tyVarargs, tyProxy, tyVar: # tuples are quite horrible as C does not support them directly and diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 3f4f39c27..ce2fa1936 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -126,7 +126,7 @@ proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openArray[string], if not (frmt[i] in {'A'..'Z', '_', 'a'..'z', '\x80'..'\xFF'}): break var idx = getVarIdx(varnames, id) if idx >= 0: app(result, varvalues[idx]) - else: rawMessage(errUnkownSubstitionVar, id) + else: rawMessage(errUnknownSubstitionVar, id) of '{': var id = "" inc(i) @@ -138,7 +138,7 @@ proc ropeFormatNamedVars(frmt: TFormatStr, varnames: openArray[string], # search for the variable: var idx = getVarIdx(varnames, id) if idx >= 0: app(result, varvalues[idx]) - else: rawMessage(errUnkownSubstitionVar, id) + else: rawMessage(errUnknownSubstitionVar, id) else: internalError("ropeFormatNamedVars") var start = i while i < L: diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index beb84b00a..34f842d4a 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -148,7 +148,7 @@ proc mapType(typ: PType): TJSTypeKind = tyVarargs: result = etyObject of tyNil: result = etyNull - of tyGenericInst, tyGenericParam, tyGenericBody, tyGenericInvokation, + of tyGenericInst, tyGenericParam, tyGenericBody, tyGenericInvocation, tyNone, tyFromExpr, tyForward, tyEmpty, tyFieldAccessor, tyExpr, tyStmt, tyStatic, tyTypeDesc, tyTypeClasses: result = etyNone diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim index b7dc277a4..e8c4e88dc 100644 --- a/compiler/lambdalifting.nim +++ b/compiler/lambdalifting.nim @@ -15,7 +15,7 @@ import discard """ The basic approach is that captured vars need to be put on the heap and - that the calling chain needs to be explicitely modelled. Things to consider: + that the calling chain needs to be explicitly modelled. Things to consider: proc a = var v = 0 @@ -583,7 +583,7 @@ proc searchForInnerProcs(o: POuterContext, n: PNode, env: PEnv) = elif it.kind == nkIdentDefs: var L = sonsLen(it) if it.sons[0].kind == nkSym: - # this can be false for recursive invokations that already + # this can be false for recursive invocations that already # transformed it into 'env.varName': env.vars.incl(it.sons[0].sym.id) searchForInnerProcs(o, it.sons[L-1], env) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 45fc2b1e2..87c6e8225 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -69,7 +69,7 @@ type errInvalidOrderInArrayConstructor, errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry, errOptionExpected, errXisNoLabel, errNotAllCasesCovered, - errUnkownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable, + errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable, errNoPragmasAllowedForX, errNoGenericParamsAllowedForX, errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent, errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX, @@ -89,7 +89,7 @@ type errTIsNotAConcreteType, errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError, errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile, - errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitely, + errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly, errOnlyACallOpCanBeDelegator, errUsingNoSymbol, errMacroBodyDependsOnGenericTypes, errDestructorNotGenericEnough, @@ -279,7 +279,7 @@ const errOptionExpected: "option expected, but found \'$1\'", errXisNoLabel: "\'$1\' is not a label", errNotAllCasesCovered: "not all cases are covered", - errUnkownSubstitionVar: "unknown substitution variable: \'$1\'", + errUnknownSubstitionVar: "unknown substitution variable: \'$1\'", errComplexStmtRequiresInd: "complex statement requires indentation", errXisNotCallable: "\'$1\' is not callable", errNoPragmasAllowedForX: "no pragmas allowed for $1", @@ -325,7 +325,7 @@ const errXisNoValidIndexFile: "\'$1\' is no valid index file", errCannotRenderX: "cannot render reStructuredText element \'$1\'", errVarVarTypeNotAllowed: "type \'var var\' is not allowed", - errInstantiateXExplicitely: "instantiate '$1' explicitely", + errInstantiateXExplicitly: "instantiate '$1' explicitly", errOnlyACallOpCanBeDelegator: "only a call operator can be a delegator", errUsingNoSymbol: "'$1' is not a variable, constant or a proc name", errMacroBodyDependsOnGenericTypes: "the macro body cannot be compiled, " & diff --git a/compiler/rodread.nim b/compiler/rodread.nim index 3b3538e5d..545a8dda9 100644 --- a/compiler/rodread.nim +++ b/compiler/rodread.nim @@ -666,7 +666,7 @@ proc newRodReader(modfilename: string, crc: TCrc32, r.readerIndex = readerIndex r.filename = modfilename initIdTable(r.syms) - # we terminate the file explicitely with ``\0``, so the cast to `cstring` + # we terminate the file explicitly with ``\0``, so the cast to `cstring` # is safe: r.s = cast[cstring](r.memfile.mem) if startsWith(r.s, "NIM:"): diff --git a/compiler/semasgn.nim b/compiler/semasgn.nim index 71ebbbafd..61e39877a 100644 --- a/compiler/semasgn.nim +++ b/compiler/semasgn.nim @@ -184,7 +184,7 @@ proc liftBodyAux(c: TLiftCtx; t: PType; x, y: PNode) = of tyFromExpr, tyIter, tyProxy, tyBuiltInTypeClass, tyUserTypeClass, tyUserTypeClassInst, tyCompositeTypeClass, tyAnd, tyOr, tyNot, tyAnything, tyMutable, tyGenericParam, tyGenericBody, tyNil, tyExpr, tyStmt, - tyTypeDesc, tyGenericInvokation, tyBigNum, tyConst, tyForward: + tyTypeDesc, tyGenericInvocation, tyBigNum, tyConst, tyForward: internalError(c.info, "assignment requested for type: " & typeToString(t)) of tyDistinct, tyOrdinal, tyRange, tyGenericInst, tyFieldAccessor, tyStatic, tyVar: diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim index 4ce610bf9..bbc68ee87 100644 --- a/compiler/semdestruct.nim +++ b/compiler/semdestruct.nim @@ -30,7 +30,7 @@ proc instantiateDestructor(c: PContext, typ: PType): PType proc doDestructorStuff(c: PContext, s: PSym, n: PNode) = var t = s.typ.sons[1].skipTypes({tyVar}) - if t.kind == tyGenericInvokation: + if t.kind == tyGenericInvocation: for i in 1 .. store(any)|store(x) +# store_unknown (performs some store) --> store(any)|store(x) # load (loads from *type*), recursive (recursive call), unsafe, # endless (has endless loops), --> user effects are defined over *patterns* # --> a TR macro can annotate the proc with user defined annotations diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 07cae5d04..9c8c80d7f 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -667,8 +667,8 @@ proc checkForMetaFields(n: PNode) = let t = n.sym.typ case t.kind of tySequence, tySet, tyArray, tyOpenArray, tyVar, tyPtr, tyRef, - tyProc, tyGenericInvokation, tyGenericInst: - let start = ord(t.kind in {tyGenericInvokation, tyGenericInst}) + tyProc, tyGenericInvocation, tyGenericInst: + let start = ord(t.kind in {tyGenericInvocation, tyGenericInst}) for i in start .. 0) and (obj.sons[0] != nil): - addInheritedFields(c, check, pos, obj.sons[0].skipGenericInvokation) + addInheritedFields(c, check, pos, obj.sons[0].skipGenericInvocation) addInheritedFieldsAux(c, check, pos, obj.n) proc semObjectNode(c: PContext, n: PNode, prev: PType): PType = @@ -632,7 +632,7 @@ proc semObjectNode(c: PContext, n: PNode, prev: PType): PType = checkSonsLen(n, 3) if n.sons[1].kind != nkEmpty: base = skipTypes(semTypeNode(c, n.sons[1].sons[0], nil), skipPtrs) - var concreteBase = skipGenericInvokation(base).skipTypes(skipPtrs) + var concreteBase = skipGenericInvocation(base).skipTypes(skipPtrs) if concreteBase.kind == tyObject and tfFinal notin concreteBase.flags: addInheritedFields(c, check, pos, concreteBase) else: @@ -777,12 +777,12 @@ proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode, result = paramType of tyGenericBody: - result = newTypeS(tyGenericInvokation, c) + result = newTypeS(tyGenericInvocation, c) result.rawAddSon(paramType) for i in 0 .. paramType.sonsLen - 2: if paramType.sons[i].kind == tyStatic: - result.rawAddSon makeTypeFromExpr(c, ast.emptyNode) # aka 'tyUnkown' + result.rawAddSon makeTypeFromExpr(c, ast.emptyNode) # aka 'tyUnknown' else: result.rawAddSon newTypeS(tyAnything, c) @@ -823,7 +823,7 @@ proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode, result = liftBody result.shouldHaveMeta - of tyGenericInvokation: + of tyGenericInvocation: for i in 1 .. tyGenericInvokation") + if x.kind == tyGenericInvocation or f.sons[0].kind != tyGenericBody: + #InternalError("typeRel: tyGenericInvocation -> tyGenericInvocation") # simply no match for now: discard elif x.kind == tyGenericInst and @@ -897,7 +897,7 @@ proc typeRel(c: var TCandidate, f, aOrig: PType, doBind = true): TTypeRelation = # we steal the generic parameters from the tyGenericBody: 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}: + if x == nil or x.kind in {tyGenericInvocation, tyGenericParam}: internalError("wrong instantiated type!") put(c.bindings, f.sons[i], x) diff --git a/compiler/types.nim b/compiler/types.nim index 3711a9668..2422d5305 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -396,7 +396,7 @@ proc rangeToStr(n: PNode): string = const typeToStr: array[TTypeKind, string] = ["None", "bool", "Char", "empty", "Array Constructor [$1]", "nil", "expr", "stmt", "typeDesc", - "GenericInvokation", "GenericBody", "GenericInst", "GenericParam", + "GenericInvocation", "GenericBody", "GenericInst", "GenericParam", "distinct $1", "enum", "ordinal[$1]", "array[$1, $2]", "object", "tuple", "set[$1]", "range[$1]", "ptr ", "ref ", "var ", "seq[$1]", "proc", "pointer", "OpenArray[$1]", "string", "CString", "Forward", @@ -432,9 +432,9 @@ proc typeToString(typ: PType, prefer: TPreferedDesc = preferName): string = result = $t.n.intVal else: result = "int literal(" & $t.n.intVal & ")" - of tyGenericBody, tyGenericInst, tyGenericInvokation: + of tyGenericBody, tyGenericInst, tyGenericInvocation: result = typeToString(t.sons[0]) & '[' - for i in countup(1, sonsLen(t) -1 -ord(t.kind != tyGenericInvokation)): + for i in countup(1, sonsLen(t) -1 -ord(t.kind != tyGenericInvocation)): if i > 1: add(result, ", ") add(result, typeToString(t.sons[i], preferGenericArg)) add(result, ']') @@ -941,7 +941,7 @@ proc sameTypeAux(x, y: PType, c: var TSameTypeClosure): bool = result = sameChildrenAux(a, b, c) and sameFlags(a, b) if result and ExactGenericParams in c.flags: result = a.sym.position == b.sym.position - of tyGenericInvokation, tyGenericBody, tySequence, + of tyGenericInvocation, tyGenericBody, tySequence, tyOpenArray, tySet, tyRef, tyPtr, tyVar, tyArrayConstr, tyArray, tyProc, tyConst, tyMutable, tyVarargs, tyIter, tyOrdinal, tyTypeClasses, tyFieldAccessor: @@ -1087,7 +1087,7 @@ proc typeAllowedAux(marker: var IntSet, typ: PType, kind: TSymKind, if taField notin flags: result = t of tyTypeClasses: if not (tfGenericTypeParam in t.flags or taField notin flags): result = t - of tyGenericBody, tyGenericParam, tyGenericInvokation, + of tyGenericBody, tyGenericParam, tyGenericInvocation, tyNone, tyForward, tyFromExpr, tyFieldAccessor: result = t of tyNil: diff --git a/doc/advopt.txt b/doc/advopt.txt index ae474afc6..197c0d7da 100644 --- a/doc/advopt.txt +++ b/doc/advopt.txt @@ -18,7 +18,7 @@ Advanced commands: track a file, currently not saved to disk --suggest suggest all possible symbols at position --def list all possible definitions at position - --context list possible invokation context + --context list possible invocation context --usages list all usages of the symbol at position --eval evaluates an expression //serve start the compiler as a service mode (CAAS) diff --git a/doc/idetools.txt b/doc/idetools.txt index 48197f8bf..81de9598c 100644 --- a/doc/idetools.txt +++ b/doc/idetools.txt @@ -27,7 +27,7 @@ integrations `_ already available. -Idetools invokation +Idetools invocation =================== Specifying the location of the query @@ -35,7 +35,7 @@ Specifying the location of the query All of the available idetools commands require you to specify a query location through the ``--track`` or ``--trackDirty`` switches. -The general idetools invokations are:: +The general idetools invocations are:: nim idetools --track:FILE,LINE,COL proj.nim @@ -129,7 +129,7 @@ the suggestions sorted first by scope (from innermost to outermost) and then by item name. -Invokation context +Invocation context ------------------ The ``--context`` idetools switch is very similar to the suggestions diff --git a/doc/intern.txt b/doc/intern.txt index a103703d7..93dcce059 100644 --- a/doc/intern.txt +++ b/doc/intern.txt @@ -236,7 +236,7 @@ too. Type converters fall into this category: If in the above example module ``B`` is re-compiled, but ``A`` is not then ``B`` needs to be aware of ``toBool`` even though ``toBool`` is not referenced -in ``B`` *explicitely*. +in ``B`` *explicitly*. Both the multi method and the type converter problems are solved by storing them in special sections in the ROD file that are loaded *unconditionally* diff --git a/koch.nim b/koch.nim index b0b4a79da..9a7afae3d 100644 --- a/koch.nim +++ b/koch.nim @@ -270,13 +270,13 @@ when defined(withUpdate): echo("Fetching updates from repo...") var pullout = execCmdEx(git & " pull origin master") if pullout[1] != 0: - quit("An error has occured.") + quit("An error has occurred.") else: if pullout[0].startsWith("Already up-to-date."): quit("No new changes fetched from the repo. " & "Local branch must be ahead of it. Exiting...") else: - quit("An error has occured.") + quit("An error has occurred.") else: echo("No repo or executable found!") diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 4c561df70..ddbd7a76f 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -76,7 +76,7 @@ type TNimrodTypeKind* = enum ntyNone, ntyBool, ntyChar, ntyEmpty, ntyArrayConstr, ntyNil, ntyExpr, ntyStmt, - ntyTypeDesc, ntyGenericInvokation, ntyGenericBody, ntyGenericInst, + ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst, ntyGenericParam, ntyDistinct, ntyEnum, ntyOrdinal, ntyArray, ntyObject, ntyTuple, ntySet, ntyRange, ntyPtr, ntyRef, ntyVar, diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index b527b9368..1ec122e78 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -320,7 +320,7 @@ template foldl*(sequence, operation: expr): expr = ## ## The ``operation`` parameter should be an expression which uses the ## variables ``a`` and ``b`` for each step of the fold. Since this is a left - ## fold, for non associative binary operations like substraction think that + ## fold, for non associative binary operations like subtraction think that ## the sequence of numbers 1, 2 and 3 will be parenthesized as (((1) - 2) - ## 3). Example: ## @@ -328,12 +328,12 @@ template foldl*(sequence, operation: expr): expr = ## let ## numbers = @[5, 9, 11] ## addition = foldl(numbers, a + b) - ## substraction = foldl(numbers, a - b) + ## subtraction = foldl(numbers, a - b) ## multiplication = foldl(numbers, a * b) ## words = @["nim", "is", "cool"] ## concatenation = foldl(words, a & b) ## assert addition == 25, "Addition is (((5)+9)+11)" - ## assert substraction == -15, "Substraction is (((5)-9)-11)" + ## assert subtraction == -15, "Substraction is (((5)-9)-11)" ## assert multiplication == 495, "Multiplication is (((5)*9)*11)" ## assert concatenation == "nimiscool" assert sequence.len > 0, "Can't fold empty sequences" @@ -356,7 +356,7 @@ template foldr*(sequence, operation: expr): expr = ## ## The ``operation`` parameter should be an expression which uses the ## variables ``a`` and ``b`` for each step of the fold. Since this is a right - ## fold, for non associative binary operations like substraction think that + ## fold, for non associative binary operations like subtraction think that ## the sequence of numbers 1, 2 and 3 will be parenthesized as (1 - (2 - ## (3))). Example: ## @@ -364,12 +364,12 @@ template foldr*(sequence, operation: expr): expr = ## let ## numbers = @[5, 9, 11] ## addition = foldr(numbers, a + b) - ## substraction = foldr(numbers, a - b) + ## subtraction = foldr(numbers, a - b) ## multiplication = foldr(numbers, a * b) ## words = @["nim", "is", "cool"] ## concatenation = foldr(words, a & b) ## assert addition == 25, "Addition is (5+(9+(11)))" - ## assert substraction == 7, "Substraction is (5-(9-(11)))" + ## assert subtraction == 7, "Substraction is (5-(9-(11)))" ## assert multiplication == 495, "Multiplication is (5*(9*(11)))" ## assert concatenation == "nimiscool" assert sequence.len > 0, "Can't fold empty sequences" @@ -507,12 +507,12 @@ when isMainModule: let numbers = @[5, 9, 11] addition = foldl(numbers, a + b) - substraction = foldl(numbers, a - b) + subtraction = foldl(numbers, a - b) multiplication = foldl(numbers, a * b) words = @["nim", "is", "cool"] concatenation = foldl(words, a & b) assert addition == 25, "Addition is (((5)+9)+11)" - assert substraction == -15, "Substraction is (((5)-9)-11)" + assert subtraction == -15, "Substraction is (((5)-9)-11)" assert multiplication == 495, "Multiplication is (((5)*9)*11)" assert concatenation == "nimiscool" @@ -520,12 +520,12 @@ when isMainModule: let numbers = @[5, 9, 11] addition = foldr(numbers, a + b) - substraction = foldr(numbers, a - b) + subtraction = foldr(numbers, a - b) multiplication = foldr(numbers, a * b) words = @["nim", "is", "cool"] concatenation = foldr(words, a & b) assert addition == 25, "Addition is (5+(9+(11)))" - assert substraction == 7, "Substraction is (5-(9-(11)))" + assert subtraction == 7, "Substraction is (5-(9-(11)))" assert multiplication == 495, "Multiplication is (5*(9*(11)))" assert concatenation == "nimiscool" diff --git a/lib/pure/colors.nim b/lib/pure/colors.nim index 7942255cb..5b1904e54 100644 --- a/lib/pure/colors.nim +++ b/lib/pure/colors.nim @@ -392,7 +392,7 @@ proc parseColor*(name: string): Color = result = Color(parseHexInt(name)) else: var idx = binaryStrSearch(colorNames, name) - if idx < 0: raise newException(ValueError, "unkown color: " & name) + if idx < 0: raise newException(ValueError, "unknown color: " & name) result = colorNames[idx][1] proc isColor*(name: string): bool = diff --git a/lib/pure/htmlparser.nim b/lib/pure/htmlparser.nim index e2cbb4949..5e4eba4e5 100644 --- a/lib/pure/htmlparser.nim +++ b/lib/pure/htmlparser.nim @@ -552,7 +552,7 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = proc parseHtml*(s: Stream, filename: string, errors: var seq[string]): XmlNode = ## parses the XML from stream `s` and returns a ``PXmlNode``. Every - ## occured parsing error is added to the `errors` sequence. + ## occurred parsing error is added to the `errors` sequence. var x: XmlParser open(x, s, filename, {reportComments, reportWhitespace}) next(x) @@ -581,7 +581,7 @@ proc parseHtml*(s: Stream): XmlNode = proc loadHtml*(path: string, errors: var seq[string]): XmlNode = ## Loads and parses HTML from file specified by ``path``, and returns - ## a ``PXmlNode``. Every occured parsing error is added to + ## a ``PXmlNode``. Every occurred parsing error is added to ## the `errors` sequence. var s = newFileStream(path, fmRead) if s == nil: raise newException(IOError, "Unable to read file: " & path) diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 2a40b4f1f..2038b246d 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -55,7 +55,7 @@ import type JsonEventKind* = enum ## enumeration of all events that may occur when parsing - jsonError, ## an error ocurred during parsing + jsonError, ## an error occurred during parsing jsonEof, ## end of file reached jsonString, ## a string literal jsonInt, ## an integer literal diff --git a/lib/pure/net.nim b/lib/pure/net.nim index 2b81b6fb0..809b7fb69 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -258,7 +258,7 @@ proc socketError*(socket: Socket, err: int = -1, async = false, of SSL_ERROR_WANT_X509_LOOKUP: raiseSSLError("Function for x509 lookup has been called.") of SSL_ERROR_SYSCALL: - var errStr = "IO error has occured " + var errStr = "IO error has occurred " let sslErr = ErrPeekLastError() if sslErr == 0 and err == 0: errStr.add "because an EOF was observed that violates the protocol" diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 820800a1a..d9a5be14a 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -185,7 +185,7 @@ const proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} = ## Retrieves the operating system's error flag, ``errno``. ## On Windows ``GetLastError`` is checked before ``errno``. - ## Returns "" if no error occured. + ## Returns "" if no error occurred. ## ## **Deprecated since version 0.9.4**: use the other ``osErrorMsg`` proc. @@ -1099,7 +1099,7 @@ when defined(windows): var env = getEnvironmentStringsW() e = env - if e == nil: return # an error occured + if e == nil: return # an error occurred while true: var eend = strEnd(e) add(environment, $e) @@ -1110,7 +1110,7 @@ when defined(windows): var env = getEnvironmentStringsA() e = env - if e == nil: return # an error occured + if e == nil: return # an error occurred while true: var eend = strEnd(e) add(environment, $e) diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 6361dfb09..cddedf48a 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -146,7 +146,7 @@ proc startProcess*(command: string, ## of `args` to `command` carefully escaping/quoting any special characters, ## since it will be passed *as is* to the system shell. Each system/shell may ## feature different escaping rules, so try to avoid this kind of shell - ## invokation if possible as it leads to non portable software. + ## invocation if possible as it leads to non portable software. ## ## Return value: The newly created process object. Nil is never returned, ## but ``EOS`` is raised in case of an error. diff --git a/lib/pure/parsecfg.nim b/lib/pure/parsecfg.nim index bb9d2aed2..bb64c8134 100644 --- a/lib/pure/parsecfg.nim +++ b/lib/pure/parsecfg.nim @@ -35,7 +35,7 @@ type cfgSectionStart, ## a ``[section]`` has been parsed cfgKeyValuePair, ## a ``key=value`` pair has been detected cfgOption, ## a ``--key=value`` command line option - cfgError ## an error ocurred during parsing + cfgError ## an error occurred during parsing CfgEvent* = object of RootObj ## describes a parsing event case kind*: CfgEventKind ## the kind of the event diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim index 2c677fdc2..abe5aa90e 100644 --- a/lib/pure/parseutils.nim +++ b/lib/pure/parseutils.nim @@ -240,7 +240,7 @@ proc parseBiggestFloat*(s: string, number: var BiggestFloat, start = 0): int {. proc parseFloat*(s: string, number: var float, start = 0): int {. rtl, extern: "npuParseFloat", 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 + ## Result is the number of processed chars or 0 if there occurred a parsing ## error. var bf: BiggestFloat result = parseBiggestFloat(s, bf, start) diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim index 39dead3c0..b957c0cf7 100644 --- a/lib/pure/parsexml.nim +++ b/lib/pure/parsexml.nim @@ -57,7 +57,7 @@ import type XmlEventKind* = enum ## enumation of all events that may occur when parsing - xmlError, ## an error ocurred during parsing + xmlError, ## an error occurred during parsing xmlEof, ## end of file reached xmlCharData, ## character data xmlWhitespace, ## whitespace has been parsed diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 11eeefcb9..6c32717a9 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -1467,7 +1467,7 @@ proc recvAsync*(socket: Socket, s: var TaintedString): bool {. of SSL_ERROR_ZERO_RETURN: raiseSslError("TLS/SSL connection failed to initiate, socket closed prematurely.") of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: - raiseSslError("Unexpected error occured.") # This should just not happen. + raiseSslError("Unexpected error occurred.") # This should just not happen. of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ: return false of SSL_ERROR_WANT_X509_LOOKUP: @@ -1610,7 +1610,7 @@ proc sendAsync*(socket: Socket, data: string): int {.tags: [WriteIOEffect].} = of SSL_ERROR_ZERO_RETURN: raiseSslError("TLS/SSL connection failed to initiate, socket closed prematurely.") of SSL_ERROR_WANT_CONNECT, SSL_ERROR_WANT_ACCEPT: - raiseSslError("Unexpected error occured.") # This should just not happen. + raiseSslError("Unexpected error occurred.") # This should just not happen. of SSL_ERROR_WANT_WRITE, SSL_ERROR_WANT_READ: return 0 of SSL_ERROR_WANT_X509_LOOKUP: diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim index 55351ffd4..67c80e592 100644 --- a/lib/pure/streams.nim +++ b/lib/pure/streams.nim @@ -122,41 +122,41 @@ proc read[T](s: Stream, result: var T) = raise newEIO("cannot read from stream") proc readChar*(s: Stream): char = - ## reads a char from the stream `s`. Raises `EIO` if an error occured. + ## reads a char from the stream `s`. Raises `EIO` if an error occurred. ## Returns '\0' as an EOF marker. if readData(s, addr(result), sizeof(result)) != 1: result = '\0' proc readBool*(s: Stream): bool = - ## reads a bool from the stream `s`. Raises `EIO` if an error occured. + ## reads a bool from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readInt8*(s: Stream): int8 = - ## reads an int8 from the stream `s`. Raises `EIO` if an error occured. + ## reads an int8 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readInt16*(s: Stream): int16 = - ## reads an int16 from the stream `s`. Raises `EIO` if an error occured. + ## reads an int16 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readInt32*(s: Stream): int32 = - ## reads an int32 from the stream `s`. Raises `EIO` if an error occured. + ## reads an int32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readInt64*(s: Stream): int64 = - ## reads an int64 from the stream `s`. Raises `EIO` if an error occured. + ## reads an int64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readFloat32*(s: Stream): float32 = - ## reads a float32 from the stream `s`. Raises `EIO` if an error occured. + ## reads a float32 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readFloat64*(s: Stream): float64 = - ## reads a float64 from the stream `s`. Raises `EIO` if an error occured. + ## reads a float64 from the stream `s`. Raises `EIO` if an error occurred. read(s, result) proc readStr*(s: Stream, length: int): TaintedString = ## reads a string of length `length` from the stream `s`. Raises `EIO` if - ## an error occured. + ## an error occurred. result = newString(length).TaintedString var L = readData(s, addr(string(result)[0]), length) if L != length: setLen(result.string, L) @@ -183,7 +183,7 @@ proc readLine*(s: Stream, line: var TaintedString): bool = proc readLine*(s: Stream): TaintedString = ## Reads a line from a stream `s`. Note: This is not very efficient. Raises - ## `EIO` if an error occured. + ## `EIO` if an error occurred. result = TaintedString"" while true: var c = readChar(s) diff --git a/lib/pure/xmlparser.nim b/lib/pure/xmlparser.nim index 8591e894c..755bfcdbc 100644 --- a/lib/pure/xmlparser.nim +++ b/lib/pure/xmlparser.nim @@ -103,7 +103,7 @@ proc parse(x: var XmlParser, errors: var seq[string]): XmlNode = proc parseXml*(s: Stream, filename: string, errors: var seq[string]): XmlNode = ## parses the XML from stream `s` and returns a ``PXmlNode``. Every - ## occured parsing error is added to the `errors` sequence. + ## occurred parsing error is added to the `errors` sequence. var x: XmlParser open(x, s, filename, {reportComments}) while true: @@ -129,7 +129,7 @@ proc parseXml*(s: Stream): XmlNode = proc loadXml*(path: string, errors: var seq[string]): XmlNode = ## Loads and parses XML from file specified by ``path``, and returns - ## a ``PXmlNode``. Every occured parsing error is added to the `errors` + ## a ``PXmlNode``. Every occurred parsing error is added to the `errors` ## sequence. var s = newFileStream(path, fmRead) if s == nil: raise newException(IOError, "Unable to read file: " & path) diff --git a/lib/system.nim b/lib/system.nim index 9dc233cb7..825c2597d 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -357,7 +357,7 @@ type ## ## See the full `exception hierarchy`_. IOError* = object of SystemError ## \ - ## Raised if an IO error occured. + ## Raised if an IO error occurred. ## ## See the full `exception hierarchy`_. OSError* = object of SystemError ## \ @@ -374,7 +374,7 @@ type ## ## See the full `exception hierarchy`_. ArithmeticError* = object of Exception ## \ - ## Raised if any kind of arithmetic error occured. + ## Raised if any kind of arithmetic error occurred. ## ## See the full `exception hierarchy`_. DivByZeroError* = object of ArithmeticError ## \ diff --git a/lib/system/hti.nim b/lib/system/hti.nim index e599668a7..7dee054ac 100644 --- a/lib/system/hti.nim +++ b/lib/system/hti.nim @@ -26,7 +26,7 @@ type tyExpr, tyStmt, tyTypeDesc, - tyGenericInvokation, # ``T[a, b]`` for types to invoke + tyGenericInvocation, # ``T[a, b]`` for types to invoke tyGenericBody, # ``T[a, b, body]`` last parameter is the body tyGenericInst, # ``T[a, b, realInstance]`` instantiated generic type tyGenericParam, # ``a`` in the example diff --git a/lib/wrappers/libffi/msvc/win32.c b/lib/wrappers/libffi/msvc/win32.c index d1149a85e..2754fd35d 100644 --- a/lib/wrappers/libffi/msvc/win32.c +++ b/lib/wrappers/libffi/msvc/win32.c @@ -90,7 +90,7 @@ noclean: // If the return value pointer is NULL, assume no return value. /* - Intel asm is weird. We have to explicitely specify 'DWORD PTR' in the nexr instruction, + Intel asm is weird. We have to explicitly specify 'DWORD PTR' in the nexr instruction, otherwise only one BYTE will be compared (instead of a DWORD)! */ cmp DWORD PTR [ebp + 24], 0 diff --git a/lib/wrappers/mysql.nim b/lib/wrappers/mysql.nim index 3857744ae..13f3cd144 100644 --- a/lib/wrappers/mysql.nim +++ b/lib/wrappers/mysql.nim @@ -790,7 +790,7 @@ proc server_init*(argc: cint, argv: cstringArray, groups: cstringArray): cint{. proc server_end*(){.cdecl, dynlib: lib, importc: "mysql_server_end".} # mysql_server_init/end need to be called when using libmysqld or # libmysqlclient (exactly, mysql_server_init() is called by mysql_init() so - # you don't need to call it explicitely; but you need to call + # you don't need to call it explicitly; but you need to call # mysql_server_end() to free memory). The names are a bit misleading # (mysql_SERVER* to be used when using libmysqlCLIENT). So we add more general # names which suit well whether you're using libmysqld or libmysqlclient. We diff --git a/lib/wrappers/readline/history.nim b/lib/wrappers/readline/history.nim index caa857ceb..495bc15e4 100644 --- a/lib/wrappers/readline/history.nim +++ b/lib/wrappers/readline/history.nim @@ -231,7 +231,7 @@ proc history_truncate_file*(a2: cstring, a3: cint): cint{.cdecl, # -1) If there was an error in expansion. # 2) If the returned line should just be printed. # -# If an error ocurred in expansion, then OUTPUT contains a descriptive +# If an error occurred in expansion, then OUTPUT contains a descriptive # error message. proc history_expand*(a2: cstring, a3: cstringArray): cint{.cdecl, diff --git a/lib/wrappers/readline/tweaked/history.h b/lib/wrappers/readline/tweaked/history.h index 53bd642b1..b79123790 100644 --- a/lib/wrappers/readline/tweaked/history.h +++ b/lib/wrappers/readline/tweaked/history.h @@ -217,7 +217,7 @@ extern int history_truncate_file PARAMS((const char *, int)); -1) If there was an error in expansion. 2) If the returned line should just be printed. - If an error ocurred in expansion, then OUTPUT contains a descriptive + If an error occurred in expansion, then OUTPUT contains a descriptive error message. */ extern int history_expand PARAMS((char *, char **)); diff --git a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim index 08f1dad50..493a2106c 100644 --- a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim +++ b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim @@ -279,7 +279,7 @@ type PSegmentQueryInfo* = ptr TSegmentQueryInfo #/ Segment query info struct. TSegmentQueryInfo*{.pf.} = object - shape*: PShape #/ The shape that was hit, NULL if no collision occured. + shape*: PShape #/ The shape that was hit, NULL if no collision occurred. t*: CpFloat #/ The normalized distance along the query segment in the range [0, 1]. n*: TVector #/ The normal of the surface hit. TShapeType*{.size: sizeof(cint).} = enum diff --git a/tests/manyloc/keineschweine/lib/zlib_helpers.nim b/tests/manyloc/keineschweine/lib/zlib_helpers.nim index ef977afb0..9a6542d75 100644 --- a/tests/manyloc/keineschweine/lib/zlib_helpers.nim +++ b/tests/manyloc/keineschweine/lib/zlib_helpers.nim @@ -8,7 +8,7 @@ proc compress*(source: string): string = result.setLen destLen var res = zlib.compress(cstring(result), addr destLen, cstring(source), sourceLen) if res != Z_OK: - echo "Error occured: ", res + echo "Error occurred: ", res elif destLen < result.len: result.setLen(destLen) @@ -17,7 +17,7 @@ proc uncompress*(source: string, destLen: var int): string = result.setLen destLen var res = zlib.uncompress(cstring(result), addr destLen, cstring(source), source.len) if res != Z_OK: - echo "Error occured: ", res + echo "Error occurred: ", res when isMainModule: diff --git a/tests/types/tforwty2.nim b/tests/types/tforwty2.nim index d103314c5..52af1c7dd 100644 --- a/tests/types/tforwty2.nim +++ b/tests/types/tforwty2.nim @@ -1,5 +1,5 @@ # Test for a hard to fix internal error -# occured in the SDL library +# occurred in the SDL library {.push dynlib: "SDL.dll", callconv: cdecl.} diff --git a/tinyc/tccgen.c b/tinyc/tccgen.c index 3135e7b37..2eacff2c7 100644 --- a/tinyc/tccgen.c +++ b/tinyc/tccgen.c @@ -1203,7 +1203,7 @@ static inline int is_integer_btype(int bt) bt == VT_INT || bt == VT_LLONG); } -/* check types for comparison or substraction of pointers */ +/* check types for comparison or subtraction of pointers */ static void check_comparison_pointer_types(SValue *p1, SValue *p2, int op) { CType *type1, *type2, tmp_type1, tmp_type2; -- cgit 1.4.1-2-gfad0 From 1e6aef62ba8e81212667e2f1fa6b50c48ee98a91 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 23 Feb 2015 10:16:20 +0100 Subject: macros.PNimrodNode is now NimNode --- compiler/condsyms.nim | 1 + compiler/semexprs.nim | 4 +++- compiler/semtypes.nim | 5 +++-- compiler/vm.nim | 2 +- compiler/vmgen.nim | 2 +- doc/astspec.txt | 32 ++++++++++++++------------------ lib/core/macros.nim | 48 ++++++++++++++++++++++++++---------------------- lib/system.nim | 14 +++++++++++--- web/support.txt | 4 ++-- 9 files changed, 62 insertions(+), 50 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index 8a5189167..7ddf44d4a 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -89,6 +89,7 @@ proc initDefines*() = defineSymbol("nimparsebiggestfloatmagic") defineSymbol("nimalias") defineSymbol("nimlocks") + defineSymbol("nimnode") # add platform specific symbols: for c in low(CPU)..high(CPU): diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index da64df9dc..89469ae50 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -1512,7 +1512,9 @@ proc semExpandToAst(c: PContext, n: PNode): PNode = # Preserve the magic symbol in order to be handled in evals.nim internalAssert n.sons[0].sym.magic == mExpandToAst - n.typ = getSysSym("PNimrodNode").typ # expandedSym.getReturnType + #n.typ = getSysSym("PNimrodNode").typ # expandedSym.getReturnType + n.typ = if getCompilerProc("NimNode") != nil: sysTypeFromName"NimNode" + else: sysTypeFromName"PNimrodNode" result = n proc semExpandToAst(c: PContext, n: PNode, magicSym: PSym, diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 808653d55..7cd748829 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -672,8 +672,9 @@ proc addParamOrResult(c: PContext, param: PSym, kind: TSymKind) = elif param.typ.kind == tyTypeDesc: addDecl(c, param) else: - # within a macro, every param has the type PNimrodNode! - let nn = getSysSym"PNimrodNode" + # within a macro, every param has the type NimNode! + let nn = if getCompilerProc("NimNode") != nil: getSysSym"NimNode" + else: getSysSym"PNimrodNode" var a = copySym(param) a.typ = nn.typ addDecl(c, a) diff --git a/compiler/vm.nim b/compiler/vm.nim index f7e7fd2af..891718274 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -154,7 +154,7 @@ proc moveConst(x: var TFullReg, y: TFullReg) = of rkNodeAddr: x.nodeAddr = y.nodeAddr # this seems to be the best way to model the reference semantics -# of PNimrodNode: +# of system.NimNode: template asgnRef(x, y: expr) = moveConst(x, y) proc copyValue(src: PNode): PNode = diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index c69957032..f367d4cf9 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -1247,7 +1247,7 @@ proc genGlobalInit(c: PCtx; n: PNode; s: PSym) = s.position = c.globals.len # This is rather hard to support, due to the laziness of the VM code # generator. See tests/compile/tmacro2 for why this is necessary: - # var decls{.compileTime.}: seq[PNimrodNode] = @[] + # var decls{.compileTime.}: seq[NimNode] = @[] let dest = c.getTemp(s.typ) c.gABx(n, opcLdGlobal, dest, s.position) let tmp = c.genx(s.ast) diff --git a/doc/astspec.txt b/doc/astspec.txt index 5c4274093..4c27272e2 100644 --- a/doc/astspec.txt +++ b/doc/astspec.txt @@ -1,14 +1,14 @@ The AST in Nim ================= This section describes how the AST is modelled with Nim's type system. -The AST consists of nodes (``PNimrodNode``) with a variable number of +The AST consists of nodes (``NimNode``) with a variable number of children. Each node has a field named ``kind`` which describes what the node contains: .. code-block:: nim type - TNimrodNodeKind = enum ## kind of a node; only explanatory + NimNodeKind = enum ## kind of a node; only explanatory nnkNone, ## invalid node kind nnkEmpty, ## empty node nnkIdent, ## node contains an identifier @@ -18,11 +18,11 @@ contains: nnkCaseStmt, ## node represents a case statement ... ## many more - PNimrodNode = ref TNimrodNode - TNimrodNode {.final.} = object - case kind: TNimrodNodeKind ## the node's kind + NimNode = ref NimNodeObj + NimNodeObj = object + case kind: NimNodeKind ## the node's kind of nnkNone, nnkEmpty, nnkNilLit: - nil ## node contains no additional fields + discard ## node contains no additional fields of nnkCharLit..nnkInt64Lit: intVal: biggestInt ## the int literal of nnkFloatLit..nnkFloat64Lit: @@ -30,13 +30,13 @@ contains: of nnkStrLit..nnkTripleStrLit: strVal: string ## the string literal of nnkIdent: - ident: TNimrodIdent ## the identifier + ident: NimIdent ## the identifier of nnkSym: - symbol: PNimrodSymbol ## the symbol (after symbol lookup phase) + symbol: NimSymbol ## the symbol (after symbol lookup phase) else: - sons: seq[PNimrodNode] ## the node's sons (or children) + sons: seq[NimNode] ## the node's sons (or children) -For the ``PNimrodNode`` type, the ``[]`` operator has been overloaded: +For the ``NimNode`` type, the ``[]`` operator has been overloaded: ``n[i]`` is ``n``'s ``i``-th child. To specify the AST for the different Nim constructs, the notation @@ -73,10 +73,7 @@ Nim expression corresponding AST ----------------- --------------------------------------------- Identifiers are ``nnkIdent`` nodes. After the name lookup pass these nodes -get transferred into ``nnkSym`` nodes. However, a macro receives an AST that -has not been checked for semantics and thus the identifiers have not been -looked up. Macros should deal with ``nnkIdent`` nodes and do not need to deal -with ``nnkSym`` nodes. +get transferred into ``nnkSym`` nodes. Calls/expressions @@ -171,13 +168,13 @@ AST: nnkStrLit("hallo")) -Dereference operator ``^`` --------------------------- +Dereference operator ``[]`` +--------------------------- Concrete syntax: .. code-block:: nim - x^ + x[] AST: @@ -573,4 +570,3 @@ Other node kinds are especially designed to make AST manipulations easier. These are explained here. To be written. - diff --git a/lib/core/macros.nim b/lib/core/macros.nim index ddbd7a76f..9697724bd 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -15,7 +15,7 @@ include "system/inclrtl" ## .. include:: ../doc/astspec.txt type - TNimrodNodeKind* = enum + NimNodeKind* = enum nnkNone, nnkEmpty, nnkIdent, nnkSym, nnkType, nnkCharLit, nnkIntLit, nnkInt8Lit, nnkInt16Lit, nnkInt32Lit, nnkInt64Lit, nnkUIntLit, nnkUInt8Lit, @@ -72,8 +72,8 @@ type nnkEnumFieldDef, nnkArglist, nnkPattern nnkReturnToken - TNimNodeKinds* = set[TNimrodNodeKind] - TNimrodTypeKind* = enum + NimNodeKinds* = set[NimNodeKind] + NimTypeKind* = enum ntyNone, ntyBool, ntyChar, ntyEmpty, ntyArrayConstr, ntyNil, ntyExpr, ntyStmt, ntyTypeDesc, ntyGenericInvocation, ntyGenericBody, ntyGenericInst, @@ -84,8 +84,8 @@ type ntyString, ntyCString, ntyForward, ntyInt, ntyInt8, ntyInt16, ntyInt32, ntyInt64, ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128 - TNimTypeKinds* = set[TNimrodTypeKind] - TNimrodSymKind* = enum + TNimTypeKinds* {.deprecated.} = set[NimTypeKind] + NimSymKind* = enum nskUnknown, nskConditional, nskDynLib, nskParam, nskGenericParam, nskTemp, nskModule, nskType, nskVar, nskLet, nskConst, nskResult, @@ -94,17 +94,21 @@ type nskEnumField, nskForVar, nskLabel, nskStub - TNimSymKinds* = set[TNimrodSymKind] + TNimSymKinds* {.deprecated.} = set[NimSymKind] type - TNimrodIdent* = object of RootObj - ## represents a Nimrod identifier in the AST + NimIdent* = object of RootObj + ## represents a Nim identifier in the AST - TNimrodSymbol {.final.} = object # hidden - PNimrodSymbol* {.compilerproc.} = ref TNimrodSymbol - ## represents a Nimrod *symbol* in the compiler; a *symbol* is a looked-up + NimSymObj {.final.} = object # hidden + NimSym* = ref NimSymObj + ## represents a Nim *symbol* in the compiler; a *symbol* is a looked-up ## *ident*. +{.deprecated: [TNimrodNodeKind: NimNodeKind, TNimNodeKinds: NimNodeKinds, + TNimrodTypeKind: NimTypeKind, TNimrodSymKind: NimSymKind, + TNimrodIdent: NimIdent, PNimrodSymbol: NimSym].} + const nnkLiterals* = {nnkCharLit..nnkNilLit} nnkCallKinds* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, @@ -117,16 +121,16 @@ proc `[]=`*(n: PNimrodNode, i: int, child: PNimrodNode) {.magic: "NSetChild", noSideEffect.} ## set `n`'s `i`'th child to `child`. -proc `!`*(s: string): TNimrodIdent {.magic: "StrToIdent", noSideEffect.} +proc `!`*(s: string): NimIdent {.magic: "StrToIdent", noSideEffect.} ## constructs an identifier from the string `s` -proc `$`*(i: TNimrodIdent): string {.magic: "IdentToStr", noSideEffect.} +proc `$`*(i: NimIdent): string {.magic: "IdentToStr", noSideEffect.} ## converts a Nimrod identifier to a string -proc `$`*(s: PNimrodSymbol): string {.magic: "IdentToStr", noSideEffect.} +proc `$`*(s: NimSym): string {.magic: "IdentToStr", noSideEffect.} ## converts a Nimrod symbol to a string -proc `==`*(a, b: TNimrodIdent): bool {.magic: "EqIdent", noSideEffect.} +proc `==`*(a, b: NimIdent): bool {.magic: "EqIdent", noSideEffect.} ## compares two Nimrod identifiers proc `==`*(a, b: PNimrodNode): bool {.magic: "EqNimrodNode", noSideEffect.} @@ -153,15 +157,15 @@ proc kind*(n: PNimrodNode): TNimrodNodeKind {.magic: "NKind", noSideEffect.} proc intVal*(n: PNimrodNode): BiggestInt {.magic: "NIntVal", noSideEffect.} proc floatVal*(n: PNimrodNode): BiggestFloat {.magic: "NFloatVal", noSideEffect.} -proc symbol*(n: PNimrodNode): PNimrodSymbol {.magic: "NSymbol", noSideEffect.} -proc ident*(n: PNimrodNode): TNimrodIdent {.magic: "NIdent", noSideEffect.} +proc symbol*(n: PNimrodNode): NimSym {.magic: "NSymbol", noSideEffect.} +proc ident*(n: PNimrodNode): NimIdent {.magic: "NIdent", noSideEffect.} proc typ*(n: PNimrodNode): typedesc {.magic: "NGetType", noSideEffect.} proc strVal*(n: PNimrodNode): string {.magic: "NStrVal", noSideEffect.} proc `intVal=`*(n: PNimrodNode, val: BiggestInt) {.magic: "NSetIntVal", noSideEffect.} proc `floatVal=`*(n: PNimrodNode, val: BiggestFloat) {.magic: "NSetFloatVal", noSideEffect.} -proc `symbol=`*(n: PNimrodNode, val: PNimrodSymbol) {.magic: "NSetSymbol", noSideEffect.} -proc `ident=`*(n: PNimrodNode, val: TNimrodIdent) {.magic: "NSetIdent", noSideEffect.} +proc `symbol=`*(n: PNimrodNode, val: NimSym) {.magic: "NSetSymbol", noSideEffect.} +proc `ident=`*(n: PNimrodNode, val: NimIdent) {.magic: "NSetIdent", noSideEffect.} #proc `typ=`*(n: PNimrodNode, typ: typedesc) {.magic: "NSetType".} # this is not sound! Unfortunately forbidding 'typ=' is not enough, as you # can easily do: @@ -201,7 +205,7 @@ proc newFloatLitNode*(f: BiggestFloat): PNimrodNode {.compileTime.} = result = newNimNode(nnkFloatLit) result.floatVal = f -proc newIdentNode*(i: TNimrodIdent): PNimrodNode {.compileTime.} = +proc newIdentNode*(i: NimIdent): PNimrodNode {.compileTime.} = ## creates an identifier node from `i` result = newNimNode(nnkIdent) result.ident = i @@ -339,7 +343,7 @@ proc newCall*(theProc: PNimrodNode, result.add(theProc) result.add(args) -proc newCall*(theProc: TNimrodIdent, +proc newCall*(theProc: NimIdent, args: varargs[PNimrodNode]): PNimrodNode {.compileTime.} = ## produces a new call node. `theProc` is the proc that is called with ## the arguments ``args[0..]``. @@ -375,7 +379,7 @@ proc newLit*(s: string): PNimrodNode {.compileTime.} = result = newNimNode(nnkStrLit) result.strVal = s -proc nestList*(theProc: TNimrodIdent, +proc nestList*(theProc: NimIdent, x: PNimrodNode): PNimrodNode {.compileTime.} = ## nests the list `x` into a tree of call expressions: ## ``[a, b, c]`` is transformed into ``theProc(a, theProc(c, d))``. diff --git a/lib/system.nim b/lib/system.nim index f89f407f0..abf31c821 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -3126,9 +3126,17 @@ proc shallow*(s: var string) {.noSideEffect, inline.} = s.reserved = s.reserved or seqShallowFlag type - TNimrodNode {.final.} = object - PNimrodNode* {.magic: "PNimrodNode".} = ref TNimrodNode - ## represents a Nim AST node. Macros operate on this type. + NimNodeObj = object + +when defined(nimnode): + type + NimNode* {.magic: "PNimrodNode".} = ref NimNodeObj + ## represents a Nim AST node. Macros operate on this type. + {.deprecated: [PNimrodNode: NimNode].} +else: + type + PNimrodNode* {.magic: "PNimrodNode".} = ref NimNodeObj + ## represents a Nim AST node. Macros operate on this type. when false: template eval*(blk: stmt): stmt = diff --git a/web/support.txt b/web/support.txt index deedf2c7b..f8375b6aa 100644 --- a/web/support.txt +++ b/web/support.txt @@ -18,8 +18,8 @@ Commercial support includes: .. container:: standout - Features Requests - ----------------- + Feature Requests + ---------------- Suggest to us any feature that you might need, we will examine your request with care and provide a proper answer about its potential for inclusion. -- cgit 1.4.1-2-gfad0 From 752052e903c8f238a6e3a6f67ae36ee7e0943801 Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 24 Feb 2015 00:13:15 +0100 Subject: implements a type API for macros --- compiler/ast.nim | 14 +++--- compiler/semtypes.nim | 19 +++++--- compiler/vm.nim | 20 +++++++- compiler/vmdeps.nim | 125 +++++++++++++++++++++++++++++++++++++++++++++++--- compiler/vmgen.nim | 7 ++- lib/core/macros.nim | 42 ++++++++++++----- todo.txt | 1 - 7 files changed, 194 insertions(+), 34 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/compiler/ast.nim b/compiler/ast.nim index 28b34095b..6afc1db26 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -945,6 +945,13 @@ template `{}`*(n: PNode, i: int): expr = n[i -| n] template `{}=`*(n: PNode, i: int, s: PNode): stmt = n.sons[i -| n] = s +when defined(useNodeIds): + const nodeIdToDebug* = -1 # 884953 # 612794 + #612840 # 612905 # 614635 # 614637 # 614641 + # 423408 + #429107 # 430443 # 441048 # 441090 # 441153 + var gNodeId: int + proc newNode*(kind: TNodeKind): PNode = new(result) result.kind = kind @@ -1061,13 +1068,6 @@ proc copyObjectSet*(dest: var TObjectSet, src: TObjectSet) = proc discardSons*(father: PNode) = father.sons = nil -when defined(useNodeIds): - const nodeIdToDebug* = -1 # 884953 # 612794 - #612840 # 612905 # 614635 # 614637 # 614641 - # 423408 - #429107 # 430443 # 441048 # 441090 # 441153 - var gNodeId: int - proc withInfo*(n: PNode, info: TLineInfo): PNode = n.info = info return n diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 7cd748829..d9c7b6c92 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -332,10 +332,15 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = if result.typ.kind != tyGenericParam: # XXX get rid of this hack! var oldInfo = n.info + when defined(useNodeIds): + let oldId = n.id reset(n[]) + when defined(useNodeIds): + n.id = oldId n.kind = nkSym n.sym = result n.info = oldInfo + n.typ = result.typ else: localError(n.info, errIdentifierExpected) result = errorSym(c, n) @@ -1179,11 +1184,12 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = var typeExpr = semExpr(c, n) if typeExpr.typ.kind != tyTypeDesc: localError(n.info, errTypeExpected) - return errorType(c) - result = typeExpr.typ.base - if result.isMetaType: - var preprocessed = semGenericStmt(c, n) - return makeTypeFromExpr(c, preprocessed) + result = errorType(c) + else: + result = typeExpr.typ.base + if result.isMetaType: + var preprocessed = semGenericStmt(c, n) + result = makeTypeFromExpr(c, preprocessed) of nkIdent, nkAccQuoted: var s = semTypeIdent(c, n) if s.typ == nil: @@ -1254,7 +1260,8 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = else: localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) - + n.typ = result + proc setMagicType(m: PSym, kind: TTypeKind, size: int) = m.typ.kind = kind m.typ.align = size.int16 diff --git a/compiler/vm.nim b/compiler/vm.nim index 891718274..e96b89f49 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -123,8 +123,12 @@ proc createStrKeepNode(x: var TFullReg) = if x.node.isNil: x.node = newNode(nkStrLit) elif x.node.kind == nkNilLit: + when defined(useNodeIds): + let id = x.node.id system.reset(x.node[]) x.node.kind = nkStrLit + when defined(useNodeIds): + x.node.id = id elif x.node.kind notin {nkStrLit..nkTripleStrLit} or nfAllConst in x.node.flags: # XXX this is hacky; tests/txmlgen triggers it: @@ -1133,7 +1137,21 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = else: stackTrace(c, tos, pc, errFieldXNotFound, "ident") of opcNGetType: - internalError(c.debug[pc], "unknown opcode " & $instr.opcode) + let rb = instr.regB + let rc = instr.regC + if rc == 0: + ensureKind(rkNode) + if regs[rb].kind == rkNode and regs[rb].node.typ != nil: + regs[ra].node = opMapTypeToAst(regs[rb].node.typ, c.debug[pc]) + else: + stackTrace(c, tos, pc, errGenerated, "node has no type") + else: + # typeKind opcode: + ensureKind(rkInt) + if regs[rb].kind == rkNode and regs[rb].node.typ != nil: + regs[ra].intVal = ord(regs[rb].node.typ.kind) + #else: + # stackTrace(c, tos, pc, errGenerated, "node has no type") of opcNStrVal: decodeB(rkNode) createStr regs[ra] diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim index c44910b81..7fa88de6e 100644 --- a/compiler/vmdeps.nim +++ b/compiler/vmdeps.nim @@ -1,13 +1,13 @@ # # # The Nim Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # -import ast, types, msgs, osproc, streams, options +import ast, types, msgs, osproc, streams, options, idents proc readOutput(p: Process): string = result = "" @@ -19,11 +19,14 @@ proc readOutput(p: Process): string = discard p.waitForExit proc opGorge*(cmd, input: string): string = - var p = startProcess(cmd, options={poEvalCommand}) - if input.len != 0: - p.inputStream.write(input) - p.inputStream.close() - result = p.readOutput + try: + var p = startProcess(cmd, options={poEvalCommand}) + if input.len != 0: + p.inputStream.write(input) + p.inputStream.close() + result = p.readOutput + except IOError, OSError: + result = "" proc opSlurp*(file: string, info: TLineInfo, module: PSym): string = try: @@ -36,3 +39,111 @@ proc opSlurp*(file: string, info: TLineInfo, module: PSym): string = except IOError: localError(info, errCannotOpenFile, file) result = "" + +proc atomicTypeX(name: string; t: PType; info: TLineInfo): PNode = + let sym = newSym(skType, getIdent(name), t.owner, info) + result = newSymNode(sym) + result.typ = t + +proc mapTypeToAst(t: PType, info: TLineInfo; allowRecursion=false): PNode + +proc mapTypeToBracket(name: string; t: PType; info: TLineInfo): PNode = + result = newNodeIT(nkBracketExpr, info, t) + result.add atomicTypeX(name, t, info) + for i in 0 .. < t.len: + result.add mapTypeToAst(t.sons[i], info) + +proc mapTypeToAst(t: PType, info: TLineInfo; allowRecursion=false): PNode = + template atomicType(name): expr = atomicTypeX(name, t, info) + + case t.kind + of tyNone: result = atomicType("none") + of tyBool: result = atomicType("bool") + of tyChar: result = atomicType("char") + of tyNil: result = atomicType("nil") + of tyExpr: result = atomicType("expr") + of tyStmt: result = atomicType("stmt") + of tyEmpty: result = atomicType"void" + of tyArrayConstr, tyArray: + result = newNodeIT(nkBracketExpr, info, t) + result.add atomicType("array") + result.add mapTypeToAst(t.sons[0], info) + result.add mapTypeToAst(t.sons[1], info) + of tyTypeDesc: + if t.base != nil: + result = newNodeIT(nkBracketExpr, info, t) + result.add atomicType("typeDesc") + result.add mapTypeToAst(t.base, info) + else: + result = atomicType"typeDesc" + of tyGenericInvocation: + result = newNodeIT(nkBracketExpr, info, t) + for i in 0 .. < t.len: + result.add mapTypeToAst(t.sons[i], info) + of tyGenericInst, tyGenericBody, tyOrdinal, tyUserTypeClassInst: + result = mapTypeToAst(t.lastSon, info) + of tyGenericParam, tyDistinct, tyForward: result = atomicType(t.sym.name.s) + of tyObject: + if allowRecursion: + result = newNodeIT(nkObjectTy, info, t) + if t.sons[0] == nil: + result.add ast.emptyNode + else: + result.add mapTypeToAst(t.sons[0], info) + result.add copyTree(t.n) + else: + result = atomicType(t.sym.name.s) + of tyEnum: + result = newNodeIT(nkEnumTy, info, t) + result.add copyTree(t.n) + of tyTuple: result = mapTypeToBracket("tuple", t, info) + of tySet: result = mapTypeToBracket("set", t, info) + of tyPtr: result = mapTypeToBracket("ptr", t, info) + of tyRef: result = mapTypeToBracket("ref", t, info) + of tyVar: result = mapTypeToBracket("var", t, info) + of tySequence: result = mapTypeToBracket("sequence", t, info) + of tyProc: result = mapTypeToBracket("proc", t, info) + of tyOpenArray: result = mapTypeToBracket("openArray", t, info) + of tyRange: + result = newNodeIT(nkBracketExpr, info, t) + result.add atomicType("range") + result.add t.n.sons[0].copyTree + result.add t.n.sons[1].copyTree + of tyPointer: result = atomicType"pointer" + of tyString: result = atomicType"string" + of tyCString: result = atomicType"cstring" + of tyInt: result = atomicType"int" + of tyInt8: result = atomicType"int8" + of tyInt16: result = atomicType"int16" + of tyInt32: result = atomicType"int32" + of tyInt64: result = atomicType"int64" + of tyFloat: result = atomicType"float" + of tyFloat32: result = atomicType"float32" + of tyFloat64: result = atomicType"float64" + of tyFloat128: result = atomicType"float128" + of tyUInt: result = atomicType"uint" + of tyUInt8: result = atomicType"uint8" + of tyUInt16: result = atomicType"uint16" + of tyUInt32: result = atomicType"uint32" + of tyUInt64: result = atomicType"uint64" + of tyBigNum: result = atomicType"bignum" + of tyConst: result = mapTypeToBracket("const", t, info) + of tyMutable: result = mapTypeToBracket("mutable", t, info) + of tyVarargs: result = mapTypeToBracket("varargs", t, info) + of tyIter: result = mapTypeToBracket("iter", t, info) + of tyProxy: result = atomicType"error" + of tyBuiltInTypeClass: result = mapTypeToBracket("builtinTypeClass", t, info) + of tyUserTypeClass: result = mapTypeToBracket("userTypeClass", t, info) + of tyCompositeTypeClass: result = mapTypeToBracket("compositeTypeClass", t, info) + of tyAnd: result = mapTypeToBracket("and", t, info) + of tyOr: result = mapTypeToBracket("or", t, info) + of tyNot: result = mapTypeToBracket("not", t, info) + of tyAnything: result = atomicType"anything" + of tyStatic, tyFromExpr, tyFieldAccessor: + result = newNodeIT(nkBracketExpr, info, t) + result.add atomicType("static") + if t.n != nil: + result.add t.n.copyTree + +proc opMapTypeToAst*(t: PType; info: TLineInfo): PNode = + result = mapTypeToAst(t, info, true) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index f367d4cf9..5b7b0b0fd 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -950,7 +950,12 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = of mNFloatVal: genUnaryABC(c, n, dest, opcNFloatVal) of mNSymbol: genUnaryABC(c, n, dest, opcNSymbol) of mNIdent: genUnaryABC(c, n, dest, opcNIdent) - of mNGetType: genUnaryABC(c, n, dest, opcNGetType) + of mNGetType: + let tmp = c.genx(n.sons[1]) + if dest < 0: dest = c.getTemp(n.typ) + c.gABC(n, opcNGetType, dest, tmp, if n[0].sym.name.s == "typeKind": 1 else: 0) + c.freeTemp(tmp) + #genUnaryABC(c, n, dest, opcNGetType) of mNStrVal: genUnaryABC(c, n, dest, opcNStrVal) of mNSetIntVal: unused(n, dest) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 9697724bd..c6453aeaa 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -83,7 +83,13 @@ type ntySequence, ntyProc, ntyPointer, ntyOpenArray, ntyString, ntyCString, ntyForward, ntyInt, ntyInt8, ntyInt16, ntyInt32, ntyInt64, - ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128 + ntyFloat, ntyFloat32, ntyFloat64, ntyFloat128, + ntyUInt, ntyUInt8, ntyUInt16, ntyUInt32, ntyUInt64, + ntyBigNum, + ntyConst, ntyMutable, ntyVarargs, + ntyIter, + ntyError + TNimTypeKinds* {.deprecated.} = set[NimTypeKind] NimSymKind* = enum nskUnknown, nskConditional, nskDynLib, nskParam, @@ -100,7 +106,7 @@ type NimIdent* = object of RootObj ## represents a Nim identifier in the AST - NimSymObj {.final.} = object # hidden + NimSymObj = object # hidden NimSym* = ref NimSymObj ## represents a Nim *symbol* in the compiler; a *symbol* is a looked-up ## *ident*. @@ -125,16 +131,16 @@ proc `!`*(s: string): NimIdent {.magic: "StrToIdent", noSideEffect.} ## constructs an identifier from the string `s` proc `$`*(i: NimIdent): string {.magic: "IdentToStr", noSideEffect.} - ## converts a Nimrod identifier to a string + ## converts a Nim identifier to a string proc `$`*(s: NimSym): string {.magic: "IdentToStr", noSideEffect.} - ## converts a Nimrod symbol to a string + ## converts a Nim symbol to a string proc `==`*(a, b: NimIdent): bool {.magic: "EqIdent", noSideEffect.} - ## compares two Nimrod identifiers + ## compares two Nim identifiers proc `==`*(a, b: PNimrodNode): bool {.magic: "EqNimrodNode", noSideEffect.} - ## compares two Nimrod nodes + ## compares two Nim nodes proc len*(n: PNimrodNode): int {.magic: "NLen", noSideEffect.} ## returns the number of children of `n`. @@ -159,7 +165,19 @@ proc intVal*(n: PNimrodNode): BiggestInt {.magic: "NIntVal", noSideEffect.} proc floatVal*(n: PNimrodNode): BiggestFloat {.magic: "NFloatVal", noSideEffect.} proc symbol*(n: PNimrodNode): NimSym {.magic: "NSymbol", noSideEffect.} proc ident*(n: PNimrodNode): NimIdent {.magic: "NIdent", noSideEffect.} -proc typ*(n: PNimrodNode): typedesc {.magic: "NGetType", noSideEffect.} + +proc getType*(n: PNimrodNode): PNimrodNode {.magic: "NGetType", noSideEffect.} + ## with 'getType' you can access the node's `type`:idx:. A Nim type is + ## mapped to a Nim AST too, so it's slightly confusing but it means the same + ## API can be used to traverse types. Recursive types are flattened for you + ## so there is no danger of infinite recursions during traversal. To + ## resolve recursive types, you have to call 'getType' again. To see what + ## kind of type it is, call `typeKind` on getType's result. + +proc typeKind*(n: PNimrodNode): NimTypeKind {.magic: "NGetType", noSideEffect.} + ## Returns the type kind of the node 'n' that should represent a type, that + ## means the node should have been obtained via `getType`. + proc strVal*(n: PNimrodNode): string {.magic: "NStrVal", noSideEffect.} proc `intVal=`*(n: PNimrodNode, val: BiggestInt) {.magic: "NSetIntVal", noSideEffect.} @@ -216,7 +234,7 @@ proc newIdentNode*(i: string): PNimrodNode {.compileTime.} = result.ident = !i type - TBindSymRule* = enum ## specifies how ``bindSym`` behaves + BindSymRule* = enum ## specifies how ``bindSym`` behaves brClosed, ## only the symbols in current scope are bound brOpen, ## open wrt overloaded symbols, but may be a single ## symbol if not ambiguous (the rules match that of @@ -225,7 +243,9 @@ type ## if not ambiguous (this cannot be achieved with ## any other means in the language currently) -proc bindSym*(ident: string, rule: TBindSymRule = brClosed): PNimrodNode {. +{.deprecated: [TBindSymRule: BindSymRule].} + +proc bindSym*(ident: string, rule: BindSymRule = brClosed): PNimrodNode {. magic: "NBindSym", noSideEffect.} ## creates a node that binds `ident` to a symbol node. The bound symbol ## may be an overloaded symbol. @@ -236,7 +256,7 @@ proc bindSym*(ident: string, rule: TBindSymRule = brClosed): PNimrodNode {. ## If ``rule == brForceOpen`` always an ``nkOpenSymChoice`` tree is ## returned even if the symbol is not ambiguous. -proc genSym*(kind: TNimrodSymKind = nskLet; ident = ""): PNimrodNode {. +proc genSym*(kind: NimSymKind = nskLet; ident = ""): PNimrodNode {. magic: "NGenSym", noSideEffect.} ## generates a fresh symbol that is guaranteed to be unique. The symbol ## needs to occur in a declaration context. @@ -245,7 +265,7 @@ proc callsite*(): PNimrodNode {.magic: "NCallSite", benign.} ## returns the AST of the invocation expression that invoked this macro. proc toStrLit*(n: PNimrodNode): PNimrodNode {.compileTime.} = - ## converts the AST `n` to the concrete Nimrod code and wraps that + ## converts the AST `n` to the concrete Nim code and wraps that ## in a string literal node return newStrLitNode(repr(n)) diff --git a/todo.txt b/todo.txt index 408bfefe5..79fe9d05a 100644 --- a/todo.txt +++ b/todo.txt @@ -74,7 +74,6 @@ version 0.9.X ============= - macros as type pragmas -- implement type API for macros - lazy overloading resolution: * special case ``tyStmt`` - document NimMain and check whether it works for threading -- cgit 1.4.1-2-gfad0 From 975f33b01d65b68ac1fea5de23998864ca2b2b8f Mon Sep 17 00:00:00 2001 From: Araq Date: Wed, 25 Feb 2015 21:14:21 +0100 Subject: disable deprecated warnings for macros module --- lib/core/macros.nim | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) (limited to 'lib/core/macros.nim') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index c6453aeaa..dbfb2ceb3 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -1,7 +1,7 @@ # # # Nim's Runtime Library -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2015 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -120,6 +120,8 @@ const nnkCallKinds* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, nnkCallStrLit} +{.push warning[deprecated]: off.} + proc `[]`*(n: PNimrodNode, i: int): PNimrodNode {.magic: "NChild", noSideEffect.} ## get `n`'s `i`'th child. @@ -808,3 +810,5 @@ when not defined(booting): macro payload: stmt {.gensym.} = result = parseStmt(e) payload() + +{.pop.} -- cgit 1.4.1-2-gfad0 From 3bfcfeb0cffa266b45f0803009787d7761881326 Mon Sep 17 00:00:00 2001 From: Araq Date: Fri, 27 Feb 2015 16:44:43 +0100 Subject: don't use stdout for nimsuggest server mode --- compiler/ast.nim | 2 +- compiler/astalgo.nim | 10 +++++----- compiler/commands.nim | 2 +- compiler/lexer.nim | 6 ++---- compiler/msgs.nim | 14 ++++++++------ compiler/options.nim | 8 ++++---- compiler/vm.nim | 12 ++++++++---- lib/core/macros.nim | 9 +++++---- 8 files changed, 34 insertions(+), 29 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/compiler/ast.nim b/compiler/ast.nim index 6afc1db26..1462d58d5 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -1413,7 +1413,7 @@ proc copyTree*(src: PNode): PNode = for i in countup(0, sonsLen(src) - 1): result.sons[i] = copyTree(src.sons[i]) -proc hasSonWith(n: PNode, kind: TNodeKind): bool = +proc hasSonWith*(n: PNode, kind: TNodeKind): bool = for i in countup(0, sonsLen(n) - 1): if n.sons[i].kind == kind: return true diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim index e9b82d74b..ea9534b1f 100644 --- a/compiler/astalgo.nim +++ b/compiler/astalgo.nim @@ -445,21 +445,21 @@ proc debugTree(n: PNode, indent: int, maxRecDepth: int; proc debug(n: PSym) = if n == nil: - writeln(stdout, "null") + msgWriteln("null") elif n.kind == skUnknown: - writeln(stdout, "skUnknown") + msgWriteln("skUnknown") else: #writeln(stdout, ropeToStr(symToYaml(n, 0, 1))) - writeln(stdout, "$1_$2: $3, $4, $5, $6" % [ + msgWriteln("$1_$2: $3, $4, $5, $6" % [ n.name.s, $n.id, flagsToStr(n.flags).ropeToStr, flagsToStr(n.loc.flags).ropeToStr, lineInfoToStr(n.info).ropeToStr, $n.kind]) proc debug(n: PType) = - writeln(stdout, ropeToStr(debugType(n))) + msgWriteln(ropeToStr(debugType(n))) proc debug(n: PNode) = - writeln(stdout, ropeToStr(debugTree(n, 0, 100))) + msgWriteln(ropeToStr(debugTree(n, 0, 100))) const EmptySeq = @[] diff --git a/compiler/commands.nim b/compiler/commands.nim index 6e594375f..a2d02e469 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -382,7 +382,7 @@ proc processSwitch(switch, arg: string, pass: TCmdLinePass, info: TLineInfo) = of "off": gOptions.excl optEndb undefSymbol("endb") - of "native": + of "native", "gdb": incl(gGlobalOptions, optCDebug) gOptions = gOptions + {optLineDir} - {optEndb} undefSymbol("endb") diff --git a/compiler/lexer.nim b/compiler/lexer.nim index fc40192b8..c86762121 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -181,10 +181,8 @@ proc prettyTok*(tok: TToken): string = else: result = tokToStr(tok) proc printTok*(tok: TToken) = - write(stdout, tok.line, ":", tok.col, "\t") - write(stdout, TokTypeToStr[tok.tokType]) - write(stdout, " ") - writeln(stdout, tokToStr(tok)) + msgWriteln($tok.line & ":" & $tok.col & "\t" & + TokTypeToStr[tok.tokType] & " " & tokToStr(tok)) var dummyIdent: PIdent diff --git a/compiler/msgs.nim b/compiler/msgs.nim index ed28fea69..a72dedf57 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -330,7 +330,7 @@ const errUsingNoSymbol: "'$1' is not a variable, constant or a proc name", errMacroBodyDependsOnGenericTypes: "the macro body cannot be compiled, " & "because the parameter '$1' has a generic type", - errDestructorNotGenericEnough: "Destructor signarue is too specific. " & + errDestructorNotGenericEnough: "Destructor signature is too specific. " & "A destructor must be associated will all instantiations of a generic type", errInlineIteratorsAsProcParams: "inline iterators can be used as parameters only for " & "templates, macros and other inline iterators", @@ -443,7 +443,7 @@ type TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints TNoteKinds* = set[TNoteKind] - TFileInfo*{.final.} = object + TFileInfo* = object fullPath: string # This is a canonical full filesystem path projPath*: string # This is relative to the project's root shortName*: string # short name of the module @@ -458,7 +458,7 @@ type # and parsed; usually 'nil' but is used # for 'nimsuggest' - TLineInfo*{.final.} = object # This is designed to be as small as possible, + TLineInfo* = object # This is designed to be as small as possible, # because it is used # in syntax nodes. We save space here by using # two int16 and an int32. @@ -493,7 +493,7 @@ proc toCChar*(c: char): string = proc makeCString*(s: string): PRope = # BUGFIX: We have to split long strings into many ropes. Otherwise - # this could trigger an InternalError(). See the ropes module for + # this could trigger an internalError(). See the ropes module for # further information. const MaxLineLength = 64 @@ -696,7 +696,9 @@ proc msgWriteln*(s: string) = #if gCmd == cmdIdeTools and optCDebug notin gGlobalOptions: return - if optStdout in gGlobalOptions: + if not isNil(writelnHook): + writelnHook(s) + elif optStdout in gGlobalOptions: if eStdErr in errorOutputs: writeln(stderr, s) else: if eStdOut in errorOutputs: writeln(stdout, s) @@ -720,7 +722,7 @@ type proc handleError(msg: TMsgKind, eh: TErrorHandling, s: string) = template quit = if defined(debug) or gVerbosity >= 3 or msg == errInternal: - if stackTraceAvailable(): + if stackTraceAvailable() and isNil(writelnHook): writeStackTrace() else: msgWriteln("No stack traceback available\nTo create a stacktrace, rerun compilation with ./koch temp " & options.command & " ") diff --git a/compiler/options.nim b/compiler/options.nim index d6d9389f5..1b4a624ab 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -283,19 +283,19 @@ when noTimeMachine: var p = startProcess("/usr/bin/tmutil", args = ["addexclusion", dir]) discard p.waitForExit p.close - except E_Base, EOS: + except Exception: discard -proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = +proc completeGeneratedFilePath*(f: string, createSubDir: bool = true): string = var (head, tail) = splitPath(f) #if len(head) > 0: head = removeTrailingDirSep(shortenDir(head & dirSep)) var subdir = getGeneratedPath() # / head if createSubDir: - try: + try: createDir(subdir) when noTimeMachine: excludeDirFromTimeMachine(subdir) - except OSError: + except OSError: writeln(stdout, "cannot create directory: " & subdir) quit(1) result = joinPath(subdir, tail) diff --git a/compiler/vm.nim b/compiler/vm.nim index e96b89f49..a36de1c20 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -776,10 +776,14 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = stackTrace(c, tos, pc, errNilAccess) of opcEcho: let rb = instr.regB - for i in ra..ra+rb-1: - #if regs[i].kind != rkNode: debug regs[i] - write(stdout, regs[i].node.strVal) - writeln(stdout, "") + if rb == 1: + msgWriteln(regs[ra].node.strVal) + else: + var outp = "" + for i in ra..ra+rb-1: + #if regs[i].kind != rkNode: debug regs[i] + outp.add(regs[i].node.strVal) + msgWriteln(outp) of opcContainsSet: decodeBC(rkInt) regs[ra].intVal = ord(inSet(regs[rb].node, regs[rc].regToNode)) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index dbfb2ceb3..4758dc0c1 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -456,10 +456,11 @@ proc lispRepr*(n: PNimrodNode): string {.compileTime, benign.} = of nnkSym: add(result, $n.symbol) of nnkNone: assert false else: - add(result, lispRepr(n[0])) - for j in 1..n.len-1: - add(result, ", ") - add(result, lispRepr(n[j])) + if n.len > 0: + add(result, lispRepr(n[0])) + for j in 1..n.len-1: + add(result, ", ") + add(result, lispRepr(n[j])) add(result, ")") -- cgit 1.4.1-2-gfad0 From df7e388e0c226731be3c46be7aad2d9993599a9e Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Mon, 2 Mar 2015 17:02:43 -0800 Subject: Make macros.nim expectKind error message with a single TNimrodNodeKind consistent with error message shown with a set of TNimrodNodeKind by displaying the actual node kind (as well as the expected) --- lib/core/macros.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 4758dc0c1..519bae209 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -339,11 +339,13 @@ proc quote*(bl: stmt, op = "``"): PNimrodNode {.magic: "QuoteAst", noSideEffect. ## if not `ex`: ## echo `info` & ": Check failed: " & `expString` +from strutils import cmpIgnoreStyle, format + proc expectKind*(n: PNimrodNode, k: TNimrodNodeKind) {.compileTime.} = ## checks that `n` is of kind `k`. If this is not the case, ## compilation aborts with an error message. This is useful for writing ## macros that check the AST that is passed to them. - if n.kind != k: error("macro expects a node of kind: " & $k) + if n.kind != k: error("Expected a node of kind $1, got $2".format(k, n.kind)) proc expectMinLen*(n: PNimrodNode, min: int) {.compileTime.} = ## checks that `n` has at least `min` children. If this is not the case, @@ -581,8 +583,6 @@ const CallNodes* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, nnkCallStrLit, nnkHiddenCallConv} -from strutils import cmpIgnoreStyle, format - proc expectKind*(n: PNimrodNode; k: set[TNimrodNodeKind]) {.compileTime.} = assert n.kind in k, "Expected one of $1, got $2".format(k, n.kind) -- cgit 1.4.1-2-gfad0 From b54dfbce1664a6f0c9deb845d94ce173e5e0831d Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 3 Mar 2015 09:22:54 -0800 Subject: Remove use of .format() from macros.nim to avoid importing into core. There is still a remaining import of cmpIgnoreStyle from strutils that needs to be removed as well --- lib/core/macros.nim | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 519bae209..19c10fb93 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -339,13 +339,13 @@ proc quote*(bl: stmt, op = "``"): PNimrodNode {.magic: "QuoteAst", noSideEffect. ## if not `ex`: ## echo `info` & ": Check failed: " & `expString` -from strutils import cmpIgnoreStyle, format +from strutils import cmpIgnoreStyle proc expectKind*(n: PNimrodNode, k: TNimrodNodeKind) {.compileTime.} = ## checks that `n` is of kind `k`. If this is not the case, ## compilation aborts with an error message. This is useful for writing ## macros that check the AST that is passed to them. - if n.kind != k: error("Expected a node of kind $1, got $2".format(k, n.kind)) + if n.kind != k: error("Expected a node of kind " & $k & ", got " & $n.kind) proc expectMinLen*(n: PNimrodNode, min: int) {.compileTime.} = ## checks that `n` has at least `min` children. If this is not the case, @@ -584,7 +584,7 @@ const nnkCallStrLit, nnkHiddenCallConv} proc expectKind*(n: PNimrodNode; k: set[TNimrodNodeKind]) {.compileTime.} = - assert n.kind in k, "Expected one of $1, got $2".format(k, n.kind) + assert n.kind in k, "Expected one of " & $k & ", got " & $n.kind proc newProc*(name = newEmptyNode(); params: openArray[PNimrodNode] = [newEmptyNode()]; body: PNimrodNode = newStmtList(), procType = nnkProcDef): PNimrodNode {.compileTime.} = @@ -654,7 +654,7 @@ proc `pragma=`*(someProc: PNimrodNode; val: PNimrodNode){.compileTime.}= template badNodeKind(k; f): stmt{.immediate.} = - assert false, "Invalid node kind $# for macros.`$2`".format(k, f) + assert false, "Invalid node kind " & $k & " for macros.`" & $f & "`" proc body*(someProc: PNimrodNode): PNimrodNode {.compileTime.} = case someProc.kind: -- cgit 1.4.1-2-gfad0 From 0553758ebd66ae7f10dca46f594d1503192ebaa6 Mon Sep 17 00:00:00 2001 From: Chris Heller Date: Tue, 3 Mar 2015 09:29:38 -0800 Subject: Clone the implementation of cmpIgnoreStyle into macros.nim from typeinfo.nim so that we get rid of any imports in the core modules --- lib/core/macros.nim | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) (limited to 'lib/core/macros.nim') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 19c10fb93..0888a8767 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -339,8 +339,6 @@ proc quote*(bl: stmt, op = "``"): PNimrodNode {.magic: "QuoteAst", noSideEffect. ## if not `ex`: ## echo `info` & ": Check failed: " & `expString` -from strutils import cmpIgnoreStyle - proc expectKind*(n: PNimrodNode, k: TNimrodNodeKind) {.compileTime.} = ## checks that `n` is of kind `k`. If this is not the case, ## compilation aborts with an error message. This is useful for writing @@ -776,6 +774,22 @@ proc copy*(node: PNimrodNode): PNimrodNode {.compileTime.} = ## An alias for copyNimTree(). return node.copyNimTree() +proc cmpIgnoreStyle(a, b: cstring): int {.noSideEffect.} = + proc toLower(c: char): char {.inline.} = + if c in {'A'..'Z'}: result = chr(ord(c) + (ord('a') - ord('A'))) + else: result = c + 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) + proc eqIdent* (a, b: string): bool = cmpIgnoreStyle(a, b) == 0 ## Check if two idents are identical. -- cgit 1.4.1-2-gfad0