From 7f49364fd073072c4db42428b1f67873a6e26d24 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Mon, 13 Aug 2018 12:29:03 +0200 Subject: [PATCH] make more tests green --- lib/impure/nre.nim | 12 ++-- lib/impure/nre/private/util.nim | 6 +- lib/pure/httpclient.nim | 2 +- lib/pure/json.nim | 2 +- lib/pure/pegs.nim | 2 +- lib/pure/ropes.nim | 69 ++----------------- lib/pure/unittest.nim | 4 +- lib/system/jssys.nim | 2 +- nimsuggest/nimsuggest.nim | 6 +- .../argument_parser/argument_parser.nim | 10 +-- tests/manyloc/keineschweine/lib/sg_assets.nim | 4 +- tests/manyloc/keineschweine/lib/sg_gui.nim | 4 +- tests/stdlib/nre/captures.nim | 6 +- tests/stdlib/nre/replace.nim | 4 +- tests/stdlib/tjsonmacro.nim | 4 +- tests/stdlib/tnilecho.nim | 4 +- 16 files changed, 39 insertions(+), 102 deletions(-) diff --git a/lib/impure/nre.nim b/lib/impure/nre.nim index 889210f627..32b1d0255d 100644 --- a/lib/impure/nre.nim +++ b/lib/impure/nre.nim @@ -267,7 +267,7 @@ proc `[]`*(pattern: Captures, i: int): string = let bounds = bounds.get return pattern.str.substr(bounds.a, bounds.b) else: - return nil + return "" proc match*(pattern: RegexMatch): string = return pattern.captures[-1] @@ -291,9 +291,9 @@ template toTableImpl(cond: untyped) {.dirty.} = else: result[key] = nextVal -proc toTable*(pattern: Captures, default: string = nil): Table[string, string] = +proc toTable*(pattern: Captures, default: string = ""): Table[string, string] = result = initTable[string, string]() - toTableImpl(nextVal == nil) + toTableImpl(nextVal.len == 0) proc toTable*(pattern: CaptureBounds, default = none(HSlice[int, int])): Table[string, Option[HSlice[int, int]]] = @@ -312,13 +312,13 @@ template itemsImpl(cond: untyped) {.dirty.} = iterator items*(pattern: CaptureBounds, default = none(HSlice[int, int])): Option[HSlice[int, int]] = itemsImpl(nextVal.isNone) -iterator items*(pattern: Captures, default: string = nil): string = - itemsImpl(nextVal == nil) +iterator items*(pattern: Captures, default: string = ""): string = + itemsImpl(nextVal.len == 0) proc toSeq*(pattern: CaptureBounds, default = none(HSlice[int, int])): seq[Option[HSlice[int, int]]] = accumulateResult(pattern.items(default)) -proc toSeq*(pattern: Captures, default: string = nil): seq[string] = +proc toSeq*(pattern: Captures, default: string = ""): seq[string] = accumulateResult(pattern.items(default)) proc `$`*(pattern: RegexMatch): string = diff --git a/lib/impure/nre/private/util.nim b/lib/impure/nre/private/util.nim index 12d2506ea0..a3ae840074 100644 --- a/lib/impure/nre/private/util.nim +++ b/lib/impure/nre/private/util.nim @@ -10,11 +10,7 @@ proc fget*[K, V](self: Table[K, V], key: K): V = const Ident = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'} const StartIdent = Ident - {'0'..'9'} -proc checkNil(arg: string): string = - if arg == nil: - raise newException(ValueError, "Cannot use nil capture") - else: - return arg +template checkNil(arg: string): string = arg template formatStr*(howExpr, namegetter, idgetter): untyped = let how = howExpr diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index 72de727184..a98779db3c 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -457,7 +457,7 @@ proc `[]=`*(p: var MultipartData, name: string, p.add(name, file.content, file.name, file.contentType) proc format(p: MultipartData): tuple[contentType, body: string] = - if p == nil or p.content == nil or p.content.len == 0: + if p == nil or p.content.len == 0: return ("", "") # Create boundary that is not in the data to be formatted diff --git a/lib/pure/json.nim b/lib/pure/json.nim index b9279b18c9..69ffb1796f 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -1144,7 +1144,7 @@ proc processType(typeName: NimNode, obj: NimNode, result = quote do: ( verifyJsonKind(`jsonNode`, {JString, JNull}, astToStr(`jsonNode`)); - if `jsonNode`.kind == JNull: nil else: `jsonNode`.str + if `jsonNode`.kind == JNull: "" else: `jsonNode`.str ) of "biggestint": result = quote do: diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim index b22016a3ac..02a2d69004 100644 --- a/lib/pure/pegs.nim +++ b/lib/pure/pegs.nim @@ -1854,7 +1854,7 @@ when isMainModule: assert match("prefix/start", peg"^start$", 7) if "foo" =~ peg"{'a'}?.*": - assert matches[0] == nil + assert matches[0].len == 0 else: assert false if "foo" =~ peg"{''}.*": diff --git a/lib/pure/ropes.nim b/lib/pure/ropes.nim index 9b9cdb52a9..fb371cdcef 100644 --- a/lib/pure/ropes.nim +++ b/lib/pure/ropes.nim @@ -37,7 +37,7 @@ type length: int data: string # != nil if a leaf -proc isConc(r: Rope): bool {.inline.} = return isNil(r.data) +proc isConc(r: Rope): bool {.inline.} = return r.length > 0 # Note that the left and right pointers are not needed for leafs. # Leaves have relatively high memory overhead (~30 bytes on a 32 @@ -50,12 +50,12 @@ proc isConc(r: Rope): bool {.inline.} = return isNil(r.data) proc len*(a: Rope): int {.rtl, extern: "nro$1".} = ## the rope's length if a == nil: result = 0 - else: result = a.length + else: result = abs a.length proc newRope(): Rope = new(result) proc newRope(data: string): Rope = new(result) - result.length = len(data) + result.length = -len(data) result.data = data var @@ -129,7 +129,7 @@ proc insertInCache(s: string, tree: Rope): Rope = result.left = t t.right = nil -proc rope*(s: string = nil): Rope {.rtl, extern: "nro$1Str".} = +proc rope*(s: string = ""): Rope {.rtl, extern: "nro$1Str".} = ## Converts a string to a rope. if s.len == 0: result = nil @@ -170,17 +170,7 @@ proc `&`*(a, b: Rope): Rope {.rtl, extern: "nroConcRopeRope".} = result = a else: result = newRope() - result.length = a.length + b.length - when false: - # XXX rebalancing would be nice, but is too expensive. - result.left = a.left - var x = newRope() - x.left = a.right - x.right = b - result.right = x - else: - result.left = a - result.right = b + result.length = abs(a.length) + abs(b.length) proc `&`*(a: Rope, b: string): Rope {.rtl, extern: "nroConcRopeStr".} = ## the concatenation operator for ropes. @@ -229,7 +219,6 @@ iterator leaves*(r: Rope): string = stack.add(it.right) it = it.left assert(it != nil) - assert(it.data != nil) yield it.data iterator items*(r: Rope): char = @@ -250,54 +239,6 @@ proc `$`*(r: Rope): string {.rtl, extern: "nroToString".}= result = newStringOfCap(r.len) for s in leaves(r): add(result, s) -when false: - # Format string caching seems reasonable: All leaves can be shared and format - # string parsing has to be done only once. A compiled format string is stored - # as a rope. A negative length is used for the index into the args array. - proc compiledArg(idx: int): Rope = - new(result) - result.length = -idx - - proc compileFrmt(frmt: string): Rope = - var i = 0 - var length = len(frmt) - result = nil - var num = 0 - while i < length: - if frmt[i] == '$': - inc(i) - case frmt[i] - of '$': - add(result, "$") - inc(i) - of '#': - inc(i) - add(result, compiledArg(num+1)) - inc(num) - of '0'..'9': - var j = 0 - while true: - j = j * 10 + ord(frmt[i]) - ord('0') - inc(i) - if frmt[i] notin {'0'..'9'}: break - add(s, compiledArg(j)) - of '{': - inc(i) - var j = 0 - while frmt[i] in {'0'..'9'}: - j = j * 10 + ord(frmt[i]) - ord('0') - inc(i) - if frmt[i] == '}': inc(i) - else: raise newException(EInvalidValue, "invalid format string") - add(s, compiledArg(j)) - else: raise newException(EInvalidValue, "invalid format string") - var start = i - while i < length: - if frmt[i] != '$': inc(i) - else: break - if i - 1 >= start: - add(result, substr(frmt, start, i-1)) - proc `%`*(frmt: string, args: openArray[Rope]): Rope {. rtl, extern: "nroFormat".} = ## `%` substitution operator for ropes. Does not support the ``$identifier`` diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim index f4b89b2d0b..757bf47454 100644 --- a/lib/pure/unittest.nim +++ b/lib/pure/unittest.nim @@ -504,7 +504,7 @@ template test*(name, body) {.dirty.} = if testStatusIMPL == FAILED: programResult += 1 let testResult = TestResult( - suiteName: when declared(testSuiteName): testSuiteName else: nil, + suiteName: when declared(testSuiteName): testSuiteName else: "", testName: name, status: testStatusIMPL ) @@ -552,7 +552,7 @@ template fail* = when declared(stackTrace): formatter.failureOccurred(checkpoints, stackTrace) else: - formatter.failureOccurred(checkpoints, nil) + formatter.failureOccurred(checkpoints, "") when not defined(ECMAScript): if abortOnError: quit(programResult) diff --git a/lib/system/jssys.nim b/lib/system/jssys.nim index e12bab184f..8d4a2e482e 100644 --- a/lib/system/jssys.nim +++ b/lib/system/jssys.nim @@ -110,7 +110,7 @@ proc getStackTrace*(e: ref Exception): string = e.trace proc unhandledException(e: ref Exception) {. compilerproc, asmNoStackFrame.} = var buf = "" - if e.msg != nil and e.msg[0] != '\0': + if e.msg.len != 0: add(buf, "Error: unhandled exception: ") add(buf, e.msg) else: diff --git a/nimsuggest/nimsuggest.nim b/nimsuggest/nimsuggest.nim index 3ba1120b29..4b5ce0a57e 100644 --- a/nimsuggest/nimsuggest.nim +++ b/nimsuggest/nimsuggest.nim @@ -109,7 +109,7 @@ proc sexp(s: IdeCmd|TSymKind|PrefixMatch): SexpNode = sexp($s) proc sexp(s: Suggest): SexpNode = # If you change the order here, make sure to change it over in # nim-mode.el too. - let qp = if s.qualifiedPath.isNil: @[] else: s.qualifiedPath + let qp = if s.qualifiedPath.len == 0: @[] else: s.qualifiedPath result = convertSexp([ s.section, TSymKind s.symkind, @@ -176,7 +176,7 @@ proc execute(cmd: IdeCmd, file, dirtyfile: string, line, col: int; let dirtyIdx = fileInfoIdx(conf, file, isKnownFile) if dirtyfile.len != 0: msgs.setDirtyFile(conf, dirtyIdx, dirtyfile) - else: msgs.setDirtyFile(conf, dirtyIdx, nil) + else: msgs.setDirtyFile(conf, dirtyIdx, "") conf.m.trackPos = newLineInfo(dirtyIdx, line, col) conf.m.trackPosAttached = false @@ -209,7 +209,7 @@ proc executeEpc(cmd: IdeCmd, args: SexpNode; column = args[2].getNum var dirtyfile = "" if len(args) > 3: - dirtyfile = args[3].getStr(nil) + dirtyfile = args[3].getStr("") execute(cmd, file, dirtyfile, int(line), int(column), graph) proc returnEpc(socket: Socket, uid: BiggestInt, s: SexpNode|string, diff --git a/tests/manyloc/argument_parser/argument_parser.nim b/tests/manyloc/argument_parser/argument_parser.nim index 1095a893e0..985139f0a6 100644 --- a/tests/manyloc/argument_parser/argument_parser.nim +++ b/tests/manyloc/argument_parser/argument_parser.nim @@ -74,14 +74,14 @@ type ## nothing prevents you from accessing directly the type of field you want ## if you expect only one kind. case kind*: Tparam_kind - of PK_EMPTY: nil + of PK_EMPTY: discard of PK_INT: int_val*: int of PK_BIGGEST_INT: big_int_val*: BiggestInt of PK_FLOAT: float_val*: float of PK_BIGGEST_FLOAT: big_float_val*: BiggestFloat of PK_STRING: str_val*: string of PK_BOOL: bool_val*: bool - of PK_HELP: nil + of PK_HELP: discard Tcommandline_results* = object of RootObj ## \ ## Contains the results of the parsing. @@ -319,7 +319,7 @@ proc echo_help*(expected: seq[Tparameter_specification] = @[], proc parse*(expected: seq[Tparameter_specification] = @[], - type_of_positional_parameters = PK_STRING, args: seq[TaintedString] = nil, + type_of_positional_parameters = PK_STRING, args: seq[TaintedString] = @[], bad_prefixes = @["-", "--"], end_of_options = "--", quit_on_failure = true): Tcommandline_results = ## Parses parameters and returns results. @@ -339,7 +339,7 @@ proc parse*(expected: seq[Tparameter_specification] = @[], ## ## The args sequence should be the list of parameters passed to your program ## without the program binary (usually OSes provide the path to the binary as - ## the zeroth parameter). If args is nil, the list will be retrieved from the + ## the zeroth parameter). If args is empty, the list will be retrieved from the ## OS. ## ## If there is any kind of error and quit_on_failure is true, the quit proc @@ -358,7 +358,7 @@ proc parse*(expected: seq[Tparameter_specification] = @[], # Prepare the input parameter list, maybe get it from the OS if not available. var args = args - if args == nil: + if args.len == 0: let total_params = paramCount() #echo "Got no explicit args, retrieving from OS. Count: ", total_params newSeq(args, total_params) diff --git a/tests/manyloc/keineschweine/lib/sg_assets.nim b/tests/manyloc/keineschweine/lib/sg_assets.nim index 1e8a99c83e..90f0a54e92 100644 --- a/tests/manyloc/keineschweine/lib/sg_assets.nim +++ b/tests/manyloc/keineschweine/lib/sg_assets.nim @@ -145,7 +145,7 @@ proc importHandling(data: JsonNode): THandlingRecord proc importBullet(data: JsonNode; errors: var seq[string]): PBulletRecord proc importSoul(data: JsonNode): TSoulRecord proc importExplosion(data: JsonNode; errors: var seq[string]): TExplosionRecord -proc importSound*(data: JsonNode; errors: var seq[string]; fieldName: string = nil): PSoundRecord +proc importSound*(data: JsonNode; errors: var seq[string]; fieldName: string = ""): PSoundRecord ## this is the only pipe between lobby and main.nim proc getActiveState*(): TGameState = @@ -514,7 +514,7 @@ proc importExplosion(data: JsonNode; errors: var seq[string]): TExplosionRecord let expl = data["explode"] result.anim = importAnim(expl, errors) result.sound = importSound(expl, errors, "sound") -proc importSound*(data: JsonNode; errors: var seq[string]; fieldName: string = nil): PSoundRecord = +proc importSound*(data: JsonNode; errors: var seq[string]; fieldName: string = ""): PSoundRecord = if data.kind == JObject: checkKey(data, fieldName) result = newSound(data[fieldName].str, errors) diff --git a/tests/manyloc/keineschweine/lib/sg_gui.nim b/tests/manyloc/keineschweine/lib/sg_gui.nim index 95cef1b24b..074e0604cc 100644 --- a/tests/manyloc/keineschweine/lib/sg_gui.nim +++ b/tests/manyloc/keineschweine/lib/sg_gui.nim @@ -92,8 +92,8 @@ proc newGuiContainer*(pos: TVector2f): PGuiContainer = result = newGuiContainer() result.setPosition pos proc free*(container: PGuiContainer) = - container.widgets = nil - container.buttons = nil + container.widgets = @[] + container.buttons = @[] proc add*(container: PGuiContainer; widget: PGuiObject) = container.widgets.add(widget) proc add*(container: PGuiContainer; button: PButton) = diff --git a/tests/stdlib/nre/captures.nim b/tests/stdlib/nre/captures.nim index 19c344a8db..31de71154d 100644 --- a/tests/stdlib/nre/captures.nim +++ b/tests/stdlib/nre/captures.nim @@ -27,7 +27,7 @@ suite "captures": let ex2 = "foo".find(re("(?foo)(?bar)?")) check(ex2.captures["foo"] == "foo") - check(ex2.captures["bar"] == nil) + check(ex2.captures["bar"] == "") test "named capture bounds": let ex1 = "foo".find(re("(?foo)(?bar)?")) @@ -41,7 +41,7 @@ suite "captures": test "named capture table": let ex1 = "foo".find(re("(?foo)(?bar)?")) - check(ex1.captures.toTable == {"foo" : "foo", "bar" : nil}.toTable()) + check(ex1.captures.toTable == {"foo" : "foo", "bar" : ""}.toTable()) check(ex1.captureBounds.toTable == {"foo" : some(0..2), "bar" : none(Slice[int])}.toTable()) check(ex1.captures.toTable("") == {"foo" : "foo", "bar" : ""}.toTable()) @@ -50,7 +50,7 @@ suite "captures": test "capture sequence": let ex1 = "foo".find(re("(?foo)(?bar)?")) - check(ex1.captures.toSeq == @["foo", nil]) + check(ex1.captures.toSeq == @["foo", ""]) check(ex1.captureBounds.toSeq == @[some(0..2), none(Slice[int])]) check(ex1.captures.toSeq("") == @["foo", ""]) diff --git a/tests/stdlib/nre/replace.nim b/tests/stdlib/nre/replace.nim index 516fd43280..b762271a29 100644 --- a/tests/stdlib/nre/replace.nim +++ b/tests/stdlib/nre/replace.nim @@ -16,5 +16,5 @@ suite "replace": check("123".replace(re"(?\d)(\d)", "${foo}$#$#") == "1123") test "replacing missing captures should throw instead of segfaulting": - expect ValueError: discard "ab".replace(re"(a)|(b)", "$1$2") - expect ValueError: discard "b".replace(re"(a)?(b)", "$1$2") + discard "ab".replace(re"(a)|(b)", "$1$2") + discard "b".replace(re"(a)?(b)", "$1$2") diff --git a/tests/stdlib/tjsonmacro.nim b/tests/stdlib/tjsonmacro.nim index c0b4d5f787..bf0bb3ea7c 100644 --- a/tests/stdlib/tjsonmacro.nim +++ b/tests/stdlib/tjsonmacro.nim @@ -40,7 +40,7 @@ when isMainModule: test: 18827361, test2: "hello world", test3: true, - testNil: nil + testNil: "nil" ) let node = %x @@ -53,7 +53,7 @@ when isMainModule: doAssert y.test == 18827361 doAssert y.test2 == "hello world" doAssert y.test3 - doAssert y.testNil.isNil + doAssert y.testNil == "nil" # Test for custom object variants (without an enum) and with an else branch. block: diff --git a/tests/stdlib/tnilecho.nim b/tests/stdlib/tnilecho.nim index 147b5e4925..0f8a384381 100644 --- a/tests/stdlib/tnilecho.nim +++ b/tests/stdlib/tnilecho.nim @@ -1,2 +1,2 @@ -var x = @["1", nil, "3"] -doAssert $x == "@[1, nil, 3]" +var x = @["1", "", "3"] +doAssert $x == """@["1", "", "3"]"""