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

@ -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.}