udpated the compiler and tester to use getOrDefault

This commit is contained in:
Araq
2015-10-13 14:10:33 +02:00
parent 2fda95a4d6
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');
</script>
""" % [config["doc.googleAnalytics"]]
""" % [config.getOrDefault"doc.googleAnalytics"]
else:
result.analytics = ""

View File

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

View File

@@ -28,6 +28,8 @@
import
pcre, strutils, rtarrays
{.deprecated.}
const
MaxSubpatterns* = 20
## defines the maximum number of subpatterns that can be captured.
@@ -46,7 +48,7 @@ type
h: ptr Pcre
e: ptr ExtraData
Regex* {.deprecated.} = ref RegexDesc ## a compiled regular expression
Regex* = ref RegexDesc ## a compiled regular expression
RegexError* = object of ValueError
## 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.msgHandler = msgHandler
let s = config["split.item.toc"]
let s = config.getOrDefault"split.item.toc"
if s != "": g.splitAfter = parseInt(s)
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.
let refname = n.rstnodeToRefname
if d.seenIndexTerms.hasKey(refname):
d.seenIndexTerms[refname] = d.seenIndexTerms[refname] + 1
d.seenIndexTerms[refname] = d.seenIndexTerms.getOrDefault(refname) + 1
else:
d.seenIndexTerms[refname] = 1
let id = refname & '_' & $d.seenIndexTerms[refname]
let id = refname & '_' & $d.seenIndexTerms.getOrDefault(refname)
var term = ""
renderAux(d, n, term)
@@ -518,7 +518,7 @@ proc generateDocumentationIndex(docs: IndexedDocs): string =
sort(titles, cmp)
for title in titles:
let tocList = generateDocumentationTOC(docs[title])
let tocList = generateDocumentationTOC(docs.getOrDefault(title))
result.add("<ul><li><a href=\"" &
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,
"""<img src="$1" width="15"
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) =
## 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
let id = $d.listingCounter
if not params.numberLines:
result = (d.config["doc.listing_start"] % id,
d.config["doc.listing_end"] % id)
result = (d.config.getOrDefault"doc.listing_start" % id,
d.config.getOrDefault"doc.listing_end" % id)
return
var codeLines = 1 + code.strip.countLines
@@ -856,9 +857,11 @@ proc buildLinesHTMLTable(d: PDoc; params: CodeBlockParams, code: string):
result.beginTable.add($line & "\n")
line.inc
codeLines.dec
result.beginTable.add("</pre></td><td>" & (d.config["doc.listing_start"] % id))
result.endTable = (d.config["doc.listing_end"] % id) &
"</td></tr></tbody></table>" & (d.config["doc.listing_button"] % id)
result.beginTable.add("</pre></td><td>" & (
d.config.getOrDefault"doc.listing_start" % 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) =
## Renders a code block, appending it to `result`.

View File

@@ -212,7 +212,7 @@ proc processClient(client: AsyncSocket, address: string,
if request.reqMethod == "post":
# Check for Expect header
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")
else:
await client.sendStatus("417 Expectation Failed")
@@ -221,7 +221,8 @@ proc processClient(client: AsyncSocket, address: string,
# - Check for Content-length header
if request.headers.hasKey("Content-Length"):
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.")
continue
else:
@@ -232,16 +233,18 @@ proc processClient(client: AsyncSocket, address: string,
continue
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)
else:
await request.respond(Http400, "Invalid request method. Got: " & request.reqMethod)
await request.respond(Http400, "Invalid request method. Got: " &
request.reqMethod)
# Persistent connections
if (request.protocol == HttpVer11 and
request.headers["connection"].normalize != "close") or
request.headers.getOrDefault("connection").normalize != "close") or
(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
# header states otherwise.
# 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 =
## Gets a cookie. If no cookie of `name` exists, "" is returned.
if gcookies == nil: gcookies = parseCookies(getHttpCookie())
result = TaintedString(gcookies[name])
result = TaintedString(gcookies.getOrDefault(name))
proc existsCookie*(name: string): bool =
## 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
## by Adam Langley.
include "system/inclrtl"
type
NodeObj[T] = object {.acyclic.}
byte: int ## byte index of the difference
@@ -149,13 +151,14 @@ template get[T](c: CritBitTree[T], key: string): T {.immediate.} =
else:
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
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists.
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.
## If `key` is not in `t`, the ``KeyError`` exception is raised.
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 =
## 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
## for sharing.
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.} =
## 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
## for sharing. Use ```[]``` instead.
s[key]

View File

@@ -68,6 +68,8 @@
import
hashes, math
include "system/inclrtl"
type
KeyValuePair[A, B] = tuple[hcode: Hash, key: A, val: B]
KeyValuePairSeq[A, B] = seq[KeyValuePair[A, B]]
@@ -115,13 +117,13 @@ template getOrDefaultImpl(t, key): untyped {.immediate.} =
var index = rawGet(t, key, hc)
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
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists.
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.
## If `key` is not in `t`, the ``KeyError`` exception is raised.
get(t, key)
@@ -293,7 +295,7 @@ iterator mvalues*[A, B](t: TableRef[A, B]): var B =
for h in 0..high(t.data):
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
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## 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 =
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
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists.
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.
## If `key` is not in `t`, the ``KeyError`` exception is raised.
get(t, key)
@@ -718,13 +720,13 @@ template ctget(t, key: untyped): untyped {.immediate.} =
else:
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`,
## the ``KeyError`` exception is raised. One can check with ``hasKey``
## whether the key exists.
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.
## If `key` is not in `t`, the ``KeyError`` exception is raised.
ctget(t, key)
@@ -873,7 +875,7 @@ iterator mvalues*[A](t: CountTableRef[A]): var int =
for h in 0..high(t.data):
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.
## If `key` is not in `t`, the ``KeyError`` exception is raised.
result = t[][key]

View File

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

View File

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

View File

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

View File

@@ -111,7 +111,7 @@ template get(t: StringTableRef, key: string): stmt {.immediate.} =
raise newException(KeyError, "key not found")
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
## ``KeyError`` exception is raised. One can check with ``hasKey`` whether
## the key exists.
@@ -162,7 +162,7 @@ proc raiseFormatException(s: string) =
raise e
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!
if useEnvironment in flags: result = os.getEnv(key).string
else: result = ""

View File

@@ -342,7 +342,7 @@ proc attr*(n: XmlNode, name: string): string =
## Returns "" on failure.
assert n.kind == xnElement
if n.attrs == nil: return ""
return n.attrs[name]
return n.attrs.getOrDefault(name)
proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode]) =
## 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.}
else:
{.pragma: benign, gcsafe.}
when defined(nimTableGet):
{.pragma: deprecatedGet, deprecated.}
else:
{.pragma: deprecatedGet.}

View File

@@ -8,7 +8,7 @@
import strutils, db_sqlite, os, osproc
var db: TDbConn
var db: DbConn
proc createDb() =
db.exec(sql"""
@@ -61,7 +61,7 @@ var
proc `()`(cmd: string{lit}): string = cmd.execProcess.string.strip
proc getMachine*(db: TDbConn): MachineId =
proc getMachine*(db: DbConn): MachineId =
var name = "hostname"()
if name.len == 0:
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 (?,?,?)",
name, system.hostOS, system.hostCPU).MachineId
proc getCommit(db: TDbConn): CommitId =
proc getCommit(db: DbConn): CommitId =
const commLen = "commit ".len
let hash = "git log -n 1"()[commLen..commLen+10]
let branch = "git symbolic-ref --short HEAD"()

View File

@@ -109,7 +109,7 @@ div.tabContent.hide { display: none; }
proc td(s: string): string =
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
for thisCommit in db.rows(sql"select id from [Commit] order by id desc"):
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],
"options", options, "file", filename.quoteShell])
var p = startProcess(command=c[0], args=c[1.. ^1],
options={poStdErrToStdOut, poUseShell})
options={poStdErrToStdOut, poUsePath})
let outp = p.outputStream
var suc = ""
var err = ""
@@ -195,7 +195,7 @@ proc generatedFile(path, name: string, target: TTarget): string =
proc codegenCheck(test: TTest, check: string, given: var TSpec) =
try:
let (path, name, ext2) = test.name.splitFile
let (path, name, _) = test.name.splitFile
let genFile = generatedFile(path, name, test.target)
let contents = readFile(genFile).string
if check[0] == '\\':
@@ -287,7 +287,7 @@ proc testSpec(r: var TResults, test: TTest) =
let isJsTarget = test.target == targetJS
var exeFile: string
if isJsTarget:
let (dir, file, ext) = splitFile(tname)
let (dir, file, _) = splitFile(tname)
exeFile = dir / "nimcache" / file & ".js" # *TODO* hardcoded "nimcache"
else:
exeFile = changeFileExt(tname, ExeExt)
@@ -332,7 +332,7 @@ proc testSpec(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
let tname = test.name.addFileExt(".nim")
#let tname = test.name.addFileExt(".nim")
inc(r.total)
let given = callCompiler(cmdTemplate, test.name, test.options, test.target)
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)
elif test.action == actionRun:
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 given.err == reSuccess: inc(r.passed)

View File

@@ -8,7 +8,11 @@ News
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
confusion with TCP/IP raw sockets, so ``newNativeSocket`` should be used
instead of ``newRawSocket``.
@@ -68,10 +72,10 @@ News
* ``libeay32.dll``: Split into ``libeay32.dll`` and ``libeay64.dll``.
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
was previously. Macros that generate nkPar nodes when object is expected are
likely to break. Macros that expect nkPar nodes to which objects are passed
are likely to break as well.
- Nim VM now treats objects as ``nkObjConstr`` nodes, and not ``nkPar`` nodes
as it was previously. Macros that generate ``nkPar`` nodes when object is
expected are likely to break. Macros that expect ``nkPar`` nodes to which
objects are passed are likely to break as well.
- Base methods now need to be annotated with the ``base`` pragma. This makes
multi methods less error-prone to use with the effect system.
- Nim's parser directive ``#!`` is now ``#?`` in order to produce no conflicts
@@ -86,7 +90,7 @@ News
echo f(0, "abc")
- The ``ftpclient`` module is now deprecated in favour of the
``asyncdispatch`` module.
``asyncftpclient`` module.
- In sequtils.nim renamed ``repeat`` function to ``cycle`` (concatenating
a sequence by itself the given times), and also introduced ``repeat``,
which repeats an element the given times.