udpated the compiler and tester to use getOrDefault

This commit is contained in:
Araq 2015-10-13 14:10:33 +02:00
commit 8be9e46403
19 changed files with 82 additions and 59 deletions

View file

@ -75,7 +75,7 @@ proc newDocumentor*(filename: string, config: StringTableRef): PDoc =
ga('send', 'pageview'); ga('send', 'pageview');
</script> </script>
""" % [config["doc.googleAnalytics"]] """ % [config.getOrDefault"doc.googleAnalytics"]
else: else:
result.analytics = "" result.analytics = ""

View file

@ -372,7 +372,7 @@ proc decodeSym(r: PRodReader, info: TLineInfo): PSym =
else: else:
internalError(info, "decodeSym: no ident") internalError(info, "decodeSym: no ident")
#echo "decoding: {", ident.s #echo "decoding: {", ident.s
result = r.syms[id] result = r.syms.getOrDefault(id)
if result == nil: if result == nil:
new(result) new(result)
result.id = id result.id = id
@ -491,7 +491,7 @@ proc processCompilerProcs(r: PRodReader, module: PSym) =
inc(r.pos) inc(r.pos)
var key = decodeVInt(r.s, r.pos) var key = decodeVInt(r.s, r.pos)
inc(r.pos) # #10 inc(r.pos) # #10
var s = r.syms[key] var s = r.syms.getOrDefault(key)
if s == nil: if s == nil:
s = newStub(r, w, key) s = newStub(r, w, key)
s.owner = module s.owner = module
@ -737,7 +737,7 @@ proc getReader(moduleId: int): PRodReader =
return nil return nil
proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym = proc rrGetSym(r: PRodReader, id: int, info: TLineInfo): PSym =
result = r.syms[id] result = r.syms.getOrDefault(id)
if result == nil: if result == nil:
# load the symbol: # load the symbol:
var d = iiTableGet(r.index.tab, id) var d = iiTableGet(r.index.tab, id)

View file

@ -28,6 +28,8 @@
import import
pcre, strutils, rtarrays pcre, strutils, rtarrays
{.deprecated.}
const const
MaxSubpatterns* = 20 MaxSubpatterns* = 20
## defines the maximum number of subpatterns that can be captured. ## defines the maximum number of subpatterns that can be captured.
@ -46,7 +48,7 @@ type
h: ptr Pcre h: ptr Pcre
e: ptr ExtraData e: ptr ExtraData
Regex* {.deprecated.} = ref RegexDesc ## a compiled regular expression Regex* = ref RegexDesc ## a compiled regular expression
RegexError* = object of ValueError RegexError* = object of ValueError
## is raised if the pattern is no valid regular expression. ## is raised if the pattern is no valid regular expression.

View file

@ -139,7 +139,7 @@ proc initRstGenerator*(g: var RstGenerator, target: OutputTarget,
g.seenIndexTerms = initTable[string, int]() g.seenIndexTerms = initTable[string, int]()
g.msgHandler = msgHandler g.msgHandler = msgHandler
let s = config["split.item.toc"] let s = config.getOrDefault"split.item.toc"
if s != "": g.splitAfter = parseInt(s) if s != "": g.splitAfter = parseInt(s)
for i in low(g.meta)..high(g.meta): g.meta[i] = "" for i in low(g.meta)..high(g.meta): g.meta[i] = ""
@ -341,10 +341,10 @@ proc renderIndexTerm*(d: PDoc, n: PRstNode, result: var string) =
## previously appeared to give a different identifier value for each. ## previously appeared to give a different identifier value for each.
let refname = n.rstnodeToRefname let refname = n.rstnodeToRefname
if d.seenIndexTerms.hasKey(refname): if d.seenIndexTerms.hasKey(refname):
d.seenIndexTerms[refname] = d.seenIndexTerms[refname] + 1 d.seenIndexTerms[refname] = d.seenIndexTerms.getOrDefault(refname) + 1
else: else:
d.seenIndexTerms[refname] = 1 d.seenIndexTerms[refname] = 1
let id = refname & '_' & $d.seenIndexTerms[refname] let id = refname & '_' & $d.seenIndexTerms.getOrDefault(refname)
var term = "" var term = ""
renderAux(d, n, term) renderAux(d, n, term)
@ -518,7 +518,7 @@ proc generateDocumentationIndex(docs: IndexedDocs): string =
sort(titles, cmp) sort(titles, cmp)
for title in titles: for title in titles:
let tocList = generateDocumentationTOC(docs[title]) let tocList = generateDocumentationTOC(docs.getOrDefault(title))
result.add("<ul><li><a href=\"" & result.add("<ul><li><a href=\"" &
title.link & "\">" & title.keyword & "</a>\n" & tocList & "</ul>\n") title.link & "\">" & title.keyword & "</a>\n" & tocList & "</ul>\n")
@ -786,7 +786,8 @@ proc renderSmiley(d: PDoc, n: PRstNode, result: var string) =
dispA(d.target, result, dispA(d.target, result,
"""<img src="$1" width="15" """<img src="$1" width="15"
height="17" hspace="2" vspace="2" class="smiley" />""", height="17" hspace="2" vspace="2" class="smiley" />""",
"\\includegraphics{$1}", [d.config["doc.smiley_format"] % n.text]) "\\includegraphics{$1}",
[d.config.getOrDefault"doc.smiley_format" % n.text])
proc parseCodeBlockField(d: PDoc, n: PRstNode, params: var CodeBlockParams) = proc parseCodeBlockField(d: PDoc, n: PRstNode, params: var CodeBlockParams) =
## Parses useful fields which can appear before a code block. ## Parses useful fields which can appear before a code block.
@ -844,8 +845,8 @@ proc buildLinesHTMLTable(d: PDoc; params: CodeBlockParams, code: string):
inc d.listingCounter inc d.listingCounter
let id = $d.listingCounter let id = $d.listingCounter
if not params.numberLines: if not params.numberLines:
result = (d.config["doc.listing_start"] % id, result = (d.config.getOrDefault"doc.listing_start" % id,
d.config["doc.listing_end"] % id) d.config.getOrDefault"doc.listing_end" % id)
return return
var codeLines = 1 + code.strip.countLines var codeLines = 1 + code.strip.countLines
@ -856,9 +857,11 @@ proc buildLinesHTMLTable(d: PDoc; params: CodeBlockParams, code: string):
result.beginTable.add($line & "\n") result.beginTable.add($line & "\n")
line.inc line.inc
codeLines.dec codeLines.dec
result.beginTable.add("</pre></td><td>" & (d.config["doc.listing_start"] % id)) result.beginTable.add("</pre></td><td>" & (
result.endTable = (d.config["doc.listing_end"] % id) & d.config.getOrDefault"doc.listing_start" % id))
"</td></tr></tbody></table>" & (d.config["doc.listing_button"] % id) result.endTable = (d.config.getOrDefault"doc.listing_end" % id) &
"</td></tr></tbody></table>" & (
d.config.getOrDefault"doc.listing_button" % id)
proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) = proc renderCodeBlock(d: PDoc, n: PRstNode, result: var string) =
## Renders a code block, appending it to `result`. ## Renders a code block, appending it to `result`.

View file

@ -212,7 +212,7 @@ proc processClient(client: AsyncSocket, address: string,
if request.reqMethod == "post": if request.reqMethod == "post":
# Check for Expect header # Check for Expect header
if request.headers.hasKey("Expect"): if request.headers.hasKey("Expect"):
if request.headers["Expect"].toLower == "100-continue": if request.headers.getOrDefault("Expect").toLower == "100-continue":
await client.sendStatus("100 Continue") await client.sendStatus("100 Continue")
else: else:
await client.sendStatus("417 Expectation Failed") await client.sendStatus("417 Expectation Failed")
@ -221,7 +221,8 @@ proc processClient(client: AsyncSocket, address: string,
# - Check for Content-length header # - Check for Content-length header
if request.headers.hasKey("Content-Length"): if request.headers.hasKey("Content-Length"):
var contentLength = 0 var contentLength = 0
if parseInt(request.headers["Content-Length"], contentLength) == 0: if parseInt(request.headers.getOrDefault("Content-Length"),
contentLength) == 0:
await request.respond(Http400, "Bad Request. Invalid Content-Length.") await request.respond(Http400, "Bad Request. Invalid Content-Length.")
continue continue
else: else:
@ -232,16 +233,18 @@ proc processClient(client: AsyncSocket, address: string,
continue continue
case request.reqMethod case request.reqMethod
of "get", "post", "head", "put", "delete", "trace", "options", "connect", "patch": of "get", "post", "head", "put", "delete", "trace", "options",
"connect", "patch":
await callback(request) await callback(request)
else: else:
await request.respond(Http400, "Invalid request method. Got: " & request.reqMethod) await request.respond(Http400, "Invalid request method. Got: " &
request.reqMethod)
# Persistent connections # Persistent connections
if (request.protocol == HttpVer11 and if (request.protocol == HttpVer11 and
request.headers["connection"].normalize != "close") or request.headers.getOrDefault("connection").normalize != "close") or
(request.protocol == HttpVer10 and (request.protocol == HttpVer10 and
request.headers["connection"].normalize == "keep-alive"): request.headers.getOrDefault("connection").normalize == "keep-alive"):
# In HTTP 1.1 we assume that connection is persistent. Unless connection # In HTTP 1.1 we assume that connection is persistent. Unless connection
# header states otherwise. # header states otherwise.
# In HTTP 1.0 we assume that the connection should not be persistent. # In HTTP 1.0 we assume that the connection should not be persistent.

View file

@ -387,7 +387,7 @@ var
proc getCookie*(name: string): TaintedString = proc getCookie*(name: string): TaintedString =
## Gets a cookie. If no cookie of `name` exists, "" is returned. ## Gets a cookie. If no cookie of `name` exists, "" is returned.
if gcookies == nil: gcookies = parseCookies(getHttpCookie()) if gcookies == nil: gcookies = parseCookies(getHttpCookie())
result = TaintedString(gcookies[name]) result = TaintedString(gcookies.getOrDefault(name))
proc existsCookie*(name: string): bool = proc existsCookie*(name: string): bool =
## Checks if a cookie of `name` exists. ## Checks if a cookie of `name` exists.

View file

@ -11,6 +11,8 @@
## container for a set or a mapping of strings. Based on the excellent paper ## container for a set or a mapping of strings. Based on the excellent paper
## by Adam Langley. ## by Adam Langley.
include "system/inclrtl"
type type
NodeObj[T] = object {.acyclic.} NodeObj[T] = object {.acyclic.}
byte: int ## byte index of the difference byte: int ## byte index of the difference
@ -149,13 +151,14 @@ template get[T](c: CritBitTree[T], key: string): T {.immediate.} =
else: else:
raise newException(KeyError, "key not found") raise newException(KeyError, "key not found")
proc `[]`*[T](c: CritBitTree[T], key: string): T {.inline.} = proc `[]`*[T](c: CritBitTree[T], key: string): T {.inline, deprecatedGet.} =
## retrieves the value at ``c[key]``. If `key` is not in `t`, the ## retrieves the value at ``c[key]``. If `key` is not in `t`, the
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists. ## the key exists.
get(c, key) get(c, key)
proc `[]`*[T](c: var CritBitTree[T], key: string): var T {.inline.} = proc `[]`*[T](c: var CritBitTree[T], key: string): var T {.inline,
deprecatedGet.} =
## retrieves the value at ``c[key]``. The value can be modified. ## retrieves the value at ``c[key]``. The value can be modified.
## If `key` is not in `t`, the ``KeyError`` exception is raised. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
get(c, key) get(c, key)

View file

@ -156,7 +156,7 @@ proc rawGet[A](s: HashSet[A], key: A, hc: var Hash): int {.inline.} =
proc `[]`*[A](s: var HashSet[A], key: A): var A = proc `[]`*[A](s: var HashSet[A], key: A): var A =
## returns the element that is actually stored in 's' which has the same ## returns the element that is actually stored in 's' which has the same
## value as 'key' or raises the ``EInvalidKey`` exception. This is useful ## value as 'key' or raises the ``KeyError`` exception. This is useful
## when one overloaded 'hash' and '==' but still needs reference semantics ## when one overloaded 'hash' and '==' but still needs reference semantics
## for sharing. ## for sharing.
assert s.isValid, "The set needs to be initialized." assert s.isValid, "The set needs to be initialized."
@ -167,7 +167,7 @@ proc `[]`*[A](s: var HashSet[A], key: A): var A =
proc mget*[A](s: var HashSet[A], key: A): var A {.deprecated.} = proc mget*[A](s: var HashSet[A], key: A): var A {.deprecated.} =
## returns the element that is actually stored in 's' which has the same ## returns the element that is actually stored in 's' which has the same
## value as 'key' or raises the ``EInvalidKey`` exception. This is useful ## value as 'key' or raises the ``KeyError`` exception. This is useful
## when one overloaded 'hash' and '==' but still needs reference semantics ## when one overloaded 'hash' and '==' but still needs reference semantics
## for sharing. Use ```[]``` instead. ## for sharing. Use ```[]``` instead.
s[key] s[key]

View file

@ -68,6 +68,8 @@
import import
hashes, math hashes, math
include "system/inclrtl"
type type
KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B] KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]] KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]]
@ -115,13 +117,13 @@ template getOrDefaultImpl(t, key): untyped {.immediate.} =
var index = rawGet(t, key, hc) var index = rawGet(t, key, hc)
if index >= 0: result = t.data[index].val if index >= 0: result = t.data[index].val
proc `[]`*[A, B](t: Table[A, B], key: A): B = proc `[]`*[A, B](t: Table[A, B], key: A): B {.deprecatedGet.} =
## retrieves the value at ``t[key]``. If `key` is not in `t`, the ## retrieves the value at ``t[key]``. If `key` is not in `t`, the
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists. ## the key exists.
get(t, key) get(t, key)
proc `[]`*[A, B](t: var Table[A, B], key: A): var B = proc `[]`*[A, B](t: var Table[A, B], key: A): var B {.deprecatedGet.} =
## retrieves the value at ``t[key]``. The value can be modified. ## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``KeyError`` exception is raised. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
get(t, key) get(t, key)
@ -293,7 +295,7 @@ iterator mvalues*[A, B](t: TableRef[A, B]): var B =
for h in 0..high(t.data): for h in 0..high(t.data):
if isFilled(t.data[h].hcode): yield t.data[h].val if isFilled(t.data[h].hcode): yield t.data[h].val
proc `[]`*[A, B](t: TableRef[A, B], key: A): var B = proc `[]`*[A, B](t: TableRef[A, B], key: A): var B {.deprecatedGet.} =
## retrieves the value at ``t[key]``. If `key` is not in `t`, the ## retrieves the value at ``t[key]``. If `key` is not in `t`, the
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists. ## the key exists.
@ -418,13 +420,13 @@ proc rawGetDeep[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int {.inline
proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int = proc rawGet[A, B](t: OrderedTable[A, B], key: A, hc: var Hash): int =
rawGetImpl() rawGetImpl()
proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B = proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B {.deprecatedGet.} =
## retrieves the value at ``t[key]``. If `key` is not in `t`, the ## retrieves the value at ``t[key]``. If `key` is not in `t`, the
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists. ## the key exists.
get(t, key) get(t, key)
proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B = proc `[]`*[A, B](t: var OrderedTable[A, B], key: A): var B{.deprecatedGet.} =
## retrieves the value at ``t[key]``. The value can be modified. ## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``KeyError`` exception is raised. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
get(t, key) get(t, key)
@ -718,13 +720,13 @@ template ctget(t, key: untyped): untyped {.immediate.} =
else: else:
raise newException(KeyError, "key not found") raise newException(KeyError, "key not found")
proc `[]`*[A](t: CountTable[A], key: A): int = proc `[]`*[A](t: CountTable[A], key: A): int {.deprecatedGet.} =
## retrieves the value at ``t[key]``. If `key` is not in `t`, ## retrieves the value at ``t[key]``. If `key` is not in `t`,
## the ``KeyError`` exception is raised. One can check with ``hasKey`` ## the ``KeyError`` exception is raised. One can check with ``hasKey``
## whether the key exists. ## whether the key exists.
ctget(t, key) ctget(t, key)
proc `[]`*[A](t: var CountTable[A], key: A): var int = proc `[]`*[A](t: var CountTable[A], key: A): var int {.deprecatedGet.} =
## retrieves the value at ``t[key]``. The value can be modified. ## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``KeyError`` exception is raised. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
ctget(t, key) ctget(t, key)
@ -873,7 +875,7 @@ iterator mvalues*[A](t: CountTableRef[A]): var int =
for h in 0..high(t.data): for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val if t.data[h].val != 0: yield t.data[h].val
proc `[]`*[A](t: CountTableRef[A], key: A): var int = proc `[]`*[A](t: CountTableRef[A], key: A): var int {.deprecatedGet.} =
## retrieves the value at ``t[key]``. The value can be modified. ## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``KeyError`` exception is raised. ## If `key` is not in `t`, the ``KeyError`` exception is raised.
result = t[][key] result = t[][key]

View file

@ -176,7 +176,7 @@ proc loadAny(p: var JsonParser, a: Any, t: var Table[BiggestInt, pointer]) =
setPointer(a, nil) setPointer(a, nil)
next(p) next(p)
of jsonInt: of jsonInt:
setPointer(a, t[p.getInt]) setPointer(a, t.getOrDefault(p.getInt))
next(p) next(p)
of jsonArrayStart: of jsonArrayStart:
next(p) next(p)

View file

@ -499,7 +499,7 @@ proc newMimetypes*(): MimeDB =
proc getMimetype*(mimedb: MimeDB, ext: string, default = "text/plain"): string = proc getMimetype*(mimedb: MimeDB, ext: string, default = "text/plain"): string =
## Gets mimetype which corresponds to ``ext``. Returns ``default`` if ``ext`` ## Gets mimetype which corresponds to ``ext``. Returns ``default`` if ``ext``
## could not be found. ## could not be found.
result = mimedb.mimes[ext] result = mimedb.mimes.getOrDefault(ext)
if result == "": if result == "":
return default return default

View file

@ -145,8 +145,8 @@ proc next*(s: var ScgiState, timeout: int = -1): bool =
L = L * 10 + ord(d) - ord('0') L = L * 10 + ord(d) - ord('0')
recvBuffer(s, L+1) recvBuffer(s, L+1)
s.headers = parseHeaders(s.input, L) s.headers = parseHeaders(s.input, L)
if s.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected") if s.headers.getOrDefault("SCGI") != "1": raiseScgiError("SCGI Version 1 expected")
L = parseInt(s.headers["CONTENT_LENGTH"]) L = parseInt(s.headers.getOrDefault("CONTENT_LENGTH"))
recvBuffer(s, L) recvBuffer(s, L)
return true return true
@ -221,10 +221,10 @@ proc handleClientRead(client: AsyncClient, s: AsyncScgiState) =
case ret case ret
of ReadFullLine: of ReadFullLine:
client.headers = parseHeaders(client.input, client.input.len-1) client.headers = parseHeaders(client.input, client.input.len-1)
if client.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected") if client.headers.getOrDefault("SCGI") != "1": raiseScgiError("SCGI Version 1 expected")
client.input = "" # For next part client.input = "" # For next part
let contentLen = parseInt(client.headers["CONTENT_LENGTH"]) let contentLen = parseInt(client.headers.getOrDefault("CONTENT_LENGTH"))
if contentLen > 0: if contentLen > 0:
client.mode = ClientReadContent client.mode = ClientReadContent
else: else:
@ -232,7 +232,8 @@ proc handleClientRead(client: AsyncClient, s: AsyncScgiState) =
checkCloseSocket(client) checkCloseSocket(client)
of ReadPartialLine, ReadDisconnected, ReadNone: return of ReadPartialLine, ReadDisconnected, ReadNone: return
of ClientReadContent: of ClientReadContent:
let L = parseInt(client.headers["CONTENT_LENGTH"])-client.input.len let L = parseInt(client.headers.getOrDefault("CONTENT_LENGTH")) -
client.input.len
if L > 0: if L > 0:
let ret = recvBufferAsync(client, L) let ret = recvBufferAsync(client, L)
case ret case ret

View file

@ -111,7 +111,7 @@ template get(t: StringTableRef, key: string): stmt {.immediate.} =
raise newException(KeyError, "key not found") raise newException(KeyError, "key not found")
proc `[]`*(t: StringTableRef, key: string): var string {. proc `[]`*(t: StringTableRef, key: string): var string {.
rtl, extern: "nstTake".} = rtl, extern: "nstTake", deprecatedGet.} =
## retrieves the location at ``t[key]``. If `key` is not in `t`, the ## retrieves the location at ``t[key]``. If `key` is not in `t`, the
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether ## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists. ## the key exists.
@ -162,7 +162,7 @@ proc raiseFormatException(s: string) =
raise e raise e
proc getValue(t: StringTableRef, flags: set[FormatFlag], key: string): string = proc getValue(t: StringTableRef, flags: set[FormatFlag], key: string): string =
if hasKey(t, key): return t[key] if hasKey(t, key): return t.getOrDefault(key)
# hm difficult: assume safety in taint mode here. XXX This is dangerous! # hm difficult: assume safety in taint mode here. XXX This is dangerous!
if useEnvironment in flags: result = os.getEnv(key).string if useEnvironment in flags: result = os.getEnv(key).string
else: result = "" else: result = ""

View file

@ -342,7 +342,7 @@ proc attr*(n: XmlNode, name: string): string =
## Returns "" on failure. ## Returns "" on failure.
assert n.kind == xnElement assert n.kind == xnElement
if n.attrs == nil: return "" if n.attrs == nil: return ""
return n.attrs[name] return n.attrs.getOrDefault(name)
proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode]) = proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode]) =
## Iterates over all the children of `n` returning those matching `tag`. ## Iterates over all the children of `n` returning those matching `tag`.

View file

@ -51,3 +51,8 @@ when defined(nimlocks):
{.pragma: benign, gcsafe, locks: 0.} {.pragma: benign, gcsafe, locks: 0.}
else: else:
{.pragma: benign, gcsafe.} {.pragma: benign, gcsafe.}
when defined(nimTableGet):
{.pragma: deprecatedGet, deprecated.}
else:
{.pragma: deprecatedGet.}

View file

@ -8,7 +8,7 @@
import strutils, db_sqlite, os, osproc import strutils, db_sqlite, os, osproc
var db: TDbConn var db: DbConn
proc createDb() = proc createDb() =
db.exec(sql""" db.exec(sql"""
@ -61,7 +61,7 @@ var
proc `()`(cmd: string{lit}): string = cmd.execProcess.string.strip proc `()`(cmd: string{lit}): string = cmd.execProcess.string.strip
proc getMachine*(db: TDbConn): MachineId = proc getMachine*(db: DbConn): MachineId =
var name = "hostname"() var name = "hostname"()
if name.len == 0: if name.len == 0:
name = when defined(posix): getenv"HOSTNAME".string name = when defined(posix): getenv"HOSTNAME".string
@ -76,7 +76,7 @@ proc getMachine*(db: TDbConn): MachineId =
result = db.insertId(sql"insert into Machine(name, os, cpu) values (?,?,?)", result = db.insertId(sql"insert into Machine(name, os, cpu) values (?,?,?)",
name, system.hostOS, system.hostCPU).MachineId name, system.hostOS, system.hostCPU).MachineId
proc getCommit(db: TDbConn): CommitId = proc getCommit(db: DbConn): CommitId =
const commLen = "commit ".len const commLen = "commit ".len
let hash = "git log -n 1"()[commLen..commLen+10] let hash = "git log -n 1"()[commLen..commLen+10]
let branch = "git symbolic-ref --short HEAD"() let branch = "git symbolic-ref --short HEAD"()

View file

@ -109,7 +109,7 @@ div.tabContent.hide { display: none; }
proc td(s: string): string = proc td(s: string): string =
result = "<td>" & s.substr(0, 200).xmlEncode & "</td>" result = "<td>" & s.substr(0, 200).xmlEncode & "</td>"
proc getCommit(db: TDbConn, c: int): string = proc getCommit(db: DbConn, c: int): string =
var commit = c var commit = c
for thisCommit in db.rows(sql"select id from [Commit] order by id desc"): for thisCommit in db.rows(sql"select id from [Commit] order by id desc"):
if commit == 0: result = thisCommit[0] if commit == 0: result = thisCommit[0]

View file

@ -64,7 +64,7 @@ proc callCompiler(cmdTemplate, filename, options: string,
let c = parseCmdLine(cmdTemplate % ["target", targetToCmd[target], let c = parseCmdLine(cmdTemplate % ["target", targetToCmd[target],
"options", options, "file", filename.quoteShell]) "options", options, "file", filename.quoteShell])
var p = startProcess(command=c[0], args=c[1.. ^1], var p = startProcess(command=c[0], args=c[1.. ^1],
options={poStdErrToStdOut, poUseShell}) options={poStdErrToStdOut, poUsePath})
let outp = p.outputStream let outp = p.outputStream
var suc = "" var suc = ""
var err = "" var err = ""
@ -195,7 +195,7 @@ proc generatedFile(path, name: string, target: TTarget): string =
proc codegenCheck(test: TTest, check: string, given: var TSpec) = proc codegenCheck(test: TTest, check: string, given: var TSpec) =
try: try:
let (path, name, ext2) = test.name.splitFile let (path, name, _) = test.name.splitFile
let genFile = generatedFile(path, name, test.target) let genFile = generatedFile(path, name, test.target)
let contents = readFile(genFile).string let contents = readFile(genFile).string
if check[0] == '\\': if check[0] == '\\':
@ -287,7 +287,7 @@ proc testSpec(r: var TResults, test: TTest) =
let isJsTarget = test.target == targetJS let isJsTarget = test.target == targetJS
var exeFile: string var exeFile: string
if isJsTarget: if isJsTarget:
let (dir, file, ext) = splitFile(tname) let (dir, file, _) = splitFile(tname)
exeFile = dir / "nimcache" / file & ".js" # *TODO* hardcoded "nimcache" exeFile = dir / "nimcache" / file & ".js" # *TODO* hardcoded "nimcache"
else: else:
exeFile = changeFileExt(tname, ExeExt) exeFile = changeFileExt(tname, ExeExt)
@ -332,7 +332,7 @@ proc testSpec(r: var TResults, test: TTest) =
proc testNoSpec(r: var TResults, test: TTest) = proc testNoSpec(r: var TResults, test: TTest) =
# does not extract the spec because the file is not supposed to have any # does not extract the spec because the file is not supposed to have any
let tname = test.name.addFileExt(".nim") #let tname = test.name.addFileExt(".nim")
inc(r.total) inc(r.total)
let given = callCompiler(cmdTemplate, test.name, test.options, test.target) let given = callCompiler(cmdTemplate, test.name, test.options, test.target)
r.addResult(test, "", given.msg, given.err) r.addResult(test, "", given.msg, given.err)
@ -348,7 +348,7 @@ proc testC(r: var TResults, test: TTest) =
r.addResult(test, "", given.msg, given.err) r.addResult(test, "", given.msg, given.err)
elif test.action == actionRun: elif test.action == actionRun:
let exeFile = changeFileExt(test.name, ExeExt) let exeFile = changeFileExt(test.name, ExeExt)
var (buf, exitCode) = execCmdEx(exeFile, options = {poStdErrToStdOut, poUseShell}) var (_, exitCode) = execCmdEx(exeFile, options = {poStdErrToStdOut, poUsePath})
if exitCode != 0: given.err = reExitCodesDiffer if exitCode != 0: given.err = reExitCodesDiffer
if given.err == reSuccess: inc(r.passed) if given.err == reSuccess: inc(r.passed)

View file

@ -8,7 +8,11 @@ News
Changes affecting backwards compatibility Changes affecting backwards compatibility
----------------------------------------- -----------------------------------------
- ``tables.[]``, ``strtabs.[]``, ``critbits.[]`` **now raise**
the ``KeyError`` **exception when the key does not exist**! Use the
new ``getOrDefault`` instead to get the old behaviour. Compile all your
code with ``-d:nimTableGet`` to get a listing of where your code
uses ``[]``!
- The ``rawsockets`` module has been renamed to ``nativesockets`` to avoid - The ``rawsockets`` module has been renamed to ``nativesockets`` to avoid
confusion with TCP/IP raw sockets, so ``newNativeSocket`` should be used confusion with TCP/IP raw sockets, so ``newNativeSocket`` should be used
instead of ``newRawSocket``. instead of ``newRawSocket``.
@ -68,10 +72,10 @@ News
* ``libeay32.dll``: Split into ``libeay32.dll`` and ``libeay64.dll``. * ``libeay32.dll``: Split into ``libeay32.dll`` and ``libeay64.dll``.
Compile with ``-d:nimOldDLLs`` to make the stdlib use the old DLL names. Compile with ``-d:nimOldDLLs`` to make the stdlib use the old DLL names.
- Nim VM now treats objects as nkObjConstr nodes, and not nkPar nodes as it - Nim VM now treats objects as ``nkObjConstr`` nodes, and not ``nkPar`` nodes
was previously. Macros that generate nkPar nodes when object is expected are as it was previously. Macros that generate ``nkPar`` nodes when object is
likely to break. Macros that expect nkPar nodes to which objects are passed expected are likely to break. Macros that expect ``nkPar`` nodes to which
are likely to break as well. objects are passed are likely to break as well.
- Base methods now need to be annotated with the ``base`` pragma. This makes - Base methods now need to be annotated with the ``base`` pragma. This makes
multi methods less error-prone to use with the effect system. multi methods less error-prone to use with the effect system.
- Nim's parser directive ``#!`` is now ``#?`` in order to produce no conflicts - Nim's parser directive ``#!`` is now ``#?`` in order to produce no conflicts
@ -86,7 +90,7 @@ News
echo f(0, "abc") echo f(0, "abc")
- The ``ftpclient`` module is now deprecated in favour of the - The ``ftpclient`` module is now deprecated in favour of the
``asyncdispatch`` module. ``asyncftpclient`` module.
- In sequtils.nim renamed ``repeat`` function to ``cycle`` (concatenating - In sequtils.nim renamed ``repeat`` function to ``cycle`` (concatenating
a sequence by itself the given times), and also introduced ``repeat``, a sequence by itself the given times), and also introduced ``repeat``,
which repeats an element the given times. which repeats an element the given times.