Skip to content

Commit

Permalink
make more tests green
Browse files Browse the repository at this point in the history
  • Loading branch information
Araq committed Aug 13, 2018
1 parent dae5450 commit 7f49364
Show file tree
Hide file tree
Showing 16 changed files with 39 additions and 102 deletions.
12 changes: 6 additions & 6 deletions lib/impure/nre.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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]
Expand All @@ -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]]] =
Expand All @@ -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 =
Expand Down
6 changes: 1 addition & 5 deletions lib/impure/nre/private/util.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/pure/httpclient.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/pure/json.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion lib/pure/pegs.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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"{''}.*":
Expand Down
69 changes: 5 additions & 64 deletions lib/pure/ropes.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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 =
Expand All @@ -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``
Expand Down
4 changes: 2 additions & 2 deletions lib/pure/unittest.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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
)
Expand Down Expand Up @@ -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)
Expand Down
2 changes: 1 addition & 1 deletion lib/system/jssys.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
6 changes: 3 additions & 3 deletions nimsuggest/nimsuggest.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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,
Expand Down
10 changes: 5 additions & 5 deletions tests/manyloc/argument_parser/argument_parser.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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.
Expand All @@ -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
Expand All @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions tests/manyloc/keineschweine/lib/sg_assets.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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 =
Expand Down Expand Up @@ -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)
Expand Down
4 changes: 2 additions & 2 deletions tests/manyloc/keineschweine/lib/sg_gui.nim
Original file line number Diff line number Diff line change
Expand Up @@ -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) =
Expand Down
6 changes: 3 additions & 3 deletions tests/stdlib/nre/captures.nim
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ suite "captures":

let ex2 = "foo".find(re("(?<foo>foo)(?<bar>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>foo)(?<bar>bar)?"))
Expand All @@ -41,7 +41,7 @@ suite "captures":

test "named capture table":
let ex1 = "foo".find(re("(?<foo>foo)(?<bar>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())

Expand All @@ -50,7 +50,7 @@ suite "captures":

test "capture sequence":
let ex1 = "foo".find(re("(?<foo>foo)(?<bar>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", ""])

Expand Down
4 changes: 2 additions & 2 deletions tests/stdlib/nre/replace.nim
Original file line number Diff line number Diff line change
Expand Up @@ -16,5 +16,5 @@ suite "replace":
check("123".replace(re"(?<foo>\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")
4 changes: 2 additions & 2 deletions tests/stdlib/tjsonmacro.nim
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ when isMainModule:
test: 18827361,
test2: "hello world",
test3: true,
testNil: nil
testNil: "nil"
)

let node = %x
Expand All @@ -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:
Expand Down
4 changes: 2 additions & 2 deletions tests/stdlib/tnilecho.nim
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
var x = @["1", nil, "3"]
doAssert $x == "@[1, nil, 3]"
var x = @["1", "", "3"]
doAssert $x == """@["1", "", "3"]"""

0 comments on commit 7f49364

Please sign in to comment.