`_.
@@ -41,8 +41,8 @@ const
## for Nimrod's ``float`` type.
type
- TFloatClass* = enum ## describes the class a floating point value belongs to.
- ## This is the type that is returned by `classify`.
+ FloatClass* = enum ## describes the class a floating point value belongs to.
+ ## This is the type that is returned by `classify`.
fcNormal, ## value is an ordinary nonzero floating point value
fcSubnormal, ## value is a subnormal (a very small) floating point value
fcZero, ## value is zero
@@ -51,10 +51,10 @@ type
fcInf, ## value is positive infinity
fcNegInf ## value is negative infinity
-proc classify*(x: float): TFloatClass =
+proc classify*(x: float): FloatClass =
## classifies a floating point value. Returns `x`'s class as specified by
- ## `TFloatClass`.
-
+ ## `FloatClass`.
+
# JavaScript and most C compilers have no classify:
if x == 0.0:
if 1.0/x == Inf:
@@ -287,12 +287,14 @@ proc random[T](a: openArray[T]): T =
result = a[random(a.low..a.len)]
type
- TRunningStat* {.pure,final.} = object ## an accumulator for statistical data
- n*: int ## number of pushed data
- sum*, min*, max*, mean*: float ## self-explaining
+ RunningStat* = object ## an accumulator for statistical data
+ n*: int ## number of pushed data
+ sum*, min*, max*, mean*: float ## self-explaining
oldM, oldS, newS: float
-proc push*(s: var TRunningStat, x: float) =
+{.deprecated: [TFloatClass: FloatClass, TRunningStat: RunningStat].}
+
+proc push*(s: var RunningStat, x: float) =
## pushes a value `x` for processing
inc(s.n)
# See Knuth TAOCP vol 2, 3rd edition, page 232
@@ -313,16 +315,16 @@ proc push*(s: var TRunningStat, x: float) =
s.oldS = s.newS
s.sum = s.sum + x
-proc push*(s: var TRunningStat, x: int) =
+proc push*(s: var RunningStat, x: int) =
## pushes a value `x` for processing. `x` is simply converted to ``float``
## and the other push operation is called.
push(s, toFloat(x))
-proc variance*(s: TRunningStat): float =
+proc variance*(s: RunningStat): float =
## computes the current variance of `s`
if s.n > 1: result = s.newS / (toFloat(s.n - 1))
-proc standardDeviation*(s: TRunningStat): float =
+proc standardDeviation*(s: RunningStat): float =
## computes the current standard deviation of `s`
result = sqrt(variance(s))
diff --git a/lib/pure/md5.nim b/lib/pure/md5.nim
index 0328932fd..322dbbe1d 100644
--- a/lib/pure/md5.nim
+++ b/lib/pure/md5.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim
index 5577fa5cf..8712df7f6 100644
--- a/lib/pure/memfiles.nim
+++ b/lib/pure/memfiles.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Nimrod Contributors
#
# See the file "copying.txt", included in this
@@ -22,7 +22,7 @@ else:
import os
type
- TMemFile* = object {.pure.} ## represents a memory mapped file
+ MemFile* = object ## represents a memory mapped file
mem*: pointer ## a pointer to the memory mapped file. The pointer
## can be used directly to change the contents of the
## file, if it was opened with write access.
@@ -34,8 +34,9 @@ type
else:
handle: cint
+{.deprecated: [TMemFile: MemFile].}
-proc mapMem*(m: var TMemFile, mode: FileMode = fmRead,
+proc mapMem*(m: var MemFile, mode: FileMode = fmRead,
mappedSize = -1, offset = 0): pointer =
var readonly = mode == fmRead
when defined(windows):
@@ -60,27 +61,27 @@ proc mapMem*(m: var TMemFile, mode: FileMode = fmRead,
osError(osLastError())
-proc unmapMem*(f: var TMemFile, p: pointer, size: int) =
+proc unmapMem*(f: var MemFile, p: pointer, size: int) =
## unmaps the memory region ``(p, ", nodecl.}
proc gettime(dummy: ptr cint): cint {.importc: "time", header: "".}
@@ -79,12 +81,12 @@ proc genOid*(): TOid =
result.fuzz = fuzz
bigEndian32(addr result.count, addr(i))
-proc generatedTime*(oid: TOid): TTime =
+proc generatedTime*(oid: Oid): Time =
## returns the generated timestamp of the OID.
var tmp: int32
var dummy = oid.time
bigEndian32(addr(tmp), addr(dummy))
- result = TTime(tmp)
+ result = Time(tmp)
when isMainModule:
let xo = genOID()
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index 483044d0a..0b4cf24c5 100644
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -29,18 +29,23 @@ else:
include "system/ansi_c"
type
- FReadEnv* = object of ReadIOEffect ## effect that denotes a read
- ## from an environment variable
- FWriteEnv* = object of WriteIOEffect ## effect that denotes a write
- ## to an environment variable
+ ReadEnvEffect* = object of ReadIOEffect ## effect that denotes a read
+ ## from an environment variable
+ WriteEnvEffect* = object of WriteIOEffect ## effect that denotes a write
+ ## to an environment variable
- FReadDir* = object of ReadIOEffect ## effect that denotes a write operation to
- ## the directory structure
- FWriteDir* = object of WriteIOEffect ## effect that denotes a write operation to
- ## the directory structure
+ ReadDirEffect* = object of ReadIOEffect ## effect that denotes a write
+ ## operation to the directory structure
+ WriteDirEffect* = object of WriteIOEffect ## effect that denotes a write operation to
+ ## the directory structure
- TOSErrorCode* = distinct int32 ## Specifies an OS Error Code.
+ OSErrorCode* = distinct int32 ## Specifies an OS Error Code.
+{.deprecated: [FReadEnv: ReadEnvEffect, FWriteEnv: WriteEnvEffect,
+ FReadDir: ReadDirEffect,
+ FWriteDir: WriteDirEffect,
+ TOSErrorCode: OSErrorCode
+].}
const
doslike = defined(windows) or defined(OS2) or defined(DOS)
# DOS-like filesystem
@@ -204,7 +209,8 @@ proc osErrorMsg*(): string {.rtl, extern: "nos$1", deprecated.} =
result = $os.strerror(errno)
{.push warning[deprecated]: off.}
-proc osError*(msg: string = "") {.noinline, rtl, extern: "nos$1", deprecated.} =
+proc raiseOSError*(msg: string = "") {.noinline, rtl, extern: "nos$1",
+ deprecated.} =
## raises an EOS exception with the given message ``msg``.
## If ``msg == ""``, the operating system's error flag
## (``errno``) is converted to a readable error message. On Windows
@@ -219,10 +225,12 @@ proc osError*(msg: string = "") {.noinline, rtl, extern: "nos$1", deprecated.} =
raise newException(OSError, msg)
{.pop.}
-proc `==`*(err1, err2: TOSErrorCode): bool {.borrow.}
-proc `$`*(err: TOSErrorCode): string {.borrow.}
+{.deprecated: [osError: raiseOSError].}
-proc osErrorMsg*(errorCode: TOSErrorCode): string =
+proc `==`*(err1, err2: OSErrorCode): bool {.borrow.}
+proc `$`*(err: OSErrorCode): string {.borrow.}
+
+proc osErrorMsg*(errorCode: OSErrorCode): string =
## Converts an OS error code into a human readable string.
##
## The error code can be retrieved using the ``OSLastError`` proc.
@@ -249,10 +257,10 @@ proc osErrorMsg*(errorCode: TOSErrorCode): string =
result = $msgbuf
if msgbuf != nil: localFree(msgbuf)
else:
- if errorCode != TOSErrorCode(0'i32):
+ if errorCode != OSErrorCode(0'i32):
result = $os.strerror(errorCode.int32)
-proc osError*(errorCode: TOSErrorCode) =
+proc raiseOSError*(errorCode: OSErrorCode) =
## Raises an ``EOS`` exception. The ``errorCode`` will determine the
## message, ``OSErrorMsg`` will be used to get this message.
##
@@ -268,7 +276,7 @@ proc osError*(errorCode: TOSErrorCode) =
raise e
{.push stackTrace:off.}
-proc osLastError*(): TOSErrorCode =
+proc osLastError*(): OSErrorCode =
## Retrieves the last operating system error code.
##
## This procedure is useful in the event when an OS call fails. In that case
@@ -285,7 +293,7 @@ proc osLastError*(): TOSErrorCode =
when defined(windows):
result = TOSErrorCode(getLastError())
else:
- result = TOSErrorCode(errno)
+ result = OSErrorCode(errno)
{.pop.}
proc unixToNativePath*(path: string, drive=""): string {.
@@ -371,7 +379,7 @@ when defined(windows):
f.cFileName[1].int == dot and f.cFileName[2].int == 0)
proc existsFile*(filename: string): bool {.rtl, extern: "nos$1",
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## Returns true if the file exists, false otherwise.
when defined(windows):
when useWinUnicode:
@@ -384,7 +392,7 @@ proc existsFile*(filename: string): bool {.rtl, extern: "nos$1",
var res: TStat
return stat(filename, res) >= 0'i32 and S_ISREG(res.st_mode)
-proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [FReadDir].} =
+proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [ReadDirEffect].} =
## Returns true iff the directory `dir` exists. If `dir` is a file, false
## is returned.
when defined(windows):
@@ -399,7 +407,7 @@ proc existsDir*(dir: string): bool {.rtl, extern: "nos$1", tags: [FReadDir].} =
return stat(dir, res) >= 0'i32 and S_ISDIR(res.st_mode)
proc symlinkExists*(link: string): bool {.rtl, extern: "nos$1",
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## Returns true iff the symlink `link` exists. Will return true
## regardless of whether the link points to a directory or file.
when defined(windows):
@@ -701,7 +709,7 @@ proc extractFilename*(path: string): string {.
result = splitPath(path).tail
proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## Returns the full path of `filename`, raises EOS in case of an error.
when defined(windows):
const bufsize = 3072'i32
@@ -800,7 +808,7 @@ when defined(Windows):
)
proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## Returns True if both pathname arguments refer to the same physical
## file or directory. Raises an exception if any of the files does not
## exist or information about it can not be obtained.
@@ -883,7 +891,7 @@ type
fpOthersRead ## read access for others
proc getFilePermissions*(filename: string): set[TFilePermission] {.
- rtl, extern: "nos$1", tags: [FReadDir].} =
+ rtl, extern: "nos$1", tags: [ReadDirEffect].} =
## retrieves file permissions for `filename`. `OSError` is raised in case of
## an error. On Windows, only the ``readonly`` flag is checked, every other
## permission is available in any case.
@@ -915,7 +923,7 @@ proc getFilePermissions*(filename: string): set[TFilePermission] {.
result = {fpUserExec..fpOthersRead}
proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
- rtl, extern: "nos$1", tags: [FWriteDir].} =
+ rtl, extern: "nos$1", tags: [WriteDirEffect].} =
## sets the file permissions for `filename`. `OSError` is raised in case of
## an error. On Windows, only the ``readonly`` flag is changed, depending on
## ``fpUserWrite``.
@@ -1014,7 +1022,7 @@ when defined(Windows):
template setFileAttributes(file, attrs: expr): expr {.immediate.} =
setFileAttributesA(file, attrs)
-proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
+proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].} =
## Removes the `file`. If this fails, `EOS` is raised. This does not fail
## if the file never existed in the first place.
## On Windows, ignores the read-only attribute.
@@ -1076,7 +1084,7 @@ when defined(windows):
while true:
var eend = strEnd(e)
add(environment, $e)
- e = cast[WideCString](cast[ByteAddress](eend)+2)
+ e = cast[WideCString](cast[TAddress](eend)+2)
if eend[1].int == 0: break
discard freeEnvironmentStringsW(env)
else:
@@ -1130,7 +1138,7 @@ proc findEnvVar(key: string): int =
if startsWith(environment[i], temp): return i
return -1
-proc getEnv*(key: string): TaintedString {.tags: [FReadEnv].} =
+proc getEnv*(key: string): TaintedString {.tags: [ReadEnvEffect].} =
## Returns the value of the `environment variable`:idx: named `key`.
##
## If the variable does not exist, "" is returned. To distinguish
@@ -1144,13 +1152,13 @@ proc getEnv*(key: string): TaintedString {.tags: [FReadEnv].} =
if env == nil: return TaintedString("")
result = TaintedString($env)
-proc existsEnv*(key: string): bool {.tags: [FReadEnv].} =
+proc existsEnv*(key: string): bool {.tags: [ReadEnvEffect].} =
## Checks whether the environment variable named `key` exists.
## Returns true if it exists, false otherwise.
if c_getenv(key) != nil: return true
else: return findEnvVar(key) >= 0
-proc putEnv*(key, val: string) {.tags: [FWriteEnv].} =
+proc putEnv*(key, val: string) {.tags: [WriteEnvEffect].} =
## Sets the value of the `environment variable`:idx: named `key` to `val`.
## If an error occurs, `EInvalidEnvVar` is raised.
@@ -1175,7 +1183,7 @@ proc putEnv*(key, val: string) {.tags: [FWriteEnv].} =
else:
if setEnvironmentVariableA(key, val) == 0'i32: osError(osLastError())
-iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [FReadEnv].} =
+iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [ReadEnvEffect].} =
## Iterate over all `environments variables`:idx:. In the first component
## of the tuple is the name of the current variable stored, in the second
## its value.
@@ -1185,7 +1193,7 @@ iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [FReadEnv].} =
yield (TaintedString(substr(environment[i], 0, p-1)),
TaintedString(substr(environment[i], p+1)))
-iterator walkFiles*(pattern: string): string {.tags: [FReadDir].} =
+iterator walkFiles*(pattern: string): string {.tags: [ReadDirEffect].} =
## Iterate over all the files that match the `pattern`. On POSIX this uses
## the `glob`:idx: call.
##
@@ -1225,7 +1233,7 @@ type
pcLinkToDir ## path refers to a symbolic link to a directory
iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## walks over the directory `dir` and yields for each directory or file in
## `dir`. The component type and full path for each item is returned.
## Walking is not recursive.
@@ -1278,7 +1286,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
discard closedir(d)
iterator walkDirRec*(dir: string, filter={pcFile, pcDir}): string {.
- tags: [FReadDir].} =
+ tags: [ReadDirEffect].} =
## walks over the directory `dir` and yields for each file in `dir`. The
## full path for each file is returned.
## **Warning**:
@@ -1318,7 +1326,7 @@ proc rawRemoveDir(dir: string) =
if rmdir(dir) != 0'i32 and errno != ENOENT: osError(osLastError())
proc removeDir*(dir: string) {.rtl, extern: "nos$1", tags: [
- FWriteDir, FReadDir].} =
+ WriteDirEffect, ReadDirEffect].} =
## Removes the directory `dir` including all subdirectories and files
## in `dir` (recursively).
##
@@ -1345,7 +1353,7 @@ proc rawCreateDir(dir: string) =
if res == 0'i32 and getLastError() != 183'i32:
osError(osLastError())
-proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [FWriteDir].} =
+proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].} =
## Creates the `directory`:idx: `dir`.
##
## The directory may contain several subdirectories that do not exist yet.
@@ -1568,7 +1576,7 @@ proc copyDirWithPermissions*(source, dest: string,
proc inclFilePermissions*(filename: string,
permissions: set[TFilePermission]) {.
- rtl, extern: "nos$1", tags: [FReadDir, FWriteDir].} =
+ rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect].} =
## a convenience procedure for:
##
## .. code-block:: nimrod
@@ -1577,14 +1585,14 @@ proc inclFilePermissions*(filename: string,
proc exclFilePermissions*(filename: string,
permissions: set[TFilePermission]) {.
- rtl, extern: "nos$1", tags: [FReadDir, FWriteDir].} =
+ rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect].} =
## a convenience procedure for:
##
## .. code-block:: nimrod
## setFilePermissions(filename, getFilePermissions(filename)-permissions)
setFilePermissions(filename, getFilePermissions(filename)-permissions)
-proc getHomeDir*(): string {.rtl, extern: "nos$1", tags: [FReadEnv].} =
+proc getHomeDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} =
## Returns the home directory of the current user.
##
## This proc is wrapped by the expandTilde proc for the convenience of
@@ -1592,12 +1600,12 @@ proc getHomeDir*(): string {.rtl, extern: "nos$1", tags: [FReadEnv].} =
when defined(windows): return string(getEnv("USERPROFILE")) & "\\"
else: return string(getEnv("HOME")) & "/"
-proc getConfigDir*(): string {.rtl, extern: "nos$1", tags: [FReadEnv].} =
+proc getConfigDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} =
## Returns the config directory of the current user for applications.
when defined(windows): return string(getEnv("APPDATA")) & "\\"
else: return string(getEnv("HOME")) & "/.config/"
-proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [FReadEnv].} =
+proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [ReadEnvEffect].} =
## Returns the temporary directory of the current user for applications to
## save temporary files in.
when defined(windows): return string(getEnv("TEMP")) & "\\"
@@ -1605,7 +1613,7 @@ proc getTempDir*(): string {.rtl, extern: "nos$1", tags: [FReadEnv].} =
when defined(nimdoc):
# Common forward declaration docstring block for parameter retrieval procs.
- proc paramCount*(): int {.tags: [FReadIO].} =
+ proc paramCount*(): int {.tags: [ReadIOEffect].} =
## Returns the number of `command line arguments`:idx: given to the
## application.
##
@@ -1625,7 +1633,7 @@ when defined(nimdoc):
## else:
## # Do something else!
- proc paramStr*(i: int): TaintedString {.tags: [FReadIO].} =
+ proc paramStr*(i: int): TaintedString {.tags: [ReadIOEffect].} =
## Returns the `i`-th `command line argument`:idx: given to the application.
##
## `i` should be in the range `1..paramCount()`, the `EInvalidIndex`
@@ -1826,7 +1834,7 @@ proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
close(f)
else: osError(osLastError())
-proc findExe*(exe: string): string {.tags: [FReadDir, FReadEnv].} =
+proc findExe*(exe: string): string {.tags: [ReadDirEffect, ReadEnvEffect].} =
## Searches for `exe` in the current working directory and then
## in directories listed in the ``PATH`` environment variable.
## Returns "" if the `exe` cannot be found. On DOS-like platforms, `exe`
@@ -1854,7 +1862,6 @@ proc expandTilde*(path: string): string =
## let configFile = expandTilde("~" / "appname.cfg")
## echo configFile
## # --> C:\Users\amber\appname.cfg
-
if len(path) > 1 and path[0] == '~' and (path[1] == '/' or path[1] == '\\'):
result = getHomeDir() / path[2..len(path)-1]
else:
@@ -1961,7 +1968,7 @@ proc getFileInfo*(handle: FileHandle): FileInfo =
rawToFormalFileInfo(rawInfo, result)
proc getFileInfo*(file: File): FileInfo =
- result = getFileInfo(file.fileHandle())
+ result = getFileInfo(file.getFileHandle())
proc getFileInfo*(path: string, followSymlink = true): FileInfo =
## Retrieves file information for the file object pointed to by `path`.
diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim
index d5ca2f5a5..25782d4f5 100644
--- a/lib/pure/osproc.nim
+++ b/lib/pure/osproc.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -24,7 +24,7 @@ when defined(linux):
import linux
type
- TProcess = object of RootObj
+ ProcessObj = object of RootObj
when defined(windows):
fProcessHandle: THandle
inHandle, outHandle, errHandle: FileHandle
@@ -35,9 +35,9 @@ type
id: TPid
exitCode: cint
- PProcess* = ref TProcess ## represents an operating system process
+ Process* = ref ProcessObj ## represents an operating system process
- TProcessOption* = enum ## options that can be passed `startProcess`
+ ProcessOption* = enum ## options that can be passed `startProcess`
poEchoCmd, ## echo the command before execution
poUsePath, ## Asks system to search for executable using PATH environment
## variable.
@@ -47,6 +47,9 @@ type
poStdErrToStdOut, ## merge stdout and stderr to the stdout stream
poParentStreams ## use the parent's streams
+{.deprecated: [TProcess: ProcessObj, PProcess: Process,
+ TProcessOption: ProcessOption].}
+
const poUseShell* {.deprecated.} = poUsePath
## Deprecated alias for poUsePath.
@@ -125,7 +128,7 @@ proc startProcess*(command: string,
args: openArray[string] = [],
env: PStringTable = nil,
options: set[TProcessOption] = {poStdErrToStdOut}):
- PProcess {.rtl, extern: "nosp$1", tags: [ExecIOEffect, FReadEnv].}
+ PProcess {.rtl, extern: "nosp$1", tags: [ExecIOEffect, ReadEnvEffect].}
## Starts a process. `Command` is the executable file, `workingDir` is the
## process's working directory. If ``workingDir == ""`` the current directory
## is used. `args` are the command line arguments that are passed to the
@@ -150,7 +153,7 @@ proc startProcess*(command: string,
proc startCmd*(command: string, options: set[TProcessOption] = {
poStdErrToStdOut, poUsePath}): PProcess {.
- tags: [ExecIOEffect, FReadEnv], deprecated.} =
+ tags: [ExecIOEffect, ReadEnvEffect], deprecated.} =
## Deprecated - use `startProcess` directly.
result = startProcess(command=command, options=options + {poEvalCommand})
@@ -233,7 +236,7 @@ proc countProcessors*(): int {.rtl, extern: "nosp$1".} =
proc execProcesses*(cmds: openArray[string],
options = {poStdErrToStdOut, poParentStreams},
n = countProcessors()): int {.rtl, extern: "nosp$1",
- tags: [ExecIOEffect, TimeEffect, FReadEnv]} =
+ tags: [ExecIOEffect, TimeEffect, ReadEnvEffect]} =
## executes the commands `cmds` in parallel. Creates `n` processes
## that execute in parallel. The highest return value of all processes
## is returned.
@@ -584,12 +587,12 @@ elif not defined(useNimRtl):
when not defined(useFork):
proc startProcessAuxSpawn(data: TStartProcessData): TPid {.
- tags: [ExecIOEffect, FReadEnv], gcsafe.}
+ tags: [ExecIOEffect, ReadEnvEffect], gcsafe.}
proc startProcessAuxFork(data: TStartProcessData): TPid {.
- tags: [ExecIOEffect, FReadEnv], gcsafe.}
+ tags: [ExecIOEffect, ReadEnvEffect], gcsafe.}
{.push stacktrace: off, profiler: off.}
proc startProcessAfterFork(data: ptr TStartProcessData) {.
- tags: [ExecIOEffect, FReadEnv], cdecl, gcsafe.}
+ tags: [ExecIOEffect, ReadEnvEffect], cdecl, gcsafe.}
{.pop.}
proc startProcess(command: string,
diff --git a/lib/pure/parsecfg.nim b/lib/pure/parsecfg.nim
index 1d61a967b..c340bf98b 100644
--- a/lib/pure/parsecfg.nim
+++ b/lib/pure/parsecfg.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -20,24 +20,24 @@
## The file ``examples/parsecfgex.nim`` demonstrates how to use the
## configuration file parser:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## :file: examples/parsecfgex.nim
-import
+import
hashes, strutils, lexbase, streams
include "system/inclrtl"
-type
- TCfgEventKind* = enum ## enumeration of all events that may occur when parsing
+type
+ CfgEventKind* = enum ## enumeration of all events that may occur when parsing
cfgEof, ## end of file reached
cfgSectionStart, ## a ``[section]`` has been parsed
cfgKeyValuePair, ## a ``key=value`` pair has been detected
cfgOption, ## a ``--key=value`` command line option
cfgError ## an error ocurred during parsing
- TCfgEvent* = object of TObject ## describes a parsing event
+ CfgEvent* = object of RootObj ## describes a parsing event
case kind*: TCfgEventKind ## the kind of the event
of cfgEof: nil
of cfgSectionStart:
@@ -53,28 +53,30 @@ type
msg*: string ## contains the error message. No exceptions
## are thrown if a parse error occurs.
- TTokKind = enum
+ TokKind = enum
tkInvalid, tkEof,
tkSymbol, tkEquals, tkColon, tkBracketLe, tkBracketRi, tkDashDash
- TToken {.final.} = object # a token
- kind: TTokKind # the type of the token
+ Token = object # a token
+ kind: TokKind # the type of the token
literal: string # the parsed (string) literal
- TCfgParser* = object of TBaseLexer ## the parser object.
- tok: TToken
+ CfgParser* = object of BaseLexer ## the parser object.
+ tok: Token
filename: string
+{.deprecated: [TCfgEventKind: CfgEventKind, TCfgEvent: CfgEvent,
+ TTokKind: TokKind, TToken: Token, TCfgParser: CfgParser].}
+
# implementation
const
- SymChars: TCharSet = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.',
- '/', '\\'}
+ SymChars: CharSet = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.',
+ '/', '\\'}
-proc rawGetTok(c: var TCfgParser, tok: var TToken) {.gcsafe.}
+proc rawGetTok(c: var CfgParser, tok: var Token) {.gcsafe.}
-proc open*(c: var TCfgParser, input: PStream, filename: string,
- lineOffset = 0) {.
- rtl, extern: "npc$1".} =
+proc open*(c: var CfgParser, input: PStream, filename: string,
+ lineOffset = 0) {.rtl, extern: "npc$1".} =
## initializes the parser with an input stream. `Filename` is only used
## for nice error messages. `lineOffset` can be used to influence the line
## number information in the generated error messages.
@@ -85,23 +87,23 @@ proc open*(c: var TCfgParser, input: PStream, filename: string,
inc(c.lineNumber, lineOffset)
rawGetTok(c, c.tok)
-proc close*(c: var TCfgParser) {.rtl, extern: "npc$1".} =
+proc close*(c: var CfgParser) {.rtl, extern: "npc$1".} =
## closes the parser `c` and its associated input stream.
lexbase.close(c)
-proc getColumn*(c: TCfgParser): int {.rtl, extern: "npc$1".} =
+proc getColumn*(c: CfgParser): int {.rtl, extern: "npc$1".} =
## get the current column the parser has arrived at.
result = getColNumber(c, c.bufpos)
-proc getLine*(c: TCfgParser): int {.rtl, extern: "npc$1".} =
+proc getLine*(c: CfgParser): int {.rtl, extern: "npc$1".} =
## get the current line the parser has arrived at.
result = c.lineNumber
-proc getFilename*(c: TCfgParser): string {.rtl, extern: "npc$1".} =
+proc getFilename*(c: CfgParser): string {.rtl, extern: "npc$1".} =
## get the filename of the file that the parser processes.
result = c.filename
-proc handleHexChar(c: var TCfgParser, xi: var int) =
+proc handleHexChar(c: var CfgParser, xi: var int) =
case c.buf[c.bufpos]
of '0'..'9':
xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0'))
@@ -115,12 +117,12 @@ proc handleHexChar(c: var TCfgParser, xi: var int) =
else:
discard
-proc handleDecChars(c: var TCfgParser, xi: var int) =
+proc handleDecChars(c: var CfgParser, xi: var int) =
while c.buf[c.bufpos] in {'0'..'9'}:
xi = (xi * 10) + (ord(c.buf[c.bufpos]) - ord('0'))
inc(c.bufpos)
-proc getEscapedChar(c: var TCfgParser, tok: var TToken) =
+proc getEscapedChar(c: var CfgParser, tok: var TToken) =
inc(c.bufpos) # skip '\'
case c.buf[c.bufpos]
of 'n', 'N':
@@ -169,13 +171,13 @@ proc getEscapedChar(c: var TCfgParser, tok: var TToken) =
else: tok.kind = tkInvalid
else: tok.kind = tkInvalid
-proc handleCRLF(c: var TCfgParser, pos: int): int =
+proc handleCRLF(c: var CfgParser, pos: int): int =
case c.buf[pos]
of '\c': result = lexbase.handleCR(c, pos)
of '\L': result = lexbase.handleLF(c, pos)
else: result = pos
-proc getString(c: var TCfgParser, tok: var TToken, rawMode: bool) =
+proc getString(c: var CfgParser, tok: var Token, rawMode: bool) =
var pos = c.bufpos + 1 # skip "
var buf = c.buf # put `buf` in a register
tok.kind = tkSymbol
@@ -221,7 +223,7 @@ proc getString(c: var TCfgParser, tok: var TToken, rawMode: bool) =
inc(pos)
c.bufpos = pos
-proc getSymbol(c: var TCfgParser, tok: var TToken) =
+proc getSymbol(c: var CfgParser, tok: var Token) =
var pos = c.bufpos
var buf = c.buf
while true:
@@ -231,7 +233,7 @@ proc getSymbol(c: var TCfgParser, tok: var TToken) =
c.bufpos = pos
tok.kind = tkSymbol
-proc skip(c: var TCfgParser) =
+proc skip(c: var CfgParser) =
var pos = c.bufpos
var buf = c.buf
while true:
@@ -247,7 +249,7 @@ proc skip(c: var TCfgParser) =
break # EndOfFile also leaves the loop
c.bufpos = pos
-proc rawGetTok(c: var TCfgParser, tok: var TToken) =
+proc rawGetTok(c: var CfgParser, tok: var Token) =
tok.kind = tkInvalid
setLen(tok.literal, 0)
skip(c)
@@ -286,19 +288,19 @@ proc rawGetTok(c: var TCfgParser, tok: var TToken) =
tok.literal = "[EOF]"
else: getSymbol(c, tok)
-proc errorStr*(c: TCfgParser, msg: string): string {.rtl, extern: "npc$1".} =
+proc errorStr*(c: CfgParser, msg: string): string {.rtl, extern: "npc$1".} =
## returns a properly formated error message containing current line and
## column information.
result = `%`("$1($2, $3) Error: $4",
[c.filename, $getLine(c), $getColumn(c), msg])
-proc warningStr*(c: TCfgParser, msg: string): string {.rtl, extern: "npc$1".} =
+proc warningStr*(c: CfgParser, msg: string): string {.rtl, extern: "npc$1".} =
## returns a properly formated warning message containing current line and
## column information.
result = `%`("$1($2, $3) Warning: $4",
[c.filename, $getLine(c), $getColumn(c), msg])
-proc ignoreMsg*(c: TCfgParser, e: TCfgEvent): string {.rtl, extern: "npc$1".} =
+proc ignoreMsg*(c: CfgParser, e: CfgEvent): string {.rtl, extern: "npc$1".} =
## returns a properly formated warning message containing that
## an entry is ignored.
case e.kind
@@ -309,7 +311,7 @@ proc ignoreMsg*(c: TCfgParser, e: TCfgEvent): string {.rtl, extern: "npc$1".} =
of cfgError: result = e.msg
of cfgEof: result = ""
-proc getKeyValPair(c: var TCfgParser, kind: TCfgEventKind): TCfgEvent =
+proc getKeyValPair(c: var CfgParser, kind: CfgEventKind): CfgEvent =
if c.tok.kind == tkSymbol:
result.kind = kind
result.key = c.tok.literal
@@ -329,7 +331,7 @@ proc getKeyValPair(c: var TCfgParser, kind: TCfgEventKind): TCfgEvent =
result.msg = errorStr(c, "symbol expected, but found: " & c.tok.literal)
rawGetTok(c, c.tok)
-proc next*(c: var TCfgParser): TCfgEvent {.rtl, extern: "npc$1".} =
+proc next*(c: var CfgParser): CfgEvent {.rtl, extern: "npc$1".} =
## retrieves the first/next event. This controls the parser.
case c.tok.kind
of tkEof:
diff --git a/lib/pure/parsecsv.nim b/lib/pure/parsecsv.nim
index 4b25babec..d267906a3 100644
--- a/lib/pure/parsecsv.nim
+++ b/lib/pure/parsecsv.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2009 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -13,16 +13,16 @@
## Example: How to use the parser
## ==============================
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## import os, parsecsv, streams
-## var s = newFileStream(ParamStr(1), fmRead)
-## if s == nil: quit("cannot open the file" & ParamStr(1))
-## var x: TCsvParser
-## open(x, s, ParamStr(1))
+## var s = newFileStream(paramStr(1), fmRead)
+## if s == nil: quit("cannot open the file" & paramStr(1))
+## var x: CsvParser
+## open(x, s, paramStr(1))
## while readRow(x):
-## Echo "new row: "
+## echo "new row: "
## for val in items(x.row):
-## Echo "##", val, "##"
+## echo "##", val, "##"
## close(x)
##
@@ -30,28 +30,30 @@ import
lexbase, streams
type
- TCsvRow* = seq[string] ## a row in a CSV file
- TCsvParser* = object of TBaseLexer ## the parser object.
- row*: TCsvRow ## the current row
+ CsvRow* = seq[string] ## a row in a CSV file
+ CsvParser* = object of BaseLexer ## the parser object.
+ row*: CsvRow ## the current row
filename: string
sep, quote, esc: char
skipWhite: bool
currRow: int
- EInvalidCsv* = object of EIO ## exception that is raised if
- ## a parsing error occurs
+ CsvError* = object of IOError ## exception that is raised if
+ ## a parsing error occurs
+
+{.deprecated: [TCsvRow: CsvRow, TCsvParser: CsvParser, EInvalidCsv: CsvError].}
proc raiseEInvalidCsv(filename: string, line, col: int,
msg: string) {.noreturn.} =
- var e: ref EInvalidCsv
+ var e: ref CsvError
new(e)
e.msg = filename & "(" & $line & ", " & $col & ") Error: " & msg
raise e
-proc error(my: TCsvParser, pos: int, msg: string) =
+proc error(my: CsvParser, pos: int, msg: string) =
raiseEInvalidCsv(my.filename, my.LineNumber, getColNumber(my, pos), msg)
-proc open*(my: var TCsvParser, input: PStream, filename: string,
+proc open*(my: var CsvParser, input: Stream, filename: string,
separator = ',', quote = '"', escape = '\0',
skipInitialSpace = false) =
## initializes the parser with an input stream. `Filename` is only used
@@ -75,7 +77,7 @@ proc open*(my: var TCsvParser, input: PStream, filename: string,
my.row = @[]
my.currRow = 0
-proc parseField(my: var TCsvParser, a: var string) =
+proc parseField(my: var CsvParser, a: var string) =
var pos = my.bufpos
var buf = my.buf
if my.skipWhite:
@@ -83,7 +85,7 @@ proc parseField(my: var TCsvParser, a: var string) =
setLen(a, 0) # reuse memory
if buf[pos] == my.quote and my.quote != '\0':
inc(pos)
- while true:
+ while true:
var c = buf[pos]
if c == '\0':
my.bufpos = pos # can continue after exception?
@@ -121,11 +123,11 @@ proc parseField(my: var TCsvParser, a: var string) =
inc(pos)
my.bufpos = pos
-proc processedRows*(my: var TCsvParser): int =
+proc processedRows*(my: var CsvParser): int =
## returns number of the processed rows
return my.currRow
-proc readRow*(my: var TCsvParser, columns = 0): bool =
+proc readRow*(my: var CsvParser, columns = 0): bool =
## reads the next row; if `columns` > 0, it expects the row to have
## exactly this many columns. Returns false if the end of the file
## has been encountered else true.
@@ -160,19 +162,19 @@ proc readRow*(my: var TCsvParser, columns = 0): bool =
$col & " columns")
inc(my.currRow)
-proc close*(my: var TCsvParser) {.inline.} =
+proc close*(my: var CsvParser) {.inline.} =
## closes the parser `my` and its associated input stream.
lexbase.close(my)
when isMainModule:
import os
- var s = newFileStream(ParamStr(1), fmRead)
- if s == nil: quit("cannot open the file" & ParamStr(1))
- var x: TCsvParser
- open(x, s, ParamStr(1))
+ var s = newFileStream(paramStr(1), fmRead)
+ if s == nil: quit("cannot open the file" & paramStr(1))
+ var x: CsvParser
+ open(x, s, paramStr(1))
while readRow(x):
- Echo "new row: "
+ echo "new row: "
for val in items(x.row):
- Echo "##", val, "##"
+ echo "##", val, "##"
close(x)
diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim
index d7379a9a9..b325bd1f5 100644
--- a/lib/pure/parseopt.nim
+++ b/lib/pure/parseopt.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
-# (c) Copyright 2012 Andreas Rumpf
+# Nim's Runtime Library
+# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## This module provides the standard Nimrod command line parser.
+## This module provides the standard Nim command line parser.
## It supports one convenience iterator over all command line options and some
## lower-level features.
##
@@ -22,26 +22,28 @@ import
os, strutils
type
- TCmdLineKind* = enum ## the detected command line token
+ CmdLineKind* = enum ## the detected command line token
cmdEnd, ## end of command line reached
cmdArgument, ## argument detected
cmdLongoption, ## a long option ``--option`` detected
cmdShortOption ## a short option ``-c`` detected
- TOptParser* =
+ OptParser* =
object of RootObj ## this object implements the command line parser
cmd: string
pos: int
inShortState: bool
- kind*: TCmdLineKind ## the dected command line token
+ kind*: CmdLineKind ## the dected command line token
key*, val*: TaintedString ## key and value pair; ``key`` is the option
## or the argument, ``value`` is not "" if
## the option was given a value
+{.deprecated: [TCmdLineKind: CmdLineKind, TOptParser: OptParser].}
+
when declared(os.paramCount):
# we cannot provide this for NimRtl creation on Posix, because we can't
# access the command line arguments then!
- proc initOptParser*(cmdline = ""): TOptParser =
+ proc initOptParser*(cmdline = ""): OptParser =
## inits the option parser. If ``cmdline == ""``, the real command line
## (as provided by the ``OS`` module) is taken.
result.pos = 0
@@ -57,7 +59,7 @@ when declared(os.paramCount):
result.val = TaintedString""
proc parseWord(s: string, i: int, w: var string,
- delim: TCharSet = {'\x09', ' ', '\0'}): int =
+ delim: CharSet = {'\x09', ' ', '\0'}): int =
result = i
if s[result] == '\"':
inc(result)
@@ -70,7 +72,7 @@ proc parseWord(s: string, i: int, w: var string,
add(w, s[result])
inc(result)
-proc handleShortOption(p: var TOptParser) =
+proc handleShortOption(p: var OptParser) =
var i = p.pos
p.kind = cmdShortOption
add(p.key.string, p.cmd[i])
@@ -87,8 +89,7 @@ proc handleShortOption(p: var TOptParser) =
if p.cmd[i] == '\0': p.inShortState = false
p.pos = i
-proc next*(p: var TOptParser) {.
- rtl, extern: "npo$1".} =
+proc next*(p: var OptParser) {.rtl, extern: "npo$1".} =
## parses the first or next option; ``p.kind`` describes what token has been
## parsed. ``p.key`` and ``p.val`` are set accordingly.
var i = p.pos
@@ -122,14 +123,12 @@ proc next*(p: var TOptParser) {.
p.kind = cmdArgument
p.pos = parseWord(p.cmd, i, p.key.string)
-proc cmdLineRest*(p: TOptParser): TaintedString {.
- rtl, extern: "npo$1".} =
+proc cmdLineRest*(p: OptParser): TaintedString {.rtl, extern: "npo$1".} =
## retrieves the rest of the command line that has not been parsed yet.
result = strip(substr(p.cmd, p.pos, len(p.cmd) - 1)).TaintedString
when declared(initOptParser):
-
- iterator getopt*(): tuple[kind: TCmdLineKind, key, val: TaintedString] =
+ iterator getopt*(): tuple[kind: CmdLineKind, key, val: TaintedString] =
## This is an convenience iterator for iterating over the command line.
## This uses the TOptParser object. Example:
##
diff --git a/lib/pure/parseopt2.nim b/lib/pure/parseopt2.nim
index 7638171d1..c283a5edf 100644
--- a/lib/pure/parseopt2.nim
+++ b/lib/pure/parseopt2.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
-# (c) Copyright 2012 Andreas Rumpf
+# Nim's Runtime Library
+# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## This module provides the standard Nimrod command line parser.
+## This module provides the standard Nim command line parser.
## It supports one convenience iterator over all command line options and some
## lower-level features.
##
@@ -25,22 +25,24 @@ import
os, strutils
type
- TCmdLineKind* = enum ## the detected command line token
+ CmdLineKind* = enum ## the detected command line token
cmdEnd, ## end of command line reached
cmdArgument, ## argument detected
cmdLongOption, ## a long option ``--option`` detected
cmdShortOption ## a short option ``-c`` detected
- TOptParser* =
+ OptParser* =
object of TObject ## this object implements the command line parser
cmd: seq[string]
pos: int
remainingShortOptions: string
- kind*: TCmdLineKind ## the dected command line token
+ kind*: CmdLineKind ## the dected command line token
key*, val*: TaintedString ## key and value pair; ``key`` is the option
## or the argument, ``value`` is not "" if
## the option was given a value
-proc initOptParser*(cmdline: seq[string]): TOptParser {.rtl.} =
+{.deprecated: [TCmdLineKind: CmdLineKind, TOptParser: OptParser].}
+
+proc initOptParser*(cmdline: seq[string]): OptParser {.rtl.} =
## Initalizes option parses with cmdline. cmdline should not contain
## argument 0 - program name.
## If cmdline == nil default to current command line arguments.
@@ -54,7 +56,7 @@ proc initOptParser*(cmdline: seq[string]): TOptParser {.rtl.} =
result.cmd = @cmdline
-proc initOptParser*(cmdline: string): TOptParser {.rtl, deprecated.} =
+proc initOptParser*(cmdline: string): OptParser {.rtl, deprecated.} =
## Initalizes option parses with cmdline. Splits cmdline in on spaces
## and calls initOptParser(openarray[string])
## Do not use.
@@ -64,13 +66,13 @@ proc initOptParser*(cmdline: string): TOptParser {.rtl, deprecated.} =
return initOptParser(cmdline.split)
when not defined(createNimRtl):
- proc initOptParser*(): TOptParser =
+ proc initOptParser*(): OptParser =
## Initializes option parser from current command line arguments.
return initOptParser(commandLineParams())
-proc next*(p: var TOptParser) {.rtl, extern: "npo$1".}
+proc next*(p: var OptParser) {.rtl, extern: "npo$1".}
-proc nextOption(p: var TOptParser, token: string, allowEmpty: bool) =
+proc nextOption(p: var OptParser, token: string, allowEmpty: bool) =
for splitchar in [':', '=']:
if splitchar in token:
let pos = token.find(splitchar)
@@ -85,7 +87,7 @@ proc nextOption(p: var TOptParser, token: string, allowEmpty: bool) =
p.remainingShortOptions = token[0..token.len-1]
p.next()
-proc next(p: var TOptParser) =
+proc next(p: var OptParser) =
if p.remainingShortOptions.len != 0:
p.kind = cmdShortOption
p.key = TaintedString(p.remainingShortOptions[0..0])
@@ -111,20 +113,22 @@ proc next(p: var TOptParser) =
p.key = token
p.val = ""
-proc cmdLineRest*(p: TOptParser): TaintedString {.rtl, extern: "npo$1", deprecated.} =
+proc cmdLineRest*(p: OptParser): TaintedString {.rtl, extern: "npo$1", deprecated.} =
## Returns part of command line string that has not been parsed yet.
## Do not use - does not correctly handle whitespace.
return p.cmd[p.pos..p.cmd.len-1].join(" ")
type
- TGetoptResult* = tuple[kind: TCmdLineKind, key, val: TaintedString]
+ GetoptResult* = tuple[kind: CmdLineKind, key, val: TaintedString]
+
+{.deprecated: [TGetoptResult: GetoptResult].}
when declared(paramCount):
- iterator getopt*(): TGetoptResult =
+ iterator getopt*(): GetoptResult =
## This is an convenience iterator for iterating over the command line.
- ## This uses the TOptParser object. Example:
+ ## This uses the OptParser object. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var
## filename = ""
## for kind, key, val in getopt():
diff --git a/lib/pure/parsesql.nim b/lib/pure/parsesql.nim
index bd8836f7c..fcca0aa44 100644
--- a/lib/pure/parsesql.nim
+++ b/lib/pure/parsesql.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2009 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -10,13 +10,13 @@
## The ``parsesql`` module implements a high performance SQL file
## parser. It parses PostgreSQL syntax and the SQL ANSI standard.
-import
+import
hashes, strutils, lexbase, streams
# ------------------- scanner -------------------------------------------------
type
- TTokKind = enum ## enumeration of all SQL tokens
+ TokKind = enum ## enumeration of all SQL tokens
tkInvalid, ## invalid token
tkEof, ## end of file reached
tkIdentifier, ## abc
@@ -38,33 +38,35 @@ type
tkBracketRi, ## ']'
tkDot ## '.'
- TToken {.final.} = object # a token
- kind: TTokKind # the type of the token
+ Token = object # a token
+ kind: TokKind # the type of the token
literal: string # the parsed (string) literal
- TSqlLexer* = object of TBaseLexer ## the parser object.
+ SqlLexer* = object of BaseLexer ## the parser object.
filename: string
+{.deprecated: [TToken: Token, TSqlLexer: SqlLexer].}
+
const
- tokKindToStr: array[TTokKind, string] = [
+ tokKindToStr: array[TokKind, string] = [
"invalid", "[EOF]", "identifier", "quoted identifier", "string constant",
"escape string constant", "dollar quoted constant", "bit string constant",
"hex string constant", "integer constant", "numeric constant", "operator",
";", ":", ",", "(", ")", "[", "]", "."
]
-proc open(L: var TSqlLexer, input: PStream, filename: string) =
+proc open(L: var SqlLexer, input: Stream, filename: string) =
lexbase.open(L, input)
L.filename = filename
-proc close(L: var TSqlLexer) =
+proc close(L: var SqlLexer) =
lexbase.close(L)
-proc getColumn(L: TSqlLexer): int =
+proc getColumn(L: SqlLexer): int =
## get the current column the parser has arrived at.
result = getColNumber(L, L.bufPos)
-proc getLine(L: TSqlLexer): int =
+proc getLine(L: SqlLexer): int =
result = L.linenumber
proc handleHexChar(c: var TSqlLexer, xi: var int) =
@@ -137,10 +139,10 @@ proc getEscapedChar(c: var TSqlLexer, tok: var TToken) =
else: tok.kind = tkInvalid
else: tok.kind = tkInvalid
-proc HandleCRLF(c: var TSqlLexer, pos: int): int =
+proc handleCRLF(c: var TSqlLexer, pos: int): int =
case c.buf[pos]
- of '\c': result = lexbase.HandleCR(c, pos)
- of '\L': result = lexbase.HandleLF(c, pos)
+ of '\c': result = lexbase.handleCR(c, pos)
+ of '\L': result = lexbase.handleLF(c, pos)
else: result = pos
proc skip(c: var TSqlLexer) =
@@ -163,7 +165,7 @@ proc skip(c: var TSqlLexer) =
case buf[pos]
of '\0': break
of '\c', '\L':
- pos = HandleCRLF(c, pos)
+ pos = handleCRLF(c, pos)
buf = c.buf
of '*':
if buf[pos+1] == '/':
@@ -181,13 +183,13 @@ proc skip(c: var TSqlLexer) =
else: inc(pos)
else: break
of '\c', '\L':
- pos = HandleCRLF(c, pos)
+ pos = handleCRLF(c, pos)
buf = c.buf
else:
break # EndOfFile also leaves the loop
c.bufpos = pos
-proc getString(c: var TSqlLexer, tok: var TToken, kind: TTokKind) =
+proc getString(c: var TSqlLexer, tok: var TToken, kind: TokKind) =
var pos = c.bufPos + 1
var buf = c.buf
tok.kind = kind
@@ -465,7 +467,7 @@ proc errorStr(L: TSqlLexer, msg: string): string =
# :: left PostgreSQL-style typecast
# [ ] left array element selection
# - right unary minus
-# ^ left exponentiation
+# ^ left exponentiation
# * / % left multiplication, division, modulo
# + - left addition, subtraction
# IS IS TRUE, IS FALSE, IS UNKNOWN, IS NULL
@@ -483,7 +485,7 @@ proc errorStr(L: TSqlLexer, msg: string): string =
# OR left logical disjunction
type
- TSqlNodeKind* = enum ## kind of SQL abstract syntax tree
+ SqlNodeKind* = enum ## kind of SQL abstract syntax tree
nkNone,
nkIdent,
nkStringLit,
@@ -536,79 +538,82 @@ type
nkEnumDef
type
- EInvalidSql* = object of EInvalidValue ## Invalid SQL encountered
- PSqlNode* = ref TSqlNode ## an SQL abstract syntax tree node
- TSqlNode* = object ## an SQL abstract syntax tree node
- case kind*: TSqlNodeKind ## kind of syntax tree
+ SqlParseError* = object of ValueError ## Invalid SQL encountered
+ SqlNode* = ref SqlNodeObj ## an SQL abstract syntax tree node
+ SqlNodeObj* = object ## an SQL abstract syntax tree node
+ case kind*: SqlNodeKind ## kind of syntax tree
of nkIdent, nkStringLit, nkBitStringLit, nkHexStringLit,
nkIntegerLit, nkNumericLit:
strVal*: string ## AST leaf: the identifier, numeric literal
## string literal, etc.
else:
- sons*: seq[PSqlNode] ## the node's children
+ sons*: seq[SqlNode] ## the node's children
- TSqlParser* = object of TSqlLexer ## SQL parser object
- tok: TToken
+ SqlParser* = object of SqlLexer ## SQL parser object
+ tok: Token
-proc newNode(k: TSqlNodeKind): PSqlNode =
+{.deprecated: [EInvalidSql: SqlParseError, PSqlNode: SqlNode,
+ TSqlNode: SqlNodeObj, TSqlParser: SqlParser, TSqlNodeKind: SqlNodeKind].}
+
+proc newNode(k: SqlNodeKind): SqlNode =
new(result)
result.kind = k
-proc newNode(k: TSqlNodeKind, s: string): PSqlNode =
+proc newNode(k: SqlNodeKind, s: string): SqlNode =
new(result)
result.kind = k
result.strVal = s
-proc len*(n: PSqlNode): int =
+proc len*(n: SqlNode): int =
if isNil(n.sons): result = 0
else: result = n.sons.len
-proc add*(father, n: PSqlNode) =
+proc add*(father, n: SqlNode) =
if isNil(father.sons): father.sons = @[]
add(father.sons, n)
-proc getTok(p: var TSqlParser) =
+proc getTok(p: var SqlParser) =
getTok(p, p.tok)
-proc sqlError(p: TSqlParser, msg: string) =
- var e: ref EInvalidSql
+proc sqlError(p: SqlParser, msg: string) =
+ var e: ref SqlParseError
new(e)
e.msg = errorStr(p, msg)
raise e
-proc isKeyw(p: TSqlParser, keyw: string): bool =
+proc isKeyw(p: SqlParser, keyw: string): bool =
result = p.tok.kind == tkIdentifier and
cmpIgnoreCase(p.tok.literal, keyw) == 0
-proc isOpr(p: TSqlParser, opr: string): bool =
+proc isOpr(p: SqlParser, opr: string): bool =
result = p.tok.kind == tkOperator and
cmpIgnoreCase(p.tok.literal, opr) == 0
-proc optKeyw(p: var TSqlParser, keyw: string) =
+proc optKeyw(p: var SqlParser, keyw: string) =
if p.tok.kind == tkIdentifier and cmpIgnoreCase(p.tok.literal, keyw) == 0:
getTok(p)
-proc expectIdent(p: TSqlParser) =
+proc expectIdent(p: SqlParser) =
if p.tok.kind != tkIdentifier and p.tok.kind != tkQuotedIdentifier:
sqlError(p, "identifier expected")
-proc expect(p: TSqlParser, kind: TTokKind) =
+proc expect(p: SqlParser, kind: TokKind) =
if p.tok.kind != kind:
sqlError(p, tokKindToStr[kind] & " expected")
-proc eat(p: var TSqlParser, kind: TTokKind) =
+proc eat(p: var SqlParser, kind: TokKind) =
if p.tok.kind == kind:
getTok(p)
else:
sqlError(p, tokKindToStr[kind] & " expected")
-proc eat(p: var TSqlParser, keyw: string) =
+proc eat(p: var SqlParser, keyw: string) =
if isKeyw(p, keyw):
getTok(p)
else:
sqlError(p, keyw.toUpper() & " expected")
-proc parseDataType(p: var TSqlParser): PSqlNode =
+proc parseDataType(p: var SqlParser): SqlNode =
if isKeyw(p, "enum"):
result = newNode(nkEnumDef)
getTok(p)
@@ -636,7 +641,7 @@ proc parseDataType(p: var TSqlParser): PSqlNode =
getTok(p)
eat(p, tkParRi)
-proc getPrecedence(p: TSqlParser): int =
+proc getPrecedence(p: SqlParser): int =
if isOpr(p, "*") or isOpr(p, "/") or isOpr(p, "%"):
result = 6
elif isOpr(p, "+") or isOpr(p, "-"):
@@ -655,9 +660,9 @@ proc getPrecedence(p: TSqlParser): int =
else:
result = - 1
-proc parseExpr(p: var TSqlParser): PSqlNode
+proc parseExpr(p: var SqlParser): SqlNode
-proc identOrLiteral(p: var TSqlParser): PSqlNode =
+proc identOrLiteral(p: var SqlParser): SqlNode =
case p.tok.kind
of tkIdentifier, tkQuotedIdentifier:
result = newNode(nkIdent, p.tok.literal)
@@ -685,7 +690,7 @@ proc identOrLiteral(p: var TSqlParser): PSqlNode =
sqlError(p, "expression expected")
getTok(p) # we must consume a token here to prevend endless loops!
-proc primary(p: var TSqlParser): PSqlNode =
+proc primary(p: var SqlParser): SqlNode =
if p.tok.kind == tkOperator or isKeyw(p, "not"):
result = newNode(nkPrefix)
result.add(newNode(nkIdent, p.tok.literal))
@@ -723,9 +728,9 @@ proc primary(p: var TSqlParser): PSqlNode =
getTok(p)
else: break
-proc lowestExprAux(p: var TSqlParser, v: var PSqlNode, limit: int): int =
+proc lowestExprAux(p: var SqlParser, v: var SqlNode, limit: int): int =
var
- v2, node, opNode: PSqlNode
+ v2, node, opNode: SqlNode
v = primary(p) # expand while operators have priorities higher than 'limit'
var opPred = getPrecedence(p)
result = opPred
@@ -740,14 +745,14 @@ proc lowestExprAux(p: var TSqlParser, v: var PSqlNode, limit: int): int =
v = node
opPred = getPrecedence(p)
-proc parseExpr(p: var TSqlParser): PSqlNode =
+proc parseExpr(p: var SqlParser): SqlNode =
discard lowestExprAux(p, result, - 1)
-proc parseTableName(p: var TSqlParser): PSqlNode =
+proc parseTableName(p: var SqlParser): SqlNode =
expectIdent(p)
result = primary(p)
-proc parseColumnReference(p: var TSqlParser): PSqlNode =
+proc parseColumnReference(p: var SqlParser): SqlNode =
result = parseTableName(p)
if p.tok.kind == tkParLe:
getTok(p)
@@ -760,12 +765,12 @@ proc parseColumnReference(p: var TSqlParser): PSqlNode =
result.add(parseTableName(p))
eat(p, tkParRi)
-proc parseCheck(p: var TSqlParser): PSqlNode =
+proc parseCheck(p: var SqlParser): SqlNode =
getTok(p)
result = newNode(nkCheck)
result.add(parseExpr(p))
-proc parseConstraint(p: var TSqlParser): PSqlNode =
+proc parseConstraint(p: var SqlParser): SqlNode =
getTok(p)
result = newNode(nkConstraint)
expectIdent(p)
@@ -774,7 +779,7 @@ proc parseConstraint(p: var TSqlParser): PSqlNode =
eat(p, "check")
result.add(parseExpr(p))
-proc parseColumnConstraints(p: var TSqlParser, result: PSqlNode) =
+proc parseColumnConstraints(p: var SqlParser, result: SqlNode) =
while true:
if isKeyw(p, "default"):
getTok(p)
@@ -806,7 +811,7 @@ proc parseColumnConstraints(p: var TSqlParser, result: PSqlNode) =
else:
break
-proc parseColumnDef(p: var TSqlParser): PSqlNode =
+proc parseColumnDef(p: var SqlParser): SqlNode =
expectIdent(p)
result = newNode(nkColumnDef)
result.add(newNode(nkIdent, p.tok.literal))
@@ -814,7 +819,7 @@ proc parseColumnDef(p: var TSqlParser): PSqlNode =
result.add(parseDataType(p))
parseColumnConstraints(p, result)
-proc parseIfNotExists(p: var TSqlParser, k: TSqlNodeKind): PSqlNode =
+proc parseIfNotExists(p: var SqlParser, k: TSqlNodeKind): SqlNode =
getTok(p)
if isKeyw(p, "if"):
getTok(p)
@@ -824,7 +829,7 @@ proc parseIfNotExists(p: var TSqlParser, k: TSqlNodeKind): PSqlNode =
else:
result = newNode(k)
-proc parseParIdentList(p: var TSqlParser, father: PSqlNode) =
+proc parseParIdentList(p: var SqlParser, father: SqlNode) =
eat(p, tkParLe)
while true:
expectIdent(p)
@@ -834,7 +839,7 @@ proc parseParIdentList(p: var TSqlParser, father: PSqlNode) =
getTok(p)
eat(p, tkParRi)
-proc parseTableConstraint(p: var TSqlParser): PSqlNode =
+proc parseTableConstraint(p: var SqlParser): SqlNode =
if isKeyw(p, "primary"):
getTok(p)
eat(p, "key")
@@ -861,7 +866,7 @@ proc parseTableConstraint(p: var TSqlParser): PSqlNode =
else:
sqlError(p, "column definition expected")
-proc parseTableDef(p: var TSqlParser): PSqlNode =
+proc parseTableDef(p: var SqlParser): SqlNode =
result = parseIfNotExists(p, nkCreateTable)
expectIdent(p)
result.add(newNode(nkIdent, p.tok.literal))
@@ -876,7 +881,7 @@ proc parseTableDef(p: var TSqlParser): PSqlNode =
if p.tok.kind != tkComma: break
eat(p, tkParRi)
-proc parseTypeDef(p: var TSqlParser): PSqlNode =
+proc parseTypeDef(p: var SqlParser): SqlNode =
result = parseIfNotExists(p, nkCreateType)
expectIdent(p)
result.add(newNode(nkIdent, p.tok.literal))
@@ -884,12 +889,12 @@ proc parseTypeDef(p: var TSqlParser): PSqlNode =
eat(p, "as")
result.add(parseDataType(p))
-proc parseWhere(p: var TSqlParser): PSqlNode =
+proc parseWhere(p: var SqlParser): SqlNode =
getTok(p)
result = newNode(nkWhere)
result.add(parseExpr(p))
-proc parseIndexDef(p: var TSqlParser): PSqlNode =
+proc parseIndexDef(p: var SqlParser): SqlNode =
result = parseIfNotExists(p, nkCreateIndex)
if isKeyw(p, "primary"):
getTok(p)
@@ -914,7 +919,7 @@ proc parseIndexDef(p: var TSqlParser): PSqlNode =
getTok(p)
eat(p, tkParRi)
-proc parseInsert(p: var TSqlParser): PSqlNode =
+proc parseInsert(p: var SqlParser): SqlNode =
getTok(p)
eat(p, "into")
expectIdent(p)
@@ -941,7 +946,7 @@ proc parseInsert(p: var TSqlParser): PSqlNode =
result.add(n)
eat(p, tkParRi)
-proc parseUpdate(p: var TSqlParser): PSqlNode =
+proc parseUpdate(p: var SqlParser): SqlNode =
getTok(p)
result = newNode(nkUpdate)
result.add(primary(p))
@@ -962,7 +967,7 @@ proc parseUpdate(p: var TSqlParser): PSqlNode =
else:
result.add(nil)
-proc parseDelete(p: var TSqlParser): PSqlNode =
+proc parseDelete(p: var SqlParser): SqlNode =
getTok(p)
result = newNode(nkDelete)
eat(p, "from")
@@ -972,7 +977,7 @@ proc parseDelete(p: var TSqlParser): PSqlNode =
else:
result.add(nil)
-proc parseSelect(p: var TSqlParser): PSqlNode =
+proc parseSelect(p: var SqlParser): SqlNode =
getTok(p)
if isKeyw(p, "distinct"):
getTok(p)
@@ -1041,7 +1046,7 @@ proc parseSelect(p: var TSqlParser): PSqlNode =
getTok(p)
result.add(n)
-proc parseStmt(p: var TSqlParser): PSqlNode =
+proc parseStmt(p: var SqlParser): SqlNode =
if isKeyw(p, "create"):
getTok(p)
optKeyw(p, "cached")
@@ -1071,7 +1076,7 @@ proc parseStmt(p: var TSqlParser): PSqlNode =
else:
sqlError(p, "CREATE expected")
-proc open(p: var TSqlParser, input: PStream, filename: string) =
+proc open(p: var SqlParser, input: PStream, filename: string) =
## opens the parser `p` and assigns the input stream `input` to it.
## `filename` is only used for error messages.
open(TSqlLexer(p), input, filename)
@@ -1079,7 +1084,7 @@ proc open(p: var TSqlParser, input: PStream, filename: string) =
p.tok.literal = ""
getTok(p)
-proc parse(p: var TSqlParser): PSqlNode =
+proc parse(p: var SqlParser): SqlNode =
## parses the content of `p`'s input stream and returns the SQL AST.
## Syntax errors raise an `EInvalidSql` exception.
result = newNode(nkStmtList)
@@ -1090,24 +1095,24 @@ proc parse(p: var TSqlParser): PSqlNode =
if result.len == 1:
result = result.sons[0]
-proc close(p: var TSqlParser) =
+proc close(p: var SqlParser) =
## closes the parser `p`. The associated input stream is closed too.
close(TSqlLexer(p))
-proc parseSQL*(input: PStream, filename: string): PSqlNode =
+proc parseSQL*(input: PStream, filename: string): SqlNode =
## parses the SQL from `input` into an AST and returns the AST.
## `filename` is only used for error messages.
## Syntax errors raise an `EInvalidSql` exception.
- var p: TSqlParser
+ var p: SqlParser
open(p, input, filename)
try:
result = parse(p)
finally:
close(p)
-proc ra(n: PSqlNode, s: var string, indent: int)
+proc ra(n: SqlNode, s: var string, indent: int)
-proc rs(n: PSqlNode, s: var string, indent: int,
+proc rs(n: SqlNode, s: var string, indent: int,
prefix = "(", suffix = ")",
sep = ", ") =
if n.len > 0:
@@ -1117,7 +1122,7 @@ proc rs(n: PSqlNode, s: var string, indent: int,
ra(n.sons[i], s, indent)
s.add(suffix)
-proc ra(n: PSqlNode, s: var string, indent: int) =
+proc ra(n: SqlNode, s: var string, indent: int) =
if n == nil: return
case n.kind
of nkNone: discard
@@ -1320,7 +1325,7 @@ proc ra(n: PSqlNode, s: var string, indent: int) =
#for x, y, z in db.select(fromm = a, b where = a.name == b.name):
# writeln x, y, z
-proc renderSQL*(n: PSqlNode): string =
+proc renderSQL*(n: SqlNode): string =
## Converts an SQL abstract syntax tree to its string representation.
result = ""
ra(n, result, 0)
diff --git a/lib/pure/parseurl.nim b/lib/pure/parseurl.nim
index 67c6de905..2637a879d 100644
--- a/lib/pure/parseurl.nim
+++ b/lib/pure/parseurl.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -15,12 +15,14 @@
import strutils
type
- TUrl* = tuple[ ## represents a *Uniform Resource Locator* (URL)
- ## any optional component is "" if it does not exist
+ Url* = tuple[ ## represents a *Uniform Resource Locator* (URL)
+ ## any optional component is "" if it does not exist
scheme, username, password,
hostname, port, path, query, anchor: string]
-
-proc parseUrl*(url: string): TUrl {.deprecated.} =
+
+{.deprecated: [TUrl: Url].}
+
+proc parseUrl*(url: string): Url {.deprecated.} =
var i = 0
var scheme, username, password: string = ""
@@ -86,7 +88,7 @@ proc parseUrl*(url: string): TUrl {.deprecated.} =
return (scheme, username, password, hostname, port, path, query, anchor)
-proc `$`*(u: TUrl): string {.deprecated.} =
+proc `$`*(u: Url): string {.deprecated.} =
## turns the URL `u` into its string representation.
result = ""
if u.scheme.len > 0:
diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim
index 0c045bc5a..38a3cbc5e 100644
--- a/lib/pure/parseutils.nim
+++ b/lib/pure/parseutils.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -35,7 +35,7 @@ proc parseHex*(s: string, number: var int, start = 0): int {.
## can use this feature to *chain* calls, though the result int will quickly
## overflow. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var value = 0
## discard parseHex("0x38", value)
## assert value == 56
@@ -332,7 +332,7 @@ proc parseFloat*(s: string, number: var float, start = 0): int {.
number = bf
type
- TInterpolatedKind* = enum ## describes for `interpolatedFragments`
+ InterpolatedKind* = enum ## describes for `interpolatedFragments`
## which part of the interpolated string is
## yielded; for example in "str$$$var${expr}"
ikStr, ## ``str`` part of the interpolated string
@@ -340,7 +340,9 @@ type
ikVar, ## ``var`` part of the interpolated string
ikExpr ## ``expr`` part of the interpolated string
-iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
+{.deprecated: [TInterpolatedKind: InterpolatedKind].}
+
+iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind,
value: string] =
## Tokenizes the string `s` into substrings for interpolation purposes.
##
@@ -360,7 +362,7 @@ iterator interpolatedFragments*(s: string): tuple[kind: TInterpolatedKind,
## (ikString, " ")
## (ikDollar, "$")
var i = 0
- var kind: TInterpolatedKind
+ var kind: InterpolatedKind
while true:
var j = i
if s[j] == '$':
diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim
index 667b8aed6..2d944917f 100644
--- a/lib/pure/parsexml.nim
+++ b/lib/pure/parsexml.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -56,7 +56,7 @@ import
# xmlElementCloseEnd, ## ``/>``
type
- TXmlEventKind* = enum ## enumation of all events that may occur when parsing
+ XmlEventKind* = enum ## enumation of all events that may occur when parsing
xmlError, ## an error ocurred during parsing
xmlEof, ## end of file reached
xmlCharData, ## character data
@@ -72,7 +72,7 @@ type
xmlEntity, ## &entity;
xmlSpecial ## ````
- TXmlError* = enum ## enumeration that lists all errors that can occur
+ XmlErrorKind* = enum ## enumeration that lists all errors that can occur
errNone, ## no error
errEndOfCDataExpected, ## ``]]>`` expected
errNameExpected, ## name expected
@@ -83,23 +83,26 @@ type
errQuoteExpected, ## ``"`` or ``'`` expected
errEndOfCommentExpected ## ``-->`` expected
- TParserState = enum
+ ParserState = enum
stateStart, stateNormal, stateAttr, stateEmptyElementTag, stateError
- TXmlParseOption* = enum ## options for the XML parser
+ XmlParseOption* = enum ## options for the XML parser
reportWhitespace, ## report whitespace
reportComments ## report comments
- TXmlParser* = object of TBaseLexer ## the parser object.
+ XmlParser* = object of TBaseLexer ## the parser object.
a, b, c: string
- kind: TXmlEventKind
- err: TXmlError
- state: TParserState
+ kind: XmlEventKind
+ err: XmlErrorKind
+ state: ParserState
filename: string
- options: set[TXmlParseOption]
-
+ options: set[XmlParseOption]
+
+{.deprecated: [TXmlParser: XmlParser, TXmlParseOptions: XmlParseOptions,
+ TXmlError: XmlErrorKind, TXmlEventKind: XmlEventKind].}
+
const
- errorMessages: array [TXmlError, string] = [
+ errorMessages: array[XmlError, string] = [
"no error",
"']]>' expected",
"name expected",
@@ -111,8 +114,8 @@ const
"'-->' expected"
]
-proc open*(my: var TXmlParser, input: PStream, filename: string,
- options: set[TXmlParseOption] = {}) =
+proc open*(my: var XmlParser, input: Stream, filename: string,
+ options: set[XmlParseOption] = {}) =
## initializes the parser with an input stream. `Filename` is only used
## for nice error messages. The parser's behaviour can be controlled by
## the `options` parameter: If `options` contains ``reportWhitespace``
@@ -127,7 +130,7 @@ proc open*(my: var TXmlParser, input: PStream, filename: string,
my.b = ""
my.options = options
-proc close*(my: var TXmlParser) {.inline.} =
+proc close*(my: var XmlParser) {.inline.} =
## closes the parser `my` and its associated input stream.
lexbase.close(my)
diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim
index efe169c1d..8bd307c7d 100644
--- a/lib/pure/pegs.nim
+++ b/lib/pure/pegs.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -32,7 +32,7 @@ const
## can be captured. More subpatterns cannot be captured!
type
- TPegKind = enum
+ PegKind = enum
pkEmpty,
pkAny, ## any character (.)
pkAnyRune, ## any Unicode character (_)
@@ -67,16 +67,16 @@ type
pkRule, ## a <- b
pkList, ## a, b
pkStartAnchor ## ^ --> Internal DSL: startAnchor()
- TNonTerminalFlag = enum
+ NonTerminalFlag = enum
ntDeclared, ntUsed
- TNonTerminal {.final.} = object ## represents a non terminal symbol
+ NonTerminalObj = object ## represents a non terminal symbol
name: string ## the name of the symbol
line: int ## line the symbol has been declared/used in
col: int ## column the symbol has been declared/used in
- flags: set[TNonTerminalFlag] ## the nonterminal's flags
+ flags: set[NonTerminalFlag] ## the nonterminal's flags
rule: TNode ## the rule that the symbol refers to
- TNode {.final, shallow.} = object
- case kind: TPegKind
+ TNode {.shallow.} = object
+ case kind: PegKind
of pkEmpty..pkWhitespace: nil
of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string
of pkChar, pkGreedyRepChar: ch: char
@@ -84,11 +84,13 @@ type
of pkNonTerminal: nt: PNonTerminal
of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns]
else: sons: seq[TNode]
- PNonTerminal* = ref TNonTerminal
+ NonTerminal* = ref NonTerminalObj
- TPeg* = TNode ## type that represents a PEG
+ Peg* = TNode ## type that represents a PEG
-proc term*(t: string): TPeg {.nosideEffect, rtl, extern: "npegs$1Str".} =
+{.deprecated: [TPeg: Peg].}
+
+proc term*(t: string): Peg {.nosideEffect, rtl, extern: "npegs$1Str".} =
## constructs a PEG from a terminal string
if t.len != 1:
result.kind = pkTerminal
@@ -97,35 +99,35 @@ proc term*(t: string): TPeg {.nosideEffect, rtl, extern: "npegs$1Str".} =
result.kind = pkChar
result.ch = t[0]
-proc termIgnoreCase*(t: string): TPeg {.
+proc termIgnoreCase*(t: string): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a PEG from a terminal string; ignore case for matching
result.kind = pkTerminalIgnoreCase
result.term = t
-proc termIgnoreStyle*(t: string): TPeg {.
+proc termIgnoreStyle*(t: string): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a PEG from a terminal string; ignore style for matching
result.kind = pkTerminalIgnoreStyle
result.term = t
-proc term*(t: char): TPeg {.nosideEffect, rtl, extern: "npegs$1Char".} =
+proc term*(t: char): Peg {.nosideEffect, rtl, extern: "npegs$1Char".} =
## constructs a PEG from a terminal char
assert t != '\0'
result.kind = pkChar
result.ch = t
-proc charSet*(s: set[char]): TPeg {.nosideEffect, rtl, extern: "npegs$1".} =
+proc charSet*(s: set[char]): Peg {.nosideEffect, rtl, extern: "npegs$1".} =
## constructs a PEG from a character set `s`
assert '\0' notin s
result.kind = pkCharChoice
new(result.charChoice)
result.charChoice[] = s
-proc len(a: TPeg): int {.inline.} = return a.sons.len
-proc add(d: var TPeg, s: TPeg) {.inline.} = add(d.sons, s)
+proc len(a: Peg): int {.inline.} = return a.sons.len
+proc add(d: var Peg, s: Peg) {.inline.} = add(d.sons, s)
-proc addChoice(dest: var TPeg, elem: TPeg) =
+proc addChoice(dest: var Peg, elem: Peg) =
var L = dest.len-1
if L >= 0 and dest.sons[L].kind == pkCharChoice:
# caution! Do not introduce false aliasing here!
@@ -137,7 +139,7 @@ proc addChoice(dest: var TPeg, elem: TPeg) =
else: add(dest, elem)
else: add(dest, elem)
-template multipleOp(k: TPegKind, localOpt: expr) =
+template multipleOp(k: PegKind, localOpt: expr) =
result.kind = k
result.sons = @[]
for x in items(a):
@@ -149,12 +151,12 @@ template multipleOp(k: TPegKind, localOpt: expr) =
if result.len == 1:
result = result.sons[0]
-proc `/`*(a: varargs[TPeg]): TPeg {.
+proc `/`*(a: varargs[Peg]): Peg {.
nosideEffect, rtl, extern: "npegsOrderedChoice".} =
## constructs an ordered choice with the PEGs in `a`
multipleOp(pkOrderedChoice, addChoice)
-proc addSequence(dest: var TPeg, elem: TPeg) =
+proc addSequence(dest: var Peg, elem: Peg) =
var L = dest.len-1
if L >= 0 and dest.sons[L].kind == pkTerminal:
# caution! Do not introduce false aliasing here!
@@ -166,12 +168,12 @@ proc addSequence(dest: var TPeg, elem: TPeg) =
else: add(dest, elem)
else: add(dest, elem)
-proc sequence*(a: varargs[TPeg]): TPeg {.
+proc sequence*(a: varargs[Peg]): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a sequence with all the PEGs from `a`
multipleOp(pkSequence, addSequence)
-proc `?`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsOptional".} =
+proc `?`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsOptional".} =
## constructs an optional for the PEG `a`
if a.kind in {pkOption, pkGreedyRep, pkGreedyAny, pkGreedyRepChar,
pkGreedyRepSet}:
@@ -182,7 +184,7 @@ proc `?`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsOptional".} =
result.kind = pkOption
result.sons = @[a]
-proc `*`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsGreedyRep".} =
+proc `*`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsGreedyRep".} =
## constructs a "greedy repetition" for the PEG `a`
case a.kind
of pkGreedyRep, pkGreedyRepChar, pkGreedyRepSet, pkGreedyAny, pkOption:
@@ -200,111 +202,99 @@ proc `*`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsGreedyRep".} =
result.kind = pkGreedyRep
result.sons = @[a]
-proc `!*`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsSearch".} =
+proc `!*`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsSearch".} =
## constructs a "search" for the PEG `a`
result.kind = pkSearch
result.sons = @[a]
-proc `!*\`*(a: TPeg): TPeg {.noSideEffect, rtl,
+proc `!*\`*(a: Peg): Peg {.noSideEffect, rtl,
extern: "npgegsCapturedSearch".} =
## constructs a "captured search" for the PEG `a`
result.kind = pkCapturedSearch
result.sons = @[a]
-
-when false:
- proc contains(a: TPeg, k: TPegKind): bool =
- if a.kind == k: return true
- case a.kind
- of pkEmpty, pkAny, pkAnyRune, pkGreedyAny, pkNewLine, pkTerminal,
- pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar, pkGreedyRepChar,
- pkCharChoice, pkGreedyRepSet: nil
- of pkNonTerminal: return true
- else:
- for i in 0..a.sons.len-1:
- if contains(a.sons[i], k): return true
-proc `+`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsGreedyPosRep".} =
+proc `+`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsGreedyPosRep".} =
## constructs a "greedy positive repetition" with the PEG `a`
return sequence(a, *a)
-proc `&`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsAndPredicate".} =
+proc `&`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsAndPredicate".} =
## constructs an "and predicate" with the PEG `a`
result.kind = pkAndPredicate
result.sons = @[a]
-proc `!`*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsNotPredicate".} =
+proc `!`*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsNotPredicate".} =
## constructs a "not predicate" with the PEG `a`
result.kind = pkNotPredicate
result.sons = @[a]
-proc any*: TPeg {.inline.} =
+proc any*: Peg {.inline.} =
## constructs the PEG `any character`:idx: (``.``)
result.kind = pkAny
-proc anyRune*: TPeg {.inline.} =
+proc anyRune*: Peg {.inline.} =
## constructs the PEG `any rune`:idx: (``_``)
result.kind = pkAnyRune
-proc newLine*: TPeg {.inline.} =
+proc newLine*: Peg {.inline.} =
## constructs the PEG `newline`:idx: (``\n``)
result.kind = pkNewline
-proc unicodeLetter*: TPeg {.inline.} =
+proc unicodeLetter*: Peg {.inline.} =
## constructs the PEG ``\letter`` which matches any Unicode letter.
result.kind = pkLetter
-proc unicodeLower*: TPeg {.inline.} =
+proc unicodeLower*: Peg {.inline.} =
## constructs the PEG ``\lower`` which matches any Unicode lowercase letter.
result.kind = pkLower
-proc unicodeUpper*: TPeg {.inline.} =
+proc unicodeUpper*: Peg {.inline.} =
## constructs the PEG ``\upper`` which matches any Unicode uppercase letter.
result.kind = pkUpper
-proc unicodeTitle*: TPeg {.inline.} =
+proc unicodeTitle*: Peg {.inline.} =
## constructs the PEG ``\title`` which matches any Unicode title letter.
result.kind = pkTitle
-proc unicodeWhitespace*: TPeg {.inline.} =
+proc unicodeWhitespace*: Peg {.inline.} =
## constructs the PEG ``\white`` which matches any Unicode
## whitespace character.
result.kind = pkWhitespace
-proc startAnchor*: TPeg {.inline.} =
+proc startAnchor*: Peg {.inline.} =
## constructs the PEG ``^`` which matches the start of the input.
result.kind = pkStartAnchor
-proc endAnchor*: TPeg {.inline.} =
+proc endAnchor*: Peg {.inline.} =
## constructs the PEG ``$`` which matches the end of the input.
result = !any()
-proc capture*(a: TPeg): TPeg {.nosideEffect, rtl, extern: "npegsCapture".} =
+proc capture*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsCapture".} =
## constructs a capture with the PEG `a`
result.kind = pkCapture
result.sons = @[a]
-proc backref*(index: range[1..MaxSubPatterns]): TPeg {.
+proc backref*(index: range[1..MaxSubPatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a back reference of the given `index`. `index` starts counting
## from 1.
result.kind = pkBackRef
result.index = index-1
-proc backrefIgnoreCase*(index: range[1..MaxSubPatterns]): TPeg {.
+proc backrefIgnoreCase*(index: range[1..MaxSubPatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a back reference of the given `index`. `index` starts counting
## from 1. Ignores case for matching.
result.kind = pkBackRefIgnoreCase
result.index = index-1
-proc backrefIgnoreStyle*(index: range[1..MaxSubPatterns]): TPeg {.
+proc backrefIgnoreStyle*(index: range[1..MaxSubPatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".}=
## constructs a back reference of the given `index`. `index` starts counting
## from 1. Ignores style for matching.
result.kind = pkBackRefIgnoreStyle
result.index = index-1
-proc spaceCost(n: TPeg): int =
+proc spaceCost(n: Peg): int =
case n.kind
of pkEmpty: discard
of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle, pkChar,
@@ -319,7 +309,7 @@ proc spaceCost(n: TPeg): int =
inc(result, spaceCost(n.sons[i]))
if result >= InlineThreshold: break
-proc nonterminal*(n: PNonTerminal): TPeg {.
+proc nonterminal*(n: PNonTerminal): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a PEG that consists of the nonterminal symbol
assert n != nil
@@ -415,7 +405,7 @@ proc charSetEsc(cc: set[char]): string =
else:
result = '[' & charSetEscAux(cc) & ']'
-proc toStrAux(r: TPeg, res: var string) =
+proc toStrAux(r: Peg, res: var string) =
case r.kind
of pkEmpty: add(res, "()")
of pkAny: add(res, '.')
@@ -501,7 +491,7 @@ proc toStrAux(r: TPeg, res: var string) =
of pkStartAnchor:
add(res, '^')
-proc `$` *(r: TPeg): string {.nosideEffect, rtl, extern: "npegsToString".} =
+proc `$` *(r: Peg): string {.nosideEffect, rtl, extern: "npegsToString".} =
## converts a PEG to its string representation
result = ""
toStrAux(r, result)
@@ -509,12 +499,14 @@ proc `$` *(r: TPeg): string {.nosideEffect, rtl, extern: "npegsToString".} =
# --------------------- core engine -------------------------------------------
type
- TCaptures* {.final.} = object ## contains the captured substrings.
+ Captures* = object ## contains the captured substrings.
matches: array[0..maxSubpatterns-1, tuple[first, last: int]]
ml: int
origStart: int
-proc bounds*(c: TCaptures,
+{.deprecated: [TCaptures: Captures].}
+
+proc bounds*(c: Captures,
i: range[0..maxSubpatterns-1]): tuple[first, last: int] =
## returns the bounds ``[first..last]`` of the `i`'th capture.
result = c.matches[i]
@@ -533,7 +525,7 @@ when not useUnicode:
proc isTitle(a: char): bool {.inline.} = return false
proc isWhiteSpace(a: char): bool {.inline.} = return a in {' ', '\9'..'\13'}
-proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {.
+proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
nosideEffect, rtl, extern: "npegs$1".} =
## low-level matching proc that implements the PEG interpreter. Use this
## for maximum efficiency (every other PEG operation ends up calling this
@@ -734,7 +726,7 @@ proc rawMatch*(s: string, p: TPeg, start: int, c: var TCaptures): int {.
of pkBackRef..pkBackRefIgnoreStyle:
if p.index >= c.ml: return -1
var (a, b) = c.matches[p.index]
- var n: TPeg
+ var n: Peg
n.kind = succ(pkTerminal, ord(p.kind)-ord(pkBackRef))
n.term = s.substr(a, b)
result = rawMatch(s, n, start, c)
@@ -747,51 +739,51 @@ template fillMatches(s, caps, c: expr) =
for k in 0..c.ml-1:
caps[k] = substr(s, c.matches[k][0], c.matches[k][1])
-proc match*(s: string, pattern: TPeg, matches: var openArray[string],
+proc match*(s: string, pattern: Peg, matches: var openArray[string],
start = 0): bool {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns ``true`` if ``s[start..]`` matches the ``pattern`` and
## the captured substrings in the array ``matches``. If it does not
## match, nothing is written into ``matches`` and ``false`` is
## returned.
- var c: TCaptures
+ var c: Captures
c.origStart = start
result = rawMatch(s, pattern, start, c) == len(s) - start
if result: fillMatches(s, matches, c)
-proc match*(s: string, pattern: TPeg,
+proc match*(s: string, pattern: Peg,
start = 0): bool {.nosideEffect, rtl, extern: "npegs$1".} =
## returns ``true`` if ``s`` matches the ``pattern`` beginning from ``start``.
- var c: TCaptures
+ var c: Captures
c.origStart = start
result = rawMatch(s, pattern, start, c) == len(s)-start
-proc matchLen*(s: string, pattern: TPeg, matches: var openArray[string],
+proc matchLen*(s: string, pattern: Peg, matches: var openArray[string],
start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## the same as ``match``, but it returns the length of the match,
## if there is no match, -1 is returned. Note that a match length
## of zero can happen. It's possible that a suffix of `s` remains
## that does not belong to the match.
- var c: TCaptures
+ var c: Captures
c.origStart = start
result = rawMatch(s, pattern, start, c)
if result >= 0: fillMatches(s, matches, c)
-proc matchLen*(s: string, pattern: TPeg,
+proc matchLen*(s: string, pattern: Peg,
start = 0): int {.nosideEffect, rtl, extern: "npegs$1".} =
## the same as ``match``, but it returns the length of the match,
## if there is no match, -1 is returned. Note that a match length
## of zero can happen. It's possible that a suffix of `s` remains
## that does not belong to the match.
- var c: TCaptures
+ var c: Captures
c.origStart = start
result = rawMatch(s, pattern, start, c)
-proc find*(s: string, pattern: TPeg, matches: var openArray[string],
+proc find*(s: string, pattern: Peg, matches: var openArray[string],
start = 0): int {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns the starting position of ``pattern`` in ``s`` and the captured
## substrings in the array ``matches``. If it does not match, nothing
## is written into ``matches`` and -1 is returned.
- var c: TCaptures
+ var c: Captures
c.origStart = start
for i in start .. s.len-1:
c.ml = 0
@@ -801,14 +793,14 @@ proc find*(s: string, pattern: TPeg, matches: var openArray[string],
return -1
# could also use the pattern here: (!P .)* P
-proc findBounds*(s: string, pattern: TPeg, matches: var openArray[string],
+proc findBounds*(s: string, pattern: Peg, matches: var openArray[string],
start = 0): tuple[first, last: int] {.
nosideEffect, rtl, extern: "npegs$1Capture".} =
## returns the starting position and end position of ``pattern`` in ``s``
## and the captured
## substrings in the array ``matches``. If it does not match, nothing
## is written into ``matches`` and (-1,0) is returned.
- var c: TCaptures
+ var c: Captures
c.origStart = start
for i in start .. s.len-1:
c.ml = 0
@@ -818,19 +810,19 @@ proc findBounds*(s: string, pattern: TPeg, matches: var openArray[string],
return (i, i+L-1)
return (-1, 0)
-proc find*(s: string, pattern: TPeg,
+proc find*(s: string, pattern: Peg,
start = 0): int {.nosideEffect, rtl, extern: "npegs$1".} =
## returns the starting position of ``pattern`` in ``s``. If it does not
## match, -1 is returned.
- var c: TCaptures
+ var c: Captures
c.origStart = start
for i in start .. s.len-1:
if rawMatch(s, pattern, i, c) >= 0: return i
return -1
-iterator findAll*(s: string, pattern: TPeg, start = 0): string =
+iterator findAll*(s: string, pattern: Peg, start = 0): string =
## yields all matching *substrings* of `s` that match `pattern`.
- var c: TCaptures
+ var c: Captures
c.origStart = start
var i = start
while i < s.len:
@@ -842,7 +834,7 @@ iterator findAll*(s: string, pattern: TPeg, start = 0): string =
yield substr(s, i, i+L-1)
inc(i, L)
-proc findAll*(s: string, pattern: TPeg, start = 0): seq[string] {.
+proc findAll*(s: string, pattern: Peg, start = 0): seq[string] {.
nosideEffect, rtl, extern: "npegs$1".} =
## returns all matching *substrings* of `s` that match `pattern`.
## If it does not match, @[] is returned.
@@ -851,11 +843,11 @@ proc findAll*(s: string, pattern: TPeg, start = 0): seq[string] {.
when not defined(nimhygiene):
{.pragma: inject.}
-template `=~`*(s: string, pattern: TPeg): bool =
+template `=~`*(s: string, pattern: Peg): bool =
## This calls ``match`` with an implicit declared ``matches`` array that
## can be used in the scope of the ``=~`` call:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## if line =~ peg"\s* {\w+} \s* '=' \s* {\w+}":
## # matches a key=value pair:
@@ -876,46 +868,46 @@ template `=~`*(s: string, pattern: TPeg): bool =
# ------------------------- more string handling ------------------------------
-proc contains*(s: string, pattern: TPeg, start = 0): bool {.
+proc contains*(s: string, pattern: Peg, start = 0): bool {.
nosideEffect, rtl, extern: "npegs$1".} =
## same as ``find(s, pattern, start) >= 0``
return find(s, pattern, start) >= 0
-proc contains*(s: string, pattern: TPeg, matches: var openArray[string],
+proc contains*(s: string, pattern: Peg, matches: var openArray[string],
start = 0): bool {.nosideEffect, rtl, extern: "npegs$1Capture".} =
## same as ``find(s, pattern, matches, start) >= 0``
return find(s, pattern, matches, start) >= 0
-proc startsWith*(s: string, prefix: TPeg, start = 0): bool {.
+proc startsWith*(s: string, prefix: Peg, start = 0): bool {.
nosideEffect, rtl, extern: "npegs$1".} =
## returns true if `s` starts with the pattern `prefix`
result = matchLen(s, prefix, start) >= 0
-proc endsWith*(s: string, suffix: TPeg, start = 0): bool {.
+proc endsWith*(s: string, suffix: Peg, start = 0): bool {.
nosideEffect, rtl, extern: "npegs$1".} =
## returns true if `s` ends with the pattern `prefix`
- var c: TCaptures
+ var c: Captures
c.origStart = start
for i in start .. s.len-1:
if rawMatch(s, suffix, i, c) == s.len - i: return true
-proc replacef*(s: string, sub: TPeg, by: string): string {.
+proc replacef*(s: string, sub: Peg, by: string): string {.
nosideEffect, rtl, extern: "npegs$1".} =
## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "var1=key; var2=key2".replace(peg"{\ident}'='{\ident}", "$1<-$2$2")
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## "var1<-keykey; val2<-key2key2"
result = ""
var i = 0
var caps: array[0..maxSubpatterns-1, string]
- var c: TCaptures
+ var c: Captures
while i < s.len:
c.ml = 0
var x = rawMatch(s, sub, i, c)
@@ -928,13 +920,13 @@ proc replacef*(s: string, sub: TPeg, by: string): string {.
inc(i, x)
add(result, substr(s, i))
-proc replace*(s: string, sub: TPeg, by = ""): string {.
+proc replace*(s: string, sub: Peg, by = ""): string {.
nosideEffect, rtl, extern: "npegs$1".} =
## Replaces `sub` in `s` by the string `by`. Captures cannot be accessed
## in `by`.
result = ""
var i = 0
- var c: TCaptures
+ var c: Captures
while i < s.len:
var x = rawMatch(s, sub, i, c)
if x <= 0:
@@ -946,13 +938,13 @@ proc replace*(s: string, sub: TPeg, by = ""): string {.
add(result, substr(s, i))
proc parallelReplace*(s: string, subs: varargs[
- tuple[pattern: TPeg, repl: string]]): string {.
+ tuple[pattern: Peg, repl: string]]): string {.
nosideEffect, rtl, extern: "npegs$1".} =
## Returns a modified copy of `s` with the substitutions in `subs`
## applied in parallel.
result = ""
var i = 0
- var c: TCaptures
+ var c: Captures
var caps: array[0..maxSubpatterns-1, string]
while i < s.len:
block searchSubs:
@@ -970,7 +962,7 @@ proc parallelReplace*(s: string, subs: varargs[
add(result, substr(s, i))
proc transformFile*(infile, outfile: string,
- subs: varargs[tuple[pattern: TPeg, repl: string]]) {.
+ subs: varargs[tuple[pattern: Peg, repl: string]]) {.
rtl, extern: "npegs$1".} =
## reads in the file `infile`, performs a parallel replacement (calls
## `parallelReplace`) and writes back to `outfile`. Raises ``EIO`` if an
@@ -978,25 +970,25 @@ proc transformFile*(infile, outfile: string,
var x = readFile(infile).string
writeFile(outfile, x.parallelReplace(subs))
-iterator split*(s: string, sep: TPeg): string =
+iterator split*(s: string, sep: Peg): string =
## Splits the string `s` into substrings.
##
## Substrings are separated by the PEG `sep`.
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in split("00232this02939is39an22example111", peg"\d+"):
## writeln(stdout, word)
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "this"
## "is"
## "an"
## "example"
##
- var c: TCaptures
+ var c: Captures
var
first = 0
last = 0
@@ -1013,7 +1005,7 @@ iterator split*(s: string, sep: TPeg): string =
if first < last:
yield substr(s, first, last-1)
-proc split*(s: string, sep: TPeg): seq[string] {.
+proc split*(s: string, sep: Peg): seq[string] {.
nosideEffect, rtl, extern: "npegs$1".} =
## Splits the string `s` into substrings.
accumulateResult(split(s, sep))
@@ -1060,7 +1052,7 @@ type
charset: set[char] ## if kind == tkCharSet
index: int ## if kind == tkBackref
- TPegLexer {.inheritable.} = object ## the lexer object.
+ PegLexer {.inheritable.} = object ## the lexer object.
bufpos: int ## the current position within the buffer
buf: cstring ## the buffer itself
LineNumber: int ## the current line number
@@ -1076,20 +1068,20 @@ const
"@", "built-in", "escaped", "$", "$", "^"
]
-proc handleCR(L: var TPegLexer, pos: int): int =
+proc handleCR(L: var PegLexer, pos: int): int =
assert(L.buf[pos] == '\c')
inc(L.linenumber)
result = pos+1
if L.buf[result] == '\L': inc(result)
L.lineStart = result
-proc handleLF(L: var TPegLexer, pos: int): int =
+proc handleLF(L: var PegLexer, pos: int): int =
assert(L.buf[pos] == '\L')
inc(L.linenumber)
result = pos+1
L.lineStart = result
-proc init(L: var TPegLexer, input, filename: string, line = 1, col = 0) =
+proc init(L: var PegLexer, input, filename: string, line = 1, col = 0) =
L.buf = input
L.bufpos = 0
L.lineNumber = line
@@ -1097,18 +1089,18 @@ proc init(L: var TPegLexer, input, filename: string, line = 1, col = 0) =
L.lineStart = 0
L.filename = filename
-proc getColumn(L: TPegLexer): int {.inline.} =
+proc getColumn(L: PegLexer): int {.inline.} =
result = abs(L.bufpos - L.lineStart) + L.colOffset
-proc getLine(L: TPegLexer): int {.inline.} =
+proc getLine(L: PegLexer): int {.inline.} =
result = L.linenumber
-proc errorStr(L: TPegLexer, msg: string, line = -1, col = -1): string =
+proc errorStr(L: PegLexer, msg: string, line = -1, col = -1): string =
var line = if line < 0: getLine(L) else: line
var col = if col < 0: getColumn(L) else: col
result = "$1($2, $3) Error: $4" % [L.filename, $line, $col, msg]
-proc handleHexChar(c: var TPegLexer, xi: var int) =
+proc handleHexChar(c: var PegLexer, xi: var int) =
case c.buf[c.bufpos]
of '0'..'9':
xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0'))
@@ -1121,7 +1113,7 @@ proc handleHexChar(c: var TPegLexer, xi: var int) =
inc(c.bufpos)
else: discard
-proc getEscapedChar(c: var TPegLexer, tok: var TToken) =
+proc getEscapedChar(c: var PegLexer, tok: var TToken) =
inc(c.bufpos)
case c.buf[c.bufpos]
of 'r', 'R', 'c', 'C':
@@ -1173,7 +1165,7 @@ proc getEscapedChar(c: var TPegLexer, tok: var TToken) =
add(tok.literal, c.buf[c.bufpos])
inc(c.bufpos)
-proc skip(c: var TPegLexer) =
+proc skip(c: var PegLexer) =
var pos = c.bufpos
var buf = c.buf
while true:
@@ -1192,7 +1184,7 @@ proc skip(c: var TPegLexer) =
break # EndOfFile also leaves the loop
c.bufpos = pos
-proc getString(c: var TPegLexer, tok: var TToken) =
+proc getString(c: var PegLexer, tok: var TToken) =
tok.kind = tkStringLit
var pos = c.bufPos + 1
var buf = c.buf
@@ -1214,7 +1206,7 @@ proc getString(c: var TPegLexer, tok: var TToken) =
inc(pos)
c.bufpos = pos
-proc getDollar(c: var TPegLexer, tok: var TToken) =
+proc getDollar(c: var PegLexer, tok: var TToken) =
var pos = c.bufPos + 1
var buf = c.buf
if buf[pos] in {'0'..'9'}:
@@ -1227,7 +1219,7 @@ proc getDollar(c: var TPegLexer, tok: var TToken) =
tok.kind = tkDollar
c.bufpos = pos
-proc getCharSet(c: var TPegLexer, tok: var TToken) =
+proc getCharSet(c: var PegLexer, tok: var TToken) =
tok.kind = tkCharSet
tok.charset = {}
var pos = c.bufPos + 1
@@ -1278,7 +1270,7 @@ proc getCharSet(c: var TPegLexer, tok: var TToken) =
c.bufpos = pos
if caret: tok.charset = {'\1'..'\xFF'} - tok.charset
-proc getSymbol(c: var TPegLexer, tok: var TToken) =
+proc getSymbol(c: var PegLexer, tok: var TToken) =
var pos = c.bufpos
var buf = c.buf
while true:
@@ -1288,7 +1280,7 @@ proc getSymbol(c: var TPegLexer, tok: var TToken) =
c.bufpos = pos
tok.kind = tkIdentifier
-proc getBuiltin(c: var TPegLexer, tok: var TToken) =
+proc getBuiltin(c: var PegLexer, tok: var TToken) =
if c.buf[c.bufpos+1] in strutils.Letters:
inc(c.bufpos)
getSymbol(c, tok)
@@ -1297,7 +1289,7 @@ proc getBuiltin(c: var TPegLexer, tok: var TToken) =
tok.kind = tkEscaped
getEscapedChar(c, tok) # may set tok.kind to tkInvalid
-proc getTok(c: var TPegLexer, tok: var TToken) =
+proc getTok(c: var PegLexer, tok: var TToken) =
tok.kind = tkInvalid
tok.modifier = modNone
setLen(tok.literal, 0)
@@ -1403,7 +1395,7 @@ proc getTok(c: var TPegLexer, tok: var TToken) =
add(tok.literal, c.buf[c.bufpos])
inc(c.bufpos)
-proc arrowIsNextTok(c: TPegLexer): bool =
+proc arrowIsNextTok(c: PegLexer): bool =
# the only look ahead we need
var pos = c.bufpos
while c.buf[pos] in {'\t', ' '}: inc(pos)
@@ -1414,31 +1406,31 @@ proc arrowIsNextTok(c: TPegLexer): bool =
type
EInvalidPeg* = object of EInvalidValue ## raised if an invalid
## PEG has been detected
- TPegParser = object of TPegLexer ## the PEG parser object
+ PegParser = object of PegLexer ## the PEG parser object
tok: TToken
nonterms: seq[PNonTerminal]
modifier: TModifier
captures: int
identIsVerbatim: bool
- skip: TPeg
+ skip: Peg
-proc pegError(p: TPegParser, msg: string, line = -1, col = -1) =
+proc pegError(p: PegParser, msg: string, line = -1, col = -1) =
var e: ref EInvalidPeg
new(e)
e.msg = errorStr(p, msg, line, col)
raise e
-proc getTok(p: var TPegParser) =
+proc getTok(p: var PegParser) =
getTok(p, p.tok)
if p.tok.kind == tkInvalid: pegError(p, "invalid token")
-proc eat(p: var TPegParser, kind: TTokKind) =
+proc eat(p: var PegParser, kind: TTokKind) =
if p.tok.kind == kind: getTok(p)
else: pegError(p, tokKindToStr[kind] & " expected")
-proc parseExpr(p: var TPegParser): TPeg
+proc parseExpr(p: var PegParser): Peg
-proc getNonTerminal(p: var TPegParser, name: string): PNonTerminal =
+proc getNonTerminal(p: var PegParser, name: string): PNonTerminal =
for i in 0..high(p.nonterms):
result = p.nonterms[i]
if cmpIgnoreStyle(result.name, name) == 0: return
@@ -1446,19 +1438,19 @@ proc getNonTerminal(p: var TPegParser, name: string): PNonTerminal =
result = newNonTerminal(name, getLine(p), getColumn(p))
add(p.nonterms, result)
-proc modifiedTerm(s: string, m: TModifier): TPeg =
+proc modifiedTerm(s: string, m: TModifier): Peg =
case m
of modNone, modVerbatim: result = term(s)
of modIgnoreCase: result = termIgnoreCase(s)
of modIgnoreStyle: result = termIgnoreStyle(s)
-proc modifiedBackref(s: int, m: TModifier): TPeg =
+proc modifiedBackref(s: int, m: TModifier): Peg =
case m
of modNone, modVerbatim: result = backref(s)
of modIgnoreCase: result = backrefIgnoreCase(s)
of modIgnoreStyle: result = backrefIgnoreStyle(s)
-proc builtin(p: var TPegParser): TPeg =
+proc builtin(p: var PegParser): Peg =
# do not use "y", "skip" or "i" as these would be ambiguous
case p.tok.literal
of "n": result = newLine()
@@ -1478,11 +1470,11 @@ proc builtin(p: var TPegParser): TPeg =
of "white": result = unicodeWhitespace()
else: pegError(p, "unknown built-in: " & p.tok.literal)
-proc token(terminal: TPeg, p: TPegParser): TPeg =
+proc token(terminal: Peg, p: PegParser): Peg =
if p.skip.kind == pkEmpty: result = terminal
else: result = sequence(p.skip, terminal)
-proc primary(p: var TPegParser): TPeg =
+proc primary(p: var PegParser): Peg =
case p.tok.kind
of tkAmp:
getTok(p)
@@ -1571,7 +1563,7 @@ proc primary(p: var TPegParser): TPeg =
getTok(p)
else: break
-proc seqExpr(p: var TPegParser): TPeg =
+proc seqExpr(p: var PegParser): Peg =
result = primary(p)
while true:
case p.tok.kind
@@ -1585,13 +1577,13 @@ proc seqExpr(p: var TPegParser): TPeg =
else: break
else: break
-proc parseExpr(p: var TPegParser): TPeg =
+proc parseExpr(p: var PegParser): Peg =
result = seqExpr(p)
while p.tok.kind == tkBar:
getTok(p)
result = result / seqExpr(p)
-proc parseRule(p: var TPegParser): PNonTerminal =
+proc parseRule(p: var PegParser): PNonTerminal =
if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
result = getNonTerminal(p, p.tok.literal)
if ntDeclared in result.flags:
@@ -1605,7 +1597,7 @@ proc parseRule(p: var TPegParser): PNonTerminal =
else:
pegError(p, "rule expected, but found: " & p.tok.literal)
-proc rawParse(p: var TPegParser): TPeg =
+proc rawParse(p: var PegParser): Peg =
## parses a rule or a PEG expression
while p.tok.kind == tkBuiltin:
case p.tok.literal
@@ -1635,12 +1627,12 @@ proc rawParse(p: var TPegParser): TPeg =
elif ntUsed notin nt.flags and i > 0:
pegError(p, "unused rule: " & nt.name, nt.line, nt.col)
-proc parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): TPeg =
- ## constructs a TPeg object from `pattern`. `filename`, `line`, `col` are
+proc parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): Peg =
+ ## constructs a Peg object from `pattern`. `filename`, `line`, `col` are
## used for error messages, but they only provide start offsets. `parsePeg`
## keeps track of line and column numbers within `pattern`.
- var p: TPegParser
- init(TPegLexer(p), pattern, filename, line, col)
+ var p: PegParser
+ init(PegLexer(p), pattern, filename, line, col)
p.tok.kind = tkInvalid
p.tok.modifier = modNone
p.tok.literal = ""
@@ -1650,8 +1642,8 @@ proc parsePeg*(pattern: string, filename = "pattern", line = 1, col = 0): TPeg =
getTok(p)
result = rawParse(p)
-proc peg*(pattern: string): TPeg =
- ## constructs a TPeg object from the `pattern`. The short name has been
+proc peg*(pattern: string): Peg =
+ ## constructs a Peg object from the `pattern`. The short name has been
## chosen to encourage its use as a raw string modifier::
##
## peg"{\ident} \s* '=' \s* {.*}"
@@ -1704,7 +1696,7 @@ when isMainModule:
expr.rule = sequence(capture(ident), *sequence(
nonterminal(ws), term('+'), nonterminal(ws), nonterminal(expr)))
- var c: TCaptures
+ var c: Captures
var s = "a+b + c +d+e+f"
assert rawMatch(s, expr.rule, 0, c) == len(s)
var a = ""
diff --git a/lib/pure/poly.nim b/lib/pure/poly.nim
index 45e528604..19bed2aca 100644
--- a/lib/pure/poly.nim
+++ b/lib/pure/poly.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Robert Persson
#
# See the file "copying.txt", included in this
@@ -12,10 +12,11 @@ import strutils
import numeric
type
- TPoly* = object
- cofs:seq[float]
+ Poly* = object
+ cofs:seq[float]
+
+{.deprecated: [TPoly: Poly].}
-
proc degree*(p:TPoly):int=
## Returns the degree of the polynomial,
## that is the number of coefficients-1
@@ -104,7 +105,7 @@ proc `$` *(p:TPoly):string =
result="0"
-proc derivative*(p:TPoly):TPoly=
+proc derivative*(p: TPoly): TPoly=
## Returns a new polynomial, which is the derivative of `p`
newSeq[float](result.cofs,p.degree)
for idx in 0..high(result.cofs):
@@ -310,10 +311,10 @@ proc getRangeForRoots(p:TPoly):tuple[xmin,xmax:float]=
var bound1,bound2:float
for i in countup(0,deg):
- var c=abs(p.cofs[i]/d)
- bound1=max(bound1,c+1.0)
- bound2=bound2+c
-
+ var c=abs(p.cofs[i]/d)
+ bound1=max(bound1,c+1.0)
+ bound2=bound2+c
+
bound2=max(1.0,bound2)
result.xmax=min(bound1,bound2)
result.xmin= -result.xmax
diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim
index fea09dfa2..14a494ecf 100644
--- a/lib/pure/rawsockets.nim
+++ b/lib/pure/rawsockets.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -28,7 +28,7 @@ else:
export fcntl, F_GETFL, O_NONBLOCK, F_SETFL, EAGAIN, EWOULDBLOCK, MSG_NOSIGNAL,
EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET
-export TSocketHandle, TSockaddr_in, TAddrinfo, INADDR_ANY, TSockAddr, TSockLen,
+export SocketHandle, Sockaddr_in, Addrinfo, INADDR_ANY, SockAddr, SockLen,
inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto
export
@@ -40,22 +40,22 @@ export
MSG_PEEK
type
- TPort* = distinct uint16 ## port type
+ Port* = distinct uint16 ## port type
- TDomain* = enum ## domain, which specifies the protocol family of the
+ Domain* = enum ## domain, which specifies the protocol family of the
## created socket. Other domains than those that are listed
## here are unsupported.
AF_UNIX, ## for local socket (using a file). Unsupported on Windows.
AF_INET = 2, ## for network protocol IPv4 or
AF_INET6 = 23 ## for network protocol IPv6.
- TType* = enum ## second argument to `socket` proc
+ SockType* = enum ## second argument to `socket` proc
SOCK_STREAM = 1, ## reliable stream-oriented service or Stream Sockets
SOCK_DGRAM = 2, ## datagram service or Datagram Sockets
SOCK_RAW = 3, ## raw protocols atop the network layer.
SOCK_SEQPACKET = 5 ## reliable sequenced packet service
- TProtocol* = enum ## third argument to `socket` proc
+ Protocol* = enum ## third argument to `socket` proc
IPPROTO_TCP = 6, ## Transmission control protocol.
IPPROTO_UDP = 17, ## User datagram protocol.
IPPROTO_IP, ## Internet protocol. Unsupported on Windows.
@@ -63,19 +63,22 @@ type
IPPROTO_RAW, ## Raw IP Packets Protocol. Unsupported on Windows.
IPPROTO_ICMP ## Control message protocol. Unsupported on Windows.
- TServent* {.pure, final.} = object ## information about a service
+ Servent* = object ## information about a service
name*: string
aliases*: seq[string]
- port*: TPort
+ port*: Port
proto*: string
- Thostent* {.pure, final.} = object ## information about a given host
+ Hostent* = object ## information about a given host
name*: string
aliases*: seq[string]
- addrtype*: TDomain
+ addrtype*: Domain
length*: int
addrList*: seq[string]
+{.deprecated: [TPort: Port, TDomain: Domain, TType: SockType,
+ TProtocol: Protocol, TServent: Servent, THostent: Hostent].}
+
when useWinVersion:
let
osInvalidSocket* = winlean.INVALID_SOCKET
@@ -86,37 +89,37 @@ when useWinVersion:
FIONBIO* = IOC_IN.int32 or ((sizeof(int32) and IOCPARM_MASK) shl 16) or
(102 shl 8) or 126
- proc ioctlsocket*(s: TSocketHandle, cmd: clong,
+ proc ioctlsocket*(s: SocketHandle, cmd: clong,
argptr: ptr clong): cint {.
stdcall, importc: "ioctlsocket", dynlib: "ws2_32.dll".}
else:
let
osInvalidSocket* = posix.INVALID_SOCKET
-proc `==`*(a, b: TPort): bool {.borrow.}
+proc `==`*(a, b: Port): bool {.borrow.}
## ``==`` for ports.
-proc `$`*(p: TPort): string {.borrow.}
+proc `$`*(p: Port): string {.borrow.}
## returns the port number as a string
-proc toInt*(domain: TDomain): cint
+proc toInt*(domain: Domain): cint
## Converts the TDomain enum to a platform-dependent ``cint``.
-proc toInt*(typ: TType): cint
+proc toInt*(typ: SockType): cint
## Converts the TType enum to a platform-dependent ``cint``.
-proc toInt*(p: TProtocol): cint
+proc toInt*(p: Protocol): cint
## Converts the TProtocol enum to a platform-dependent ``cint``.
when not useWinVersion:
- proc toInt(domain: TDomain): cint =
+ proc toInt(domain: Domain): cint =
case domain
of AF_UNIX: result = posix.AF_UNIX
of AF_INET: result = posix.AF_INET
of AF_INET6: result = posix.AF_INET6
else: discard
- proc toInt(typ: TType): cint =
+ proc toInt(typ: SockType): cint =
case typ
of SOCK_STREAM: result = posix.SOCK_STREAM
of SOCK_DGRAM: result = posix.SOCK_DGRAM
@@ -124,7 +127,7 @@ when not useWinVersion:
of SOCK_RAW: result = posix.SOCK_RAW
else: discard
- proc toInt(p: TProtocol): cint =
+ proc toInt(p: Protocol): cint =
case p
of IPPROTO_TCP: result = posix.IPPROTO_TCP
of IPPROTO_UDP: result = posix.IPPROTO_UDP
@@ -135,22 +138,22 @@ when not useWinVersion:
else: discard
else:
- proc toInt(domain: TDomain): cint =
+ proc toInt(domain: Domain): cint =
result = toU16(ord(domain))
- proc toInt(typ: TType): cint =
+ proc toInt(typ: SockType): cint =
result = cint(ord(typ))
- proc toInt(p: TProtocol): cint =
+ proc toInt(p: Protocol): cint =
result = cint(ord(p))
-proc newRawSocket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM,
- protocol: TProtocol = IPPROTO_TCP): TSocketHandle =
+proc newRawSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM,
+ protocol: Protocol = IPPROTO_TCP): SocketHandle =
## Creates a new socket; returns `InvalidSocket` if an error occurs.
socket(toInt(domain), toInt(typ), toInt(protocol))
-proc close*(socket: TSocketHandle) =
+proc close*(socket: SocketHandle) =
## closes a socket.
when useWinVersion:
discard winlean.closeSocket(socket)
@@ -159,10 +162,10 @@ proc close*(socket: TSocketHandle) =
# TODO: These values should not be discarded. An EOS should be raised.
# http://stackoverflow.com/questions/12463473/what-happens-if-you-call-close-on-a-bsd-socket-multiple-times
-proc bindAddr*(socket: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint =
+proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint =
result = bindSocket(socket, name, namelen)
-proc listen*(socket: TSocketHandle, backlog = SOMAXCONN): cint {.tags: [FReadIO].} =
+proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [FReadIO].} =
## Marks ``socket`` as accepting connections.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
@@ -171,12 +174,12 @@ proc listen*(socket: TSocketHandle, backlog = SOMAXCONN): cint {.tags: [FReadIO]
else:
result = posix.listen(socket, cint(backlog))
-proc getAddrInfo*(address: string, port: TPort, af: TDomain = AF_INET, typ: TType = SOCK_STREAM,
- prot: TProtocol = IPPROTO_TCP): ptr TAddrInfo =
+proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockType = SOCK_STREAM,
+ prot: Protocol = IPPROTO_TCP): ptr AddrInfo =
##
##
## **Warning**: The resulting ``ptr TAddrInfo`` must be freed using ``dealloc``!
- var hints: TAddrInfo
+ var hints: AddrInfo
result = nil
hints.ai_family = toInt(af)
hints.ai_socktype = toInt(typ)
@@ -184,11 +187,11 @@ proc getAddrInfo*(address: string, port: TPort, af: TDomain = AF_INET, typ: TTyp
var gaiResult = getAddrInfo(address, $port, addr(hints), result)
if gaiResult != 0'i32:
when useWinVersion:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
raise newException(EOS, $gai_strerror(gaiResult))
-proc dealloc*(ai: ptr TAddrInfo) =
+proc dealloc*(ai: ptr AddrInfo) =
freeaddrinfo(ai)
proc ntohl*(x: int32): int32 =
@@ -220,7 +223,7 @@ proc htons*(x: int16): int16 =
## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
result = rawsockets.ntohs(x)
-proc getServByName*(name, proto: string): TServent {.tags: [FReadIO].} =
+proc getServByName*(name, proto: string): Servent {.tags: [FReadIO].} =
## Searches the database from the beginning and finds the first entry for
## which the service name specified by ``name`` matches the s_name member
## and the protocol name specified by ``proto`` matches the s_proto member.
@@ -233,10 +236,10 @@ proc getServByName*(name, proto: string): TServent {.tags: [FReadIO].} =
if s == nil: raise newException(EOS, "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
- result.port = TPort(s.s_port)
+ result.port = Port(s.s_port)
result.proto = $s.s_proto
-proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} =
+proc getServByPort*(port: Port, proto: string): Servent {.tags: [FReadIO].} =
## Searches the database from the beginning and finds the first entry for
## which the port specified by ``port`` matches the s_port member and the
## protocol name specified by ``proto`` matches the s_proto member.
@@ -249,28 +252,28 @@ proc getServByPort*(port: TPort, proto: string): TServent {.tags: [FReadIO].} =
if s == nil: raise newException(EOS, "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
- result.port = TPort(s.s_port)
+ result.port = Port(s.s_port)
result.proto = $s.s_proto
-proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
+proc getHostByAddr*(ip: string): Hostent {.tags: [FReadIO].} =
## This function will lookup the hostname of an IP Address.
- var myaddr: TInAddr
+ var myaddr: InAddr
myaddr.s_addr = inet_addr(ip)
when useWinVersion:
var s = winlean.gethostbyaddr(addr(myaddr), sizeof(myaddr).cuint,
cint(rawsockets.AF_INET))
- if s == nil: osError(osLastError())
+ if s == nil: raiseOSError(osLastError())
else:
- var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).TSocklen,
+ var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen,
cint(posix.AF_INET))
if s == nil:
raise newException(EOS, $hstrerror(h_errno))
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
- when useWinVersion:
- result.addrtype = TDomain(s.h_addrtype)
+ when useWinVersion:
+ result.addrtype = Domain(s.h_addrtype)
else:
if s.h_addrtype == posix.AF_INET:
result.addrtype = AF_INET
@@ -281,17 +284,17 @@ proc getHostByAddr*(ip: string): Thostent {.tags: [FReadIO].} =
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
-proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
+proc getHostByName*(name: string): Hostent {.tags: [FReadIO].} =
## This function will lookup the IP address of a hostname.
when useWinVersion:
var s = winlean.gethostbyname(name)
else:
var s = posix.gethostbyname(name)
- if s == nil: osError(osLastError())
+ if s == nil: raiseOSError(osLastError())
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
- when useWinVersion:
- result.addrtype = TDomain(s.h_addrtype)
+ when useWinVersion:
+ result.addrtype = Domain(s.h_addrtype)
else:
if s.h_addrtype == posix.AF_INET:
result.addrtype = AF_INET
@@ -302,69 +305,69 @@ proc getHostByName*(name: string): Thostent {.tags: [FReadIO].} =
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
-proc getSockName*(socket: TSocketHandle): TPort =
+proc getSockName*(socket: SocketHandle): Port =
## returns the socket's associated port number.
- var name: Tsockaddr_in
+ var name: Sockaddr_in
when useWinVersion:
name.sin_family = int16(ord(AF_INET))
else:
name.sin_family = posix.AF_INET
#name.sin_port = htons(cint16(port))
#name.sin_addr.s_addr = htonl(INADDR_ANY)
- var namelen = sizeof(name).TSocklen
- if getsockname(socket, cast[ptr TSockAddr](addr(name)),
+ var namelen = sizeof(name).Socklen
+ if getsockname(socket, cast[ptr SockAddr](addr(name)),
addr(namelen)) == -1'i32:
- osError(osLastError())
- result = TPort(rawsockets.ntohs(name.sin_port))
+ raiseOSError(osLastError())
+ result = Port(rawsockets.ntohs(name.sin_port))
-proc getSockOptInt*(socket: TSocketHandle, level, optname: int): int {.
+proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
tags: [FReadIO].} =
## getsockopt for integer options.
var res: cint
- var size = sizeof(res).TSocklen
+ var size = sizeof(res).Socklen
if getsockopt(socket, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
result = int(res)
-proc setSockOptInt*(socket: TSocketHandle, level, optname, optval: int) {.
+proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {.
tags: [FWriteIO].} =
## setsockopt for integer options.
var value = cint(optval)
if setsockopt(socket, cint(level), cint(optname), addr(value),
- sizeof(value).TSocklen) < 0'i32:
- osError(osLastError())
+ sizeof(value).Socklen) < 0'i32:
+ raiseOSError(osLastError())
-proc setBlocking*(s: TSocketHandle, blocking: bool) =
+proc setBlocking*(s: SocketHandle, blocking: bool) =
## Sets blocking mode on socket.
##
## Raises EOS on error.
when useWinVersion:
var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
if ioctlsocket(s, FIONBIO, addr(mode)) == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
else: # BSD sockets
var x: int = fcntl(s, F_GETFL, 0)
if x == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
var mode = if blocking: x and not O_NONBLOCK else: x or O_NONBLOCK
if fcntl(s, F_SETFL, mode) == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
-proc timeValFromMilliseconds(timeout = 500): Ttimeval =
+proc timeValFromMilliseconds(timeout = 500): Timeval =
if timeout != -1:
var seconds = timeout div 1000
result.tv_sec = seconds.int32
result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
-proc createFdSet(fd: var TFdSet, s: seq[TSocketHandle], m: var int) =
+proc createFdSet(fd: var FdSet, s: seq[SocketHandle], m: var int) =
FD_ZERO(fd)
for i in items(s):
m = max(m, int(i))
FD_SET(i, fd)
-proc pruneSocketSet(s: var seq[TSocketHandle], fd: var TFdSet) =
+proc pruneSocketSet(s: var seq[SocketHandle], fd: var FdSet) =
var i = 0
var L = s.len
while i < L:
@@ -375,7 +378,7 @@ proc pruneSocketSet(s: var seq[TSocketHandle], fd: var TFdSet) =
inc(i)
setLen(s, L)
-proc select*(readfds: var seq[TSocketHandle], timeout = 500): int =
+proc select*(readfds: var seq[SocketHandle], timeout = 500): int =
## Traditional select function. This function will return the number of
## sockets that are ready to be read from, written to, or which have errors.
## If there are none; 0 is returned.
@@ -396,7 +399,7 @@ proc select*(readfds: var seq[TSocketHandle], timeout = 500): int =
pruneSocketSet(readfds, (rd))
-proc selectWrite*(writefds: var seq[TSocketHandle],
+proc selectWrite*(writefds: var seq[SocketHandle],
timeout = 500): int {.tags: [FReadIO].} =
## When a socket in ``writefds`` is ready to be written to then a non-zero
## value will be returned specifying the count of the sockets which can be
@@ -405,7 +408,7 @@ proc selectWrite*(writefds: var seq[TSocketHandle],
##
## ``timeout`` is specified in miliseconds and ``-1`` can be specified for
## an unlimited time.
- var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
+ var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
var wr: TFdSet
var m = 0
@@ -419,5 +422,5 @@ proc selectWrite*(writefds: var seq[TSocketHandle],
pruneSocketSet(writefds, (wr))
when defined(Windows):
- var wsa: TWSADATA
- if WSAStartup(0x0101'i16, addr wsa) != 0: osError(osLastError())
+ var wsa: WSADATA
+ if WSAStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())
diff --git a/lib/pure/redis.nim b/lib/pure/redis.nim
index 959f5c6ef..ab3b81f37 100644
--- a/lib/pure/redis.nim
+++ b/lib/pure/redis.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -20,36 +20,40 @@ const
redisNil* = "\0\0"
type
- PPipeline = ref object
+ Pipeline = ref object
enabled: bool
buffer: string
expected: int ## number of replies expected if pipelined
type
- TSendMode = enum
+ SendMode = enum
normal, pipelined, multiple
type
- TRedis* {.pure, final.} = object
+ Redis* = object
socket: TSocket
connected: bool
- pipeline: PPipeline
+ pipeline: Pipeline
- TRedisStatus* = string
- TRedisInteger* = biggestInt
- TRedisString* = string ## Bulk reply
- TRedisList* = seq[TRedisString] ## Multi-bulk reply
+ RedisStatus* = string
+ RedisInteger* = BiggestInt
+ RedisString* = string ## Bulk reply
+ RedisList* = seq[RedisString] ## Multi-bulk reply
- EInvalidReply* = object of ESynch ## Invalid reply from redis
- ERedis* = object of ESynch ## Error in redis
+ ReplyError* = object of IOError ## Invalid reply from redis
+ RedisError* = object of IOError ## Error in redis
-proc newPipeline(): PPipeline =
+{.deprecated: [TSendMode: SendMode, TRedis: Redis, TRedisStatus: RedisStatus,
+ TRedisInteger: RedisInteger, TRedisString: RedisString,
+ TRedisList: RedistList, EInvalidReply: ReplyError, ERedis: RedisError].}
+
+proc newPipeline(): Pipeline =
new(result)
result.buffer = ""
result.enabled = false
result.expected = 0
-proc open*(host = "localhost", port = 6379.TPort): TRedis =
+proc open*(host = "localhost", port = 6379.Port): Redis =
## Opens a connection to the redis server.
result.socket = socket(buffered = false)
if result.socket == InvalidSocket:
@@ -58,24 +62,24 @@ proc open*(host = "localhost", port = 6379.TPort): TRedis =
result.pipeline = newPipeline()
proc raiseInvalidReply(expected, got: char) =
- raise newException(EInvalidReply,
+ raise newException(ReplyError,
"Expected '$1' at the beginning of a status reply got '$2'" %
[$expected, $got])
-proc raiseNoOK(status: string, pipelineEnabled:bool) =
+proc raiseNoOK(status: string, pipelineEnabled: bool) =
if pipelineEnabled and not (status == "QUEUED" or status == "PIPELINED"):
raise newException(EInvalidReply, "Expected \"QUEUED\" or \"PIPELINED\" got \"$1\"" % status)
elif not pipelineEnabled and status != "OK":
raise newException(EInvalidReply, "Expected \"OK\" got \"$1\"" % status)
-template readSocket(r: TRedis, dummyVal:expr): stmt =
- var line {.inject.} :TaintedString = ""
+template readSocket(r: Redis, dummyVal:expr): stmt =
+ var line {.inject.}: TaintedString = ""
if r.pipeline.enabled:
return dummyVal
else:
readLine(r.socket, line)
-proc parseStatus(r: TRedis, line: string = ""): TRedisStatus =
+proc parseStatus(r: Redis, line: string = ""): RedisStatus =
if r.pipeline.enabled:
return "PIPELINED"
diff --git a/lib/pure/romans.nim b/lib/pure/romans.nim
index dee3226d8..79fb75526 100644
--- a/lib/pure/romans.nim
+++ b/lib/pure/romans.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2011 Philippe Lhoste
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/ropes.nim b/lib/pure/ropes.nim
index eb3792bce..8205203ba 100644
--- a/lib/pure/ropes.nim
+++ b/lib/pure/ropes.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -30,13 +30,15 @@ var
cacheEnabled = false
type
- PRope* = ref TRope ## empty rope is represented by nil
- TRope {.acyclic, final, pure.} = object
- left, right: PRope
+ Rope* = ref RopeObj ## empty rope is represented by nil
+ RopeObj {.acyclic.} = object
+ left, right: Rope
length: int
data: string # != nil if a leaf
-proc isConc(r: PRope): bool {.inline.} = return isNil(r.data)
+{.deprecated: [PRope: Rope].}
+
+proc isConc(r: Rope): bool {.inline.} = return isNil(r.data)
# Note that the left and right pointers are not needed for leafs.
# Leaves have relatively high memory overhead (~30 bytes on a 32
@@ -46,25 +48,25 @@ proc isConc(r: PRope): bool {.inline.} = return isNil(r.data)
# performance. But for the caching tree we use the leaf's left and right
# pointers.
-proc len*(a: PRope): int {.rtl, extern: "nro$1".} =
+proc len*(a: Rope): int {.rtl, extern: "nro$1".} =
## the rope's length
if a == nil: result = 0
else: result = a.length
-proc newRope(): PRope = new(result)
-proc newRope(data: string): PRope =
+proc newRope(): Rope = new(result)
+proc newRope(data: string): Rope =
new(result)
result.length = len(data)
result.data = data
var
- cache {.threadvar.}: PRope # the root of the cache tree
- N {.threadvar.}: PRope # dummy rope needed for splay algorithm
+ cache {.threadvar.}: Rope # the root of the cache tree
+ N {.threadvar.}: Rope # dummy rope needed for splay algorithm
when countCacheMisses:
var misses, hits: int
-proc splay(s: string, tree: PRope, cmpres: var int): PRope =
+proc splay(s: string, tree: Rope, cmpres: var int): Rope =
var c: int
var t = tree
N.left = nil
@@ -102,7 +104,7 @@ proc splay(s: string, tree: PRope, cmpres: var int): PRope =
t.right = N.left
result = t
-proc insertInCache(s: string, tree: PRope): PRope =
+proc insertInCache(s: string, tree: Rope): Rope =
var t = tree
if t == nil:
result = newRope(s)
@@ -128,7 +130,7 @@ proc insertInCache(s: string, tree: PRope): PRope =
result.left = t
t.right = nil
-proc rope*(s: string): PRope {.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
@@ -138,11 +140,11 @@ proc rope*(s: string): PRope {.rtl, extern: "nro$1Str".} =
else:
result = newRope(s)
-proc rope*(i: BiggestInt): PRope {.rtl, extern: "nro$1BiggestInt".} =
+proc rope*(i: BiggestInt): Rope {.rtl, extern: "nro$1BiggestInt".} =
## Converts an int to a rope.
result = rope($i)
-proc rope*(f: BiggestFloat): PRope {.rtl, extern: "nro$1BiggestFloat".} =
+proc rope*(f: BiggestFloat): Rope {.rtl, extern: "nro$1BiggestFloat".} =
## Converts a float to a rope.
result = rope($f)
@@ -156,7 +158,7 @@ proc disableCache*() {.rtl, extern: "nro$1".} =
cache = nil
cacheEnabled = false
-proc `&`*(a, b: PRope): PRope {.rtl, extern: "nroConcRopeRope".} =
+proc `&`*(a, b: Rope): Rope {.rtl, extern: "nroConcRopeRope".} =
## the concatenation operator for ropes.
if a == nil:
result = b
@@ -176,27 +178,27 @@ proc `&`*(a, b: PRope): PRope {.rtl, extern: "nroConcRopeRope".} =
result.left = a
result.right = b
-proc `&`*(a: PRope, b: string): PRope {.rtl, extern: "nroConcRopeStr".} =
+proc `&`*(a: Rope, b: string): Rope {.rtl, extern: "nroConcRopeStr".} =
## the concatenation operator for ropes.
result = a & rope(b)
-proc `&`*(a: string, b: PRope): PRope {.rtl, extern: "nroConcStrRope".} =
+proc `&`*(a: string, b: Rope): Rope {.rtl, extern: "nroConcStrRope".} =
## the concatenation operator for ropes.
result = rope(a) & b
-proc `&`*(a: openarray[PRope]): PRope {.rtl, extern: "nroConcOpenArray".} =
+proc `&`*(a: openarray[Rope]): Rope {.rtl, extern: "nroConcOpenArray".} =
## the concatenation operator for an openarray of ropes.
for i in countup(0, high(a)): result = result & a[i]
-proc add*(a: var PRope, b: PRope) {.rtl, extern: "nro$1Rope".} =
+proc add*(a: var Rope, b: Rope) {.rtl, extern: "nro$1Rope".} =
## adds `b` to the rope `a`.
a = a & b
-proc add*(a: var PRope, b: string) {.rtl, extern: "nro$1Str".} =
+proc add*(a: var Rope, b: string) {.rtl, extern: "nro$1Str".} =
## adds `b` to the rope `a`.
a = a & b
-proc `[]`*(r: PRope, i: int): char {.rtl, extern: "nroCharAt".} =
+proc `[]`*(r: Rope, i: int): char {.rtl, extern: "nroCharAt".} =
## returns the character at position `i` in the rope `r`. This is quite
## expensive! Worst-case: O(n). If ``i >= r.len``, ``\0`` is returned.
var x = r
@@ -213,7 +215,7 @@ proc `[]`*(r: PRope, i: int): char {.rtl, extern: "nroCharAt".} =
x = x.right
dec(j, x.len)
-iterator leaves*(r: PRope): string =
+iterator leaves*(r: Rope): string =
## iterates over any leaf string in the rope `r`.
if r != nil:
var stack = @[r]
@@ -226,16 +228,16 @@ iterator leaves*(r: PRope): string =
assert(it.data != nil)
yield it.data
-iterator items*(r: PRope): char =
+iterator items*(r: Rope): char =
## iterates over any character in the rope `r`.
for s in leaves(r):
for c in items(s): yield c
-proc write*(f: TFile, r: PRope) {.rtl, extern: "nro$1".} =
+proc write*(f: TFile, r: Rope) {.rtl, extern: "nro$1".} =
## writes a rope to a file.
for s in leaves(r): write(f, s)
-proc `$`*(r: PRope): string {.rtl, extern: "nroToString".}=
+proc `$`*(r: Rope): string {.rtl, extern: "nroToString".}=
## converts a rope back to a string.
result = newString(r.len)
setLen(result, 0)
@@ -245,11 +247,11 @@ 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): PRope =
+ proc compiledArg(idx: int): Rope =
new(result)
result.length = -idx
- proc compileFrmt(frmt: string): PRope =
+ proc compileFrmt(frmt: string): Rope =
var i = 0
var length = len(frmt)
result = nil
@@ -289,7 +291,7 @@ when false:
if i - 1 >= start:
add(result, substr(frmt, start, i-1))
-proc `%`*(frmt: string, args: openarray[PRope]): PRope {.
+proc `%`*(frmt: string, args: openarray[Rope]): Rope {.
rtl, extern: "nroFormat".} =
## `%` substitution operator for ropes. Does not support the ``$identifier``
## nor ``${identifier}`` notations.
@@ -332,12 +334,12 @@ proc `%`*(frmt: string, args: openarray[PRope]): PRope {.
if i - 1 >= start:
add(result, substr(frmt, start, i - 1))
-proc addf*(c: var PRope, frmt: string, args: openarray[PRope]) {.
+proc addf*(c: var Rope, frmt: string, args: openarray[Rope]) {.
rtl, extern: "nro$1".} =
## shortcut for ``add(c, frmt % args)``.
add(c, frmt % args)
-proc equalsFile*(r: PRope, f: TFile): bool {.rtl, extern: "nro$1File".} =
+proc equalsFile*(r: Rope, f: TFile): bool {.rtl, extern: "nro$1File".} =
## returns true if the contents of the file `f` equal `r`.
var bufSize = 1024 # reasonable start value
var buf = alloc(BufSize)
@@ -352,7 +354,7 @@ proc equalsFile*(r: PRope, f: TFile): bool {.rtl, extern: "nro$1File".} =
result = readBuffer(f, buf, 1) == 0 # really at the end of file?
dealloc(buf)
-proc equalsFile*(r: PRope, f: string): bool {.rtl, extern: "nro$1Str".} =
+proc equalsFile*(r: Rope, f: string): bool {.rtl, extern: "nro$1Str".} =
## returns true if the contents of the file `f` equal `r`. If `f` does not
## exist, false is returned.
var bin: TFile
diff --git a/lib/pure/scgi.nim b/lib/pure/scgi.nim
index 45f837833..fa8605a69 100644
--- a/lib/pure/scgi.nim
+++ b/lib/pure/scgi.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Andreas Rumpf, Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -9,13 +9,13 @@
## This module implements helper procs for SCGI applications. Example:
##
-## .. code-block:: Nimrod
+## .. code-block:: Nim
##
## import strtabs, sockets, scgi
##
## var counter = 0
-## proc handleRequest(client: TSocket, input: string,
-## headers: PStringTable): bool {.procvar.} =
+## proc handleRequest(client: Socket, input: string,
+## headers: StringTableRef): bool {.procvar.} =
## inc(counter)
## client.writeStatusOkTextContent()
## client.send("Hello for the $#th time." % $counter & "\c\L")
@@ -31,11 +31,11 @@ include "system/inclrtl"
import sockets, strutils, os, strtabs, asyncio
type
- EScgi* = object of EIO ## the exception that is raised, if a SCGI error occurs
+ ScgiError* = object of IOError ## the exception that is raised, if a SCGI error occurs
-proc scgiError*(msg: string) {.noreturn.} =
- ## raises an EScgi exception with message `msg`.
- var e: ref EScgi
+proc raiseScgiError*(msg: string) {.noreturn.} =
+ ## raises an ScgiError exception with message `msg`.
+ var e: ref ScgiError
new(e)
e.msg = msg
raise e
@@ -45,7 +45,7 @@ proc parseWord(inp: string, outp: var string, start: int): int =
while inp[result] != '\0': inc(result)
outp = substr(inp, start, result-1)
-proc parseHeaders(s: string, L: int): PStringTable =
+proc parseHeaders(s: string, L: int): StringTableRef =
result = newStringTable()
var i = 0
while i < L:
@@ -54,73 +54,77 @@ proc parseHeaders(s: string, L: int): PStringTable =
i = parseWord(s, val, i)+1
result[key] = val
if s[i] == ',': inc(i)
- else: scgiError("',' after netstring expected")
+ else: raiseScgiError("',' after netstring expected")
-proc recvChar(s: TSocket): char =
+proc recvChar(s: Socket): char =
var c: char
if recv(s, addr(c), sizeof(c)) == sizeof(c):
result = c
type
- TScgiState* = object of TObject ## SCGI state object
- server: TSocket
+ ScgiState* = object of RootObj ## SCGI state object
+ server: Socket
bufLen: int
- client*: TSocket ## the client socket to send data to
- headers*: PStringTable ## the parsed headers
+ client*: Socket ## the client socket to send data to
+ headers*: StringTableRef ## the parsed headers
input*: string ## the input buffer
# Async
- TClientMode = enum
+ ClientMode = enum
ClientReadChar, ClientReadHeaders, ClientReadContent
- PAsyncClient = ref object
- c: PAsyncSocket
- mode: TClientMode
+ AsyncClient = ref object
+ c: AsyncSocket
+ mode: ClientMode
dataLen: int
headers: PStringTable ## the parsed headers
input: string ## the input buffer
- TAsyncScgiState = object
- handleRequest: proc (client: PAsyncSocket,
- input: string, headers: PStringTable) {.closure,gcsafe.}
- asyncServer: PAsyncSocket
- disp: PDispatcher
- PAsyncScgiState* = ref TAsyncScgiState
-
-proc recvBuffer(s: var TScgiState, L: int) =
+ AsyncScgiStateObj = object
+ handleRequest: proc (client: AsyncSocket,
+ input: string,
+ headers: StringTableRef) {.closure, gcsafe.}
+ asyncServer: AsyncSocket
+ disp: Dispatcher
+ AsyncScgiState* = ref AsyncScgiStateObj
+
+{.deprected: [EScgi: ScgiError, TScgiState: ScgiState,
+ PAsyncScgiState: AsyncScgiState, scgiError: raiseScgiError].}
+
+proc recvBuffer(s: var ScgiState, L: int) =
if L > s.bufLen:
s.bufLen = L
s.input = newString(L)
if L > 0 and recv(s.client, cstring(s.input), L) != L:
- scgiError("could not read all data")
+ raiseScgiError("could not read all data")
setLen(s.input, L)
-proc open*(s: var TScgiState, port = TPort(4000), address = "127.0.0.1",
- reuseAddr = False) =
+proc open*(s: var ScgiState, port = Port(4000), address = "127.0.0.1",
+ reuseAddr = false) =
## opens a connection.
s.bufLen = 4000
s.input = newString(s.buflen) # will be reused
s.server = socket()
- if s.server == InvalidSocket: osError(osLastError())
+ if s.server == InvalidSocket: raiseOSError(osLastError())
new(s.client) # Initialise s.client for `next`
- if s.server == InvalidSocket: scgiError("could not open socket")
+ if s.server == InvalidSocket: raiseScgiError("could not open socket")
#s.server.connect(connectionName, port)
if reuseAddr:
s.server.setSockOpt(OptReuseAddr, True)
bindAddr(s.server, port, address)
listen(s.server)
-proc close*(s: var TScgiState) =
+proc close*(s: var ScgiState) =
## closes the connection.
s.server.close()
-proc next*(s: var TScgistate, timeout: int = -1): bool =
+proc next*(s: var ScgiState, timeout: int = -1): bool =
## proceed to the first/next request. Waits ``timeout`` miliseconds for a
## request, if ``timeout`` is `-1` then this function will never time out.
- ## Returns `True` if a new request has been processed.
+ ## Returns `true` if a new request has been processed.
var rsocks = @[s.server]
if select(rsocks, timeout) == 1 and rsocks.len == 1:
new(s.client)
@@ -132,17 +136,17 @@ proc next*(s: var TScgistate, timeout: int = -1): bool =
s.client.close()
return false
if d notin strutils.digits:
- if d != ':': scgiError("':' after length expected")
+ if d != ':': raiseScgiError("':' after length expected")
break
L = L * 10 + ord(d) - ord('0')
recvBuffer(s, L+1)
s.headers = parseHeaders(s.input, L)
- if s.headers["SCGI"] != "1": scgiError("SCGI Version 1 expected")
+ if s.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected")
L = parseInt(s.headers["CONTENT_LENGTH"])
recvBuffer(s, L)
return True
-proc writeStatusOkTextContent*(c: TSocket, contentType = "text/html") =
+proc writeStatusOkTextContent*(c: Socket, contentType = "text/html") =
## sends the following string to the socket `c`::
##
## Status: 200 OK\r\LContent-Type: text/html\r\L\r\L
@@ -151,11 +155,11 @@ proc writeStatusOkTextContent*(c: TSocket, contentType = "text/html") =
c.send("Status: 200 OK\r\L" &
"Content-Type: $1\r\L\r\L" % contentType)
-proc run*(handleRequest: proc (client: TSocket, input: string,
- headers: PStringTable): bool {.nimcall,gcsafe.},
- port = TPort(4000)) =
+proc run*(handleRequest: proc (client: Socket, input: string,
+ headers: StringTableRef): bool {.nimcall,gcsafe.},
+ port = Port(4000)) =
## encapsulates the SCGI object and main loop.
- var s: TScgiState
+ var s: ScgiState
s.open(port)
var stop = false
while not stop:
@@ -166,11 +170,11 @@ proc run*(handleRequest: proc (client: TSocket, input: string,
# -- AsyncIO start
-proc recvBufferAsync(client: PAsyncClient, L: int): TReadLineResult =
+proc recvBufferAsync(client: AsyncClient, L: int): ReadLineResult =
result = ReadPartialLine
var data = ""
if L < 1:
- scgiError("Cannot read negative or zero length: " & $L)
+ raiseScgiError("Cannot read negative or zero length: " & $L)
let ret = recvAsync(client.c, data, L)
if ret == 0 and data == "":
client.c.close()
@@ -181,16 +185,16 @@ proc recvBufferAsync(client: PAsyncClient, L: int): TReadLineResult =
if ret == L:
return ReadFullLine
-proc checkCloseSocket(client: PAsyncClient) =
+proc checkCloseSocket(client: AsyncClient) =
if not client.c.isClosed:
if client.c.isSendDataBuffered:
- client.c.setHandleWrite do (s: PAsyncSocket):
+ client.c.setHandleWrite do (s: AsyncSocket):
if not s.isClosed and not s.isSendDataBuffered:
s.close()
s.delHandleWrite()
else: client.c.close()
-proc handleClientRead(client: PAsyncClient, s: PAsyncScgiState) =
+proc handleClientRead(client: AsyncClient, s: AsyncScgiState) =
case client.mode
of ClientReadChar:
while true:
@@ -203,7 +207,7 @@ proc handleClientRead(client: PAsyncClient, s: PAsyncScgiState) =
if ret == -1:
return # No more data available
if d[0] notin strutils.digits:
- if d[0] != ':': scgiError("':' after length expected")
+ if d[0] != ':': raiseScgiError("':' after length expected")
break
client.dataLen = client.dataLen * 10 + ord(d[0]) - ord('0')
client.mode = ClientReadHeaders
@@ -213,7 +217,7 @@ proc handleClientRead(client: PAsyncClient, s: PAsyncScgiState) =
case ret
of ReadFullLine:
client.headers = parseHeaders(client.input, client.input.len-1)
- if client.headers["SCGI"] != "1": scgiError("SCGI Version 1 expected")
+ if client.headers["SCGI"] != "1": raiseScgiError("SCGI Version 1 expected")
client.input = "" # For next part
let contentLen = parseInt(client.headers["CONTENT_LENGTH"])
@@ -236,50 +240,50 @@ proc handleClientRead(client: PAsyncClient, s: PAsyncScgiState) =
s.handleRequest(client.c, client.input, client.headers)
checkCloseSocket(client)
-proc handleAccept(sock: PAsyncSocket, s: PAsyncScgiState) =
- var client: PAsyncSocket
+proc handleAccept(sock: AsyncSocket, s: AsyncScgiState) =
+ var client: AsyncSocket
new(client)
accept(s.asyncServer, client)
- var asyncClient = PAsyncClient(c: client, mode: ClientReadChar, dataLen: 0,
+ var asyncClient = AsyncClient(c: client, mode: ClientReadChar, dataLen: 0,
headers: newStringTable(), input: "")
client.handleRead =
- proc (sock: PAsyncSocket) =
+ proc (sock: AsyncSocket) =
handleClientRead(asyncClient, s)
s.disp.register(client)
-proc open*(handleRequest: proc (client: PAsyncSocket,
- input: string, headers: PStringTable) {.
+proc open*(handleRequest: proc (client: AsyncSocket,
+ input: string, headers: StringTableRef) {.
closure, gcsafe.},
- port = TPort(4000), address = "127.0.0.1",
- reuseAddr = false): PAsyncScgiState =
- ## Creates an ``PAsyncScgiState`` object which serves as a SCGI server.
+ port = Port(4000), address = "127.0.0.1",
+ reuseAddr = false): AsyncScgiState =
+ ## Creates an ``AsyncScgiState`` object which serves as a SCGI server.
##
## After the execution of ``handleRequest`` the client socket will be closed
## automatically unless it has already been closed.
- var cres: PAsyncScgiState
+ var cres: AsyncScgiState
new(cres)
cres.asyncServer = AsyncSocket()
- cres.asyncServer.handleAccept = proc (s: PAsyncSocket) = handleAccept(s, cres)
+ cres.asyncServer.handleAccept = proc (s: AsyncSocket) = handleAccept(s, cres)
if reuseAddr:
- cres.asyncServer.setSockOpt(OptReuseAddr, True)
+ cres.asyncServer.setSockOpt(OptReuseAddr, true)
bindAddr(cres.asyncServer, port, address)
listen(cres.asyncServer)
cres.handleRequest = handleRequest
result = cres
-proc register*(d: PDispatcher, s: PAsyncScgiState): PDelegate {.discardable.} =
+proc register*(d: Dispatcher, s: AsyncScgiState): Delegate {.discardable.} =
## Registers ``s`` with dispatcher ``d``.
result = d.register(s.asyncServer)
s.disp = d
-proc close*(s: PAsyncScgiState) =
- ## Closes the ``PAsyncScgiState``.
+proc close*(s: AsyncScgiState) =
+ ## Closes the ``AsyncScgiState``.
s.asyncServer.close()
when false:
var counter = 0
- proc handleRequest(client: TSocket, input: string,
- headers: PStringTable): bool {.procvar.} =
+ proc handleRequest(client: Socket, input: string,
+ headers: StringTableRef): bool {.procvar.} =
inc(counter)
client.writeStatusOkTextContent()
client.send("Hello for the $#th time." % $counter & "\c\L")
diff --git a/lib/pure/selectors.nim b/lib/pure/selectors.nim
index bd53c2dbf..33939537a 100644
--- a/lib/pure/selectors.nim
+++ b/lib/pure/selectors.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -18,57 +18,57 @@ elif defined(windows):
else:
import posix
-proc hash*(x: TSocketHandle): THash {.borrow.}
-proc `$`*(x: TSocketHandle): string {.borrow.}
+proc hash*(x: SocketHandle): THash {.borrow.}
+proc `$`*(x: SocketHandle): string {.borrow.}
type
- TEvent* = enum
+ Event* = enum
EvRead, EvWrite
- PSelectorKey* = ref object
- fd*: TSocketHandle
- events*: set[TEvent] ## The events which ``fd`` listens for.
- data*: PObject ## User object.
+ SelectorKey* = ref object
+ fd*: SocketHandle
+ events*: set[Event] ## The events which ``fd`` listens for.
+ data*: RootRef ## User object.
- TReadyInfo* = tuple[key: PSelectorKey, events: set[TEvent]]
+ ReadyInfo* = tuple[key: SelectorKey, events: set[Event]]
when defined(nimdoc):
type
- PSelector* = ref object
+ Selector* = ref object
## An object which holds file descripters to be checked for read/write
## status.
- fds: TTable[TSocketHandle, PSelectorKey]
+ fds: Table[SocketHandle, SelectorKey]
- proc register*(s: PSelector, fd: TSocketHandle, events: set[TEvent],
- data: PObject): PSelectorKey {.discardable.} =
+ proc register*(s: Selector, fd: SocketHandle, events: set[Event],
+ data: RootRef): SelectorKey {.discardable.} =
## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent
## ``events``.
- proc update*(s: PSelector, fd: TSocketHandle,
- events: set[TEvent]): PSelectorKey {.discardable.} =
+ proc update*(s: Selector, fd: SocketHandle,
+ events: set[Event]): SelectorKey {.discardable.} =
## Updates the events which ``fd`` wants notifications for.
- proc select*(s: PSelector, timeout: int): seq[TReadyInfo] =
+ proc select*(s: Selector, timeout: int): seq[ReadyInfo] =
## The ``events`` field of the returned ``key`` contains the original events
## for which the ``fd`` was bound. This is contrary to the ``events`` field
## of the ``TReadyInfo`` tuple which determines which events are ready
## on the ``fd``.
- proc contains*(s: PSelector, fd: TSocketHandle): bool =
+ proc contains*(s: Selector, fd: SocketHandle): bool =
## Determines whether selector contains a file descriptor.
- proc `[]`*(s: PSelector, fd: TSocketHandle): PSelectorKey =
+ proc `[]`*(s: Selector, fd: SocketHandle): SelectorKey =
## Retrieves the selector key for ``fd``.
elif defined(linux):
type
- PSelector* = ref object
+ Selector* = ref object
epollFD: cint
events: array[64, epoll_event]
- fds: TTable[TSocketHandle, PSelectorKey]
+ fds: Table[SocketHandle, SelectorKey]
- proc createEventStruct(events: set[TEvent], fd: TSocketHandle): epoll_event =
+ proc createEventStruct(events: set[Event], fd: SocketHandle): epoll_event =
if EvRead in events:
result.events = EPOLLIN
if EvWrite in events:
@@ -76,22 +76,22 @@ elif defined(linux):
result.events = result.events or EPOLLRDHUP
result.data.fd = fd.cint
- proc register*(s: PSelector, fd: TSocketHandle, events: set[TEvent],
- data: PObject): PSelectorKey {.discardable.} =
+ proc register*(s: Selector, fd: SocketHandle, events: set[Event],
+ data: RootRef): SelectorKey {.discardable.} =
## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent
## ``events``.
var event = createEventStruct(events, fd)
if events != {}:
if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0:
- OSError(OSLastError())
+ raiseOSError(osLastError())
- var key = PSelectorKey(fd: fd, events: events, data: data)
+ var key = SelectorKey(fd: fd, events: events, data: data)
s.fds[fd] = key
result = key
- proc update*(s: PSelector, fd: TSocketHandle,
- events: set[TEvent]): PSelectorKey {.discardable.} =
+ proc update*(s: Selector, fd: SocketHandle,
+ events: set[Event]): SelectorKey {.discardable.} =
## Updates the events which ``fd`` wants notifications for.
if s.fds[fd].events != events:
if events == {}:
@@ -101,7 +101,7 @@ elif defined(linux):
# because its got fds which are waiting for no events and
# are therefore constantly ready. (leading to 100% CPU usage).
if epoll_ctl(s.epollFD, EPOLL_CTL_DEL, fd, nil) != 0:
- OSError(OSLastError())
+ raiseOSError(osLastError())
s.fds[fd].events = events
else:
var event = createEventStruct(events, fd)
@@ -109,36 +109,36 @@ elif defined(linux):
# This fd is idle. It's not a member of this epoll instance and must
# be re-registered.
if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0:
- OSError(OSLastError())
+ raiseOSError(osLastError())
else:
if epoll_ctl(s.epollFD, EPOLL_CTL_MOD, fd, addr(event)) != 0:
- OSError(OSLastError())
+ raiseOSError(osLastError())
s.fds[fd].events = events
result = s.fds[fd]
- proc unregister*(s: PSelector, fd: TSocketHandle): PSelectorKey {.discardable.} =
+ proc unregister*(s: Selector, fd: SocketHandle): SelectorKey {.discardable.} =
if epoll_ctl(s.epollFD, EPOLL_CTL_DEL, fd, nil) != 0:
- let err = OSLastError()
+ let err = osLastError()
if err.cint notin {ENOENT, EBADF}: # TODO: Why do we sometimes get an EBADF? Is this normal?
- OSError(err)
+ raiseOSError(err)
result = s.fds[fd]
s.fds.del(fd)
- proc close*(s: PSelector) =
- if s.epollFD.close() != 0: OSError(OSLastError())
+ proc close*(s: Selector) =
+ if s.epollFD.close() != 0: raiseOSError(osLastError())
dealloc(addr s.events) # TODO: Test this
- proc epollHasFd(s: PSelector, fd: TSocketHandle): bool =
+ proc epollHasFd(s: Selector, fd: SocketHandle): bool =
result = true
var event = createEventStruct(s.fds[fd].events, fd)
if epoll_ctl(s.epollFD, EPOLL_CTL_MOD, fd, addr(event)) != 0:
let err = osLastError()
if err.cint in {ENOENT, EBADF}:
return false
- OSError(OSLastError())
+ raiseOSError(osLastError())
- proc select*(s: PSelector, timeout: int): seq[TReadyInfo] =
+ proc select*(s: Selector, timeout: int): seq[ReadyInfo] =
##
## The ``events`` field of the returned ``key`` contains the original events
## for which the ``fd`` was bound. This is contrary to the ``events`` field
@@ -146,12 +146,12 @@ elif defined(linux):
## on the ``fd``.
result = @[]
let evNum = epoll_wait(s.epollFD, addr s.events[0], 64.cint, timeout.cint)
- if evNum < 0: OSError(OSLastError())
+ if evNum < 0: raiseOSError(osLastError())
if evNum == 0: return @[]
for i in 0 .. 0 and c == '\L':
discard recv(socket, addr(c), 1)
- elif n <= 0: socket.socketError()
+ elif n <= 0: socket.raiseSocketError()
addNLIfEmpty()
return
elif c == '\L':
@@ -1357,7 +1367,7 @@ proc readLineAsync*(socket: TSocket,
setLen(line.string, 0)
template errorOrNone =
- socket.socketError(async = true)
+ socket.raiseSocketError(async = true)
return ReadNone
while true:
@@ -1390,7 +1400,7 @@ proc recv*(socket: TSocket): TaintedString {.tags: [ReadIOEffect], deprecated.}
var pos = 0
while true:
var bytesRead = recv(socket, addr(string(result)[pos]), bufSize-1)
- if bytesRead == -1: osError(osLastError())
+ if bytesRead == -1: raiseOSError(osLastError())
setLen(result.string, pos + bytesRead)
if bytesRead != bufSize-1: break
# increase capacity:
@@ -1463,11 +1473,11 @@ proc recvAsync*(socket: TSocket, s: var TaintedString): bool {.
when defined(windows):
if err.int32 == WSAEWOULDBLOCK:
return false
- else: osError(err)
+ else: raiseOSError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return false
- else: osError(err)
+ else: raiseOSError(err)
setLen(s.string, pos + bytesRead)
if bytesRead != bufSize-1: break
@@ -1516,11 +1526,11 @@ proc recvFromAsync*(socket: TSocket, data: var string, length: int,
when defined(windows):
if err.int32 == WSAEWOULDBLOCK:
return false
- else: osError(err)
+ else: raiseOSError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return false
- else: osError(err)
+ else: raiseOSError(err)
proc skip*(socket: TSocket) {.tags: [ReadIOEffect], deprecated.} =
## skips all the data that is pending for the socket
@@ -1570,7 +1580,7 @@ proc send*(socket: TSocket, data: string) {.tags: [WriteIOEffect].} =
if socket.isSSL:
SSLError()
- osError(osLastError())
+ raiseOSError(osLastError())
if sent != data.len:
raise newException(OSError, "Could not send all data.")
@@ -1607,11 +1617,11 @@ proc sendAsync*(socket: TSocket, data: string): int {.tags: [WriteIOEffect].} =
when defined(windows):
if err.int32 == WSAEINPROGRESS:
return 0
- else: osError(err)
+ else: raiseOSError(err)
else:
if err.int32 == EAGAIN or err.int32 == EWOULDBLOCK:
return 0
- else: osError(err)
+ else: raiseOSError(err)
proc trySend*(socket: TSocket, data: string): bool {.tags: [WriteIOEffect].} =
@@ -1667,15 +1677,15 @@ proc setBlocking(s: TSocket, blocking: bool) =
when defined(Windows):
var mode = clong(ord(not blocking)) # 1 for non-blocking, 0 for blocking
if ioctlsocket(s.fd, FIONBIO, addr(mode)) == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
else: # BSD sockets
var x: int = fcntl(s.fd, F_GETFL, 0)
if x == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
var mode = if blocking: x and not O_NONBLOCK else: x or O_NONBLOCK
if fcntl(s.fd, F_SETFL, mode) == -1:
- osError(osLastError())
+ raiseOSError(osLastError())
s.nonblocking = not blocking
discard """ proc setReuseAddr*(s: TSocket) =
@@ -1715,6 +1725,6 @@ proc isBlocking*(socket: TSocket): bool = not socket.nonblocking
when defined(Windows):
var wsa: TWSAData
- if wsaStartup(0x0101'i16, addr wsa) != 0: osError(osLastError())
+ if wsaStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())
diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim
index c4e969f21..bc0f1c540 100644
--- a/lib/pure/streams.nim
+++ b/lib/pure/streams.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -8,8 +8,8 @@
#
## This module provides a stream interface and two implementations thereof:
-## the `PFileStream` and the `PStringStream` which implement the stream
-## interface for Nimrod file objects (`TFile`) and strings. Other modules
+## the `FileStream` and the `StringStream` which implement the stream
+## interface for Nimrod file objects (`File`) and strings. Other modules
## may provide other implementations for this standard stream interface.
include "system/inclrtl"
@@ -19,81 +19,83 @@ proc newEIO(msg: string): ref IOError =
result.msg = msg
type
- PStream* = ref TStream
- TStream* = object of RootObj ## Stream interface that supports
- ## writing or reading. Note that these fields
- ## here shouldn't be used directly. They are
- ## accessible so that a stream implementation
- ## can override them.
- closeImpl*: proc (s: PStream) {.nimcall, tags: [], gcsafe.}
- atEndImpl*: proc (s: PStream): bool {.nimcall, tags: [], gcsafe.}
- setPositionImpl*: proc (s: PStream, pos: int) {.nimcall, tags: [], gcsafe.}
- getPositionImpl*: proc (s: PStream): int {.nimcall, tags: [], gcsafe.}
- readDataImpl*: proc (s: PStream, buffer: pointer,
+ Stream* = ref StreamObj
+ StreamObj* = object of RootObj ## Stream interface that supports
+ ## writing or reading. Note that these fields
+ ## here shouldn't be used directly. They are
+ ## accessible so that a stream implementation
+ ## can override them.
+ closeImpl*: proc (s: Stream) {.nimcall, tags: [], gcsafe.}
+ atEndImpl*: proc (s: Stream): bool {.nimcall, tags: [], gcsafe.}
+ setPositionImpl*: proc (s: Stream, pos: int) {.nimcall, tags: [], gcsafe.}
+ getPositionImpl*: proc (s: Stream): int {.nimcall, tags: [], gcsafe.}
+ readDataImpl*: proc (s: Stream, buffer: pointer,
bufLen: int): int {.nimcall, tags: [ReadIOEffect], gcsafe.}
- writeDataImpl*: proc (s: PStream, buffer: pointer, bufLen: int) {.nimcall,
+ writeDataImpl*: proc (s: Stream, buffer: pointer, bufLen: int) {.nimcall,
tags: [WriteIOEffect], gcsafe.}
- flushImpl*: proc (s: PStream) {.nimcall, tags: [WriteIOEffect], gcsafe.}
+ flushImpl*: proc (s: Stream) {.nimcall, tags: [WriteIOEffect], gcsafe.}
-proc flush*(s: PStream) =
+{.deprecated: [PStream: Stream, TStream: StreamObj].}
+
+proc flush*(s: Stream) =
## flushes the buffers that the stream `s` might use.
if not isNil(s.flushImpl): s.flushImpl(s)
-proc close*(s: PStream) =
+proc close*(s: Stream) =
## closes the stream `s`.
if not isNil(s.closeImpl): s.closeImpl(s)
-proc close*(s, unused: PStream) {.deprecated.} =
+proc close*(s, unused: Stream) {.deprecated.} =
## closes the stream `s`.
s.closeImpl(s)
-proc atEnd*(s: PStream): bool =
+proc atEnd*(s: Stream): bool =
## checks if more data can be read from `f`. Returns true if all data has
## been read.
result = s.atEndImpl(s)
-proc atEnd*(s, unused: PStream): bool {.deprecated.} =
+proc atEnd*(s, unused: Stream): bool {.deprecated.} =
## checks if more data can be read from `f`. Returns true if all data has
## been read.
result = s.atEndImpl(s)
-proc setPosition*(s: PStream, pos: int) =
+proc setPosition*(s: Stream, pos: int) =
## sets the position `pos` of the stream `s`.
s.setPositionImpl(s, pos)
-proc setPosition*(s, unused: PStream, pos: int) {.deprecated.} =
+proc setPosition*(s, unused: Stream, pos: int) {.deprecated.} =
## sets the position `pos` of the stream `s`.
s.setPositionImpl(s, pos)
-proc getPosition*(s: PStream): int =
+proc getPosition*(s: Stream): int =
## retrieves the current position in the stream `s`.
result = s.getPositionImpl(s)
-proc getPosition*(s, unused: PStream): int {.deprecated.} =
+proc getPosition*(s, unused: Stream): int {.deprecated.} =
## retrieves the current position in the stream `s`.
result = s.getPositionImpl(s)
-proc readData*(s: PStream, buffer: pointer, bufLen: int): int =
+proc readData*(s: Stream, buffer: pointer, bufLen: int): int =
## low level proc that reads data into an untyped `buffer` of `bufLen` size.
result = s.readDataImpl(s, buffer, bufLen)
-proc readData*(s, unused: PStream, buffer: pointer,
+proc readData*(s, unused: Stream, buffer: pointer,
bufLen: int): int {.deprecated.} =
## low level proc that reads data into an untyped `buffer` of `bufLen` size.
result = s.readDataImpl(s, buffer, bufLen)
-proc writeData*(s: PStream, buffer: pointer, bufLen: int) =
+proc writeData*(s: Stream, buffer: pointer, bufLen: int) =
## low level proc that writes an untyped `buffer` of `bufLen` size
## to the stream `s`.
s.writeDataImpl(s, buffer, bufLen)
-proc writeData*(s, unused: PStream, buffer: pointer,
+proc writeData*(s, unused: Stream, buffer: pointer,
bufLen: int) {.deprecated.} =
## low level proc that writes an untyped `buffer` of `bufLen` size
## to the stream `s`.
s.writeDataImpl(s, buffer, bufLen)
-proc write*[T](s: PStream, x: T) =
+proc write*[T](s: Stream, x: T) =
## generic write procedure. Writes `x` to the stream `s`. Implementation:
##
## .. code-block:: Nimrod
@@ -103,63 +105,63 @@ proc write*[T](s: PStream, x: T) =
shallowCopy(y, x)
writeData(s, addr(y), sizeof(y))
-proc write*(s: PStream, x: string) =
+proc write*(s: Stream, x: string) =
## writes the string `x` to the the stream `s`. No length field or
## terminating zero is written.
writeData(s, cstring(x), x.len)
-proc writeln*(s: PStream, args: varargs[string, `$`]) =
+proc writeln*(s: Stream, args: varargs[string, `$`]) =
## writes one or more strings to the the stream `s` followed
## by a new line. No length field or terminating zero is written.
for str in args: write(s, str)
write(s, "\n")
-proc read[T](s: PStream, result: var T) =
+proc read[T](s: Stream, result: var T) =
## generic read procedure. Reads `result` from the stream `s`.
if readData(s, addr(result), sizeof(T)) != sizeof(T):
raise newEIO("cannot read from stream")
-proc readChar*(s: PStream): char =
+proc readChar*(s: Stream): char =
## reads a char from the stream `s`. Raises `EIO` if an error occured.
## Returns '\0' as an EOF marker.
if readData(s, addr(result), sizeof(result)) != 1: result = '\0'
-proc readBool*(s: PStream): bool =
+proc readBool*(s: Stream): bool =
## reads a bool from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readInt8*(s: PStream): int8 =
+proc readInt8*(s: Stream): int8 =
## reads an int8 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readInt16*(s: PStream): int16 =
+proc readInt16*(s: Stream): int16 =
## reads an int16 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readInt32*(s: PStream): int32 =
+proc readInt32*(s: Stream): int32 =
## reads an int32 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readInt64*(s: PStream): int64 =
+proc readInt64*(s: Stream): int64 =
## reads an int64 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readFloat32*(s: PStream): float32 =
+proc readFloat32*(s: Stream): float32 =
## reads a float32 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readFloat64*(s: PStream): float64 =
+proc readFloat64*(s: Stream): float64 =
## reads a float64 from the stream `s`. Raises `EIO` if an error occured.
read(s, result)
-proc readStr*(s: PStream, length: int): TaintedString =
+proc readStr*(s: Stream, length: int): TaintedString =
## reads a string of length `length` from the stream `s`. Raises `EIO` if
## an error occured.
result = newString(length).TaintedString
var L = readData(s, addr(string(result)[0]), length)
if L != length: setLen(result.string, L)
-proc readLine*(s: PStream, line: var TaintedString): bool =
+proc readLine*(s: Stream, line: var TaintedString): bool =
## reads a line of text from the stream `s` into `line`. `line` must not be
## ``nil``! May throw an IO exception.
## A line of text may be delimited by ``CR``, ``LF`` or
@@ -179,7 +181,7 @@ proc readLine*(s: PStream, line: var TaintedString): bool =
line.string.add(c)
result = true
-proc readLine*(s: PStream): TaintedString =
+proc readLine*(s: Stream): TaintedString =
## Reads a line from a stream `s`. Note: This is not very efficient. Raises
## `EIO` if an error occured.
result = TaintedString""
@@ -194,42 +196,44 @@ proc readLine*(s: PStream): TaintedString =
result.string.add(c)
type
- PStringStream* = ref TStringStream ## a stream that encapsulates a string
- TStringStream* = object of TStream
+ StringStream* = ref StringStreamObj ## a stream that encapsulates a string
+ StringStreamObj* = object of StreamObj
data*: string
pos: int
-
-proc ssAtEnd(s: PStream): bool =
- var s = PStringStream(s)
+
+{.deprecated: [PStringStream: StringStream, TStringStream: StringStreamObj].}
+
+proc ssAtEnd(s: Stream): bool =
+ var s = StringStream(s)
return s.pos >= s.data.len
-proc ssSetPosition(s: PStream, pos: int) =
- var s = PStringStream(s)
+proc ssSetPosition(s: Stream, pos: int) =
+ var s = StringStream(s)
s.pos = clamp(pos, 0, s.data.high)
-proc ssGetPosition(s: PStream): int =
- var s = PStringStream(s)
+proc ssGetPosition(s: Stream): int =
+ var s = StringStream(s)
return s.pos
-proc ssReadData(s: PStream, buffer: pointer, bufLen: int): int =
- var s = PStringStream(s)
+proc ssReadData(s: Stream, buffer: pointer, bufLen: int): int =
+ var s = StringStream(s)
result = min(bufLen, s.data.len - s.pos)
if result > 0:
copyMem(buffer, addr(s.data[s.pos]), result)
inc(s.pos, result)
-proc ssWriteData(s: PStream, buffer: pointer, bufLen: int) =
- var s = PStringStream(s)
+proc ssWriteData(s: Stream, buffer: pointer, bufLen: int) =
+ var s = StringStream(s)
if bufLen > 0:
setLen(s.data, s.data.len + bufLen)
copyMem(addr(s.data[s.pos]), buffer, bufLen)
inc(s.pos, bufLen)
-proc ssClose(s: PStream) =
- var s = PStringStream(s)
+proc ssClose(s: Stream) =
+ var s = StringStream(s)
s.data = nil
-proc newStringStream*(s: string = ""): PStringStream =
+proc newStringStream*(s: string = ""): StringStream =
## creates a new stream from the string `s`.
new(result)
result.data = s
@@ -244,27 +248,28 @@ proc newStringStream*(s: string = ""): PStringStream =
when not defined(js):
type
- PFileStream* = ref TFileStream ## a stream that encapsulates a `TFile`
- TFileStream* = object of TStream
+ FileStream* = ref FileStreamObj ## a stream that encapsulates a `TFile`
+ FileStreamObj* = object of Stream
f: File
+ {.deprecated: [PFileStream: FileStream, TFileStream: FileStreamObj].}
- proc fsClose(s: PStream) =
- if PFileStream(s).f != nil:
- close(PFileStream(s).f)
- PFileStream(s).f = nil
- proc fsFlush(s: PStream) = flushFile(PFileStream(s).f)
- proc fsAtEnd(s: PStream): bool = return endOfFile(PFileStream(s).f)
- proc fsSetPosition(s: PStream, pos: int) = setFilePos(PFileStream(s).f, pos)
- proc fsGetPosition(s: PStream): int = return int(getFilePos(PFileStream(s).f))
+ proc fsClose(s: Stream) =
+ if FileStream(s).f != nil:
+ close(FileStream(s).f)
+ FileStream(s).f = nil
+ proc fsFlush(s: Stream) = flushFile(FileStream(s).f)
+ proc fsAtEnd(s: Stream): bool = return endOfFile(FileStream(s).f)
+ proc fsSetPosition(s: Stream, pos: int) = setFilePos(FileStream(s).f, pos)
+ proc fsGetPosition(s: Stream): int = return int(getFilePos(FileStream(s).f))
- proc fsReadData(s: PStream, buffer: pointer, bufLen: int): int =
- result = readBuffer(PFileStream(s).f, buffer, bufLen)
+ proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int =
+ result = readBuffer(FileStream(s).f, buffer, bufLen)
- proc fsWriteData(s: PStream, buffer: pointer, bufLen: int) =
- if writeBuffer(PFileStream(s).f, buffer, bufLen) != bufLen:
+ proc fsWriteData(s: Stream, buffer: pointer, bufLen: int) =
+ if writeBuffer(FileStream(s).f, buffer, bufLen) != bufLen:
raise newEIO("cannot write to stream")
- proc newFileStream*(f: File): PFileStream =
+ proc newFileStream*(f: File): FileStream =
## creates a new stream from the file `f`.
new(result)
result.f = f
@@ -276,7 +281,7 @@ when not defined(js):
result.writeDataImpl = fsWriteData
result.flushImpl = fsFlush
- proc newFileStream*(filename: string, mode: FileMode): PFileStream =
+ proc newFileStream*(filename: string, mode: FileMode): FileStream =
## creates a new stream from the file named `filename` with the mode `mode`.
## If the file cannot be opened, nil is returned. See the `system
## `_ module for a list of available TFileMode enums.
@@ -288,45 +293,47 @@ when true:
discard
else:
type
- TFileHandle* = cint ## Operating system file handle
- PFileHandleStream* = ref TFileHandleStream
- TFileHandleStream* = object of TStream
- handle*: TFileHandle
+ FileHandleStream* = ref FileHandleStreamObj
+ FileHandleStreamObj* = object of Stream
+ handle*: FileHandle
pos: int
- proc newEOS(msg: string): ref EOS =
+ {.deprecated: [PFileHandleStream: FileHandleStream,
+ TFileHandleStream: FileHandleStreamObj].}
+
+ proc newEOS(msg: string): ref OSError =
new(result)
result.msg = msg
- proc hsGetPosition(s: PFileHandleStream): int =
+ proc hsGetPosition(s: FileHandleStream): int =
return s.pos
when defined(windows):
# do not import windows as this increases compile times:
- nil
+ discard
else:
import posix
- proc hsSetPosition(s: PFileHandleStream, pos: int) =
+ proc hsSetPosition(s: FileHandleStream, pos: int) =
discard lseek(s.handle, pos, SEEK_SET)
- proc hsClose(s: PFileHandleStream) = discard close(s.handle)
- proc hsAtEnd(s: PFileHandleStream): bool =
+ proc hsClose(s: FileHandleStream) = discard close(s.handle)
+ proc hsAtEnd(s: FileHandleStream): bool =
var pos = hsGetPosition(s)
var theEnd = lseek(s.handle, 0, SEEK_END)
result = pos >= theEnd
hsSetPosition(s, pos) # set position back
- proc hsReadData(s: PFileHandleStream, buffer: pointer, bufLen: int): int =
+ proc hsReadData(s: FileHandleStream, buffer: pointer, bufLen: int): int =
result = posix.read(s.handle, buffer, bufLen)
inc(s.pos, result)
- proc hsWriteData(s: PFileHandleStream, buffer: pointer, bufLen: int) =
+ proc hsWriteData(s: FileHandleStream, buffer: pointer, bufLen: int) =
if posix.write(s.handle, buffer, bufLen) != bufLen:
raise newEIO("cannot write to stream")
inc(s.pos, bufLen)
- proc newFileHandleStream*(handle: TFileHandle): PFileHandleStream =
+ proc newFileHandleStream*(handle: FileHandle): FileHandleStream =
new(result)
result.handle = handle
result.pos = 0
@@ -338,9 +345,9 @@ else:
result.writeData = hsWriteData
proc newFileHandleStream*(filename: string,
- mode: TFileMode): PFileHandleStream =
- when defined(windows):
- nil
+ mode: FileMode): FileHandleStream =
+ when defined(windows):
+ discard
else:
var flags: cint
case mode
diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim
index 12621a0fc..71d16192f 100644
--- a/lib/pure/strtabs.nim
+++ b/lib/pure/strtabs.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -18,20 +18,23 @@ import
include "system/inclrtl"
type
- TStringTableMode* = enum ## describes the tables operation mode
+ StringTableMode* = enum ## describes the tables operation mode
modeCaseSensitive, ## the table is case sensitive
modeCaseInsensitive, ## the table is case insensitive
modeStyleInsensitive ## the table is style insensitive
- TKeyValuePair = tuple[key, val: string]
- TKeyValuePairSeq = seq[TKeyValuePair]
- TStringTable* = object of RootObj
+ KeyValuePair = tuple[key, val: string]
+ KeyValuePairSeq = seq[KeyValuePair]
+ StringTableObj* = object of RootObj
counter: int
- data: TKeyValuePairSeq
- mode: TStringTableMode
+ data: KeyValuePairSeq
+ mode: StringTableMode
- PStringTable* = ref TStringTable ## use this type to declare string tables
+ StringTableRef* = ref StringTableObj ## use this type to declare string tables
-proc len*(t: PStringTable): int {.rtl, extern: "nst$1".} =
+{.deprecated: [TStringTableMode: StringTableMode,
+ TStringTable: StringTableObj, PStringTable: StringTableRef].}
+
+proc len*(t: StringTableRef): int {.rtl, extern: "nst$1".} =
## returns the number of keys in `t`.
result = t.counter
@@ -54,7 +57,7 @@ iterator values*(t: PStringTable): string =
yield t.data[h].val
type
- TFormatFlag* = enum ## flags for the `%` operator
+ FormatFlag* = enum ## flags for the `%` operator
useEnvironment, ## use environment variable if the ``$key``
## is not found in the table
useEmpty, ## use the empty string as a default, thus it
@@ -63,6 +66,8 @@ type
useKey ## do not replace ``$key`` if it is not found
## in the table (or in the environment)
+{.deprecated: [TFormatFlag: FormatFlag].}
+
# implementation
const
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index cc62ad1ee..82516653c 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -23,7 +23,7 @@ import parseutils
include "system/inclrtl"
type
- TCharSet* = set[char] # for compatibility with Nim
+ TCharSet* {.deprecated.} = set[char] # for compatibility with Nim
const
Whitespace* = {' ', '\t', '\v', '\r', '\l', '\f'}
@@ -54,7 +54,7 @@ const
## make the `find() proc <#find,string,set[char],int>`_ find **invalid**
## characters in strings. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## let invalid = AllChars - Digits
## doAssert "01234".find(invalid) == -1
## doAssert "01A34".find(invalid) == 2
@@ -205,7 +205,7 @@ iterator split*(s: string, seps: set[char] = Whitespace): string =
## a single split point and leading/trailing separators will be ignored.
## The following example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in split(" this is an example "):
## writeln(stdout, word)
##
@@ -219,13 +219,13 @@ iterator split*(s: string, seps: set[char] = Whitespace): string =
##
## And the following code:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in split(";;this;is;an;;example;;;", {';'}):
## writeln(stdout, word)
##
## ...produces the same output as the first example. The code:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## let date = "2012-11-20T22:08:08.398990"
## let separators = {' ', '-', ':', 'T'}
## for number in split(date, separators):
@@ -258,7 +258,7 @@ iterator split*(s: string, sep: char): string =
## characters, this proc will not coalesce groups of the
## separator, returning a string for each found character. The code:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in split(";;this;is;an;;example;;;", ';'):
## writeln(stdout, word)
##
@@ -308,13 +308,13 @@ iterator splitLines*(s: string): string =
##
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for line in splitLines("\nthis\nis\nan\n\nexample\n"):
## writeln(stdout, line)
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## ""
## "this"
## "is"
@@ -417,7 +417,7 @@ proc parseInt*(s: string): int {.noSideEffect, procvar,
rtl, extern: "nsuParseInt".} =
## Parses a decimal integer value contained in `s`.
##
- ## If `s` is not a valid integer, `EInvalidValue` is raised.
+ ## If `s` is not a valid integer, `ValueError` is raised.
var L = parseutils.parseInt(s, result, 0)
if L != s.len or L == 0:
raise newException(ValueError, "invalid integer: " & s)
@@ -426,7 +426,7 @@ proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
rtl, extern: "nsuParseBiggestInt".} =
## Parses a decimal integer value contained in `s`.
##
- ## If `s` is not a valid integer, `EInvalidValue` is raised.
+ ## If `s` is not a valid integer, `ValueError` is raised.
var L = parseutils.parseBiggestInt(s, result, 0)
if L != s.len or L == 0:
raise newException(ValueError, "invalid integer: " & s)
@@ -434,7 +434,7 @@ proc parseBiggestInt*(s: string): BiggestInt {.noSideEffect, procvar,
proc parseFloat*(s: string): float {.noSideEffect, procvar,
rtl, extern: "nsuParseFloat".} =
## Parses a decimal floating point value contained in `s`. If `s` is not
- ## a valid floating point number, `EInvalidValue` is raised. ``NAN``,
+ ## a valid floating point number, `ValueError` is raised. ``NAN``,
## ``INF``, ``-INF`` are also supported (case insensitive comparison).
var L = parseutils.parseFloat(s, result, 0)
if L != s.len or L == 0:
@@ -444,7 +444,7 @@ proc parseHexInt*(s: string): int {.noSideEffect, procvar,
rtl, extern: "nsuParseHexInt".} =
## Parses a hexadecimal integer value contained in `s`.
##
- ## If `s` is not a valid integer, `EInvalidValue` is raised. `s` can have one
+ ## If `s` is not a valid integer, `ValueError` is raised. `s` can have one
## of the following optional prefixes: ``0x``, ``0X``, ``#``. Underscores
## within `s` are ignored.
var i = 0
@@ -471,7 +471,7 @@ proc parseBool*(s: string): bool =
## If ``s`` is one of the following values: ``y, yes, true, 1, on``, then
## returns `true`. If ``s`` is one of the following values: ``n, no, false,
## 0, off``, then returns `false`. If ``s`` is something else a
- ## ``EInvalidValue`` exception is raised.
+ ## ``ValueError`` exception is raised.
case normalize(s)
of "y", "yes", "true", "1", "on": result = true
of "n", "no", "false", "0", "off": result = false
@@ -480,7 +480,7 @@ proc parseBool*(s: string): bool =
proc parseEnum*[T: enum](s: string): T =
## Parses an enum ``T``.
##
- ## Raises ``EInvalidValue`` for an invalid value in `s`. The comparison is
+ ## Raises ``ValueError`` for an invalid value in `s`. The comparison is
## done in a style insensitive way.
for e in low(T)..high(T):
if cmpIgnoreStyle(s, $e) == 0:
@@ -502,7 +502,7 @@ proc repeatChar*(count: int, c: char = ' '): string {.noSideEffect,
## Returns a string of length `count` consisting only of
## the character `c`. You can use this proc to left align strings. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## let
## width = 15
## text1 = "Hello user!"
@@ -527,7 +527,7 @@ proc align*(s: string, count: int, padding = ' '): string {.
## returned unchanged. If you need to left align a string use the `repeatChar
## proc <#repeatChar>`_. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## assert align("abc", 4) == " abc"
## assert align("a", 0) == "a"
## assert align("1232", 6) == " 1232"
@@ -547,13 +547,13 @@ iterator tokenize*(s: string, seps: set[char] = Whitespace): tuple[
## Substrings are separated by a substring containing only `seps`.
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in tokenize(" this is an example "):
## writeln(stdout, word)
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## (" ", true)
## ("this", false)
## (" ", true)
@@ -676,7 +676,7 @@ proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect,
##
## A shorthand for:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## if dest.len > startLen: add(dest, sep)
##
## This is often useful for generating some code where the items need to
@@ -684,7 +684,7 @@ proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect,
## `startLen`. The following example creates a string describing
## an array of integers:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var arr = "["
## for x in items([2, 3, 5, 7, 11]):
## addSep(arr, startLen=len("["))
@@ -692,7 +692,7 @@ proc addSep*(dest: var string, sep = ", ", startLen = 0) {.noSideEffect,
## add(arr, "]")
if dest.len > startLen: add(dest, sep)
-proc allCharsInSet*(s: string, theSet: TCharSet): bool =
+proc allCharsInSet*(s: string, theSet: set[char]): bool =
## Returns true iff each character of `s` is in the set `theSet`.
for c in items(s):
if c notin theSet: return false
@@ -739,14 +739,14 @@ proc join*(a: openArray[string]): string {.
result = ""
type
- TSkipTable = array[char, int]
+ SkipTable = array[char, int]
-proc preprocessSub(sub: string, a: var TSkipTable) =
+proc preprocessSub(sub: string, a: var SkipTable) =
var m = len(sub)
for i in 0..0xff: a[chr(i)] = m+1
for i in 0..m-1: a[sub[i]] = m-i
-proc findAux(s, sub: string, start: int, a: TSkipTable): int =
+proc findAux(s, sub: string, start: int, a: SkipTable): int =
# Fast "quick search" algorithm:
var
m = len(sub)
@@ -762,7 +762,7 @@ proc findAux(s, sub: string, start: int, a: TSkipTable): int =
return -1
proc find*(s, sub: string, start: int = 0): int {.noSideEffect,
- rtl, extern: "nsuFindStr", operator: 6.} =
+ rtl, extern: "nsuFindStr".} =
## Searches for `sub` in `s` starting at position `start`.
##
## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
@@ -827,9 +827,9 @@ proc contains*(s: string, chars: set[char]): bool {.noSideEffect.} =
return find(s, chars) >= 0
proc replace*(s, sub: string, by = ""): string {.noSideEffect,
- rtl, extern: "nsuReplaceStr", operator: 1.} =
+ rtl, extern: "nsuReplaceStr".} =
## Replaces `sub` in `s` by the string `by`.
- var a {.noinit.}: TSkipTable
+ var a {.noinit.}: SkipTable
result = ""
preprocessSub(sub, a)
var i = 0
@@ -862,7 +862,7 @@ proc replaceWord*(s, sub: string, by = ""): string {.noSideEffect,
## (comparable to ``\\w`` in regular expressions), otherwise it is not
## replaced.
const wordChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\128'..'\255'}
- var a {.noinit.}: TSkipTable
+ var a {.noinit.}: SkipTable
result = ""
preprocessSub(sub, a)
var i = 0
@@ -899,7 +899,7 @@ proc parseOctInt*(s: string): int {.noSideEffect,
rtl, extern: "nsuParseOctInt".} =
## Parses an octal integer value contained in `s`.
##
- ## If `s` is not a valid integer, `EInvalidValue` is raised. `s` can have one
+ ## If `s` is not a valid integer, `ValueError` is raised. `s` can have one
## of the following optional prefixes: ``0o``, ``0O``. Underscores within
## `s` are ignored.
var i = 0
@@ -999,7 +999,7 @@ proc unescape*(s: string, prefix = "\"", suffix = "\""): string {.noSideEffect,
## operations.
##
## If `s` does not begin with ``prefix`` and end with ``suffix`` a
- ## EInvalidValue exception will be raised.
+ ## ValueError exception will be raised.
result = newStringOfCap(s.len)
var i = 0
if s[0 .. prefix.len-1] != prefix:
@@ -1138,12 +1138,14 @@ proc c_sprintf(buf, frmt: cstring) {.header: "", importc: "sprintf",
varargs, noSideEffect.}
type
- TFloatFormat* = enum ## the different modes of floating point formating
+ FloatFormatMode* = enum ## the different modes of floating point formating
ffDefault, ## use the shorter floating point notation
ffDecimal, ## use decimal floating point notation
ffScientific ## use scientific notation (using ``e`` character)
-proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault,
+{.deprecated: [TFloatFormat: FloatFormatMode].}
+
+proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
precision: range[0..32] = 16): string {.
noSideEffect, operator: 2, rtl, extern: "nsu$1".} =
## Converts a floating point value `f` to a string.
@@ -1174,7 +1176,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: TFloatFormat = ffDefault,
c_sprintf(buf, frmtstr, f)
result = $buf
-proc formatFloat*(f: float, format: TFloatFormat = ffDefault,
+proc formatFloat*(f: float, format: FloatFormatMode = ffDefault,
precision: range[0..32] = 16): string {.
noSideEffect, operator: 2, rtl, extern: "nsu$1".} =
## Converts a floating point value `f` to a string.
@@ -1190,7 +1192,7 @@ proc formatFloat*(f: float, format: TFloatFormat = ffDefault,
proc formatSize*(bytes: BiggestInt, decimalSep = '.'): string =
## Rounds and formats `bytes`. Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## formatSize(1'i64 shl 31 + 300'i64) == "2.204GB"
## formatSize(4096) == "4KB"
@@ -1280,12 +1282,12 @@ proc `%` *(formatstr: string, a: openArray[string]): string {.noSideEffect,
##
## This is best explained by an example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "$1 eats $2." % ["The cat", "fish"]
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "The cat eats fish."
##
## The substitution variables (the thing after the ``$``) are enumerated
@@ -1294,7 +1296,7 @@ proc `%` *(formatstr: string, a: openArray[string]): string {.noSideEffect,
## The notation ``$#`` can be used to refer to the next substitution
## variable:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "$# eats $#." % ["The cat", "fish"]
##
## Substitution variables can also be words (that is
@@ -1302,15 +1304,15 @@ proc `%` *(formatstr: string, a: openArray[string]): string {.noSideEffect,
## indices are keys and with odd indices are the corresponding values.
## An example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "$animal eats $food." % ["animal", "The cat", "food", "fish"]
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "The cat eats fish."
##
- ## The variables are compared with `cmpIgnoreStyle`. `EInvalidValue` is
+ ## The variables are compared with `cmpIgnoreStyle`. `ValueError` is
## raised if an ill-formed format string has been passed to the `%` operator.
result = newStringOfCap(formatstr.len + a.len shl 4)
addf(result, formatstr, a)
@@ -1350,7 +1352,7 @@ when isMainModule:
doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz "
doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz abc"
- type TMyEnum = enum enA, enB, enC, enuD, enE
- doAssert parseEnum[TMyEnum]("enu_D") == enuD
+ type MyEnum = enum enA, enB, enC, enuD, enE
+ doAssert parseEnum[MyEnum]("enu_D") == enuD
doAssert parseEnum("invalid enum value", enC) == enC
diff --git a/lib/pure/subexes.nim b/lib/pure/subexes.nim
index ed87610d6..452978c09 100644
--- a/lib/pure/subexes.nim
+++ b/lib/pure/subexes.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## Nimrod support for `substitution expressions`:idx: (`subex`:idx:).
+## Nim support for `substitution expressions`:idx: (`subex`:idx:).
##
## .. include:: ../doc/subexes.txt
##
@@ -28,11 +28,13 @@ proc findNormalized(x: string, inArray: openarray[string]): int =
return -1
type
- EInvalidSubex* = object of EInvalidValue ## exception that is raised for
- ## an invalid subex
+ SubexError* = object of ValueError ## exception that is raised for
+ ## an invalid subex
+
+{.deprecated: [EInvalidSubex: SubexError].}
proc raiseInvalidFormat(msg: string) {.noinline.} =
- raise newException(EInvalidSubex, "invalid format string: " & msg)
+ raise newException(SubexError, "invalid format string: " & msg)
type
TFormatParser = object {.pure, final.}
@@ -291,14 +293,16 @@ proc scanDollar(p: var TFormatParser, a: openarray[string], s: var string) =
type
- TSubex* = distinct string ## string that contains a substitution expression
+ Subex* = distinct string ## string that contains a substitution expression
-proc subex*(s: string): TSubex =
+{.deprecated: [TSubex: Subex].}
+
+proc subex*(s: string): Subex =
## constructs a *substitution expression* from `s`. Currently this performs
## no syntax checking but this may change in later versions.
- result = TSubex(s)
+ result = Subex(s)
-proc addf*(s: var string, formatstr: TSubex, a: varargs[string, `$`]) {.
+proc addf*(s: var string, formatstr: Subex, a: varargs[string, `$`]) {.
noSideEffect, rtl, extern: "nfrmtAddf".} =
## The same as ``add(s, formatstr % a)``, but more efficient.
var p: TFormatParser
@@ -312,7 +316,7 @@ proc addf*(s: var string, formatstr: TSubex, a: varargs[string, `$`]) {.
emitChar(p, s, p.f[i])
inc(i)
-proc `%` *(formatstr: TSubex, a: openarray[string]): string {.noSideEffect,
+proc `%` *(formatstr: Subex, a: openarray[string]): string {.noSideEffect,
rtl, extern: "nfrmtFormatOpenArray".} =
## The `substitution`:idx: operator performs string substitutions in
## `formatstr` and returns a modified `formatstr`. This is often called
@@ -321,13 +325,13 @@ proc `%` *(formatstr: TSubex, a: openarray[string]): string {.noSideEffect,
result = newStringOfCap(formatstr.string.len + a.len shl 4)
addf(result, formatstr, a)
-proc `%` *(formatstr: TSubex, a: string): string {.noSideEffect,
+proc `%` *(formatstr: Subex, a: string): string {.noSideEffect,
rtl, extern: "nfrmtFormatSingleElem".} =
## This is the same as ``formatstr % [a]``.
result = newStringOfCap(formatstr.string.len + a.len)
addf(result, formatstr, [a])
-proc format*(formatstr: TSubex, a: varargs[string, `$`]): string {.noSideEffect,
+proc format*(formatstr: Subex, a: varargs[string, `$`]): string {.noSideEffect,
rtl, extern: "nfrmtFormatVarargs".} =
## The `substitution`:idx: operator performs string substitutions in
## `formatstr` and returns a modified `formatstr`. This is often called
diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim
index 20f1d0695..0ebe8a39e 100644
--- a/lib/pure/terminal.nim
+++ b/lib/pure/terminal.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -27,11 +27,11 @@ when defined(windows):
var hTemp = GetStdHandle(STD_OUTPUT_HANDLE)
if DuplicateHandle(GetCurrentProcess(), hTemp, GetCurrentProcess(),
addr(conHandle), 0, 1, DUPLICATE_SAME_ACCESS) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
proc getCursorPos(): tuple [x,y: int] =
var c: TCONSOLESCREENBUFFERINFO
- if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: osError(osLastError())
+ if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: raiseOSError(osLastError())
return (int(c.dwCursorPosition.x), int(c.dwCursorPosition.y))
proc getAttributes(): int16 =
@@ -51,7 +51,7 @@ proc setCursorPos*(x, y: int) =
var c: TCOORD
c.x = int16(x)
c.y = int16(y)
- if SetConsoleCursorPosition(conHandle, c) == 0: osError(osLastError())
+ if SetConsoleCursorPosition(conHandle, c) == 0: raiseOSError(osLastError())
else:
stdout.write("\e[" & $y & ';' & $x & 'f')
@@ -61,10 +61,10 @@ proc setCursorXPos*(x: int) =
when defined(windows):
var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.x = int16(x)
- if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
else:
stdout.write("\e[" & $x & 'G')
@@ -75,10 +75,10 @@ when defined(windows):
when defined(windows):
var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.y = int16(y)
- if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
else:
discard
@@ -155,18 +155,18 @@ proc eraseLine* =
var scrbuf: TCONSOLESCREENBUFFERINFO
var numwrote: DWORD
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.x = 0'i16
- if SetConsoleCursorPosition(conHandle, origin) == 0: osError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
var ht = scrbuf.dwSize.Y - origin.Y
var wt = scrbuf.dwSize.X - origin.X
if FillConsoleOutputCharacter(hStdout,' ', ht*wt,
origin, addr(numwrote)) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes, ht * wt,
scrbuf.dwCursorPosition, addr(numwrote)) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
stdout.write("\e[2K")
setCursorXPos(0)
@@ -178,14 +178,14 @@ proc eraseScreen* =
var numwrote: DWORD
var origin: TCOORD # is inititalized to 0, 0
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: osError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
if FillConsoleOutputCharacter(hStdout, ' ', scrbuf.dwSize.X*scrbuf.dwSize.Y,
origin, addr(numwrote)) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
if FillConsoleOutputAttribute(hStdout, scrbuf.wAttributes,
scrbuf.dwSize.X * scrbuf.dwSize.Y,
origin, addr(numwrote)) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
setCursorXPos(0)
else:
stdout.write("\e[2J")
@@ -199,7 +199,7 @@ proc resetAttributes* {.noconv.} =
stdout.write("\e[0m")
type
- TStyle* = enum ## different styles for text output
+ Style* = enum ## different styles for text output
styleBright = 1, ## bright text
styleDim, ## dim text
styleUnknown, ## unknown
@@ -208,6 +208,8 @@ type
styleReverse = 7, ## unknown
styleHidden ## hidden text
+{.deprecated: [TStyle: Style].}
+
when not defined(windows):
var
# XXX: These better be thread-local
@@ -244,7 +246,7 @@ proc writeStyled*(txt: string, style: set[TStyle] = {styleBright}) =
stdout.write("\e[" & $ord(gBG) & 'm')
type
- TForegroundColor* = enum ## terminal's foreground colors
+ ForegroundColor* = enum ## terminal's foreground colors
fgBlack = 30, ## black
fgRed, ## red
fgGreen, ## green
@@ -254,7 +256,7 @@ type
fgCyan, ## cyan
fgWhite ## white
- TBackgroundColor* = enum ## terminal's background colors
+ BackgroundColor* = enum ## terminal's background colors
bgBlack = 40, ## black
bgRed, ## red
bgGreen, ## green
@@ -264,13 +266,16 @@ type
bgCyan, ## cyan
bgWhite ## white
-proc setForegroundColor*(fg: TForegroundColor, bright=false) =
+{.deprecated: [TForegroundColor: ForegroundColor,
+ TBackgroundColor: BackgroundColor].}
+
+proc setForegroundColor*(fg: ForegroundColor, bright=false) =
## sets the terminal's foreground color
when defined(windows):
var old = getAttributes() and not 0x0007
if bright:
old = old or FOREGROUND_INTENSITY
- const lookup: array [TForegroundColor, int] = [
+ const lookup: array [ForegroundColor, int] = [
0,
(FOREGROUND_RED),
(FOREGROUND_GREEN),
@@ -285,13 +290,13 @@ proc setForegroundColor*(fg: TForegroundColor, bright=false) =
if bright: inc(gFG, 60)
stdout.write("\e[" & $gFG & 'm')
-proc setBackgroundColor*(bg: TBackgroundColor, bright=false) =
+proc setBackgroundColor*(bg: BackgroundColor, bright=false) =
## sets the terminal's background color
when defined(windows):
var old = getAttributes() and not 0x0070
if bright:
old = old or BACKGROUND_INTENSITY
- const lookup: array [TBackgroundColor, int] = [
+ const lookup: array [BackgroundColor, int] = [
0,
(BACKGROUND_RED),
(BACKGROUND_GREEN),
@@ -306,22 +311,22 @@ proc setBackgroundColor*(bg: TBackgroundColor, bright=false) =
if bright: inc(gBG, 60)
stdout.write("\e[" & $gBG & 'm')
-proc isatty*(f: TFile): bool =
+proc isatty*(f: File): bool =
## returns true if `f` is associated with a terminal device.
when defined(posix):
- proc isatty(fildes: TFileHandle): cint {.
+ proc isatty(fildes: FileHandle): cint {.
importc: "isatty", header: "".}
else:
- proc isatty(fildes: TFileHandle): cint {.
+ proc isatty(fildes: FileHandle): cint {.
importc: "_isatty", header: "".}
- result = isatty(fileHandle(f)) != 0'i32
+ result = isatty(getFileHandle(f)) != 0'i32
-proc styledEchoProcessArg(s: string) = write stdout, s
-proc styledEchoProcessArg(style: TStyle) = setStyle({style})
-proc styledEchoProcessArg(style: set[TStyle]) = setStyle style
-proc styledEchoProcessArg(color: TForegroundColor) = setForegroundColor color
-proc styledEchoProcessArg(color: TBackgroundColor) = setBackgroundColor color
+proc styledEchoProcessArg(s: string) = write stdout, s
+proc styledEchoProcessArg(style: Style) = setStyle({style})
+proc styledEchoProcessArg(style: set[Style]) = setStyle style
+proc styledEchoProcessArg(color: ForegroundColor) = setForegroundColor color
+proc styledEchoProcessArg(color: BackgroundColor) = setBackgroundColor color
macro styledEcho*(m: varargs[expr]): stmt =
## to be documented.
diff --git a/lib/pure/times.nim b/lib/pure/times.nim
index c156a4479..2c09fcc4c 100644
--- a/lib/pure/times.nim
+++ b/lib/pure/times.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -21,9 +21,9 @@ import
include "system/inclrtl"
type
- TMonth* = enum ## represents a month
+ Month* = enum ## represents a month
mJan, mFeb, mMar, mApr, mMay, mJun, mJul, mAug, mSep, mOct, mNov, mDec
- TWeekDay* = enum ## represents a weekday
+ WeekDay* = enum ## represents a weekday
dMon, dTue, dWed, dThu, dFri, dSat, dSun
var
@@ -32,12 +32,12 @@ var
when defined(posix) and not defined(JS):
type
- TTimeImpl {.importc: "time_t", header: "".} = int
- TTime* = distinct TTimeImpl ## distinct type that represents a time
- ## measured as number of seconds since the epoch
+ TimeImpl {.importc: "time_t", header: "".} = int
+ Time* = distinct TimeImpl ## distinct type that represents a time
+ ## measured as number of seconds since the epoch
- Ttimeval {.importc: "struct timeval", header: "",
- final, pure.} = object ## struct timeval
+ Timeval {.importc: "struct timeval",
+ header: "".} = object ## struct timeval
tv_sec: int ## Seconds.
tv_usec: int ## Microseconds.
@@ -45,7 +45,7 @@ when defined(posix) and not defined(JS):
# Ok, we could, but I don't want circular dependencies.
# And gettimeofday() is not defined in the posix module anyway. Sigh.
- proc posix_gettimeofday(tp: var Ttimeval, unused: pointer = nil) {.
+ proc posix_gettimeofday(tp: var Timeval, unused: pointer = nil) {.
importc: "gettimeofday", header: "".}
elif defined(windows):
@@ -53,16 +53,16 @@ elif defined(windows):
when defined(vcc):
# newest version of Visual C++ defines time_t to be of 64 bits
- type TTimeImpl {.importc: "time_t", header: "".} = int64
+ type TimeImpl {.importc: "time_t", header: "".} = int64
else:
- type TTimeImpl {.importc: "time_t", header: "".} = int32
+ type TimeImpl {.importc: "time_t", header: "".} = int32
type
- TTime* = distinct TTimeImpl
+ Time* = distinct TimeImpl
elif defined(JS):
type
- TTime* {.final, importc.} = object
+ Time* {.importc.} = object
getDay: proc (): int {.tags: [], raises: [], gcsafe.}
getFullYear: proc (): int {.tags: [], raises: [], gcsafe.}
getHours: proc (): int {.tags: [], raises: [], gcsafe.}
@@ -82,7 +82,7 @@ elif defined(JS):
getUTCSeconds: proc (): int {.tags: [], raises: [], gcsafe.}
getUTCDay: proc (): int {.tags: [], raises: [], gcsafe.}
getYear: proc (): int {.tags: [], raises: [], gcsafe.}
- parse: proc (s: cstring): TTime {.tags: [], raises: [], gcsafe.}
+ parse: proc (s: cstring): Time {.tags: [], raises: [], gcsafe.}
setDate: proc (x: int) {.tags: [], raises: [], gcsafe.}
setFullYear: proc (x: int) {.tags: [], raises: [], gcsafe.}
setHours: proc (x: int) {.tags: [], raises: [], gcsafe.}
@@ -103,7 +103,7 @@ elif defined(JS):
toLocaleString: proc (): cstring {.tags: [], raises: [], gcsafe.}
type
- TTimeInfo* = object of RootObj ## represents a time in different parts
+ TimeInfo* = object of RootObj ## represents a time in different parts
second*: range[0..61] ## The number of seconds after the minute,
## normally in the range 0 to 59, but can
## be up to 61 to allow for leap seconds.
@@ -112,9 +112,9 @@ type
hour*: range[0..23] ## The number of hours past midnight,
## in the range 0 to 23.
monthday*: range[1..31] ## The day of the month, in the range 1 to 31.
- month*: TMonth ## The current month.
+ month*: Month ## The current month.
year*: range[-10_000..10_000] ## The current year.
- weekday*: TWeekDay ## The current day of the week.
+ weekday*: WeekDay ## The current day of the week.
yearday*: range[0..365] ## The number of days since January 1,
## in the range 0 to 365.
## Always 0 if the target is JS.
@@ -127,7 +127,7 @@ type
## I make some assumptions about the data in here. Either
## everything should be positive or everything negative. Zero is
## fine too. Mixed signs will lead to unexpected results.
- TTimeInterval* {.pure.} = object ## a time interval
+ TimeInterval* = object ## a time interval
miliseconds*: int ## The number of miliseconds
seconds*: int ## The number of seconds
minutes*: int ## The number of minutes
@@ -136,55 +136,58 @@ type
months*: int ## The number of months
years*: int ## The number of years
-proc getTime*(): TTime {.tags: [TimeEffect], gcsafe.}
+{.deprecated: [TMonth: Month, TWeekDay: WeekDay, TTime: Time, TTimeval: Timeval,
+ TTimeInterval: TimeInterval, TTimeInfo: TimeInfo].}
+
+proc getTime*(): Time {.tags: [TimeEffect], gcsafe.}
## gets the current calendar time as a UNIX epoch value (number of seconds
## elapsed since 1970) with integer precission. Use epochTime for higher
## resolution.
-proc getLocalTime*(t: TTime): TTimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
+proc getLocalTime*(t: Time): TimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
## converts the calendar time `t` to broken-time representation,
## expressed relative to the user's specified time zone.
-proc getGMTime*(t: TTime): TTimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
+proc getGMTime*(t: Time): TimeInfo {.tags: [TimeEffect], raises: [], gcsafe.}
## converts the calendar time `t` to broken-down time representation,
## expressed in Coordinated Universal Time (UTC).
-proc timeInfoToTime*(timeInfo: TTimeInfo): TTime {.tags: [], gcsafe.}
+proc timeInfoToTime*(timeInfo: TimeInfo): Time {.tags: [], gcsafe.}
## converts a broken-down time structure to
## calendar time representation. The function ignores the specified
## contents of the structure members `weekday` and `yearday` and recomputes
## them from the other information in the broken-down time structure.
-proc fromSeconds*(since1970: float): TTime {.tags: [], raises: [], gcsafe.}
+proc fromSeconds*(since1970: float): Time {.tags: [], raises: [], gcsafe.}
## Takes a float which contains the number of seconds since the unix epoch and
## returns a time object.
-proc fromSeconds*(since1970: int64): TTime {.tags: [], raises: [], gcsafe.} =
+proc fromSeconds*(since1970: int64): Time {.tags: [], raises: [], gcsafe.} =
## Takes an int which contains the number of seconds since the unix epoch and
## returns a time object.
fromSeconds(float(since1970))
-proc toSeconds*(time: TTime): float {.tags: [], raises: [], gcsafe.}
+proc toSeconds*(time: Time): float {.tags: [], raises: [], gcsafe.}
## Returns the time in seconds since the unix epoch.
-proc `$` *(timeInfo: TTimeInfo): string {.tags: [], raises: [], gcsafe.}
- ## converts a `TTimeInfo` object to a string representation.
-proc `$` *(time: TTime): string {.tags: [], raises: [], gcsafe.}
+proc `$` *(timeInfo: TimeInfo): string {.tags: [], raises: [], gcsafe.}
+ ## converts a `TimeInfo` object to a string representation.
+proc `$` *(time: Time): string {.tags: [], raises: [], gcsafe.}
## converts a calendar time to a string representation.
-proc `-`*(a, b: TTime): int64 {.
+proc `-`*(a, b: Time): int64 {.
rtl, extern: "ntDiffTime", tags: [], raises: [].}
## computes the difference of two calendar times. Result is in seconds.
-proc `<`*(a, b: TTime): bool {.
+proc `<`*(a, b: Time): bool {.
rtl, extern: "ntLtTime", tags: [], raises: [].} =
## returns true iff ``a < b``, that is iff a happened before b.
result = a - b < 0
-proc `<=` * (a, b: TTime): bool {.
+proc `<=` * (a, b: Time): bool {.
rtl, extern: "ntLeTime", tags: [], raises: [].}=
## returns true iff ``a <= b``.
result = a - b <= 0
-proc `==`*(a, b: TTime): bool {.
+proc `==`*(a, b: Time): bool {.
rtl, extern: "ntEqTime", tags: [], raises: [].} =
## returns true if ``a == b``, that is if both times represent the same value
result = a - b == 0
@@ -203,8 +206,8 @@ proc getStartMilsecs*(): int {.deprecated, tags: [TimeEffect], gcsafe.}
## version 0.8.10.** Use ``epochTime`` or ``cpuTime`` instead.
proc initInterval*(miliseconds, seconds, minutes, hours, days, months,
- years: int = 0): TTimeInterval =
- ## creates a new ``TTimeInterval``.
+ years: int = 0): TimeInterval =
+ ## creates a new ``TimeInterval``.
result.miliseconds = miliseconds
result.seconds = seconds
result.minutes = minutes
@@ -234,7 +237,7 @@ proc getDaysInMonth*(month: TMonth, year: int): int =
of mApr, mJun, mSep, mNov: result = 30
else: result = 31
-proc toSeconds(a: TTimeInfo, interval: TTimeInterval): float =
+proc toSeconds(a: TimeInfo, interval: TimeInterval): float =
## Calculates how many seconds the interval is worth by adding up
## all the fields
@@ -257,7 +260,7 @@ proc toSeconds(a: TTimeInfo, interval: TTimeInterval): float =
result += float(newinterv.seconds)
result += newinterv.miliseconds / 1000
-proc `+`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
+proc `+`*(a: TimeInfo, interval: TimeInterval): TimeInfo =
## adds ``interval`` time.
##
## **Note:** This has been only briefly tested and it may not be
@@ -269,7 +272,7 @@ proc `+`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
else:
result = getLocalTime(fromSeconds(t + secs))
-proc `-`*(a: TTimeInfo, interval: TTimeInterval): TTimeInfo =
+proc `-`*(a: TimeInfo, interval: TimeInterval): TimeInfo =
## subtracts ``interval`` time.
##
## **Note:** This has been only briefly tested, it is inaccurate especially
@@ -314,38 +317,36 @@ when not defined(JS):
yearday {.importc: "tm_yday".},
isdst {.importc: "tm_isdst".}: cint
- PTimeInfo = ptr StructTM
- PTime = ptr TTime
+ TimeInfoPtr = ptr StructTM
+ Clock {.importc: "clock_t".} = distinct int
- TClock {.importc: "clock_t".} = distinct int
-
- proc localtime(timer: PTime): PTimeInfo {.
+ proc localtime(timer: ptr Time): TimeInfoPtr {.
importc: "localtime", header: "", tags: [].}
- proc gmtime(timer: PTime): PTimeInfo {.
+ proc gmtime(timer: ptr Time): TimeInfoPtr {.
importc: "gmtime", header: "", tags: [].}
- proc timec(timer: PTime): TTime {.
+ proc timec(timer: ptr Time): Time {.
importc: "time", header: "", tags: [].}
- proc mktime(t: StructTM): TTime {.
+ proc mktime(t: StructTM): Time {.
importc: "mktime", header: "", tags: [].}
proc asctime(tblock: StructTM): cstring {.
importc: "asctime", header: "", tags: [].}
- proc ctime(time: PTime): cstring {.
+ proc ctime(time: ptr Time): cstring {.
importc: "ctime", header: "", tags: [].}
# strftime(s: CString, maxsize: int, fmt: CString, t: tm): int {.
# importc: "strftime", header: "".}
- proc clock(): TClock {.importc: "clock", header: "", tags: [TimeEffect].}
- proc difftime(a, b: TTime): float {.importc: "difftime", header: "",
+ proc getClock(): Clock {.importc: "clock", header: "", tags: [TimeEffect].}
+ proc difftime(a, b: Time): float {.importc: "difftime", header: "",
tags: [].}
var
clocksPerSec {.importc: "CLOCKS_PER_SEC", nodecl.}: int
# our own procs on top of that:
- proc tmToTimeInfo(tm: StructTM, local: bool): TTimeInfo =
+ proc tmToTimeInfo(tm: StructTM, local: bool): TimeInfo =
const
- weekDays: array [0..6, TWeekDay] = [
+ weekDays: array [0..6, WeekDay] = [
dSun, dMon, dTue, dWed, dThu, dFri, dSat]
- TTimeInfo(second: int(tm.second),
+ TimeInfo(second: int(tm.second),
minute: int(tm.minute),
hour: int(tm.hour),
monthday: int(tm.monthday),
@@ -364,9 +365,9 @@ when not defined(JS):
timezone: if local: getTimezone() else: 0
)
- proc timeInfoToTM(t: TTimeInfo): StructTM =
+ proc timeInfoToTM(t: TimeInfo): StructTM =
const
- weekDays: array [TWeekDay, int8] = [1'i8,2'i8,3'i8,4'i8,5'i8,6'i8,0'i8]
+ weekDays: array [WeekDay, int8] = [1'i8,2'i8,3'i8,4'i8,5'i8,6'i8,0'i8]
result.second = t.second
result.minute = t.minute
result.hour = t.hour
@@ -378,36 +379,36 @@ when not defined(JS):
result.isdst = if t.isDST: 1 else: 0
when not defined(useNimRtl):
- proc `-` (a, b: TTime): int64 =
+ proc `-` (a, b: Time): int64 =
return toBiggestInt(difftime(a, b))
proc getStartMilsecs(): int =
- #echo "clocks per sec: ", clocksPerSec, "clock: ", int(clock())
- #return clock() div (clocksPerSec div 1000)
+ #echo "clocks per sec: ", clocksPerSec, "clock: ", int(getClock())
+ #return getClock() div (clocksPerSec div 1000)
when defined(macosx):
- result = toInt(toFloat(int(clock())) / (toFloat(clocksPerSec) / 1000.0))
+ result = toInt(toFloat(int(getClock())) / (toFloat(clocksPerSec) / 1000.0))
else:
- result = int(clock()) div (clocksPerSec div 1000)
+ result = int(getClock()) div (clocksPerSec div 1000)
when false:
- var a: Ttimeval
+ var a: Timeval
posix_gettimeofday(a)
result = a.tv_sec * 1000'i64 + a.tv_usec div 1000'i64
#echo "result: ", result
- proc getTime(): TTime = return timec(nil)
- proc getLocalTime(t: TTime): TTimeInfo =
+ proc getTime(): Time = return timec(nil)
+ proc getLocalTime(t: Time): TimeInfo =
var a = t
result = tmToTimeInfo(localtime(addr(a))[], true)
# copying is needed anyway to provide reentrancity; thus
# the conversion is not expensive
- proc getGMTime(t: TTime): TTimeInfo =
+ proc getGMTime(t: Time): TimeInfo =
var a = t
result = tmToTimeInfo(gmtime(addr(a))[], false)
# copying is needed anyway to provide reentrancity; thus
# the conversion is not expensive
- proc timeInfoToTime(timeInfo: TTimeInfo): TTime =
+ proc timeInfoToTime(timeInfo: TimeInfo): Time =
var cTimeInfo = timeInfo # for C++ we have to make a copy,
# because the header of mktime is broken in my version of libc
return mktime(timeInfoToTM(cTimeInfo))
@@ -419,12 +420,12 @@ when not defined(JS):
add(result, p[i])
inc(i)
- proc `$`(timeInfo: TTimeInfo): string =
+ proc `$`(timeInfo: TimeInfo): string =
# BUGFIX: asctime returns a newline at the end!
var p = asctime(timeInfoToTM(timeInfo))
result = toStringTillNL(p)
- proc `$`(time: TTime): string =
+ proc `$`(time: Time): string =
# BUGFIX: ctime returns a newline at the end!
var a = time
return toStringTillNL(ctime(addr(a)))
@@ -433,13 +434,13 @@ when not defined(JS):
epochDiff = 116444736000000000'i64
rateDiff = 10000000'i64 # 100 nsecs
- proc unixTimeToWinTime*(t: TTime): int64 =
- ## converts a UNIX `TTime` (``time_t``) to a Windows file time
+ proc unixTimeToWinTime*(t: Time): int64 =
+ ## converts a UNIX `Time` (``time_t``) to a Windows file time
result = int64(t) * rateDiff + epochDiff
- proc winTimeToUnixTime*(t: int64): TTime =
- ## converts a Windows time to a UNIX `TTime` (``time_t``)
- result = TTime((t - epochDiff) div rateDiff)
+ proc winTimeToUnixTime*(t: int64): Time =
+ ## converts a Windows time to a UNIX `Time` (``time_t``)
+ result = Time((t - epochDiff) div rateDiff)
proc getTzname(): tuple[nonDST, DST: string] =
return ($tzname[0], $tzname[1])
@@ -447,9 +448,9 @@ when not defined(JS):
proc getTimezone(): int =
return timezone
- proc fromSeconds(since1970: float): TTime = TTime(since1970)
+ proc fromSeconds(since1970: float): Time = Time(since1970)
- proc toSeconds(time: TTime): float = float(time)
+ proc toSeconds(time: Time): float = float(time)
when not defined(useNimRtl):
proc epochTime(): float =
@@ -468,15 +469,15 @@ when not defined(JS):
{.error: "unknown OS".}
proc cpuTime(): float =
- result = toFloat(int(clock())) / toFloat(clocksPerSec)
+ result = toFloat(int(getClock())) / toFloat(clocksPerSec)
elif defined(JS):
- proc newDate(): TTime {.importc: "new Date".}
- proc internGetTime(): TTime {.importc: "new Date", tags: [].}
+ proc newDate(): Time {.importc: "new Date".}
+ proc internGetTime(): Time {.importc: "new Date", tags: [].}
- proc newDate(value: float): TTime {.importc: "new Date".}
- proc newDate(value: string): TTime {.importc: "new Date".}
- proc getTime(): TTime =
+ proc newDate(value: float): Time {.importc: "new Date".}
+ proc newDate(value: string): Time {.importc: "new Date".}
+ proc getTime(): Time =
# Warning: This is something different in JS.
return newDate()
@@ -484,7 +485,7 @@ elif defined(JS):
weekDays: array [0..6, TWeekDay] = [
dSun, dMon, dTue, dWed, dThu, dFri, dSat]
- proc getLocalTime(t: TTime): TTimeInfo =
+ proc getLocalTime(t: Time): TimeInfo =
result.second = t.getSeconds()
result.minute = t.getMinutes()
result.hour = t.getHours()
@@ -494,7 +495,7 @@ elif defined(JS):
result.weekday = weekDays[t.getDay()]
result.yearday = 0
- proc getGMTime(t: TTime): TTimeInfo =
+ proc getGMTime(t: Time): TimeInfo =
result.second = t.getUTCSeconds()
result.minute = t.getUTCMinutes()
result.hour = t.getUTCHours()
@@ -504,7 +505,7 @@ elif defined(JS):
result.weekday = weekDays[t.getUTCDay()]
result.yearday = 0
- proc timeInfoToTime*(timeInfo: TTimeInfo): TTime =
+ proc timeInfoToTime*(timeInfo: TimeInfo): Time =
result = internGetTime()
result.setSeconds(timeInfo.second)
result.setMinutes(timeInfo.minute)
@@ -513,10 +514,10 @@ elif defined(JS):
result.setFullYear(timeInfo.year)
result.setDate(timeInfo.monthday)
- proc `$`(timeInfo: TTimeInfo): string = return $(TimeInfoToTIme(timeInfo))
- proc `$`(time: TTime): string = return $time.toLocaleString()
+ proc `$`(timeInfo: TimeInfo): string = return $(TimeInfoToTIme(timeInfo))
+ proc `$`(time: Time): string = return $time.toLocaleString()
- proc `-` (a, b: TTime): int64 =
+ proc `-` (a, b: Time): int64 =
return a.getTime() - b.getTime()
var
@@ -526,11 +527,11 @@ elif defined(JS):
## get the miliseconds from the start of the program
return int(getTime() - startMilsecs)
- proc valueOf(time: TTime): float {.importcpp: "getTime", tags:[]}
+ proc valueOf(time: Time): float {.importcpp: "getTime", tags:[]}
- proc fromSeconds(since1970: float): TTime = result = newDate(since1970)
+ proc fromSeconds(since1970: float): Time = result = newDate(since1970)
- proc toSeconds(time: TTime): float = result = time.valueOf() / 1000
+ proc toSeconds(time: Time): float = result = time.valueOf() / 1000
proc getTimezone(): int = result = newDate().getTimezoneOffset()
@@ -546,20 +547,20 @@ proc getClockStr*(): string {.rtl, extern: "nt$1", tags: [TimeEffect].} =
result = intToStr(ti.hour, 2) & ':' & intToStr(ti.minute, 2) &
':' & intToStr(ti.second, 2)
-proc `$`*(day: TWeekDay): string =
- ## stingify operator for ``TWeekDay``.
- const lookup: array[TWeekDay, string] = ["Monday", "Tuesday", "Wednesday",
+proc `$`*(day: WeekDay): string =
+ ## stingify operator for ``WeekDay``.
+ const lookup: array[WeekDay, string] = ["Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday", "Sunday"]
return lookup[day]
-proc `$`*(m: TMonth): string =
+proc `$`*(m: Month): string =
## stingify operator for ``TMonth``.
- const lookup: array[TMonth, string] = ["January", "February", "March",
+ const lookup: array[Month, string] = ["January", "February", "March",
"April", "May", "June", "July", "August", "September", "October",
"November", "December"]
return lookup[m]
-proc format_token(info: TTimeInfo, token: string, buf: var string) =
+proc formatToken(info: TimeInfo, token: string, buf: var string) =
## Helper of the format proc to parse individual tokens.
##
## Pass the found token in the user input string, and the buffer where the
@@ -672,7 +673,7 @@ proc format_token(info: TTimeInfo, token: string, buf: var string) =
raise newException(ValueError, "Invalid format string: " & token)
-proc format*(info: TTimeInfo, f: string): string =
+proc format*(info: TimeInfo, f: string): string =
## This function formats `info` as specified by `f`. The following format
## specifiers are available:
##
@@ -718,7 +719,7 @@ proc format*(info: TTimeInfo, f: string): string =
while true:
case f[i]
of ' ', '-', '/', ':', '\'', '\0', '(', ')', '[', ']', ',':
- format_token(info, currentF, result)
+ formatToken(info, currentF, result)
currentF = ""
if f[i] == '\0': break
@@ -735,7 +736,7 @@ proc format*(info: TTimeInfo, f: string): string =
if currentF.len < 1 or currentF[high(currentF)] == f[i]:
currentF.add(f[i])
else:
- format_token(info, currentF, result)
+ formatToken(info, currentF, result)
dec(i) # Move position back to re-process the character separately.
currentF = ""
@@ -764,7 +765,7 @@ when isMainModule:
" ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") ==
"27 27 Mon Monday 4 04 16 16 6 06 1 01 Jan January 29 29 P PM 5 75 975 1975 01975 0 00 00:00 UTC"
- when not defined(JS) and sizeof(TTime) == 8:
+ when not defined(JS) and sizeof(Time) == 8:
var t3 = getGMTime(fromSeconds(889067643645)) # Fri 7 Jun 19:20:45 BST 30143
assert t3.format("d dd ddd dddd h hh H HH m mm M MM MMM MMMM s" &
" ss t tt y yy yyy yyyy yyyyy z zz zzz ZZZ") ==
diff --git a/lib/pure/typetraits.nim b/lib/pure/typetraits.nim
index 3203ee699..1180b98f0 100644
--- a/lib/pure/typetraits.nim
+++ b/lib/pure/typetraits.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Nimrod Contributors
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/unicode.nim b/lib/pure/unicode.nim
index 6e73eea3f..c2eb001f6 100644
--- a/lib/pure/unicode.nim
+++ b/lib/pure/unicode.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -14,13 +14,15 @@
include "system/inclrtl"
type
- IRune = int # underlying type of TRune
- TRune* = distinct IRune ## type that can hold any Unicode character
- TRune16* = distinct int16 ## 16 bit Unicode character
+ RuneImpl = int # underlying type of Rune
+ Rune* = distinct RuneImpl ## type that can hold any Unicode character
+ Rune16* = distinct int16 ## 16 bit Unicode character
+
+{.deprecated: [TRune: Rune, TRune16: Rune16].}
-proc `<=%`*(a, b: TRune): bool = return int(a) <=% int(b)
-proc `<%`*(a, b: TRune): bool = return int(a) <% int(b)
-proc `==`*(a, b: TRune): bool = return int(a) == int(b)
+proc `<=%`*(a, b: Rune): bool = return int(a) <=% int(b)
+proc `<%`*(a, b: Rune): bool = return int(a) <% int(b)
+proc `==`*(a, b: Rune): bool = return int(a) == int(b)
template ones(n: expr): expr = ((1 shl n)-1)
@@ -52,17 +54,17 @@ template fastRuneAt*(s: string, i: int, result: expr, doInc = true) =
## `i` is incremented by the number of bytes that have been processed.
bind ones
if ord(s[i]) <=% 127:
- result = TRune(ord(s[i]))
+ result = Rune(ord(s[i]))
when doInc: inc(i)
elif ord(s[i]) shr 5 == 0b110:
# assert(ord(s[i+1]) shr 6 == 0b10)
- result = TRune((ord(s[i]) and (ones(5))) shl 6 or
- (ord(s[i+1]) and ones(6)))
+ result = Rune((ord(s[i]) and (ones(5))) shl 6 or
+ (ord(s[i+1]) and ones(6)))
when doInc: inc(i, 2)
elif ord(s[i]) shr 4 == 0b1110:
# assert(ord(s[i+1]) shr 6 == 0b10)
# assert(ord(s[i+2]) shr 6 == 0b10)
- result = TRune((ord(s[i]) and ones(4)) shl 12 or
+ result = Rune((ord(s[i]) and ones(4)) shl 12 or
(ord(s[i+1]) and ones(6)) shl 6 or
(ord(s[i+2]) and ones(6)))
when doInc: inc(i, 3)
@@ -70,7 +72,7 @@ template fastRuneAt*(s: string, i: int, result: expr, doInc = true) =
# assert(ord(s[i+1]) shr 6 == 0b10)
# assert(ord(s[i+2]) shr 6 == 0b10)
# assert(ord(s[i+3]) shr 6 == 0b10)
- result = TRune((ord(s[i]) and ones(3)) shl 18 or
+ result = Rune((ord(s[i]) and ones(3)) shl 18 or
(ord(s[i+1]) and ones(6)) shl 12 or
(ord(s[i+2]) and ones(6)) shl 6 or
(ord(s[i+3]) and ones(6)))
@@ -80,7 +82,7 @@ template fastRuneAt*(s: string, i: int, result: expr, doInc = true) =
# assert(ord(s[i+2]) shr 6 == 0b10)
# assert(ord(s[i+3]) shr 6 == 0b10)
# assert(ord(s[i+4]) shr 6 == 0b10)
- result = TRune((ord(s[i]) and ones(2)) shl 24 or
+ result = Rune((ord(s[i]) and ones(2)) shl 24 or
(ord(s[i+1]) and ones(6)) shl 18 or
(ord(s[i+2]) and ones(6)) shl 12 or
(ord(s[i+3]) and ones(6)) shl 6 or
@@ -92,7 +94,7 @@ template fastRuneAt*(s: string, i: int, result: expr, doInc = true) =
# assert(ord(s[i+3]) shr 6 == 0b10)
# assert(ord(s[i+4]) shr 6 == 0b10)
# assert(ord(s[i+5]) shr 6 == 0b10)
- result = TRune((ord(s[i]) and ones(1)) shl 30 or
+ result = Rune((ord(s[i]) and ones(1)) shl 30 or
(ord(s[i+1]) and ones(6)) shl 24 or
(ord(s[i+2]) and ones(6)) shl 18 or
(ord(s[i+3]) and ones(6)) shl 12 or
@@ -100,16 +102,16 @@ template fastRuneAt*(s: string, i: int, result: expr, doInc = true) =
(ord(s[i+5]) and ones(6)))
when doInc: inc(i, 6)
else:
- result = TRune(ord(s[i]))
+ result = Rune(ord(s[i]))
when doInc: inc(i)
-proc runeAt*(s: string, i: int): TRune =
+proc runeAt*(s: string, i: int): Rune =
## returns the unicode character in `s` at byte index `i`
fastRuneAt(s, i, result, false)
-proc toUTF8*(c: TRune): string {.rtl, extern: "nuc$1".} =
+proc toUTF8*(c: Rune): string {.rtl, extern: "nuc$1".} =
## converts a rune into its UTF8 representation
- var i = IRune(c)
+ var i = RuneImpl(c)
if i <=% 127:
result = newString(1)
result[0] = chr(i)
@@ -132,11 +134,11 @@ proc toUTF8*(c: TRune): string {.rtl, extern: "nuc$1".} =
result = newString(1)
result[0] = chr(i)
-proc `$`*(rune: TRune): string =
+proc `$`*(rune: Rune): string =
## converts a rune to a string
rune.toUTF8
-proc `$`*(runes: seq[TRune]): string =
+proc `$`*(runes: seq[Rune]): string =
## converts a sequence of runes to a string
result = ""
for rune in runes: result.add(rune.toUTF8)
@@ -1100,7 +1102,7 @@ const
0x01f1, 501, #
0x01f3, 499] #
-proc binarySearch(c: IRune, tab: openArray[IRune], len, stride: int): int =
+proc binarySearch(c: RuneImpl, tab: openArray[RuneImpl], len, stride: int): int =
var n = len
var t = 0
while n > 1:
@@ -1115,41 +1117,41 @@ proc binarySearch(c: IRune, tab: openArray[IRune], len, stride: int): int =
return t
return -1
-proc toLower*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
+proc toLower*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into lower case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`.
- var c = IRune(c)
+ var c = RuneImpl(c)
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
- return TRune(c + tolowerRanges[p+2] - 500)
+ return Rune(c + tolowerRanges[p+2] - 500)
p = binarySearch(c, tolowerSinglets, len(tolowerSinglets) div 2, 2)
if p >= 0 and c == tolowerSinglets[p]:
- return TRune(c + tolowerSinglets[p+1] - 500)
- return TRune(c)
+ return Rune(c + tolowerSinglets[p+1] - 500)
+ return Rune(c)
-proc toUpper*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
+proc toUpper*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
## Converts `c` into upper case. This works for any Unicode character.
## If possible, prefer `toLower` over `toUpper`.
- var c = IRune(c)
+ var c = RuneImpl(c)
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
- return TRune(c + toupperRanges[p+2] - 500)
+ return Rune(c + toupperRanges[p+2] - 500)
p = binarySearch(c, toupperSinglets, len(toupperSinglets) div 2, 2)
if p >= 0 and c == toupperSinglets[p]:
- return TRune(c + toupperSinglets[p+1] - 500)
- return TRune(c)
+ return Rune(c + toupperSinglets[p+1] - 500)
+ return Rune(c)
-proc toTitle*(c: TRune): TRune {.rtl, extern: "nuc$1", procvar.} =
- var c = IRune(c)
+proc toTitle*(c: Rune): Rune {.rtl, extern: "nuc$1", procvar.} =
+ var c = RuneImpl(c)
var p = binarySearch(c, toTitleSinglets, len(toTitleSinglets) div 2, 2)
if p >= 0 and c == toTitleSinglets[p]:
- return TRune(c + toTitleSinglets[p+1] - 500)
- return TRune(c)
+ return Rune(c + toTitleSinglets[p+1] - 500)
+ return Rune(c)
-proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
+proc isLower*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a lower case Unicode character
## If possible, prefer `isLower` over `isUpper`.
- var c = IRune(c)
+ var c = RuneImpl(c)
# Note: toUpperRanges is correct here!
var p = binarySearch(c, toupperRanges, len(toupperRanges) div 3, 3)
if p >= 0 and c >= toupperRanges[p] and c <= toupperRanges[p+1]:
@@ -1158,10 +1160,10 @@ proc isLower*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
if p >= 0 and c == toupperSinglets[p]:
return true
-proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
+proc isUpper*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a upper case Unicode character
## If possible, prefer `isLower` over `isUpper`.
- var c = IRune(c)
+ var c = RuneImpl(c)
# Note: toLowerRanges is correct here!
var p = binarySearch(c, tolowerRanges, len(tolowerRanges) div 3, 3)
if p >= 0 and c >= tolowerRanges[p] and c <= tolowerRanges[p+1]:
@@ -1170,11 +1172,11 @@ proc isUpper*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
if p >= 0 and c == tolowerSinglets[p]:
return true
-proc isAlpha*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
+proc isAlpha*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is an *alpha* Unicode character (i.e. a letter)
if isUpper(c) or isLower(c):
return true
- var c = IRune(c)
+ var c = RuneImpl(c)
var p = binarySearch(c, alphaRanges, len(alphaRanges) div 2, 2)
if p >= 0 and c >= alphaRanges[p] and c <= alphaRanges[p+1]:
return true
@@ -1182,21 +1184,21 @@ proc isAlpha*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
if p >= 0 and c == alphaSinglets[p]:
return true
-proc isTitle*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
+proc isTitle*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
return isUpper(c) and isLower(c)
-proc isWhiteSpace*(c: TRune): bool {.rtl, extern: "nuc$1", procvar.} =
+proc isWhiteSpace*(c: Rune): bool {.rtl, extern: "nuc$1", procvar.} =
## returns true iff `c` is a Unicode whitespace character
- var c = IRune(c)
+ var c = RuneImpl(c)
var p = binarySearch(c, spaceRanges, len(spaceRanges) div 2, 2)
if p >= 0 and c >= spaceRanges[p] and c <= spaceRanges[p+1]:
return true
-iterator runes*(s: string): TRune =
+iterator runes*(s: string): Rune =
## iterates over any unicode character of the string `s`.
var
i = 0
- result: TRune
+ result: Rune
while i < len(s):
fastRuneAt(s, i, result, true)
yield result
@@ -1209,12 +1211,12 @@ proc cmpRunesIgnoreCase*(a, b: string): int {.rtl, extern: "nuc$1", procvar.} =
## | > 0 iff a > b
var i = 0
var j = 0
- var ar, br: TRune
+ var ar, br: Rune
while i < a.len and j < b.len:
# slow path:
fastRuneAt(a, i, ar)
fastRuneAt(b, j, br)
- result = IRune(toLower(ar)) - IRune(toLower(br))
+ result = RuneImpl(toLower(ar)) - RuneImpl(toLower(br))
if result != 0: return
result = a.len - b.len
diff --git a/lib/pure/unidecode/unidecode.nim b/lib/pure/unidecode/unidecode.nim
index 1d36d11b5..798eef5d0 100644
--- a/lib/pure/unidecode/unidecode.nim
+++ b/lib/pure/unidecode/unidecode.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -55,7 +55,7 @@ proc unidecode*(s: string): string =
##
## Example:
##
- ## ..code-block:: nimrod
+ ## ..code-block:: nim
##
## unidecode("\x53\x17\x4E\xB0")
##
diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim
index 7cc95f0ad..f26d8c3e6 100644
--- a/lib/pure/unittest.nim
+++ b/lib/pure/unittest.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Nimrod Contributors
#
# See the file "copying.txt", included in this
@@ -26,16 +26,19 @@ when not defined(ECMAScript):
import terminal
type
- TTestStatus* = enum OK, FAILED
- TOutputLevel* = enum PRINT_ALL, PRINT_FAILURES, PRINT_NONE
+ TestStatus* = enum OK, FAILED
+ OutputLevel* = enum PRINT_ALL, PRINT_FAILURES, PRINT_NONE
+
+{.deprecated: [TTestStatus: TestStatus, TOutputLevel: OutputLevel]}
var
- # XXX: These better be thread-local
- AbortOnError*: bool
- OutputLevel*: TOutputLevel
- ColorOutput*: bool
+ abortOnError* {.threadvar.}: bool
+ outputLevel* {.threadvar.}: OutputLevel
+ colorOutput* {.threadvar.}: bool
- checkpoints: seq[string] = @[]
+ checkpoints {.threadvar.}: seq[string]
+
+checkpoints = @[]
template TestSetupIMPL*: stmt {.immediate, dirty.} = discard
template TestTeardownIMPL*: stmt {.immediate, dirty.} = discard
@@ -53,7 +56,7 @@ template suite*(name: expr, body: stmt): stmt {.immediate, dirty.} =
body
-proc testDone(name: string, s: TTestStatus) =
+proc testDone(name: string, s: TestStatus) =
if s == FAILED:
program_result += 1
@@ -192,15 +195,15 @@ when declared(stdout):
## Reading settings
var envOutLvl = os.getEnv("NIMTEST_OUTPUT_LVL").string
- AbortOnError = existsEnv("NIMTEST_ABORT_ON_ERROR")
- ColorOutput = not existsEnv("NIMTEST_NO_COLOR")
+ abortOnError = existsEnv("NIMTEST_ABORT_ON_ERROR")
+ colorOutput = not existsEnv("NIMTEST_NO_COLOR")
else:
var envOutLvl = "" # TODO
- ColorOutput = false
+ colorOutput = false
if envOutLvl.len > 0:
- for opt in countup(low(TOutputLevel), high(TOutputLevel)):
+ for opt in countup(low(OutputLevel), high(OutputLevel)):
if $opt == envOutLvl:
- OutputLevel = opt
+ outputLevel = opt
break
diff --git a/lib/pure/uri.nim b/lib/pure/uri.nim
index 7ec823033..ed1059cc2 100644
--- a/lib/pure/uri.nim
+++ b/lib/pure/uri.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -11,12 +11,14 @@
import strutils, parseutils
type
- TUrl* = distinct string
+ Url* = distinct string
- TUri* = object
+ Uri* = object
scheme*, username*, password*: string
hostname*, port*, path*, query*, anchor*: string
+{.deprecated: [TUrl: Url, TUri: Uri].}
+
proc `$`*(url: TUrl): string {.deprecated.} =
## **Deprecated since 0.9.6**: Use ``TUri`` instead.
return string(url)
@@ -172,7 +174,7 @@ proc combine*(base: TUri, reference: TUri): TUri =
##
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block::
## let foo = combine(parseUri("http://example.com/foo/bar"), parseUri("/baz"))
## assert foo.path == "/baz"
##
@@ -229,7 +231,7 @@ proc `/`*(x: TUri, path: string): TUri =
##
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block::
## let foo = parseUri("http://example.com/foo/bar") / parseUri("/baz")
## assert foo.path == "/foo/bar/baz"
##
diff --git a/lib/pure/xmldom.nim b/lib/pure/xmldom.nim
index d63b6c5dd..afd26a584 100644
--- a/lib/pure/xmldom.nim
+++ b/lib/pure/xmldom.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -9,7 +9,8 @@
import strutils
-## This module implements XML DOM Level 2 Core specification(http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html)
+## This module implements XML DOM Level 2 Core
+## specification (http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html)
#http://www.w3.org/TR/2000/REC-DOM-Level-2-Core-20001113/core.html
diff --git a/lib/pure/xmldomparser.nim b/lib/pure/xmldomparser.nim
index fda46bac0..b92a9600c 100644
--- a/lib/pure/xmldomparser.nim
+++ b/lib/pure/xmldomparser.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Dominik Picheta
#
# See the file "copying.txt", included in this
@@ -156,7 +156,7 @@ proc loadXMLFile*(path: string): PDocument =
when isMainModule:
- var xml = loadXMLFile(r"C:\Users\Dominik\Desktop\Code\Nimrod\xmldom\test.xml")
+ var xml = loadXMLFile("nim/xmldom/test.xml")
#echo(xml.getElementsByTagName("m:test2")[0].namespaceURI)
#echo(xml.getElementsByTagName("bla:test")[0].namespaceURI)
#echo(xml.getElementsByTagName("test")[0].namespaceURI)
diff --git a/lib/pure/xmlparser.nim b/lib/pure/xmlparser.nim
index 8b8bb3b03..83bd45e7d 100644
--- a/lib/pure/xmlparser.nim
+++ b/lib/pure/xmlparser.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -12,9 +12,11 @@
import streams, parsexml, strtabs, xmltree
type
- EInvalidXml* = object of EInvalidValue ## exception that is raised
- ## for invalid XML
- errors*: seq[string] ## all detected parsing errors
+ XmlError* = object of ValueError ## exception that is raised
+ ## for invalid XML
+ errors*: seq[string] ## all detected parsing errors
+
+{.deprecated: [EInvalidXml: XmlError].}
proc raiseInvalidXml(errors: seq[string]) =
var e: ref EInvalidXml
@@ -23,12 +25,12 @@ proc raiseInvalidXml(errors: seq[string]) =
e.errors = errors
raise e
-proc addNode(father, son: PXmlNode) =
+proc addNode(father, son: XmlNode) =
if son != nil: add(father, son)
-proc parse(x: var TXmlParser, errors: var seq[string]): PXmlNode
+proc parse(x: var XmlParser, errors: var seq[string]): XmlNode
-proc untilElementEnd(x: var TXmlParser, result: PXmlNode,
+proc untilElementEnd(x: var XmlParser, result: XmlNode,
errors: var seq[string]) =
while true:
case x.kind
@@ -45,7 +47,7 @@ proc untilElementEnd(x: var TXmlParser, result: PXmlNode,
else:
result.addNode(parse(x, errors))
-proc parse(x: var TXmlParser, errors: var seq[string]): PXmlNode =
+proc parse(x: var XmlParser, errors: var seq[string]): XmlNode =
case x.kind
of xmlComment:
result = newComment(x.charData)
@@ -98,11 +100,11 @@ proc parse(x: var TXmlParser, errors: var seq[string]): PXmlNode =
next(x)
of xmlEof: discard
-proc parseXml*(s: PStream, filename: string,
- errors: var seq[string]): PXmlNode =
+proc parseXml*(s: Stream, filename: string,
+ errors: var seq[string]): XmlNode =
## parses the XML from stream `s` and returns a ``PXmlNode``. Every
## occured parsing error is added to the `errors` sequence.
- var x: TXmlParser
+ var x: XmlParser
open(x, s, filename, {reportComments})
while true:
x.next()
@@ -118,14 +120,14 @@ proc parseXml*(s: PStream, filename: string,
break
close(x)
-proc parseXml*(s: PStream): PXmlNode =
+proc parseXml*(s: Stream): XmlNode =
## parses the XTML from stream `s` and returns a ``PXmlNode``. All parsing
## errors are turned into an ``EInvalidXML`` exception.
var errors: seq[string] = @[]
result = parseXml(s, "unknown_html_doc", errors)
if errors.len > 0: raiseInvalidXMl(errors)
-proc loadXml*(path: string, errors: var seq[string]): PXmlNode =
+proc loadXml*(path: string, errors: var seq[string]): XmlNode =
## Loads and parses XML from file specified by ``path``, and returns
## a ``PXmlNode``. Every occured parsing error is added to the `errors`
## sequence.
@@ -133,7 +135,7 @@ proc loadXml*(path: string, errors: var seq[string]): PXmlNode =
if s == nil: raise newException(EIO, "Unable to read file: " & path)
result = parseXml(s, path, errors)
-proc loadXml*(path: string): PXmlNode =
+proc loadXml*(path: string): XmlNode =
## Loads and parses XML from file specified by ``path``, and returns
## a ``PXmlNode``. All parsing errors are turned into an ``EInvalidXML``
## exception.
@@ -148,7 +150,7 @@ when isMainModule:
var x = loadXml(paramStr(1), errors)
for e in items(errors): echo e
- var f: TFile
+ var f: File
if open(f, "xmltest.txt", fmWrite):
f.write($x)
f.close()
diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim
index 7392eb470..6007232c5 100644
--- a/lib/pure/xmltree.nim
+++ b/lib/pure/xmltree.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -12,33 +12,36 @@
import macros, strtabs
type
- PXmlNode* = ref TXmlNode ## an XML tree consists of ``PXmlNode``'s.
+ XmlNode* = ref TXmlNode ## an XML tree consists of ``PXmlNode``'s.
- TXmlNodeKind* = enum ## different kinds of ``PXmlNode``'s
+ XmlNodeKind* = enum ## different kinds of ``PXmlNode``'s
xnText, ## a text element
xnElement, ## an element with 0 or more children
xnCData, ## a CDATA node
xnEntity, ## an entity (like ``&thing;``)
xnComment ## an XML comment
- PXmlAttributes* = PStringTable ## an alias for a string to string mapping
+ XmlAttributes* = StringTableRef ## an alias for a string to string mapping
- TXmlNode {.pure, final, acyclic.} = object
- case k: TXmlNodeKind # private, use the kind() proc to read this field.
+ XmlNodeObj {.acyclic.} = object
+ case k: XmlNodeKind # private, use the kind() proc to read this field.
of xnText, xnComment, xnCData, xnEntity:
fText: string
of xnElement:
fTag: string
- s: seq[PXmlNode]
- fAttr: PXmlAttributes
+ s: seq[XmlNode]
+ fAttr: XmlAttributes
fClientData: int ## for other clients
-
-proc newXmlNode(kind: TXmlNodeKind): PXmlNode =
- ## creates a new ``PXmlNode``.
+
+{.deprecated: [PXmlNode: XmlNode, TXmlNodeKind: XmlNodeKind, PXmlAttributes:
+ XmlAttributes, TXmlNode: XmlNodeObj].}
+
+proc newXmlNode(kind: XmlNodeKind): XmlNode =
+ ## creates a new ``XmlNode``.
new(result)
result.k = kind
-proc newElement*(tag: string): PXmlNode =
+proc newElement*(tag: string): XmlNode =
## creates a new ``PXmlNode`` of kind ``xnText`` with the given `tag`.
result = newXmlNode(xnElement)
result.fTag = tag
@@ -304,10 +307,10 @@ proc findAll*(n: PXmlNode, tag: string, result: var seq[PXmlNode]) =
## Found nodes satisfying the condition will be appended to the `result`
## sequence, which can't be nil or the proc will crash. Usage example:
##
- ## .. code-block:: nimrod
+ ## .. code-block::
## var
- ## html: PXmlNode
- ## tags: seq[PXmlNode] = @[]
+ ## html: XmlNode
+ ## tags: seq[XmlNode] = @[]
##
## html = buildHtml()
## findAll(html, "img", tags)
@@ -326,8 +329,8 @@ proc findAll*(n: PXmlNode, tag: string, result: var seq[PXmlNode]) =
proc findAll*(n: PXmlNode, tag: string): seq[PXmlNode] =
## Shortcut version to assign in let blocks. Example:
##
- ## .. code-block:: nimrod
- ## var html: PXmlNode
+ ## .. code-block::
+ ## var html: XmlNode
##
## html = buildHtml(html)
## for imgTag in html.findAll("img"):
diff --git a/lib/system.nim b/lib/system.nim
index ad1cbd423..0e9712c24 100644
--- a/lib/system.nim
+++ b/lib/system.nim
@@ -2437,6 +2437,8 @@ when not defined(JS): #and not defined(NimrodVM):
## returns the OS file handle of the file ``f``. This is only useful for
## platform specific programming.
+ {.deprecated: [fileHandle: getFileHandle].}
+
proc cstringArrayToSeq*(a: cstringArray, len: int): seq[string] =
## converts a ``cstringArray`` to a ``seq[string]``. `a` is supposed to be
## of length ``len``.
diff --git a/todo.txt b/todo.txt
index 68965584b..fef88efc2 100644
--- a/todo.txt
+++ b/todo.txt
@@ -49,7 +49,6 @@ Bugs
- bug: type conversions concerning proc types are weird
- compilation of niminst takes way too long. looks like a regression
- docgen: sometimes effects are listed twice
-- 'result' is not properly cleaned for NRVO --> use uninit checking instead
- blocks can "export" an identifier but the CCG generates {} for them ...
From df172806ea153c2b058165cc09f836dd79350774 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 00:24:52 +0200
Subject: [PATCH 012/409] big rename
---
compiler/cgen.nim | 2 +-
lib/posix/posix.nim | 7 +-
lib/pure/collections/sets.nim | 10 +--
lib/pure/collections/tables.nim | 4 +-
lib/pure/lexbase.nim | 4 +-
lib/pure/memfiles.nim | 4 +-
lib/pure/os.nim | 124 ++++++++++++++++----------------
lib/pure/osproc.nim | 34 ++++-----
lib/pure/strtabs.nim | 6 +-
lib/pure/strutils.nim | 4 +-
lib/pure/times.nim | 8 +--
lib/windows/winlean.nim | 4 +-
12 files changed, 108 insertions(+), 103 deletions(-)
diff --git a/compiler/cgen.nim b/compiler/cgen.nim
index 315b55801..deccf9ced 100644
--- a/compiler/cgen.nim
+++ b/compiler/cgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim
index e1bcd9dfc..43139389b 100644
--- a/lib/posix/posix.nim
+++ b/lib/posix/posix.nim
@@ -29,7 +29,7 @@
{.deadCodeElim:on.}
-from times import TTime
+from times import Time
const
hasSpawnH = not defined(haiku) # should exist for every Posix system nowadays
@@ -83,8 +83,11 @@ else:
## A type representing a directory stream.
type
- TSocketHandle* = distinct cint # The type used to represent socket descriptors
+ SocketHandle* = distinct cint # The type used to represent socket descriptors
+{.deprecated: [TSocketHandle: SocketHandle].}
+
+type
Tdirent* {.importc: "struct dirent",
header: "", final, pure.} = object ## dirent_t struct
d_ino*: Tino ## File serial number.
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index 1201241f1..27f5ef07a 100644
--- a/lib/pure/collections/sets.nim
+++ b/lib/pure/collections/sets.nim
@@ -149,11 +149,11 @@ proc contains*[A](s: TSet[A], key: A): bool =
var index = rawGet(s, key)
result = index >= 0
-proc rawInsert[A](s: var TSet[A], data: var TKeyValuePairSeq[A], key: A) =
+proc rawInsert[A](s: var TSet[A], data: var KeyValuePairSeq[A], key: A) =
rawInsertImpl()
proc enlarge[A](s: var TSet[A]) =
- var n: TKeyValuePairSeq[A]
+ var n: KeyValuePairSeq[A]
newSeq(n, len(s.data) * growthFactor)
for i in countup(0, high(s.data)):
if s.data[i].slot == seFilled: rawInsert(s, n, s.data[i].key)
@@ -500,7 +500,7 @@ type
##
## Use `init() <#init,OrderedSet[A],int>`_ or `initOrderedSet[type]()
## <#initOrderedSet>`_ before calling other procs on it.
- data: TOrderedKeyValuePairSeq[A]
+ data: OrderedKeyValuePairSeq[A]
counter, first, last: int
{.deprecated: [TOrderedSet: OrderedSet].}
@@ -588,7 +588,7 @@ proc contains*[A](s: TOrderedSet[A], key: A): bool =
result = index >= 0
proc rawInsert[A](s: var TOrderedSet[A],
- data: var TOrderedKeyValuePairSeq[A], key: A) =
+ data: var OrderedKeyValuePairSeq[A], key: A) =
rawInsertImpl()
data[h].next = -1
if s.first < 0: s.first = h
@@ -596,7 +596,7 @@ proc rawInsert[A](s: var TOrderedSet[A],
s.last = h
proc enlarge[A](s: var TOrderedSet[A]) =
- var n: TOrderedKeyValuePairSeq[A]
+ var n: OrderedKeyValuePairSeq[A]
newSeq(n, len(s.data) * growthFactor)
var h = s.first
s.first = -1
diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim
index 320d54111..c6ac01da8 100644
--- a/lib/pure/collections/tables.nim
+++ b/lib/pure/collections/tables.nim
@@ -422,7 +422,7 @@ proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool =
result = rawGet(t, key) >= 0
proc rawInsert[A, B](t: var TOrderedTable[A, B],
- data: var TOrderedKeyValuePairSeq[A, B],
+ data: var OrderedKeyValuePairSeq[A, B],
key: A, val: B) =
rawInsertImpl()
data[h].next = -1
@@ -431,7 +431,7 @@ proc rawInsert[A, B](t: var TOrderedTable[A, B],
t.last = h
proc enlarge[A, B](t: var TOrderedTable[A, B]) =
- var n: TOrderedKeyValuePairSeq[A, B]
+ var n: OrderedKeyValuePairSeq[A, B]
newSeq(n, len(t.data) * growthFactor)
var h = t.first
t.first = -1
diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim
index 361374177..63c2599b9 100644
--- a/lib/pure/lexbase.nim
+++ b/lib/pure/lexbase.nim
@@ -25,8 +25,8 @@ const
#
type
- TBaseLexer* = object of RootObj ## the base lexer. Inherit your lexer from
- ## this object.
+ BaseLexer* = object of RootObj ## the base lexer. Inherit your lexer from
+ ## this object.
bufpos*: int ## the current position within the buffer
buf*: cstring ## the buffer itself
bufLen*: int ## length of buffer in characters
diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim
index 8712df7f6..c85c2b498 100644
--- a/lib/pure/memfiles.nim
+++ b/lib/pure/memfiles.nim
@@ -48,7 +48,7 @@ proc mapMem*(m: var MemFile, mode: FileMode = fmRead,
if mappedSize == -1: 0 else: mappedSize,
nil)
if result == nil:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
assert mappedSize > 0
result = mmap(
@@ -58,7 +58,7 @@ proc mapMem*(m: var MemFile, mode: FileMode = fmRead,
if readonly: (MAP_PRIVATE or MAP_POPULATE) else: (MAP_SHARED or MAP_POPULATE),
m.handle, offset)
if result == cast[pointer](MAP_FAILED):
- osError(osLastError())
+ raiseOSError(osLastError())
proc unmapMem*(f: var MemFile, p: pointer, size: int) =
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index 0b4cf24c5..76100deba 100644
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -243,7 +243,7 @@ proc osErrorMsg*(errorCode: OSErrorCode): string =
## message.
result = ""
when defined(Windows):
- if errorCode != TOSErrorCode(0'i32):
+ if errorCode != OSErrorCode(0'i32):
when useWinUnicode:
var msgbuf: WideCString
if formatMessageW(0x00000100 or 0x00001000 or 0x00000200,
@@ -291,7 +291,7 @@ proc osLastError*(): OSErrorCode =
## immediately after an OS call fails. On POSIX systems this is not a problem.
when defined(windows):
- result = TOSErrorCode(getLastError())
+ result = OSErrorCode(getLastError())
else:
result = OSErrorCode(errno)
{.pop.}
@@ -429,44 +429,44 @@ proc dirExists*(dir: string): bool {.inline.} =
## Synonym for existsDir
existsDir(dir)
-proc getLastModificationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
+proc getLastModificationTime*(file: string): Time {.rtl, extern: "nos$1".} =
## Returns the `file`'s last modification time.
when defined(posix):
var res: TStat
- if stat(file, res) < 0'i32: osError(osLastError())
+ if stat(file, res) < 0'i32: raiseOSError(osLastError())
return res.st_mtime
else:
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
- if h == -1'i32: osError(osLastError())
+ if h == -1'i32: raiseOSError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastWriteTime))
findClose(h)
-proc getLastAccessTime*(file: string): TTime {.rtl, extern: "nos$1".} =
+proc getLastAccessTime*(file: string): Time {.rtl, extern: "nos$1".} =
## Returns the `file`'s last read or write access time.
when defined(posix):
var res: TStat
- if stat(file, res) < 0'i32: osError(osLastError())
+ if stat(file, res) < 0'i32: raiseOSError(osLastError())
return res.st_atime
else:
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
- if h == -1'i32: osError(osLastError())
+ if h == -1'i32: raiseOSError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftLastAccessTime))
findClose(h)
-proc getCreationTime*(file: string): TTime {.rtl, extern: "nos$1".} =
+proc getCreationTime*(file: string): Time {.rtl, extern: "nos$1".} =
## Returns the `file`'s creation time.
## Note that under posix OS's, the returned time may actually be the time at
## which the file's attribute's were last modified.
when defined(posix):
var res: TStat
- if stat(file, res) < 0'i32: osError(osLastError())
+ if stat(file, res) < 0'i32: raiseOSError(osLastError())
return res.st_ctime
else:
var f: TWIN32_FIND_DATA
var h = findFirstFile(file, f)
- if h == -1'i32: osError(osLastError())
+ if h == -1'i32: raiseOSError(osLastError())
result = winTimeToUnixTime(rdFileTime(f.ftCreationTime))
findClose(h)
@@ -482,19 +482,19 @@ proc getCurrentDir*(): string {.rtl, extern: "nos$1", tags: [].} =
when useWinUnicode:
var res = newWideCString("", bufsize)
var L = getCurrentDirectoryW(bufsize, res)
- if L == 0'i32: osError(osLastError())
+ if L == 0'i32: raiseOSError(osLastError())
result = res$L
else:
result = newString(bufsize)
var L = getCurrentDirectoryA(bufsize, result)
- if L == 0'i32: osError(osLastError())
+ if L == 0'i32: raiseOSError(osLastError())
setLen(result, L)
else:
result = newString(bufsize)
if getcwd(result, bufsize) != nil:
setLen(result, c_strlen(result))
else:
- osError(osLastError())
+ raiseOSError(osLastError())
proc setCurrentDir*(newDir: string) {.inline, tags: [].} =
## Sets the `current working directory`:idx:; `EOS` is raised if
@@ -502,11 +502,11 @@ proc setCurrentDir*(newDir: string) {.inline, tags: [].} =
when defined(Windows):
when useWinUnicode:
if setCurrentDirectoryW(newWideCString(newDir)) == 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
- if setCurrentDirectoryA(newDir) == 0'i32: osError(osLastError())
+ if setCurrentDirectoryA(newDir) == 0'i32: raiseOSError(osLastError())
else:
- if chdir(newDir) != 0'i32: osError(osLastError())
+ if chdir(newDir) != 0'i32: raiseOSError(osLastError())
proc joinPath*(head, tail: string): string {.
noSideEffect, rtl, extern: "nos$1".} =
@@ -718,19 +718,19 @@ proc expandFilename*(filename: string): string {.rtl, extern: "nos$1",
var res = newWideCString("", bufsize div 2)
var L = getFullPathNameW(newWideCString(filename), bufsize, res, unused)
if L <= 0'i32 or L >= bufsize:
- osError(osLastError())
+ raiseOSError(osLastError())
result = res$L
else:
var unused: cstring
result = newString(bufsize)
var L = getFullPathNameA(filename, bufsize, result, unused)
- if L <= 0'i32 or L >= bufsize: osError(osLastError())
+ if L <= 0'i32 or L >= bufsize: raiseOSError(osLastError())
setLen(result, L)
else:
# careful, realpath needs to take an allocated buffer according to Posix:
result = newString(pathMax)
var r = realpath(filename, result)
- if r.isNil: osError(osLastError())
+ if r.isNil: raiseOSError(osLastError())
setLen(result, c_strlen(result))
proc changeFileExt*(filename, ext: string): string {.
@@ -820,7 +820,7 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
var f1 = openHandle(path1)
var f2 = openHandle(path2)
- var lastErr: TOSErrorCode
+ var lastErr: OSErrorCode
if f1 != INVALID_HANDLE_VALUE and f2 != INVALID_HANDLE_VALUE:
var fi1, fi2: TBY_HANDLE_FILE_INFORMATION
@@ -839,11 +839,11 @@ proc sameFile*(path1, path2: string): bool {.rtl, extern: "nos$1",
discard closeHandle(f1)
discard closeHandle(f2)
- if not success: osError(lastErr)
+ if not success: raiseOSError(lastErr)
else:
var a, b: TStat
if stat(path1, a) < 0'i32 or stat(path2, b) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
result = a.st_dev == b.st_dev and a.st_ino == b.st_ino
@@ -897,7 +897,7 @@ proc getFilePermissions*(filename: string): set[TFilePermission] {.
## permission is available in any case.
when defined(posix):
var a: TStat
- if stat(filename, a) < 0'i32: osError(osLastError())
+ if stat(filename, a) < 0'i32: raiseOSError(osLastError())
result = {}
if (a.st_mode and S_IRUSR) != 0'i32: result.incl(fpUserRead)
if (a.st_mode and S_IWUSR) != 0'i32: result.incl(fpUserWrite)
@@ -915,7 +915,7 @@ proc getFilePermissions*(filename: string): set[TFilePermission] {.
wrapUnary(res, getFileAttributesW, filename)
else:
var res = getFileAttributesA(filename)
- if res == -1'i32: osError(osLastError())
+ if res == -1'i32: raiseOSError(osLastError())
if (res and FILE_ATTRIBUTE_READONLY) != 0'i32:
result = {fpUserExec, fpUserRead, fpGroupExec, fpGroupRead,
fpOthersExec, fpOthersRead}
@@ -941,13 +941,13 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
if fpOthersWrite in permissions: p = p or S_IWOTH
if fpOthersExec in permissions: p = p or S_IXOTH
- if chmod(filename, p) != 0: osError(osLastError())
+ if chmod(filename, p) != 0: raiseOSError(osLastError())
else:
when useWinUnicode:
wrapUnary(res, getFileAttributesW, filename)
else:
var res = getFileAttributesA(filename)
- if res == -1'i32: osError(osLastError())
+ if res == -1'i32: raiseOSError(osLastError())
if fpUserWrite in permissions:
res = res and not FILE_ATTRIBUTE_READONLY
else:
@@ -956,7 +956,7 @@ proc setFilePermissions*(filename: string, permissions: set[TFilePermission]) {.
wrapBinary(res2, setFileAttributesW, filename, res)
else:
var res2 = setFileAttributesA(filename, res)
- if res2 == - 1'i32: osError(osLastError())
+ if res2 == - 1'i32: raiseOSError(osLastError())
proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
tags: [ReadIOEffect, WriteIOEffect].} =
@@ -974,17 +974,17 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
when useWinUnicode:
let s = newWideCString(source)
let d = newWideCString(dest)
- if copyFileW(s, d, 0'i32) == 0'i32: osError(osLastError())
+ if copyFileW(s, d, 0'i32) == 0'i32: raiseOSError(osLastError())
else:
- if copyFileA(source, dest, 0'i32) == 0'i32: osError(osLastError())
+ if copyFileA(source, dest, 0'i32) == 0'i32: raiseOSError(osLastError())
else:
# generic version of copyFile which works for any platform:
const bufSize = 8000 # better for memory manager
var d, s: File
- if not open(s, source): osError(osLastError())
+ if not open(s, source): raiseOSError(osLastError())
if not open(d, dest, fmWrite):
close(s)
- osError(osLastError())
+ raiseOSError(osLastError())
var buf = alloc(bufSize)
while true:
var bytesread = readBuffer(s, buf, bufSize)
@@ -994,7 +994,7 @@ proc copyFile*(source, dest: string) {.rtl, extern: "nos$1",
dealloc(buf)
close(s)
close(d)
- osError(osLastError())
+ raiseOSError(osLastError())
if bytesread != bufSize: break
dealloc(buf)
close(s)
@@ -1034,9 +1034,9 @@ proc removeFile*(file: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].}
if deleteFile(f) == 0:
if getLastError() == ERROR_ACCESS_DENIED:
if setFileAttributes(f, FILE_ATTRIBUTE_NORMAL) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
if deleteFile(f) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if c_remove(file) != 0'i32 and errno != ENOENT:
raise newException(OSError, $strerror(errno))
@@ -1084,7 +1084,7 @@ when defined(windows):
while true:
var eend = strEnd(e)
add(environment, $e)
- e = cast[WideCString](cast[TAddress](eend)+2)
+ e = cast[WideCString](cast[ByteAddress](eend)+2)
if eend[1].int == 0: break
discard freeEnvironmentStringsW(env)
else:
@@ -1095,7 +1095,7 @@ when defined(windows):
while true:
var eend = strEnd(e)
add(environment, $e)
- e = cast[cstring](cast[TAddress](eend)+1)
+ e = cast[cstring](cast[ByteAddress](eend)+1)
if eend[1] == '\0': break
discard freeEnvironmentStringsA(env)
envComputed = true
@@ -1174,14 +1174,14 @@ proc putEnv*(key, val: string) {.tags: [WriteEnvEffect].} =
indx = high(environment)
when defined(unix):
if c_putenv(environment[indx]) != 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
when useWinUnicode:
var k = newWideCString(key)
var v = newWideCString(val)
- if setEnvironmentVariableW(k, v) == 0'i32: osError(osLastError())
+ if setEnvironmentVariableW(k, v) == 0'i32: raiseOSError(osLastError())
else:
- if setEnvironmentVariableA(key, val) == 0'i32: osError(osLastError())
+ if setEnvironmentVariableA(key, val) == 0'i32: raiseOSError(osLastError())
iterator envPairs*(): tuple[key, value: TaintedString] {.tags: [ReadEnvEffect].} =
## Iterate over all `environments variables`:idx:. In the first component
@@ -1321,9 +1321,9 @@ proc rawRemoveDir(dir: string) =
let lastError = osLastError()
if res == 0'i32 and lastError.int32 != 3'i32 and
lastError.int32 != 18'i32 and lastError.int32 != 2'i32:
- osError(lastError)
+ raiseOSError(lastError)
else:
- if rmdir(dir) != 0'i32 and errno != ENOENT: osError(osLastError())
+ if rmdir(dir) != 0'i32 and errno != ENOENT: raiseOSError(osLastError())
proc removeDir*(dir: string) {.rtl, extern: "nos$1", tags: [
WriteDirEffect, ReadDirEffect].} =
@@ -1341,17 +1341,17 @@ proc removeDir*(dir: string) {.rtl, extern: "nos$1", tags: [
proc rawCreateDir(dir: string) =
when defined(solaris):
if mkdir(dir, 0o711) != 0'i32 and errno != EEXIST and errno != ENOSYS:
- osError(osLastError())
+ raiseOSError(osLastError())
elif defined(unix):
if mkdir(dir, 0o711) != 0'i32 and errno != EEXIST:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
when useWinUnicode:
wrapUnary(res, createDirectoryW, dir)
else:
var res = createDirectoryA(dir)
if res == 0'i32 and getLastError() != 183'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
proc createDir*(dir: string) {.rtl, extern: "nos$1", tags: [WriteDirEffect].} =
## Creates the `directory`:idx: `dir`.
@@ -1403,13 +1403,13 @@ proc createSymlink*(src, dest: string) =
var wSrc = newWideCString(src)
var wDst = newWideCString(dest)
if createSymbolicLinkW(wDst, wSrc, flag) == 0 or getLastError() != 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if createSymbolicLinkA(dest, src, flag) == 0 or getLastError() != 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if symlink(src, dest) != 0:
- osError(osLastError())
+ raiseOSError(osLastError())
proc createHardlink*(src, dest: string) =
## Create a hard link at `dest` which points to the item specified
@@ -1422,13 +1422,13 @@ proc createHardlink*(src, dest: string) =
var wSrc = newWideCString(src)
var wDst = newWideCString(dest)
if createHardLinkW(wDst, wSrc, nil) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if createHardLinkA(dest, src, nil) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if link(src, dest) != 0:
- osError(osLastError())
+ raiseOSError(osLastError())
proc parseCmdLine*(c: string): seq[string] {.
noSideEffect, rtl, extern: "nos$1".} =
@@ -1824,7 +1824,7 @@ proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
when defined(windows):
var a: TWIN32_FIND_DATA
var resA = findFirstFile(file, a)
- if resA == -1: osError(osLastError())
+ if resA == -1: raiseOSError(osLastError())
result = rdFileSize(a)
findClose(resA)
else:
@@ -1832,7 +1832,7 @@ proc getFileSize*(file: string): BiggestInt {.rtl, extern: "nos$1",
if open(f, file):
result = getFileSize(f)
close(f)
- else: osError(osLastError())
+ else: raiseOSError(osLastError())
proc findExe*(exe: string): string {.tags: [ReadDirEffect, ReadEnvEffect].} =
## Searches for `exe` in the current working directory and then
@@ -1884,9 +1884,9 @@ type
size*: BiggestInt # Size of file.
permissions*: set[TFilePermission] # File permissions
linkCount*: BiggestInt # Number of hard links the file object has.
- lastAccessTime*: TTime # Time file was last accessed.
- lastWriteTime*: TTime # Time file was last modified/written to.
- creationTime*: TTime # Time file was created. Not supported on all systems!
+ lastAccessTime*: Time # Time file was last accessed.
+ lastWriteTime*: Time # Time file was last modified/written to.
+ creationTime*: Time # Time file was created. Not supported on all systems!
template rawToFormalFileInfo(rawInfo, formalInfo): expr =
## Transforms the native file info structure into the one nimrod uses.
@@ -1959,12 +1959,12 @@ proc getFileInfo*(handle: FileHandle): FileInfo =
# To transform the C file descripter to a native file handle.
var realHandle = get_osfhandle(handle)
if getFileInformationByHandle(realHandle, addr rawInfo) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
rawToFormalFileInfo(rawInfo, result)
else:
var rawInfo: TStat
if fstat(handle, rawInfo) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
rawToFormalFileInfo(rawInfo, result)
proc getFileInfo*(file: File): FileInfo =
@@ -1989,19 +1989,19 @@ proc getFileInfo*(path: string, followSymlink = true): FileInfo =
handle = openHandle(path, followSymlink)
rawInfo: TBY_HANDLE_FILE_INFORMATION
if handle == INVALID_HANDLE_VALUE:
- osError(osLastError())
+ raiseOSError(osLastError())
if getFileInformationByHandle(handle, addr rawInfo) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
rawToFormalFileInfo(rawInfo, result)
discard closeHandle(handle)
else:
var rawInfo: TStat
if followSymlink:
if lstat(path, rawInfo) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
if stat(path, rawInfo) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
rawToFormalFileInfo(rawInfo, result)
proc isHidden*(path: string): bool =
diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim
index 25782d4f5..957a91d06 100644
--- a/lib/pure/osproc.nim
+++ b/lib/pure/osproc.nim
@@ -334,7 +334,7 @@ when defined(Windows) and not defined(useNimRtl):
# TRUE and zero bytes returned (EOF).
# TRUE and n (>0) bytes returned (good data).
# FALSE and bytes returned undefined (system error).
- if a == 0 and br != 0: osError(osLastError())
+ if a == 0 and br != 0: raiseOSError(osLastError())
s.atTheEnd = br < bufLen
result = br
@@ -342,7 +342,7 @@ when defined(Windows) and not defined(useNimRtl):
var s = PFileHandleStream(s)
var bytesWritten: int32
var a = winlean.writeFile(s.handle, buffer, bufLen.cint, bytesWritten, nil)
- if a == 0: osError(osLastError())
+ if a == 0: raiseOSError(osLastError())
proc newFileHandleStream(handle: THandle): PFileHandleStream =
new(result)
@@ -383,7 +383,7 @@ when defined(Windows) and not defined(useNimRtl):
piInheritablePipe.lpSecurityDescriptor = nil
piInheritablePipe.bInheritHandle = 1
if createPipe(rdHandle, wrHandle, piInheritablePipe, 1024) == 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
proc fileClose(h: THandle) {.inline.} =
if h > 4: discard closeHandle(h)
@@ -450,7 +450,7 @@ when defined(Windows) and not defined(useNimRtl):
fileClose(si.hStdError)
if e != nil: dealloc(e)
- if success == 0: osError(lastError)
+ if success == 0: raiseOSError(lastError)
# Close the handle now so anyone waiting is woken:
discard closeHandle(procInfo.hThread)
result.fProcessHandle = procInfo.hProcess
@@ -521,7 +521,7 @@ when defined(Windows) and not defined(useNimRtl):
var res = winlean.createProcessA(nil, command, nil, nil, 0,
NORMAL_PRIORITY_CLASS, nil, nil, si, procInfo)
if res == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
process = procInfo.hProcess
discard closeHandle(procInfo.hThread)
@@ -544,7 +544,7 @@ when defined(Windows) and not defined(useNimRtl):
of WAIT_TIMEOUT:
return 0
of WAIT_FAILED:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
var i = ret - WAIT_OBJECT_0
readfds.del(i)
@@ -607,7 +607,7 @@ elif not defined(useNimRtl):
if poParentStreams notin options:
if pipe(pStdin) != 0'i32 or pipe(pStdout) != 0'i32 or
pipe(pStderr) != 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
var sysCommand: string
var sysArgsRaw: seq[string]
@@ -683,7 +683,7 @@ elif not defined(useNimRtl):
var fops: Tposix_spawn_file_actions
template chck(e: expr) =
- if e != 0'i32: osError(osLastError())
+ if e != 0'i32: raiseOSError(osLastError())
chck posix_spawn_file_actions_init(fops)
chck posix_spawnattr_init(attr)
@@ -726,7 +726,7 @@ elif not defined(useNimRtl):
proc startProcessAuxFork(data: TStartProcessData): TPid =
if pipe(data.pErrorPipe) != 0:
- osError(osLastError())
+ raiseOSError(osLastError())
finally:
discard close(data.pErrorPipe[readIdx])
@@ -751,12 +751,12 @@ elif not defined(useNimRtl):
exitnow(1)
discard close(data.pErrorPipe[writeIdx])
- if pid < 0: osError(osLastError())
+ if pid < 0: raiseOSError(osLastError())
var error: cint
let sizeRead = read(data.pErrorPipe[readIdx], addr error, sizeof(error))
if sizeRead == sizeof(error):
- osError($strerror(error))
+ raiseOSError($strerror(error))
return pid
@@ -818,10 +818,10 @@ elif not defined(useNimRtl):
discard close(p.errHandle)
proc suspend(p: PProcess) =
- if kill(-p.id, SIGSTOP) != 0'i32: osError(osLastError())
+ if kill(-p.id, SIGSTOP) != 0'i32: raiseOSError(osLastError())
proc resume(p: PProcess) =
- if kill(-p.id, SIGCONT) != 0'i32: osError(osLastError())
+ if kill(-p.id, SIGCONT) != 0'i32: raiseOSError(osLastError())
proc running(p: PProcess): bool =
var ret = waitpid(p.id, p.exitCode, WNOHANG)
@@ -831,8 +831,8 @@ elif not defined(useNimRtl):
proc terminate(p: PProcess) =
if kill(-p.id, SIGTERM) == 0'i32:
if p.running():
- if kill(-p.id, SIGKILL) != 0'i32: osError(osLastError())
- else: osError(osLastError())
+ if kill(-p.id, SIGKILL) != 0'i32: raiseOSError(osLastError())
+ else: raiseOSError(osLastError())
proc waitForExit(p: PProcess, timeout: int = -1): int =
#if waitPid(p.id, p.exitCode, 0) == int(p.id):
@@ -842,7 +842,7 @@ elif not defined(useNimRtl):
if p.exitCode != -3: return p.exitCode
if waitpid(p.id, p.exitCode, 0) < 0:
p.exitCode = -3
- osError(osLastError())
+ raiseOSError(osLastError())
result = int(p.exitCode) shr 8
proc peekExitCode(p: PProcess): int =
@@ -856,7 +856,7 @@ elif not defined(useNimRtl):
proc createStream(stream: var PStream, handle: var FileHandle,
fileMode: FileMode) =
var f: File
- if not open(f, handle, fileMode): osError(osLastError())
+ if not open(f, handle, fileMode): raiseOSError(osLastError())
stream = newFileStream(f)
proc inputStream(p: PProcess): PStream =
diff --git a/lib/pure/strtabs.nim b/lib/pure/strtabs.nim
index 71d16192f..e016fc6ad 100644
--- a/lib/pure/strtabs.nim
+++ b/lib/pure/strtabs.nim
@@ -121,7 +121,7 @@ proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
-proc rawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) =
+proc rawInsert(t: PStringTable, data: var KeyValuePairSeq, key, val: string) =
var h: THash = myhash(t, key) and high(data)
while not isNil(data[h].key):
h = nextTry(h, high(data))
@@ -129,7 +129,7 @@ proc rawInsert(t: PStringTable, data: var TKeyValuePairSeq, key, val: string) =
data[h].val = val
proc enlarge(t: PStringTable) =
- var n: TKeyValuePairSeq
+ var n: KeyValuePairSeq
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if not isNil(t.data[i].key): rawInsert(t, n, t.data[i].key, t.data[i].val)
@@ -182,7 +182,7 @@ proc newStringTable*(keyValuePairs: varargs[string],
inc(i, 2)
proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]],
- mode: TStringTableMode = modeCaseSensitive): PStringTable {.
+ mode: StringTableMode = modeCaseSensitive): PStringTable {.
rtl, extern: "nst$1WithTableConstr".} =
## creates a new string table with given key value pairs.
## Example::
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 82516653c..2af973b6e 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -766,7 +766,7 @@ proc find*(s, sub: string, start: int = 0): int {.noSideEffect,
## Searches for `sub` in `s` starting at position `start`.
##
## Searching is case-sensitive. If `sub` is not in `s`, -1 is returned.
- var a {.noinit.}: TSkipTable
+ var a {.noinit.}: SkipTable
preprocessSub(sub, a)
result = findAux(s, sub, start, a)
@@ -1158,7 +1158,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
## after the decimal point for Nimrod's ``biggestFloat`` type.
##
## If ``precision == 0``, it tries to format it nicely.
- const floatFormatToChar: array[TFloatFormat, char] = ['g', 'f', 'e']
+ const floatFormatToChar: array[FloatFormatMode, char] = ['g', 'f', 'e']
var
frmtstr {.noinit.}: array[0..5, char]
buf {.noinit.}: array[0..2500, char]
diff --git a/lib/pure/times.nim b/lib/pure/times.nim
index 2c09fcc4c..5d92218b3 100644
--- a/lib/pure/times.nim
+++ b/lib/pure/times.nim
@@ -136,7 +136,7 @@ type
months*: int ## The number of months
years*: int ## The number of years
-{.deprecated: [TMonth: Month, TWeekDay: WeekDay, TTime: Time, TTimeval: Timeval,
+{.deprecated: [TMonth: Month, TWeekDay: WeekDay, TTime: Time,
TTimeInterval: TimeInterval, TTimeInfo: TimeInfo].}
proc getTime*(): Time {.tags: [TimeEffect], gcsafe.}
@@ -228,7 +228,7 @@ proc isLeapYear*(year: int): bool =
else:
return false
-proc getDaysInMonth*(month: TMonth, year: int): int =
+proc getDaysInMonth*(month: Month, year: int): int =
## gets the amount of days in a ``month`` of a ``year``
# http://www.dispersiondesign.com/articles/time/number_of_days_in_a_month
@@ -350,7 +350,7 @@ when not defined(JS):
minute: int(tm.minute),
hour: int(tm.hour),
monthday: int(tm.monthday),
- month: TMonth(tm.month),
+ month: Month(tm.month),
year: tm.year + 1900'i32,
weekday: weekDays[int(tm.weekday)],
yearday: int(tm.yearday),
@@ -455,7 +455,7 @@ when not defined(JS):
when not defined(useNimRtl):
proc epochTime(): float =
when defined(posix):
- var a: Ttimeval
+ var a: Timeval
posix_gettimeofday(a)
result = toFloat(a.tv_sec) + toFloat(a.tv_usec)*0.00_0001
elif defined(windows):
diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim
index 293551bc9..55ae87a1f 100644
--- a/lib/windows/winlean.nim
+++ b/lib/windows/winlean.nim
@@ -363,7 +363,9 @@ const
proc wsaGetLastError*(): cint {.importc: "WSAGetLastError", dynlib: ws2dll.}
type
- TSocketHandle* = distinct int
+ SocketHandle* = distinct int
+
+{.deprecated: [TSocketHandle: SocketHandle].}
type
TWSAData* {.pure, final, importc: "WSADATA", header: "Winsock2.h".} = object
From 27869b6c7b07e6b42dd1ccef9e37145e200bd39f Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 00:36:14 +0200
Subject: [PATCH 013/409] big rename
---
lib/pure/algorithm.nim | 6 +-
lib/pure/asyncdispatch.nim | 158 +++++++++++------------
lib/pure/collections/sets.nim | 96 +++++++-------
lib/pure/collections/tables.nim | 216 ++++++++++++++++----------------
lib/pure/net.nim | 202 ++++++++++++++---------------
lib/pure/rawsockets.nim | 36 +++---
lib/windows/winlean.nim | 46 +++----
7 files changed, 380 insertions(+), 380 deletions(-)
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim
index b27ccb93c..dd9131c05 100644
--- a/lib/pure/algorithm.nim
+++ b/lib/pure/algorithm.nim
@@ -16,7 +16,7 @@ type
{.deprecated: [TSortOrder: SortOrder].}
-proc `*`*(x: int, order: TSortOrder): int {.inline.} =
+proc `*`*(x: int, order: SortOrder): int {.inline.} =
## flips `x` if ``order == Descending``;
## if ``order == Ascending`` then `x` is returned.
## `x` is supposed to be the result of a comparator, ie ``< 0`` for
@@ -103,7 +103,7 @@ proc lowerBound*[T](a: openArray[T], key: T, cmp: proc(x,y: T): int {.closure.})
proc lowerBound*[T](a: openArray[T], key: T): int = lowerBound(a, key, cmp[T])
proc merge[T](a, b: var openArray[T], lo, m, hi: int,
- cmp: proc (x, y: T): int {.closure.}, order: TSortOrder) =
+ cmp: proc (x, y: T): int {.closure.}, order: SortOrder) =
template `<-` (a, b: expr) =
when false:
a = b
@@ -150,7 +150,7 @@ proc merge[T](a, b: var openArray[T], lo, m, hi: int,
proc sort*[T](a: var openArray[T],
cmp: proc (x, y: T): int {.closure.},
- order = TSortOrder.Ascending) =
+ order = SortOrder.Ascending) =
## Default Nimrod sort. The sorting is guaranteed to be stable and
## the worst case is guaranteed to be O(n log n).
## The current implementation uses an iterative
diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim
index 194c6ee1b..f3875dfa6 100644
--- a/lib/pure/asyncdispatch.nim
+++ b/lib/pure/asyncdispatch.nim
@@ -156,12 +156,12 @@ proc read*[T](future: Future[T]): T =
return future.value
else:
# TODO: Make a custom exception type for this?
- raise newException(EInvalidValue, "Future still in progress.")
+ raise newException(ValueError, "Future still in progress.")
-proc readError*[T](future: Future[T]): ref EBase =
+proc readError*[T](future: Future[T]): ref Exception =
if future.error != nil: return future.error
else:
- raise newException(EInvalidValue, "No error in future.")
+ raise newException(ValueError, "No error in future.")
proc finished*[T](future: Future[T]): bool =
## Determines whether ``future`` has completed.
@@ -206,7 +206,7 @@ proc `or`*[T, Y](fut1: Future[T], fut2: Future[Y]): Future[void] =
fut2.callback = cb
type
- PDispatcherBase = ref object of PObject
+ PDispatcherBase = ref object of RootRef
timers: seq[tuple[finishAt: float, fut: Future[void]]]
proc processTimers(p: PDispatcherBase) =
@@ -226,11 +226,11 @@ when defined(windows) or defined(nimdoc):
TCompletionData* = object
sock: TAsyncFD
cb: proc (sock: TAsyncFD, bytesTransferred: DWORD,
- errcode: TOSErrorCode) {.closure,gcsafe.}
+ errcode: OSErrorCode) {.closure,gcsafe.}
PDispatcher* = ref object of PDispatcherBase
ioPort: THandle
- handles: TSet[TAsyncFD]
+ handles: HashSet[TAsyncFD]
TCustomOverlapped = object of TOVERLAPPED
data*: TCompletionData
@@ -245,7 +245,7 @@ when defined(windows) or defined(nimdoc):
proc newDispatcher*(): PDispatcher =
## Creates a new Dispatcher instance.
new result
- result.ioPort = CreateIOCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1)
+ result.ioPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 1)
result.handles = initSet[TAsyncFD]()
result.timers = @[]
@@ -258,16 +258,16 @@ when defined(windows) or defined(nimdoc):
proc register*(sock: TAsyncFD) =
## Registers ``sock`` with the dispatcher.
let p = getGlobalDispatcher()
- if CreateIOCompletionPort(sock.THandle, p.ioPort,
+ if CreateIoCompletionPort(sock.THandle, p.ioPort,
cast[TCompletionKey](sock), 1) == 0:
- osError(osLastError())
+ raiseOSError(osLastError())
p.handles.incl(sock)
proc verifyPresence(sock: TAsyncFD) =
## Ensures that socket has been registered with the dispatcher.
let p = getGlobalDispatcher()
if sock notin p.handles:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Operation performed on a socket which has not been registered with" &
" the dispatcher yet.")
@@ -275,7 +275,7 @@ when defined(windows) or defined(nimdoc):
## Waits for completion events and processes them.
let p = getGlobalDispatcher()
if p.handles.len == 0 and p.timers.len == 0:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"No handles or timers registered in dispatcher.")
let llTimeout =
@@ -286,7 +286,7 @@ when defined(windows) or defined(nimdoc):
var customOverlapped: PCustomOverlapped
let res = GetQueuedCompletionStatus(p.ioPort,
addr lpNumberOfBytesTransferred, addr lpCompletionKey,
- cast[ptr POverlapped](addr customOverlapped), llTimeout).bool
+ cast[ptr POVERLAPPED](addr customOverlapped), llTimeout).bool
# http://stackoverflow.com/a/12277264/492186
# TODO: http://www.serverframework.com/handling-multiple-pending-socket-read-and-write-operations.html
@@ -295,7 +295,7 @@ when defined(windows) or defined(nimdoc):
assert customOverlapped.data.sock == lpCompletionKey.TAsyncFD
customOverlapped.data.cb(customOverlapped.data.sock,
- lpNumberOfBytesTransferred, TOSErrorCode(-1))
+ lpNumberOfBytesTransferred, OSErrorCode(-1))
GC_unref(customOverlapped)
else:
let errCode = osLastError()
@@ -308,7 +308,7 @@ when defined(windows) or defined(nimdoc):
if errCode.int32 == WAIT_TIMEOUT:
# Timed out
discard
- else: osError(errCode)
+ else: raiseOSError(errCode)
# Timer processing.
processTimers(p)
@@ -317,9 +317,9 @@ when defined(windows) or defined(nimdoc):
var acceptExPtr: pointer = nil
var getAcceptExSockAddrsPtr: pointer = nil
- proc initPointer(s: TSocketHandle, func: var pointer, guid: var TGUID): bool =
+ proc initPointer(s: SocketHandle, func: var pointer, guid: var TGUID): bool =
# Ref: https://github.com/powdahound/twisted/blob/master/twisted/internet/iocpreactor/iocpsupport/winsock_pointers.c
- var bytesRet: DWord
+ var bytesRet: DWORD
func = nil
result = WSAIoctl(s, SIO_GET_EXTENSION_FUNCTION_POINTER, addr guid,
sizeof(TGUID).dword, addr func, sizeof(pointer).DWORD,
@@ -328,34 +328,34 @@ when defined(windows) or defined(nimdoc):
proc initAll() =
let dummySock = newRawSocket()
if not initPointer(dummySock, connectExPtr, WSAID_CONNECTEX):
- osError(osLastError())
+ raiseOSError(osLastError())
if not initPointer(dummySock, acceptExPtr, WSAID_ACCEPTEX):
- osError(osLastError())
+ raiseOSError(osLastError())
if not initPointer(dummySock, getAcceptExSockAddrsPtr, WSAID_GETACCEPTEXSOCKADDRS):
- osError(osLastError())
+ raiseOSError(osLastError())
- proc connectEx(s: TSocketHandle, name: ptr TSockAddr, namelen: cint,
+ proc connectEx(s: SocketHandle, name: ptr TSockAddr, namelen: cint,
lpSendBuffer: pointer, dwSendDataLength: dword,
- lpdwBytesSent: PDWORD, lpOverlapped: POverlapped): bool =
- if connectExPtr.isNil: raise newException(EInvalidValue, "Need to initialise ConnectEx().")
+ lpdwBytesSent: PDWORD, lpOverlapped: POVERLAPPED): bool =
+ if connectExPtr.isNil: raise newException(ValueError, "Need to initialise ConnectEx().")
let func =
- cast[proc (s: TSocketHandle, name: ptr TSockAddr, namelen: cint,
+ cast[proc (s: SocketHandle, name: ptr TSockAddr, namelen: cint,
lpSendBuffer: pointer, dwSendDataLength: dword,
- lpdwBytesSent: PDWORD, lpOverlapped: POverlapped): bool {.stdcall,gcsafe.}](connectExPtr)
+ lpdwBytesSent: PDWORD, lpOverlapped: POVERLAPPED): bool {.stdcall,gcsafe.}](connectExPtr)
result = func(s, name, namelen, lpSendBuffer, dwSendDataLength, lpdwBytesSent,
lpOverlapped)
- proc acceptEx(listenSock, acceptSock: TSocketHandle, lpOutputBuffer: pointer,
+ proc acceptEx(listenSock, acceptSock: SocketHandle, lpOutputBuffer: pointer,
dwReceiveDataLength, dwLocalAddressLength,
dwRemoteAddressLength: DWORD, lpdwBytesReceived: PDWORD,
- lpOverlapped: POverlapped): bool =
- if acceptExPtr.isNil: raise newException(EInvalidValue, "Need to initialise AcceptEx().")
+ lpOverlapped: POVERLAPPED): bool =
+ if acceptExPtr.isNil: raise newException(ValueError, "Need to initialise AcceptEx().")
let func =
- cast[proc (listenSock, acceptSock: TSocketHandle, lpOutputBuffer: pointer,
+ cast[proc (listenSock, acceptSock: SocketHandle, lpOutputBuffer: pointer,
dwReceiveDataLength, dwLocalAddressLength,
dwRemoteAddressLength: DWORD, lpdwBytesReceived: PDWORD,
- lpOverlapped: POverlapped): bool {.stdcall,gcsafe.}](acceptExPtr)
+ lpOverlapped: POVERLAPPED): bool {.stdcall,gcsafe.}](acceptExPtr)
result = func(listenSock, acceptSock, lpOutputBuffer, dwReceiveDataLength,
dwLocalAddressLength, dwRemoteAddressLength, lpdwBytesReceived,
lpOverlapped)
@@ -365,7 +365,7 @@ when defined(windows) or defined(nimdoc):
LocalSockaddr: ptr ptr TSockAddr, LocalSockaddrLength: lpint,
RemoteSockaddr: ptr ptr TSockAddr, RemoteSockaddrLength: lpint) =
if getAcceptExSockAddrsPtr.isNil:
- raise newException(EInvalidValue, "Need to initialise getAcceptExSockAddrs().")
+ raise newException(ValueError, "Need to initialise getAcceptExSockAddrs().")
let func =
cast[proc (lpOutputBuffer: pointer,
@@ -378,7 +378,7 @@ when defined(windows) or defined(nimdoc):
dwRemoteAddressLength, LocalSockaddr, LocalSockaddrLength,
RemoteSockaddr, RemoteSockaddrLength)
- proc connect*(socket: TAsyncFD, address: string, port: TPort,
+ proc connect*(socket: TAsyncFD, address: string, port: Port,
af = AF_INET): Future[void] =
## Connects ``socket`` to server at ``address:port``.
##
@@ -391,13 +391,13 @@ when defined(windows) or defined(nimdoc):
saddr.sin_family = int16(toInt(af))
saddr.sin_port = 0
saddr.sin_addr.s_addr = INADDR_ANY
- if bindAddr(socket.TSocketHandle, cast[ptr TSockAddr](addr(saddr)),
+ if bindAddr(socket.SocketHandle, cast[ptr TSockAddr](addr(saddr)),
sizeof(saddr).TSockLen) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
var aiList = getAddrInfo(address, port, af)
var success = false
- var lastError: TOSErrorCode
+ var lastError: OSErrorCode
var it = aiList
while it != nil:
# "the OVERLAPPED structure must remain valid until the I/O completes"
@@ -405,17 +405,17 @@ when defined(windows) or defined(nimdoc):
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = TCompletionData(sock: socket, cb:
- proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) =
+ proc (sock: TAsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
- if errcode == TOSErrorCode(-1):
+ if errcode == OSErrorCode(-1):
retFuture.complete()
else:
- retFuture.fail(newException(EOS, osErrorMsg(errcode)))
+ retFuture.fail(newException(OSError, osErrorMsg(errcode)))
)
- var ret = connectEx(socket.TSocketHandle, it.ai_addr,
- sizeof(TSockAddrIn).cint, nil, 0, nil,
- cast[POverlapped](ol))
+ var ret = connectEx(socket.SocketHandle, it.ai_addr,
+ sizeof(Tsockaddr_in).cint, nil, 0, nil,
+ cast[POVERLAPPED](ol))
if ret:
# Request to connect completed immediately.
success = true
@@ -437,11 +437,11 @@ when defined(windows) or defined(nimdoc):
dealloc(aiList)
if not success:
- retFuture.fail(newException(EOS, osErrorMsg(lastError)))
+ retFuture.fail(newException(OSError, osErrorMsg(lastError)))
return retFuture
proc recv*(socket: TAsyncFD, size: int,
- flags = {TSocketFlags.SafeDisconn}): Future[string] =
+ flags = {SocketFlag.SafeDisconn}): Future[string] =
## Reads **up to** ``size`` bytes from ``socket``. Returned future will
## complete once all the data requested is read, a part of the data has been
## read, or the socket has disconnected in which case the future will
@@ -460,14 +460,14 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = cast[cstring](alloc0(size))
dataBuf.len = size
- var bytesReceived: DWord
- var flagsio = flags.toOSFlags().DWord
+ var bytesReceived: DWORD
+ var flagsio = flags.toOSFlags().DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = TCompletionData(sock: socket, cb:
- proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) =
+ proc (sock: TAsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
- if errcode == TOSErrorCode(-1):
+ if errcode == OSErrorCode(-1):
if bytesCount == 0 and dataBuf.buf[0] == '\0':
retFuture.complete("")
else:
@@ -479,14 +479,14 @@ when defined(windows) or defined(nimdoc):
if flags.isDisconnectionError(errcode):
retFuture.complete("")
else:
- retFuture.fail(newException(EOS, osErrorMsg(errcode)))
+ retFuture.fail(newException(OSError, osErrorMsg(errcode)))
if dataBuf.buf != nil:
dealloc dataBuf.buf
dataBuf.buf = nil
)
- let ret = WSARecv(socket.TSocketHandle, addr dataBuf, 1, addr bytesReceived,
- addr flagsio, cast[POverlapped](ol), nil)
+ let ret = WSARecv(socket.SocketHandle, addr dataBuf, 1, addr bytesReceived,
+ addr flagsio, cast[POVERLAPPED](ol), nil)
if ret == -1:
let err = osLastError()
if err.int32 != ERROR_IO_PENDING:
@@ -497,7 +497,7 @@ when defined(windows) or defined(nimdoc):
if flags.isDisconnectionError(err):
retFuture.complete("")
else:
- retFuture.fail(newException(EOS, osErrorMsg(err)))
+ retFuture.fail(newException(OSError, osErrorMsg(err)))
elif ret == 0 and bytesReceived == 0 and dataBuf.buf[0] == '\0':
# We have to ensure that the buffer is empty because WSARecv will tell
# us immediatelly when it was disconnected, even when there is still
@@ -529,7 +529,7 @@ when defined(windows) or defined(nimdoc):
return retFuture
proc send*(socket: TAsyncFD, data: string,
- flags = {TSocketFlags.SafeDisconn}): Future[void] =
+ flags = {SocketFlag.SafeDisconn}): Future[void] =
## Sends ``data`` to ``socket``. The returned future will complete once all
## data has been sent.
verifyPresence(socket)
@@ -539,23 +539,23 @@ when defined(windows) or defined(nimdoc):
dataBuf.buf = data # since this is not used in a callback, this is fine
dataBuf.len = data.len
- var bytesReceived, lowFlags: DWord
+ var bytesReceived, lowFlags: DWORD
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = TCompletionData(sock: socket, cb:
- proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) =
+ proc (sock: TAsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
- if errcode == TOSErrorCode(-1):
+ if errcode == OSErrorCode(-1):
retFuture.complete()
else:
if flags.isDisconnectionError(errcode):
retFuture.complete()
else:
- retFuture.fail(newException(EOS, osErrorMsg(errcode)))
+ retFuture.fail(newException(OSError, osErrorMsg(errcode)))
)
- let ret = WSASend(socket.TSocketHandle, addr dataBuf, 1, addr bytesReceived,
- lowFlags, cast[POverlapped](ol), nil)
+ let ret = WSASend(socket.SocketHandle, addr dataBuf, 1, addr bytesReceived,
+ lowFlags, cast[POVERLAPPED](ol), nil)
if ret == -1:
let err = osLastError()
if err.int32 != ERROR_IO_PENDING:
@@ -563,7 +563,7 @@ when defined(windows) or defined(nimdoc):
if flags.isDisconnectionError(err):
retFuture.complete()
else:
- retFuture.fail(newException(EOS, osErrorMsg(err)))
+ retFuture.fail(newException(OSError, osErrorMsg(err)))
else:
retFuture.complete()
# We don't deallocate ``ol`` here because even though this completed
@@ -571,7 +571,7 @@ when defined(windows) or defined(nimdoc):
# free ``ol``.
return retFuture
- proc acceptAddr*(socket: TAsyncFD, flags = {TSocketFlags.SafeDisconn}):
+ proc acceptAddr*(socket: TAsyncFD, flags = {SocketFlag.SafeDisconn}):
Future[tuple[address: string, client: TAsyncFD]] =
## Accepts a new connection. Returns a future containing the client socket
## corresponding to that connection and the remote address of the client.
@@ -588,21 +588,21 @@ when defined(windows) or defined(nimdoc):
var retFuture = newFuture[tuple[address: string, client: TAsyncFD]]("acceptAddr")
var clientSock = newRawSocket()
- if clientSock == osInvalidSocket: osError(osLastError())
+ if clientSock == osInvalidSocket: raiseOSError(osLastError())
const lpOutputLen = 1024
var lpOutputBuf = newString(lpOutputLen)
var dwBytesReceived: DWORD
let dwReceiveDataLength = 0.DWORD # We don't want any data to be read.
- let dwLocalAddressLength = DWORD(sizeof (TSockaddr_in) + 16)
- let dwRemoteAddressLength = DWORD(sizeof(TSockaddr_in) + 16)
+ let dwLocalAddressLength = DWORD(sizeof (Tsockaddr_in) + 16)
+ let dwRemoteAddressLength = DWORD(sizeof(Tsockaddr_in) + 16)
template completeAccept(): stmt {.immediate, dirty.} =
var listenSock = socket
let setoptRet = setsockopt(clientSock, SOL_SOCKET,
SO_UPDATE_ACCEPT_CONTEXT, addr listenSock,
sizeof(listenSock).TSockLen)
- if setoptRet != 0: osError(osLastError())
+ if setoptRet != 0: raiseOSError(osLastError())
var LocalSockaddr, RemoteSockaddr: ptr TSockAddr
var localLen, remoteLen: int32
@@ -627,25 +627,25 @@ when defined(windows) or defined(nimdoc):
else:
retFuture.complete(newAcceptFut.read)
else:
- retFuture.fail(newException(EOS, osErrorMsg(errcode)))
+ retFuture.fail(newException(OSError, osErrorMsg(errcode)))
var ol = PCustomOverlapped()
GC_ref(ol)
ol.data = TCompletionData(sock: socket, cb:
- proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) =
+ proc (sock: TAsyncFD, bytesCount: DWORD, errcode: OSErrorCode) =
if not retFuture.finished:
- if errcode == TOSErrorCode(-1):
+ if errcode == OSErrorCode(-1):
completeAccept()
else:
failAccept(errcode)
)
# http://msdn.microsoft.com/en-us/library/windows/desktop/ms737524%28v=vs.85%29.aspx
- let ret = acceptEx(socket.TSocketHandle, clientSock, addr lpOutputBuf[0],
+ let ret = acceptEx(socket.SocketHandle, clientSock, addr lpOutputBuf[0],
dwReceiveDataLength,
dwLocalAddressLength,
dwRemoteAddressLength,
- addr dwBytesReceived, cast[POverlapped](ol))
+ addr dwBytesReceived, cast[POVERLAPPED](ol))
if not ret:
let err = osLastError()
@@ -660,17 +660,17 @@ when defined(windows) or defined(nimdoc):
return retFuture
- proc newAsyncRawSocket*(domain: TDomain = AF_INET,
- typ: TType = SOCK_STREAM,
- protocol: TProtocol = IPPROTO_TCP): TAsyncFD =
+ proc newAsyncRawSocket*(domain: Domain = AF_INET,
+ typ: SockType = SOCK_STREAM,
+ protocol: Protocol = IPPROTO_TCP): TAsyncFD =
## Creates a new socket and registers it with the dispatcher implicitly.
result = newRawSocket(domain, typ, protocol).TAsyncFD
- result.TSocketHandle.setBlocking(false)
+ result.SocketHandle.setBlocking(false)
register(result)
proc closeSocket*(socket: TAsyncFD) =
## Closes a socket and ensures that it is unregistered.
- socket.TSocketHandle.close()
+ socket.SocketHandle.close()
getGlobalDispatcher().handles.excl(socket)
proc unregister*(fd: TAsyncFD) =
@@ -925,7 +925,7 @@ proc sleepAsync*(ms: int): Future[void] =
return retFuture
proc accept*(socket: TAsyncFD,
- flags = {TSocketFlags.SafeDisconn}): Future[TAsyncFD] =
+ flags = {SocketFlag.SafeDisconn}): Future[TAsyncFD] =
## Accepts a new connection. Returns a future containing the client socket
## corresponding to that connection.
## The future will complete when the connection is successfully accepted.
@@ -1010,14 +1010,14 @@ proc processBody(node, retFutureSym: PNimrodNode,
of nnkReturnStmt:
result = newNimNode(nnkStmtList, node)
if node[0].kind == nnkEmpty:
- if not subtypeIsVoid:
+ if not subTypeIsVoid:
result.add newCall(newIdentNode("complete"), retFutureSym,
newIdentNode("result"))
else:
result.add newCall(newIdentNode("complete"), retFutureSym)
else:
result.add newCall(newIdentNode("complete"), retFutureSym,
- node[0].processBody(retFutureSym, subtypeIsVoid, exceptBranch))
+ node[0].processBody(retFutureSym, subTypeIsVoid, exceptBranch))
result.add newNimNode(nnkReturnStmt, node).add(newNilLit())
return # Don't process the children of this return stmt
@@ -1072,7 +1072,7 @@ proc processBody(node, retFutureSym: PNimrodNode,
res: PNimrodNode): bool {.compileTime.} =
result = false
while i < n[0].len:
- var processed = processBody(n[0][i], retFutureSym, subtypeIsVoid, n[1])
+ var processed = processBody(n[0][i], retFutureSym, subTypeIsVoid, n[1])
if processed.kind != n[0][i].kind or processed.len != n[0][i].len:
expectKind(processed, nnkStmtList)
expectKind(processed[2][1], nnkElse)
@@ -1092,7 +1092,7 @@ proc processBody(node, retFutureSym: PNimrodNode,
else: discard
for i in 0 .. 0 and c == "\L":
discard await recv(socket, 1)
addNLIfEmpty()
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index 27f5ef07a..994023b3f 100644
--- a/lib/pure/collections/sets.nim
+++ b/lib/pure/collections/sets.nim
@@ -37,7 +37,7 @@ type
{.deprecated: [TSet: HashSet].}
-proc isValid*[A](s: TSet[A]): bool =
+proc isValid*[A](s: HashSet[A]): bool =
## Returns `true` if the set has been initialized with `initSet <#initSet>`_.
##
## Most operations over an uninitialized set will crash at runtime and
@@ -51,7 +51,7 @@ proc isValid*[A](s: TSet[A]): bool =
## # Do stuff here, may crash in release builds!
result = not s.data.isNil
-proc len*[A](s: TSet[A]): int =
+proc len*[A](s: HashSet[A]): int =
## Returns the number of keys in `s`.
##
## Due to an implementation detail you can call this proc on variables which
@@ -65,14 +65,14 @@ proc len*[A](s: TSet[A]): int =
## assert values.len == 0
result = s.counter
-proc card*[A](s: TSet[A]): int =
+proc card*[A](s: HashSet[A]): int =
## Alias for `len() <#len,TSet[A]>`_.
##
## Card stands for the `cardinality
## `_ of a set.
result = s.counter
-iterator items*[A](s: TSet[A]): A =
+iterator items*[A](s: HashSet[A]): A =
## Iterates over keys in the set `s`.
##
## If you need a sequence with the keys you can use `sequtils.toSeq()
@@ -120,10 +120,10 @@ template rawInsertImpl() {.dirty.} =
data[h].key = key
data[h].slot = seFilled
-proc rawGet[A](s: TSet[A], key: A): int =
+proc rawGet[A](s: HashSet[A], key: A): int =
rawGetImpl()
-proc mget*[A](s: var TSet[A], key: A): var A =
+proc mget*[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
## when one overloaded 'hash' and '==' but still needs reference semantics
@@ -133,7 +133,7 @@ proc mget*[A](s: var TSet[A], key: A): var A =
if index >= 0: result = t.data[index].key
else: raise newException(KeyError, "key not found: " & $key)
-proc contains*[A](s: TSet[A], key: A): bool =
+proc contains*[A](s: HashSet[A], key: A): bool =
## Returns true iff `key` is in `s`.
##
## Example:
@@ -149,10 +149,10 @@ proc contains*[A](s: TSet[A], key: A): bool =
var index = rawGet(s, key)
result = index >= 0
-proc rawInsert[A](s: var TSet[A], data: var KeyValuePairSeq[A], key: A) =
+proc rawInsert[A](s: var HashSet[A], data: var KeyValuePairSeq[A], key: A) =
rawInsertImpl()
-proc enlarge[A](s: var TSet[A]) =
+proc enlarge[A](s: var HashSet[A]) =
var n: KeyValuePairSeq[A]
newSeq(n, len(s.data) * growthFactor)
for i in countup(0, high(s.data)):
@@ -175,7 +175,7 @@ template containsOrInclImpl() {.dirty.} =
rawInsert(s, s.data, key)
inc(s.counter)
-proc incl*[A](s: var TSet[A], key: A) =
+proc incl*[A](s: var HashSet[A], key: A) =
## Includes an element `key` in `s`.
##
## This doesn't do anything if `key` is already in `s`. Example:
@@ -188,7 +188,7 @@ proc incl*[A](s: var TSet[A], key: A) =
assert s.isValid, "The set needs to be initialized."
inclImpl()
-proc incl*[A](s: var TSet[A], other: TSet[A]) =
+proc incl*[A](s: var HashSet[A], other: TSet[A]) =
## Includes all elements from `other` into `s`.
##
## Example:
@@ -203,7 +203,7 @@ proc incl*[A](s: var TSet[A], other: TSet[A]) =
assert other.isValid, "The set `other` needs to be initialized."
for item in other: incl(s, item)
-proc excl*[A](s: var TSet[A], key: A) =
+proc excl*[A](s: var HashSet[A], key: A) =
## Excludes `key` from the set `s`.
##
## This doesn't do anything if `key` is not found in `s`. Example:
@@ -219,7 +219,7 @@ proc excl*[A](s: var TSet[A], key: A) =
s.data[index].slot = seDeleted
dec(s.counter)
-proc excl*[A](s: var TSet[A], other: TSet[A]) =
+proc excl*[A](s: var HashSet[A], other: TSet[A]) =
## Excludes everything in `other` from `s`.
##
## Example:
@@ -235,7 +235,7 @@ proc excl*[A](s: var TSet[A], other: TSet[A]) =
assert other.isValid, "The set `other` needs to be initialized."
for item in other: excl(s, item)
-proc containsOrIncl*[A](s: var TSet[A], key: A): bool =
+proc containsOrIncl*[A](s: var HashSet[A], key: A): bool =
## Includes `key` in the set `s` and tells if `key` was added to `s`.
##
## The difference with regards to the `incl() <#incl,TSet[A],A>`_ proc is
@@ -250,7 +250,7 @@ proc containsOrIncl*[A](s: var TSet[A], key: A): bool =
assert s.isValid, "The set needs to be initialized."
containsOrInclImpl()
-proc init*[A](s: var TSet[A], initialSize=64) =
+proc init*[A](s: var HashSet[A], initialSize=64) =
## Initializes a hash set.
##
## The `initialSize` parameter needs to be a power of too. You can use
@@ -273,7 +273,7 @@ proc init*[A](s: var TSet[A], initialSize=64) =
s.counter = 0
newSeq(s.data, initialSize)
-proc initSet*[A](initialSize=64): TSet[A] =
+proc initSet*[A](initialSize=64): HashSet[A] =
## Wrapper around `init() <#init,TSet[A],int>`_ for initialization of hash
## sets.
##
@@ -285,7 +285,7 @@ proc initSet*[A](initialSize=64): TSet[A] =
## a.incl(2)
result.init(initialSize)
-proc toSet*[A](keys: openArray[A]): TSet[A] =
+proc toSet*[A](keys: openArray[A]): HashSet[A] =
## Creates a new hash set that contains the given `keys`.
##
## Example:
@@ -304,7 +304,7 @@ template dollarImpl(): stmt {.dirty.} =
result.add($key)
result.add("}")
-proc `$`*[A](s: TSet[A]): string =
+proc `$`*[A](s: HashSet[A]): string =
## Converts the set `s` to a string, mostly for logging purposes.
##
## Don't use this proc for serialization, the representation may change at
@@ -320,7 +320,7 @@ proc `$`*[A](s: TSet[A]): string =
assert s.isValid, "The set needs to be initialized."
dollarImpl()
-proc union*[A](s1, s2: TSet[A]): TSet[A] =
+proc union*[A](s1, s2: HashSet[A]): TSet[A] =
## Returns the union of the sets `s1` and `s2`.
##
## The union of two sets is represented mathematically as *A ∪ B* and is the
@@ -337,7 +337,7 @@ proc union*[A](s1, s2: TSet[A]): TSet[A] =
result = s1
incl(result, s2)
-proc intersection*[A](s1, s2: TSet[A]): TSet[A] =
+proc intersection*[A](s1, s2: HashSet[A]): TSet[A] =
## Returns the intersection of the sets `s1` and `s2`.
##
## The intersection of two sets is represented mathematically as *A ∩ B* and
@@ -356,7 +356,7 @@ proc intersection*[A](s1, s2: TSet[A]): TSet[A] =
for item in s1:
if item in s2: incl(result, item)
-proc difference*[A](s1, s2: TSet[A]): TSet[A] =
+proc difference*[A](s1, s2: HashSet[A]): TSet[A] =
## Returns the difference of the sets `s1` and `s2`.
##
## The difference of two sets is represented mathematically as *A \ B* and is
@@ -376,7 +376,7 @@ proc difference*[A](s1, s2: TSet[A]): TSet[A] =
if not contains(s2, item):
incl(result, item)
-proc symmetricDifference*[A](s1, s2: TSet[A]): TSet[A] =
+proc symmetricDifference*[A](s1, s2: HashSet[A]): TSet[A] =
## Returns the symmetric difference of the sets `s1` and `s2`.
##
## The symmetric difference of two sets is represented mathematically as *A â–³
@@ -395,23 +395,23 @@ proc symmetricDifference*[A](s1, s2: TSet[A]): TSet[A] =
for item in s2:
if containsOrIncl(result, item): excl(result, item)
-proc `+`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} =
+proc `+`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
## Alias for `union(s1, s2) <#union>`_.
result = union(s1, s2)
-proc `*`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} =
+proc `*`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
## Alias for `intersection(s1, s2) <#intersection>`_.
result = intersection(s1, s2)
-proc `-`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} =
+proc `-`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
## Alias for `difference(s1, s2) <#difference>`_.
result = difference(s1, s2)
-proc `-+-`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} =
+proc `-+-`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
## Alias for `symmetricDifference(s1, s2) <#symmetricDifference>`_.
result = symmetricDifference(s1, s2)
-proc disjoint*[A](s1, s2: TSet[A]): bool =
+proc disjoint*[A](s1, s2: HashSet[A]): bool =
## Returns true iff the sets `s1` and `s2` have no items in common.
##
## Example:
@@ -428,7 +428,7 @@ proc disjoint*[A](s1, s2: TSet[A]): bool =
if item in s2: return false
return true
-proc `<`*[A](s, t: TSet[A]): bool =
+proc `<`*[A](s, t: HashSet[A]): bool =
## Returns true if `s` is a strict or proper subset of `t`.
##
## A strict or proper subset `s` has all of its members in `t` but `t` has
@@ -443,7 +443,7 @@ proc `<`*[A](s, t: TSet[A]): bool =
## assert((a < a) == false)
s.counter != t.counter and s <= t
-proc `<=`*[A](s, t: TSet[A]): bool =
+proc `<=`*[A](s, t: HashSet[A]): bool =
## Returns true if `s` is subset of `t`.
##
## A subset `s` has all of its members in `t` and `t` doesn't necessarily
@@ -464,7 +464,7 @@ proc `<=`*[A](s, t: TSet[A]): bool =
result = false
return
-proc `==`*[A](s, t: TSet[A]): bool =
+proc `==`*[A](s, t: HashSet[A]): bool =
## Returns true if both `s` and `t` have the same members and set size.
##
## Example:
@@ -477,7 +477,7 @@ proc `==`*[A](s, t: TSet[A]): bool =
## assert a == b
s.counter == t.counter and s <= t
-proc map*[A, B](data: TSet[A], op: proc (x: A): B {.closure.}): TSet[B] =
+proc map*[A, B](data: HashSet[A], op: proc (x: A): B {.closure.}): TSet[B] =
## Returns a new set after applying `op` on each of the elements of `data`.
##
## You can use this proc to transform the elements from a set. Example:
@@ -534,7 +534,7 @@ proc len*[A](s: OrderedSet[A]): int {.inline.} =
## assert values.len == 0
result = s.counter
-proc card*[A](s: TOrderedSet[A]): int {.inline.} =
+proc card*[A](s: OrderedSet[A]): int {.inline.} =
## Alias for `len() <#len,TOrderedSet[A]>`_.
##
## Card stands for the `cardinality
@@ -548,7 +548,7 @@ template forAllOrderedPairs(yieldStmt: stmt) {.dirty, immediate.} =
if s.data[h].slot == seFilled: yieldStmt
h = nxt
-iterator items*[A](s: TOrderedSet[A]): A =
+iterator items*[A](s: OrderedSet[A]): A =
## Iterates over keys in the ordered set `s` in insertion order.
##
## If you need a sequence with the keys you can use `sequtils.toSeq()
@@ -570,10 +570,10 @@ iterator items*[A](s: TOrderedSet[A]): A =
forAllOrderedPairs:
yield s.data[h].key
-proc rawGet[A](s: TOrderedSet[A], key: A): int =
+proc rawGet[A](s: OrderedSet[A], key: A): int =
rawGetImpl()
-proc contains*[A](s: TOrderedSet[A], key: A): bool =
+proc contains*[A](s: OrderedSet[A], key: A): bool =
## Returns true iff `key` is in `s`.
##
## Example:
@@ -587,7 +587,7 @@ proc contains*[A](s: TOrderedSet[A], key: A): bool =
var index = rawGet(s, key)
result = index >= 0
-proc rawInsert[A](s: var TOrderedSet[A],
+proc rawInsert[A](s: var OrderedSet[A],
data: var OrderedKeyValuePairSeq[A], key: A) =
rawInsertImpl()
data[h].next = -1
@@ -595,7 +595,7 @@ proc rawInsert[A](s: var TOrderedSet[A],
if s.last >= 0: data[s.last].next = h
s.last = h
-proc enlarge[A](s: var TOrderedSet[A]) =
+proc enlarge[A](s: var OrderedSet[A]) =
var n: OrderedKeyValuePairSeq[A]
newSeq(n, len(s.data) * growthFactor)
var h = s.first
@@ -608,7 +608,7 @@ proc enlarge[A](s: var TOrderedSet[A]) =
h = nxt
swap(s.data, n)
-proc incl*[A](s: var TOrderedSet[A], key: A) =
+proc incl*[A](s: var OrderedSet[A], key: A) =
## Includes an element `key` in `s`.
##
## This doesn't do anything if `key` is already in `s`. Example:
@@ -621,7 +621,7 @@ proc incl*[A](s: var TOrderedSet[A], key: A) =
assert s.isValid, "The set needs to be initialized."
inclImpl()
-proc incl*[A](s: var TSet[A], other: TOrderedSet[A]) =
+proc incl*[A](s: var HashSet[A], other: TOrderedSet[A]) =
## Includes all elements from `other` into `s`.
##
## Example:
@@ -636,7 +636,7 @@ proc incl*[A](s: var TSet[A], other: TOrderedSet[A]) =
assert other.isValid, "The set `other` needs to be initialized."
for item in other: incl(s, item)
-proc containsOrIncl*[A](s: var TOrderedSet[A], key: A): bool =
+proc containsOrIncl*[A](s: var OrderedSet[A], key: A): bool =
## Includes `key` in the set `s` and tells if `key` was added to `s`.
##
## The difference with regards to the `incl() <#incl,TOrderedSet[A],A>`_ proc
@@ -651,7 +651,7 @@ proc containsOrIncl*[A](s: var TOrderedSet[A], key: A): bool =
assert s.isValid, "The set needs to be initialized."
containsOrInclImpl()
-proc init*[A](s: var TOrderedSet[A], initialSize=64) =
+proc init*[A](s: var OrderedSet[A], initialSize=64) =
## Initializes an ordered hash set.
##
## The `initialSize` parameter needs to be a power of too. You can use
@@ -676,7 +676,7 @@ proc init*[A](s: var TOrderedSet[A], initialSize=64) =
s.last = -1
newSeq(s.data, initialSize)
-proc initOrderedSet*[A](initialSize=64): TOrderedSet[A] =
+proc initOrderedSet*[A](initialSize=64): OrderedSet[A] =
## Wrapper around `init() <#init,TOrderedSet[A],int>`_ for initialization of
## ordered hash sets.
##
@@ -688,7 +688,7 @@ proc initOrderedSet*[A](initialSize=64): TOrderedSet[A] =
## a.incl(2)
result.init(initialSize)
-proc toOrderedSet*[A](keys: openArray[A]): TOrderedSet[A] =
+proc toOrderedSet*[A](keys: openArray[A]): OrderedSet[A] =
## Creates a new ordered hash set that contains the given `keys`.
##
## Example:
@@ -700,7 +700,7 @@ proc toOrderedSet*[A](keys: openArray[A]): TOrderedSet[A] =
result = initOrderedSet[A](nextPowerOfTwo(keys.len+10))
for key in items(keys): result.incl(key)
-proc `$`*[A](s: TOrderedSet[A]): string =
+proc `$`*[A](s: OrderedSet[A]): string =
## Converts the ordered hash set `s` to a string, mostly for logging purposes.
##
## Don't use this proc for serialization, the representation may change at
@@ -716,7 +716,7 @@ proc `$`*[A](s: TOrderedSet[A]): string =
assert s.isValid, "The set needs to be initialized."
dollarImpl()
-proc `==`*[A](s, t: TOrderedSet[A]): bool =
+proc `==`*[A](s, t: OrderedSet[A]): bool =
## Equality for ordered sets.
if s.counter != t.counter: return false
var h = s.first
@@ -738,7 +738,7 @@ proc testModule() =
## Internal micro test to validate docstrings and such.
block isValidTest:
var options: HashSet[string]
- proc savePreferences(options: TSet[string]) =
+ proc savePreferences(options: HashSet[string]) =
assert options.isValid, "Pass an initialized set!"
options = initSet[string]()
options.savePreferences
@@ -839,7 +839,7 @@ proc testModule() =
block isValidTest:
var cards: OrderedSet[string]
- proc saveTarotCards(cards: TOrderedSet[string]) =
+ proc saveTarotCards(cards: OrderedSet[string]) =
assert cards.isValid, "Pass an initialized set!"
cards = initOrderedSet[string]()
cards.saveTarotCards
@@ -891,7 +891,7 @@ proc testModule() =
a.incl(2)
assert a.len == 1
- var b: TSet[int]
+ var b: HashSet[int]
b.init(4)
b.incl(2)
b.init
diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim
index c6ac01da8..41dfdaca6 100644
--- a/lib/pure/collections/tables.nim
+++ b/lib/pure/collections/tables.nim
@@ -74,32 +74,32 @@ type
when not defined(nimhygiene):
{.pragma: dirty.}
-proc len*[A, B](t: TTable[A, B]): int =
+proc len*[A, B](t: Table[A, B]): int =
## returns the number of keys in `t`.
result = t.counter
-iterator pairs*[A, B](t: TTable[A, B]): tuple[key: A, val: B] =
+iterator pairs*[A, B](t: Table[A, B]): tuple[key: A, val: B] =
## iterates over any (key, value) pair in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A, B](t: var TTable[A, B]): tuple[key: A, val: var B] =
+iterator mpairs*[A, B](t: var Table[A, B]): tuple[key: A, val: var B] =
## iterates over any (key, value) pair in the table `t`. The values
## can be modified.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val)
-iterator keys*[A, B](t: TTable[A, B]): A =
+iterator keys*[A, B](t: Table[A, B]): A =
## iterates over any key in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].key
-iterator values*[A, B](t: TTable[A, B]): B =
+iterator values*[A, B](t: Table[A, B]): B =
## iterates over any value in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].val
-iterator mvalues*[A, B](t: var TTable[A, B]): var B =
+iterator mvalues*[A, B](t: var Table[A, B]): var B =
## iterates over any value in the table `t`. The values can be modified.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].val
@@ -130,10 +130,10 @@ template rawInsertImpl() {.dirty.} =
data[h].val = val
data[h].slot = seFilled
-proc rawGet[A, B](t: TTable[A, B], key: A): int =
+proc rawGet[A, B](t: Table[A, B], key: A): int =
rawGetImpl()
-proc `[]`*[A, B](t: TTable[A, B], key: A): B =
+proc `[]`*[A, B](t: Table[A, B], key: A): B =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
@@ -141,14 +141,14 @@ proc `[]`*[A, B](t: TTable[A, B], key: A): B =
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
-proc mget*[A, B](t: var TTable[A, B], key: A): var B =
+proc mget*[A, B](t: var Table[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(KeyError, "key not found: " & $key)
-iterator allValues*[A, B](t: TTable[A, B]; key: A): B =
+iterator allValues*[A, B](t: Table[A, B]; key: A): B =
## iterates over any value in the table `t` that belongs to the given `key`.
var h: THash = hash(key) and high(t.data)
while t.data[h].slot != seEmpty:
@@ -156,15 +156,15 @@ iterator allValues*[A, B](t: TTable[A, B]; key: A): B =
yield t.data[h].val
h = nextTry(h, high(t.data))
-proc hasKey*[A, B](t: TTable[A, B], key: A): bool =
+proc hasKey*[A, B](t: Table[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
-proc rawInsert[A, B](t: var TTable[A, B], data: var KeyValuePairSeq[A, B],
+proc rawInsert[A, B](t: var Table[A, B], data: var KeyValuePairSeq[A, B],
key: A, val: B) =
rawInsertImpl()
-proc enlarge[A, B](t: var TTable[A, B]) =
+proc enlarge[A, B](t: var Table[A, B]) =
var n: KeyValuePairSeq[A, B]
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
@@ -196,22 +196,22 @@ when false:
inc(t.counter)
result = false
-proc `[]=`*[A, B](t: var TTable[A, B], key: A, val: B) =
+proc `[]=`*[A, B](t: var Table[A, B], key: A, val: B) =
## puts a (key, value)-pair into `t`.
putImpl()
-proc add*[A, B](t: var TTable[A, B], key: A, val: B) =
+proc add*[A, B](t: var Table[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
addImpl()
-proc del*[A, B](t: var TTable[A, B], key: A) =
+proc del*[A, B](t: var Table[A, B], key: A) =
## deletes `key` from hash table `t`.
let index = rawGet(t, key)
if index >= 0:
t.data[index].slot = seDeleted
dec(t.counter)
-proc initTable*[A, B](initialSize=64): TTable[A, B] =
+proc initTable*[A, B](initialSize=64): Table[A, B] =
## creates a new hash table that is empty.
##
## `initialSize` needs to be a power of two. If you need to accept runtime
@@ -222,7 +222,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] =
newSeq(result.data, initialSize)
proc toTable*[A, B](pairs: openArray[tuple[key: A,
- val: B]]): TTable[A, B] =
+ val: B]]): Table[A, B] =
## creates a new hash table that contains the given `pairs`.
result = initTable[A, B](nextPowerOfTwo(pairs.len+10))
for key, val in items(pairs): result[key] = val
@@ -239,7 +239,7 @@ template dollarImpl(): stmt {.dirty.} =
result.add($val)
result.add("}")
-proc `$`*[A, B](t: TTable[A, B]): string =
+proc `$`*[A, B](t: Table[A, B]): string =
## The `$` operator for hash tables.
dollarImpl()
@@ -253,93 +253,93 @@ template equalsImpl() =
if t[key] != val: return false
return true
-proc `==`*[A, B](s, t: TTable[A, B]): bool =
+proc `==`*[A, B](s, t: Table[A, B]): bool =
equalsImpl()
-proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): TTable[C, B] =
+proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): Table[C, B] =
## Index the collection with the proc provided.
# TODO: As soon as supported, change collection: A to collection: A[B]
result = initTable[C, B]()
for item in collection:
result[index(item)] = item
-proc len*[A, B](t: PTable[A, B]): int =
+proc len*[A, B](t: TableRef[A, B]): int =
## returns the number of keys in `t`.
result = t.counter
-iterator pairs*[A, B](t: PTable[A, B]): tuple[key: A, val: B] =
+iterator pairs*[A, B](t: TableRef[A, B]): tuple[key: A, val: B] =
## iterates over any (key, value) pair in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A, B](t: PTable[A, B]): tuple[key: A, val: var B] =
+iterator mpairs*[A, B](t: TableRef[A, B]): tuple[key: A, val: var B] =
## iterates over any (key, value) pair in the table `t`. The values
## can be modified.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val)
-iterator keys*[A, B](t: PTable[A, B]): A =
+iterator keys*[A, B](t: TableRef[A, B]): A =
## iterates over any key in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].key
-iterator values*[A, B](t: PTable[A, B]): B =
+iterator values*[A, B](t: TableRef[A, B]): B =
## iterates over any value in the table `t`.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].val
-iterator mvalues*[A, B](t: PTable[A, B]): var B =
+iterator mvalues*[A, B](t: TableRef[A, B]): var B =
## iterates over any value in the table `t`. The values can be modified.
for h in 0..high(t.data):
if t.data[h].slot == seFilled: yield t.data[h].val
-proc `[]`*[A, B](t: PTable[A, B], key: A): B =
+proc `[]`*[A, B](t: TableRef[A, B], key: A): B =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
## exists.
result = t[][key]
-proc mget*[A, B](t: PTable[A, B], key: A): var B =
+proc mget*[A, B](t: TableRef[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
t[].mget(key)
-proc hasKey*[A, B](t: PTable[A, B], key: A): bool =
+proc hasKey*[A, B](t: TableRef[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = t[].hasKey(key)
-proc `[]=`*[A, B](t: PTable[A, B], key: A, val: B) =
+proc `[]=`*[A, B](t: TableRef[A, B], key: A, val: B) =
## puts a (key, value)-pair into `t`.
t[][key] = val
-proc add*[A, B](t: PTable[A, B], key: A, val: B) =
+proc add*[A, B](t: TableRef[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
t[].add(key, val)
-proc del*[A, B](t: PTable[A, B], key: A) =
+proc del*[A, B](t: TableRef[A, B], key: A) =
## deletes `key` from hash table `t`.
t[].del(key)
-proc newTable*[A, B](initialSize=64): PTable[A, B] =
+proc newTable*[A, B](initialSize=64): TableRef[A, B] =
new(result)
result[] = initTable[A, B](initialSize)
-proc newTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): PTable[A, B] =
+proc newTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): TableRef[A, B] =
## creates a new hash table that contains the given `pairs`.
new(result)
result[] = toTable[A, B](pairs)
-proc `$`*[A, B](t: PTable[A, B]): string =
+proc `$`*[A, B](t: TableRef[A, B]): string =
## The `$` operator for hash tables.
dollarImpl()
-proc `==`*[A, B](s, t: PTable[A, B]): bool =
+proc `==`*[A, B](s, t: TableRef[A, B]): bool =
if isNil(s): result = isNil(t)
elif isNil(t): result = false
else: result = equalsImpl()
-proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): PTable[C, B] =
+proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): TableRef[C, B] =
## Index the collection with the proc provided.
# TODO: As soon as supported, change collection: A to collection: A[B]
result = newTable[C, B]()
@@ -360,7 +360,7 @@ type
{.deprecated: [TOrderedTable: OrderedTable, POrderedTable: OrderedTableRef].}
-proc len*[A, B](t: TOrderedTable[A, B]): int {.inline.} =
+proc len*[A, B](t: OrderedTable[A, B]): int {.inline.} =
## returns the number of keys in `t`.
result = t.counter
@@ -371,38 +371,38 @@ template forAllOrderedPairs(yieldStmt: stmt) {.dirty, immediate.} =
if t.data[h].slot == seFilled: yieldStmt
h = nxt
-iterator pairs*[A, B](t: TOrderedTable[A, B]): tuple[key: A, val: B] =
+iterator pairs*[A, B](t: OrderedTable[A, B]): tuple[key: A, val: B] =
## iterates over any (key, value) pair in the table `t` in insertion
## order.
forAllOrderedPairs:
yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A, B](t: var TOrderedTable[A, B]): tuple[key: A, val: var B] =
+iterator mpairs*[A, B](t: var OrderedTable[A, B]): tuple[key: A, val: var B] =
## iterates over any (key, value) pair in the table `t` in insertion
## order. The values can be modified.
forAllOrderedPairs:
yield (t.data[h].key, t.data[h].val)
-iterator keys*[A, B](t: TOrderedTable[A, B]): A =
+iterator keys*[A, B](t: OrderedTable[A, B]): A =
## iterates over any key in the table `t` in insertion order.
forAllOrderedPairs:
yield t.data[h].key
-iterator values*[A, B](t: TOrderedTable[A, B]): B =
+iterator values*[A, B](t: OrderedTable[A, B]): B =
## iterates over any value in the table `t` in insertion order.
forAllOrderedPairs:
yield t.data[h].val
-iterator mvalues*[A, B](t: var TOrderedTable[A, B]): var B =
+iterator mvalues*[A, B](t: var OrderedTable[A, B]): var B =
## iterates over any value in the table `t` in insertion order. The values
## can be modified.
forAllOrderedPairs:
yield t.data[h].val
-proc rawGet[A, B](t: TOrderedTable[A, B], key: A): int =
+proc rawGet[A, B](t: OrderedTable[A, B], key: A): int =
rawGetImpl()
-proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B =
+proc `[]`*[A, B](t: OrderedTable[A, B], key: A): B =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
@@ -410,18 +410,18 @@ proc `[]`*[A, B](t: TOrderedTable[A, B], key: A): B =
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
-proc mget*[A, B](t: var TOrderedTable[A, B], key: A): var B =
+proc mget*[A, B](t: var OrderedTable[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(KeyError, "key not found: " & $key)
-proc hasKey*[A, B](t: TOrderedTable[A, B], key: A): bool =
+proc hasKey*[A, B](t: OrderedTable[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
-proc rawInsert[A, B](t: var TOrderedTable[A, B],
+proc rawInsert[A, B](t: var OrderedTable[A, B],
data: var OrderedKeyValuePairSeq[A, B],
key: A, val: B) =
rawInsertImpl()
@@ -430,7 +430,7 @@ proc rawInsert[A, B](t: var TOrderedTable[A, B],
if t.last >= 0: data[t.last].next = h
t.last = h
-proc enlarge[A, B](t: var TOrderedTable[A, B]) =
+proc enlarge[A, B](t: var OrderedTable[A, B]) =
var n: OrderedKeyValuePairSeq[A, B]
newSeq(n, len(t.data) * growthFactor)
var h = t.first
@@ -443,15 +443,15 @@ proc enlarge[A, B](t: var TOrderedTable[A, B]) =
h = nxt
swap(t.data, n)
-proc `[]=`*[A, B](t: var TOrderedTable[A, B], key: A, val: B) =
+proc `[]=`*[A, B](t: var OrderedTable[A, B], key: A, val: B) =
## puts a (key, value)-pair into `t`.
putImpl()
-proc add*[A, B](t: var TOrderedTable[A, B], key: A, val: B) =
+proc add*[A, B](t: var OrderedTable[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
addImpl()
-proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] =
+proc initOrderedTable*[A, B](initialSize=64): OrderedTable[A, B] =
## creates a new ordered hash table that is empty.
##
## `initialSize` needs to be a power of two. If you need to accept runtime
@@ -464,16 +464,16 @@ proc initOrderedTable*[A, B](initialSize=64): TOrderedTable[A, B] =
newSeq(result.data, initialSize)
proc toOrderedTable*[A, B](pairs: openArray[tuple[key: A,
- val: B]]): TOrderedTable[A, B] =
+ val: B]]): OrderedTable[A, B] =
## creates a new ordered hash table that contains the given `pairs`.
result = initOrderedTable[A, B](nextPowerOfTwo(pairs.len+10))
for key, val in items(pairs): result[key] = val
-proc `$`*[A, B](t: TOrderedTable[A, B]): string =
+proc `$`*[A, B](t: OrderedTable[A, B]): string =
## The `$` operator for ordered hash tables.
dollarImpl()
-proc sort*[A, B](t: var TOrderedTable[A, B],
+proc sort*[A, B](t: var OrderedTable[A, B],
cmp: proc (x,y: tuple[key: A, val: B]): int) =
## sorts `t` according to `cmp`. This modifies the internal list
## that kept the insertion order, so insertion order is lost after this
@@ -519,7 +519,7 @@ proc sort*[A, B](t: var TOrderedTable[A, B],
t.first = list
t.last = tail
-proc len*[A, B](t: POrderedTable[A, B]): int {.inline.} =
+proc len*[A, B](t: OrderedTableRef[A, B]): int {.inline.} =
## returns the number of keys in `t`.
result = t.counter
@@ -530,59 +530,59 @@ template forAllOrderedPairs(yieldStmt: stmt) {.dirty, immediate.} =
if t.data[h].slot == seFilled: yieldStmt
h = nxt
-iterator pairs*[A, B](t: POrderedTable[A, B]): tuple[key: A, val: B] =
+iterator pairs*[A, B](t: OrderedTableRef[A, B]): tuple[key: A, val: B] =
## iterates over any (key, value) pair in the table `t` in insertion
## order.
forAllOrderedPairs:
yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A, B](t: POrderedTable[A, B]): tuple[key: A, val: var B] =
+iterator mpairs*[A, B](t: OrderedTableRef[A, B]): tuple[key: A, val: var B] =
## iterates over any (key, value) pair in the table `t` in insertion
## order. The values can be modified.
forAllOrderedPairs:
yield (t.data[h].key, t.data[h].val)
-iterator keys*[A, B](t: POrderedTable[A, B]): A =
+iterator keys*[A, B](t: OrderedTableRef[A, B]): A =
## iterates over any key in the table `t` in insertion order.
forAllOrderedPairs:
yield t.data[h].key
-iterator values*[A, B](t: POrderedTable[A, B]): B =
+iterator values*[A, B](t: OrderedTableRef[A, B]): B =
## iterates over any value in the table `t` in insertion order.
forAllOrderedPairs:
yield t.data[h].val
-iterator mvalues*[A, B](t: POrderedTable[A, B]): var B =
+iterator mvalues*[A, B](t: OrderedTableRef[A, B]): var B =
## iterates over any value in the table `t` in insertion order. The values
## can be modified.
forAllOrderedPairs:
yield t.data[h].val
-proc `[]`*[A, B](t: POrderedTable[A, B], key: A): B =
+proc `[]`*[A, B](t: OrderedTableRef[A, B], key: A): B =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## default empty value for the type `B` is returned
## and no exception is raised. One can check with ``hasKey`` whether the key
## exists.
result = t[][key]
-proc mget*[A, B](t: POrderedTable[A, B], key: A): var B =
+proc mget*[A, B](t: OrderedTableRef[A, B], key: A): var B =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
result = t[].mget(key)
-proc hasKey*[A, B](t: POrderedTable[A, B], key: A): bool =
+proc hasKey*[A, B](t: OrderedTableRef[A, B], key: A): bool =
## returns true iff `key` is in the table `t`.
result = t[].hasKey(key)
-proc `[]=`*[A, B](t: POrderedTable[A, B], key: A, val: B) =
+proc `[]=`*[A, B](t: OrderedTableRef[A, B], key: A, val: B) =
## puts a (key, value)-pair into `t`.
t[][key] = val
-proc add*[A, B](t: POrderedTable[A, B], key: A, val: B) =
+proc add*[A, B](t: OrderedTableRef[A, B], key: A, val: B) =
## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
t[].add(key, val)
-proc newOrderedTable*[A, B](initialSize=64): POrderedTable[A, B] =
+proc newOrderedTable*[A, B](initialSize=64): OrderedTableRef[A, B] =
## creates a new ordered hash table that is empty.
##
## `initialSize` needs to be a power of two. If you need to accept runtime
@@ -592,16 +592,16 @@ proc newOrderedTable*[A, B](initialSize=64): POrderedTable[A, B] =
result[] = initOrderedTable[A, B]()
proc newOrderedTable*[A, B](pairs: openArray[tuple[key: A,
- val: B]]): POrderedTable[A, B] =
+ val: B]]): OrderedTableRef[A, B] =
## creates a new ordered hash table that contains the given `pairs`.
result = newOrderedTable[A, B](nextPowerOfTwo(pairs.len+10))
for key, val in items(pairs): result[key] = val
-proc `$`*[A, B](t: POrderedTable[A, B]): string =
+proc `$`*[A, B](t: OrderedTableRef[A, B]): string =
## The `$` operator for ordered hash tables.
dollarImpl()
-proc sort*[A, B](t: POrderedTable[A, B],
+proc sort*[A, B](t: OrderedTableRef[A, B],
cmp: proc (x,y: tuple[key: A, val: B]): int) =
## sorts `t` according to `cmp`. This modifies the internal list
## that kept the insertion order, so insertion order is lost after this
@@ -620,81 +620,81 @@ type
{.deprecated: [TCountTable: CountTable, PCountTable: CountTableRef].}
-proc len*[A](t: TCountTable[A]): int =
+proc len*[A](t: CountTable[A]): int =
## returns the number of keys in `t`.
result = t.counter
-iterator pairs*[A](t: TCountTable[A]): tuple[key: A, val: int] =
+iterator pairs*[A](t: CountTable[A]): tuple[key: A, val: int] =
## iterates over any (key, value) pair in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A](t: var TCountTable[A]): tuple[key: A, val: var int] =
+iterator mpairs*[A](t: var CountTable[A]): tuple[key: A, val: var int] =
## iterates over any (key, value) pair in the table `t`. The values can
## be modified.
for h in 0..high(t.data):
if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val)
-iterator keys*[A](t: TCountTable[A]): A =
+iterator keys*[A](t: CountTable[A]): A =
## iterates over any key in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].key
-iterator values*[A](t: TCountTable[A]): int =
+iterator values*[A](t: CountTable[A]): int =
## iterates over any value in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val
-iterator mvalues*[A](t: TCountTable[A]): var int =
+iterator mvalues*[A](t: CountTable[A]): var int =
## iterates over any value in the table `t`. The values can be modified.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val
-proc rawGet[A](t: TCountTable[A], key: A): int =
+proc rawGet[A](t: CountTable[A], key: A): int =
var h: THash = hash(key) and high(t.data) # start with real hash value
while t.data[h].val != 0:
if t.data[h].key == key: return h
h = nextTry(h, high(t.data))
result = -1
-proc `[]`*[A](t: TCountTable[A], key: A): int =
+proc `[]`*[A](t: CountTable[A], key: A): int =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## 0 is returned. One can check with ``hasKey`` whether the key
## exists.
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
-proc mget*[A](t: var TCountTable[A], key: A): var int =
+proc mget*[A](t: var CountTable[A], key: A): var int =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
var index = rawGet(t, key)
if index >= 0: result = t.data[index].val
else: raise newException(KeyError, "key not found: " & $key)
-proc hasKey*[A](t: TCountTable[A], key: A): bool =
+proc hasKey*[A](t: CountTable[A], key: A): bool =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
-proc rawInsert[A](t: TCountTable[A], data: var seq[tuple[key: A, val: int]],
+proc rawInsert[A](t: CountTable[A], data: var seq[tuple[key: A, val: int]],
key: A, val: int) =
var h: THash = hash(key) and high(data)
while data[h].val != 0: h = nextTry(h, high(data))
data[h].key = key
data[h].val = val
-proc enlarge[A](t: var TCountTable[A]) =
+proc enlarge[A](t: var CountTable[A]) =
var n: seq[tuple[key: A, val: int]]
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if t.data[i].val != 0: rawInsert(t, n, t.data[i].key, t.data[i].val)
swap(t.data, n)
-proc `[]=`*[A](t: var TCountTable[A], key: A, val: int) =
+proc `[]=`*[A](t: var CountTable[A], key: A, val: int) =
## puts a (key, value)-pair into `t`. `val` has to be positive.
assert val > 0
putImpl()
-proc initCountTable*[A](initialSize=64): TCountTable[A] =
+proc initCountTable*[A](initialSize=64): CountTable[A] =
## creates a new count table that is empty.
##
## `initialSize` needs to be a power of two. If you need to accept runtime
@@ -704,16 +704,16 @@ proc initCountTable*[A](initialSize=64): TCountTable[A] =
result.counter = 0
newSeq(result.data, initialSize)
-proc toCountTable*[A](keys: openArray[A]): TCountTable[A] =
+proc toCountTable*[A](keys: openArray[A]): CountTable[A] =
## creates a new count table with every key in `keys` having a count of 1.
result = initCountTable[A](nextPowerOfTwo(keys.len+10))
for key in items(keys): result[key] = 1
-proc `$`*[A](t: TCountTable[A]): string =
+proc `$`*[A](t: CountTable[A]): string =
## The `$` operator for count tables.
dollarImpl()
-proc inc*[A](t: var TCountTable[A], key: A, val = 1) =
+proc inc*[A](t: var CountTable[A], key: A, val = 1) =
## increments `t[key]` by `val`.
var index = rawGet(t, key)
if index >= 0:
@@ -723,7 +723,7 @@ proc inc*[A](t: var TCountTable[A], key: A, val = 1) =
rawInsert(t, t.data, key, val)
inc(t.counter)
-proc smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
+proc smallest*[A](t: CountTable[A]): tuple[key: A, val: int] =
## returns the largest (key,val)-pair. Efficiency: O(n)
assert t.len > 0
var minIdx = 0
@@ -732,7 +732,7 @@ proc smallest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
result.key = t.data[minIdx].key
result.val = t.data[minIdx].val
-proc largest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
+proc largest*[A](t: CountTable[A]): tuple[key: A, val: int] =
## returns the (key,val)-pair with the largest `val`. Efficiency: O(n)
assert t.len > 0
var maxIdx = 0
@@ -741,7 +741,7 @@ proc largest*[A](t: TCountTable[A]): tuple[key: A, val: int] =
result.key = t.data[maxIdx].key
result.val = t.data[maxIdx].val
-proc sort*[A](t: var TCountTable[A]) =
+proc sort*[A](t: var CountTable[A]) =
## sorts the count table so that the entry with the highest counter comes
## first. This is destructive! You must not modify `t` afterwards!
## You can use the iterators `pairs`, `keys`, and `values` to iterate over
@@ -762,57 +762,57 @@ proc sort*[A](t: var TCountTable[A]) =
if j < h: break
if h == 1: break
-proc len*[A](t: PCountTable[A]): int =
+proc len*[A](t: CountTableRef[A]): int =
## returns the number of keys in `t`.
result = t.counter
-iterator pairs*[A](t: PCountTable[A]): tuple[key: A, val: int] =
+iterator pairs*[A](t: CountTableRef[A]): tuple[key: A, val: int] =
## iterates over any (key, value) pair in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val)
-iterator mpairs*[A](t: PCountTable[A]): tuple[key: A, val: var int] =
+iterator mpairs*[A](t: CountTableRef[A]): tuple[key: A, val: var int] =
## iterates over any (key, value) pair in the table `t`. The values can
## be modified.
for h in 0..high(t.data):
if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val)
-iterator keys*[A](t: PCountTable[A]): A =
+iterator keys*[A](t: CountTableRef[A]): A =
## iterates over any key in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].key
-iterator values*[A](t: PCountTable[A]): int =
+iterator values*[A](t: CountTableRef[A]): int =
## iterates over any value in the table `t`.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val
-iterator mvalues*[A](t: PCountTable[A]): var int =
+iterator mvalues*[A](t: CountTableRef[A]): var int =
## iterates over any value in the table `t`. The values can be modified.
for h in 0..high(t.data):
if t.data[h].val != 0: yield t.data[h].val
-proc `[]`*[A](t: PCountTable[A], key: A): int =
+proc `[]`*[A](t: CountTableRef[A], key: A): int =
## retrieves the value at ``t[key]``. If `key` is not in `t`,
## 0 is returned. One can check with ``hasKey`` whether the key
## exists.
result = t[][key]
-proc mget*[A](t: PCountTable[A], key: A): var int =
+proc mget*[A](t: CountTableRef[A], key: A): var int =
## retrieves the value at ``t[key]``. The value can be modified.
## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
result = t[].mget(key)
-proc hasKey*[A](t: PCountTable[A], key: A): bool =
+proc hasKey*[A](t: CountTableRef[A], key: A): bool =
## returns true iff `key` is in the table `t`.
result = t[].hasKey(key)
-proc `[]=`*[A](t: PCountTable[A], key: A, val: int) =
+proc `[]=`*[A](t: CountTableRef[A], key: A, val: int) =
## puts a (key, value)-pair into `t`. `val` has to be positive.
assert val > 0
t[][key] = val
-proc newCountTable*[A](initialSize=64): PCountTable[A] =
+proc newCountTable*[A](initialSize=64): CountTableRef[A] =
## creates a new count table that is empty.
##
## `initialSize` needs to be a power of two. If you need to accept runtime
@@ -821,28 +821,28 @@ proc newCountTable*[A](initialSize=64): PCountTable[A] =
new(result)
result[] = initCountTable[A](initialSize)
-proc newCountTable*[A](keys: openArray[A]): PCountTable[A] =
+proc newCountTable*[A](keys: openArray[A]): CountTableRef[A] =
## creates a new count table with every key in `keys` having a count of 1.
result = newCountTable[A](nextPowerOfTwo(keys.len+10))
for key in items(keys): result[key] = 1
-proc `$`*[A](t: PCountTable[A]): string =
+proc `$`*[A](t: CountTableRef[A]): string =
## The `$` operator for count tables.
dollarImpl()
-proc inc*[A](t: PCountTable[A], key: A, val = 1) =
+proc inc*[A](t: CountTableRef[A], key: A, val = 1) =
## increments `t[key]` by `val`.
t[].inc(key, val)
-proc smallest*[A](t: PCountTable[A]): tuple[key: A, val: int] =
+proc smallest*[A](t: CountTableRef[A]): tuple[key: A, val: int] =
## returns the largest (key,val)-pair. Efficiency: O(n)
t[].smallest
-proc largest*[A](t: PCountTable[A]): tuple[key: A, val: int] =
+proc largest*[A](t: CountTableRef[A]): tuple[key: A, val: int] =
## returns the (key,val)-pair with the largest `val`. Efficiency: O(n)
t[].largest
-proc sort*[A](t: PCountTable[A]) =
+proc sort*[A](t: CountTableRef[A]) =
## sorts the count table so that the entry with the highest counter comes
## first. This is destructive! You must not modify `t` afterwards!
## You can use the iterators `pairs`, `keys`, and `values` to iterate over
diff --git a/lib/pure/net.nim b/lib/pure/net.nim
index 1e17f1d7a..a64294a77 100644
--- a/lib/pure/net.nim
+++ b/lib/pure/net.nim
@@ -94,11 +94,11 @@ proc toOSFlags*(socketFlags: set[SocketFlag]): cint =
## Converts the flags into the underlying OS representation.
for f in socketFlags:
case f
- of TSocketFlags.Peek:
+ of SocketFlag.Peek:
result = result or MSG_PEEK
- of TSocketFlags.SafeDisconn: continue
+ of SocketFlag.SafeDisconn: continue
-proc createSocket(fd: TSocketHandle, isBuff: bool): PSocket =
+proc createSocket(fd: TSocketHandle, isBuff: bool): Socket =
assert fd != osInvalidSocket
new(result)
result.fd = fd
@@ -106,14 +106,14 @@ proc createSocket(fd: TSocketHandle, isBuff: bool): PSocket =
if isBuff:
result.currPos = 0
-proc newSocket*(domain: TDomain = AF_INET, typ: TType = SOCK_STREAM,
- protocol: TProtocol = IPPROTO_TCP, buffered = true): PSocket =
+proc newSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM,
+ protocol: Protocol = IPPROTO_TCP, buffered = true): Socket =
## Creates a new socket.
##
## If an error occurs EOS will be raised.
let fd = newRawSocket(domain, typ, protocol)
if fd == osInvalidSocket:
- osError(osLastError())
+ raiseOSError(osLastError())
result = createSocket(fd, buffered)
when defined(ssl):
@@ -218,8 +218,8 @@ when defined(ssl):
if SSLSetFd(socket.sslHandle, socket.fd) != 1:
SSLError()
-proc socketError*(socket: PSocket, err: int = -1, async = false,
- lastError = (-1).TOSErrorCode) =
+proc socketError*(socket: Socket, err: int = -1, async = false,
+ lastError = (-1).OSErrorCode) =
## Raises an EOS error based on the error code returned by ``SSLGetError``
## (for SSL sockets) and ``osLastError`` otherwise.
##
@@ -254,23 +254,23 @@ proc socketError*(socket: PSocket, err: int = -1, async = false,
when useWinVersion:
if lastE.int32 == WSAEWOULDBLOCK:
return
- else: osError(lastE)
+ else: raiseOSError(lastE)
else:
if lastE.int32 == EAGAIN or lastE.int32 == EWOULDBLOCK:
return
else: osError(lastE)
- else: osError(lastE)
+ else: raiseOSError(lastE)
-proc listen*(socket: PSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} =
+proc listen*(socket: Socket, backlog = SOMAXCONN) {.tags: [ReadIOEffect].} =
## Marks ``socket`` as accepting connections.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
##
## Raises an EOS error upon failure.
- if listen(socket.fd, backlog) < 0'i32: osError(osLastError())
+ if listen(socket.fd, backlog) < 0'i32: raiseOSError(osLastError())
-proc bindAddr*(socket: PSocket, port = TPort(0), address = "") {.
- tags: [FReadIO].} =
+proc bindAddr*(socket: Socket, port = Port(0), address = "") {.
+ tags: [ReadIOEffect].} =
## Binds ``address``:``port`` to the socket.
##
## If ``address`` is "" then ADDR_ANY will be bound.
@@ -285,16 +285,16 @@ proc bindAddr*(socket: PSocket, port = TPort(0), address = "") {.
name.sin_addr.s_addr = htonl(INADDR_ANY)
if bindAddr(socket.fd, cast[ptr TSockAddr](addr(name)),
sizeof(name).TSocklen) < 0'i32:
- osError(osLastError())
+ raiseOSError(osLastError())
else:
var aiList = getAddrInfo(address, port, AF_INET)
if bindAddr(socket.fd, aiList.ai_addr, aiList.ai_addrlen.TSocklen) < 0'i32:
dealloc(aiList)
- osError(osLastError())
+ raiseOSError(osLastError())
dealloc(aiList)
-proc acceptAddr*(server: PSocket, client: var PSocket, address: var string,
- flags = {TSocketFlags.SafeDisconn}) {.tags: [FReadIO].} =
+proc acceptAddr*(server: Socket, client: var Socket, address: var string,
+ flags = {SocketFlag.SafeDisconn}) {.tags: [ReadIOEffect].} =
## Blocks until a connection is being made from a client. When a connection
## is made sets ``client`` to the client socket and ``address`` to the address
## of the connecting client.
@@ -311,7 +311,7 @@ proc acceptAddr*(server: PSocket, client: var PSocket, address: var string,
## flag is specified then this error will not be raised and instead
## accept will be called again.
assert(client != nil)
- var sockAddress: Tsockaddr_in
+ var sockAddress: TSockaddr_in
var addrLen = sizeof(sockAddress).TSocklen
var sock = accept(server.fd, cast[ptr TSockAddr](addr(sockAddress)),
addr(addrLen))
@@ -320,7 +320,7 @@ proc acceptAddr*(server: PSocket, client: var PSocket, address: var string,
let err = osLastError()
if flags.isDisconnectionError(err):
acceptAddr(server, client, address, flags)
- osError(err)
+ raiseOSError(err)
else:
client.fd = sock
client.isBuffered = server.isBuffered
@@ -389,8 +389,8 @@ when false: #defined(ssl):
acceptAddrPlain(AcceptNoClient, AcceptSuccess):
doHandshake()
-proc accept*(server: PSocket, client: var PSocket,
- flags = {TSocketFlags.SafeDisconn}) {.tags: [FReadIO].} =
+proc accept*(server: Socket, client: var Socket,
+ flags = {SocketFlag.SafeDisconn}) {.tags: [ReadIOEffect].} =
## Equivalent to ``acceptAddr`` but doesn't return the address, only the
## socket.
##
@@ -404,7 +404,7 @@ proc accept*(server: PSocket, client: var PSocket,
var addrDummy = ""
acceptAddr(server, client, addrDummy, flags)
-proc close*(socket: PSocket) =
+proc close*(socket: Socket) =
## Closes a socket.
socket.fd.close()
when defined(ssl):
@@ -416,7 +416,7 @@ proc close*(socket: PSocket) =
elif res != 1:
socketError(socket)
-proc toCInt(opt: TSOBool): cint =
+proc toCInt(opt: SOBool): cint =
case opt
of OptAcceptConn: SO_ACCEPTCONN
of OptBroadcast: SO_BROADCAST
@@ -426,20 +426,20 @@ proc toCInt(opt: TSOBool): cint =
of OptOOBInline: SO_OOBINLINE
of OptReuseAddr: SO_REUSEADDR
-proc getSockOpt*(socket: PSocket, opt: TSOBool, level = SOL_SOCKET): bool {.
- tags: [FReadIO].} =
+proc getSockOpt*(socket: Socket, opt: SOBool, level = SOL_SOCKET): bool {.
+ tags: [ReadIOEffect].} =
## Retrieves option ``opt`` as a boolean value.
- var res = getsockoptint(socket.fd, cint(level), toCInt(opt))
+ var res = getSockOptInt(socket.fd, cint(level), toCInt(opt))
result = res != 0
-proc setSockOpt*(socket: PSocket, opt: TSOBool, value: bool, level = SOL_SOCKET) {.
- tags: [FWriteIO].} =
+proc setSockOpt*(socket: Socket, opt: SOBool, value: bool, level = SOL_SOCKET) {.
+ tags: [WriteIOEffect].} =
## Sets option ``opt`` to a boolean value specified by ``value``.
var valuei = cint(if value: 1 else: 0)
- setsockoptint(socket.fd, cint(level), toCInt(opt), valuei)
+ setSockOptInt(socket.fd, cint(level), toCInt(opt), valuei)
-proc connect*(socket: PSocket, address: string, port = TPort(0),
- af: TDomain = AF_INET) {.tags: [FReadIO].} =
+proc connect*(socket: Socket, address: string, port = Port(0),
+ af: Domain = AF_INET) {.tags: [ReadIOEffect].} =
## Connects socket to ``address``:``port``. ``Address`` can be an IP address or a
## host name. If ``address`` is a host name, this function will try each IP
## of that host name. ``htons`` is already performed on ``port`` so you must
@@ -449,7 +449,7 @@ proc connect*(socket: PSocket, address: string, port = TPort(0),
var aiList = getAddrInfo(address, port, af)
# try all possibilities:
var success = false
- var lastError: TOSErrorCode
+ var lastError: OSErrorCode
var it = aiList
while it != nil:
if connect(socket.fd, it.ai_addr, it.ai_addrlen.TSocklen) == 0'i32:
@@ -459,7 +459,7 @@ proc connect*(socket: PSocket, address: string, port = TPort(0),
it = it.ai_next
dealloc(aiList)
- if not success: osError(lastError)
+ if not success: raiseOSError(lastError)
when defined(ssl):
if socket.isSSL:
@@ -507,7 +507,7 @@ when defined(ssl):
else:
SSLError("Socket is not an SSL socket.")
-proc hasDataBuffered*(s: PSocket): bool =
+proc hasDataBuffered*(s: Socket): bool =
## Determines whether a socket has data buffered.
result = false
if s.isBuffered:
@@ -517,15 +517,15 @@ proc hasDataBuffered*(s: PSocket): bool =
if s.isSSL and not result:
result = s.sslHasPeekChar
-proc select(readfd: PSocket, timeout = 500): int =
+proc select(readfd: Socket, timeout = 500): int =
## Used for socket operation timeouts.
if readfd.hasDataBuffered:
return 1
- var fds = @[readFd.fd]
+ var fds = @[readfd.fd]
result = select(fds, timeout)
-proc readIntoBuf(socket: PSocket, flags: int32): int =
+proc readIntoBuf(socket: Socket, flags: int32): int =
result = 0
when defined(ssl):
if socket.isSSL:
@@ -549,7 +549,7 @@ template retRead(flags, readBytes: int) {.dirty.} =
else:
return res
-proc recv*(socket: PSocket, data: pointer, size: int): int {.tags: [FReadIO].} =
+proc recv*(socket: Socket, data: pointer, size: int): int {.tags: [ReadIOEffect].} =
## Receives data from a socket.
##
## **Note**: This is a low-level function, you may be interested in the higher
@@ -590,8 +590,8 @@ proc recv*(socket: PSocket, data: pointer, size: int): int {.tags: [FReadIO].} =
else:
result = recv(socket.fd, data, size.cint, 0'i32)
-proc waitFor(socket: PSocket, waited: var float, timeout, size: int,
- funcName: string): int {.tags: [FTime].} =
+proc waitFor(socket: Socket, waited: var float, timeout, size: int,
+ funcName: string): int {.tags: [TimeEffect].} =
## determines the amount of characters that can be read. Result will never
## be larger than ``size``. For unbuffered sockets this will be ``1``.
## For buffered sockets it can be as big as ``BufferSize``.
@@ -606,7 +606,7 @@ proc waitFor(socket: PSocket, waited: var float, timeout, size: int,
result = min(result, size)
else:
if timeout - int(waited * 1000.0) < 1:
- raise newException(ETimeout, "Call to '" & funcName & "' timed out.")
+ raise newException(TimeoutError, "Call to '" & funcName & "' timed out.")
when defined(ssl):
if socket.isSSL:
@@ -619,13 +619,13 @@ proc waitFor(socket: PSocket, waited: var float, timeout, size: int,
var startTime = epochTime()
let selRet = select(socket, timeout - int(waited * 1000.0))
- if selRet < 0: osError(osLastError())
+ if selRet < 0: raiseOSError(osLastError())
if selRet != 1:
- raise newException(ETimeout, "Call to '" & funcName & "' timed out.")
+ raise newException(TimeoutError, "Call to '" & funcName & "' timed out.")
waited += (epochTime() - startTime)
-proc recv*(socket: PSocket, data: pointer, size: int, timeout: int): int {.
- tags: [FReadIO, FTime].} =
+proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {.
+ tags: [ReadIOEffect, FTime].} =
## overload with a ``timeout`` parameter in miliseconds.
var waited = 0.0 # number of seconds already waited
@@ -642,8 +642,8 @@ proc recv*(socket: PSocket, data: pointer, size: int, timeout: int): int {.
result = read
-proc recv*(socket: PSocket, data: var string, size: int, timeout = -1,
- flags = {TSocketFlags.SafeDisconn}): int =
+proc recv*(socket: Socket, data: var string, size: int, timeout = -1,
+ flags = {SocketFlag.SafeDisconn}): int =
## Higher-level version of ``recv``.
##
## When 0 is returned the socket's connection has been closed.
@@ -666,7 +666,7 @@ proc recv*(socket: PSocket, data: var string, size: int, timeout = -1,
socket.socketError(result, lastError = lastError)
data.setLen(result)
-proc peekChar(socket: PSocket, c: var char): int {.tags: [FReadIO].} =
+proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} =
if socket.isBuffered:
result = 1
if socket.bufLen == 0 or socket.currPos > socket.bufLen-1:
@@ -686,9 +686,9 @@ proc peekChar(socket: PSocket, c: var char): int {.tags: [FReadIO].} =
return
result = recv(socket.fd, addr(c), 1, MSG_PEEK)
-proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1,
- flags = {TSocketFlags.SafeDisconn}) {.
- tags: [FReadIO, FTime].} =
+proc readLine*(socket: Socket, line: var TaintedString, timeout = -1,
+ flags = {SocketFlag.SafeDisconn}) {.
+ tags: [ReadIOEffect, FTime].} =
## Reads a line of data from ``socket``.
##
## If a full line is read ``\r\L`` is not
@@ -735,9 +735,9 @@ proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1,
return
add(line.string, c)
-proc recvFrom*(socket: PSocket, data: var string, length: int,
- address: var string, port: var TPort, flags = 0'i32): int {.
- tags: [FReadIO].} =
+proc recvFrom*(socket: Socket, data: var string, length: int,
+ address: var string, port: var Port, flags = 0'i32): int {.
+ tags: [ReadIOEffect].} =
## Receives data from ``socket``. This function should normally be used with
## connection-less sockets (UDP sockets).
##
@@ -751,7 +751,7 @@ proc recvFrom*(socket: PSocket, data: var string, length: int,
# TODO: Buffered sockets
data.setLen(length)
- var sockAddress: Tsockaddr_in
+ var sockAddress: TSockaddr_in
var addrLen = sizeof(sockAddress).TSocklen
result = recvfrom(socket.fd, cstring(data), length.cint, flags.cint,
cast[ptr TSockAddr](addr(sockAddress)), addr(addrLen))
@@ -759,11 +759,11 @@ proc recvFrom*(socket: PSocket, data: var string, length: int,
if result != -1:
data.setLen(result)
address = $inet_ntoa(sockAddress.sin_addr)
- port = ntohs(sockAddress.sin_port).TPort
+ port = ntohs(sockAddress.sin_port).Port
else:
- osError(osLastError())
+ raiseOSError(osLastError())
-proc skip*(socket: PSocket, size: int, timeout = -1) =
+proc skip*(socket: Socket, size: int, timeout = -1) =
## Skips ``size`` amount of bytes.
##
## An optional timeout can be specified in miliseconds, if skipping the
@@ -778,8 +778,8 @@ proc skip*(socket: PSocket, size: int, timeout = -1) =
bytesSkipped += recv(socket, dummy, avail)
dealloc(dummy)
-proc send*(socket: PSocket, data: pointer, size: int): int {.
- tags: [FWriteIO].} =
+proc send*(socket: Socket, data: pointer, size: int): int {.
+ tags: [WriteIOEffect].} =
## Sends data to a socket.
##
## **Note**: This is a low-level version of ``send``. You likely should use
@@ -795,8 +795,8 @@ proc send*(socket: PSocket, data: pointer, size: int): int {.
const MSG_NOSIGNAL = 0
result = send(socket.fd, data, size, int32(MSG_NOSIGNAL))
-proc send*(socket: PSocket, data: string,
- flags = {TSocketFlags.SafeDisconn}) {.tags: [FWriteIO].} =
+proc send*(socket: Socket, data: string,
+ flags = {SocketFlag.SafeDisconn}) {.tags: [WriteIOEffect].} =
## sends data to a socket.
let sent = send(socket, cstring(data), data.len)
if sent < 0:
@@ -805,16 +805,16 @@ proc send*(socket: PSocket, data: string,
socketError(socket, lastError = lastError)
if sent != data.len:
- raise newException(EOS, "Could not send all data.")
+ raise newException(OSError, "Could not send all data.")
-proc trySend*(socket: PSocket, data: string): bool {.tags: [FWriteIO].} =
+proc trySend*(socket: Socket, data: string): bool {.tags: [WriteIOEffect].} =
## Safe alternative to ``send``. Does not raise an EOS when an error occurs,
## and instead returns ``false`` on failure.
result = send(socket, cstring(data), data.len) == data.len
-proc sendTo*(socket: PSocket, address: string, port: TPort, data: pointer,
- size: int, af: TDomain = AF_INET, flags = 0'i32): int {.
- tags: [FWriteIO].} =
+proc sendTo*(socket: Socket, address: string, port: Port, data: pointer,
+ size: int, af: Domain = AF_INET, flags = 0'i32): int {.
+ tags: [WriteIOEffect].} =
## This proc sends ``data`` to the specified ``address``,
## which may be an IP address or a hostname, if a hostname is specified
## this function will try each IP of that hostname.
@@ -839,8 +839,8 @@ proc sendTo*(socket: PSocket, address: string, port: TPort, data: pointer,
dealloc(aiList)
-proc sendTo*(socket: PSocket, address: string, port: TPort,
- data: string): int {.tags: [FWriteIO].} =
+proc sendTo*(socket: Socket, address: string, port: Port,
+ data: string): int {.tags: [WriteIOEffect].} =
## This proc sends ``data`` to the specified ``address``,
## which may be an IP address or a hostname, if a hostname is specified
## this function will try each IP of that hostname.
@@ -848,8 +848,8 @@ proc sendTo*(socket: PSocket, address: string, port: TPort,
## This is the high-level version of the above ``sendTo`` function.
result = socket.sendTo(address, port, cstring(data), data.len)
-proc connectAsync(socket: PSocket, name: string, port = TPort(0),
- af: TDomain = AF_INET) {.tags: [FReadIO].} =
+proc connectAsync(socket: Socket, name: string, port = Port(0),
+ af: Domain = AF_INET) {.tags: [ReadIOEffect].} =
## A variant of ``connect`` for non-blocking sockets.
##
## This procedure will immediatelly return, it will not block until a connection
@@ -861,7 +861,7 @@ proc connectAsync(socket: PSocket, name: string, port = TPort(0),
var aiList = getAddrInfo(name, port, af)
# try all possibilities:
var success = false
- var lastError: TOSErrorCode
+ var lastError: OSErrorCode
var it = aiList
while it != nil:
var ret = connect(socket.fd, it.ai_addr, it.ai_addrlen.TSocklen)
@@ -883,10 +883,10 @@ proc connectAsync(socket: PSocket, name: string, port = TPort(0),
it = it.ai_next
dealloc(aiList)
- if not success: osError(lastError)
+ if not success: raiseOSError(lastError)
-proc connect*(socket: PSocket, address: string, port = TPort(0), timeout: int,
- af: TDomain = AF_INET) {.tags: [FReadIO, FWriteIO].} =
+proc connect*(socket: Socket, address: string, port = Port(0), timeout: int,
+ af: Domain = AF_INET) {.tags: [ReadIOEffect, FWriteIO].} =
## Connects to server as specified by ``address`` on port specified by ``port``.
##
## The ``timeout`` paremeter specifies the time in miliseconds to allow for
@@ -896,7 +896,7 @@ proc connect*(socket: PSocket, address: string, port = TPort(0), timeout: int,
socket.connectAsync(address, port, af)
var s = @[socket.fd]
if selectWrite(s, timeout) != 1:
- raise newException(ETimeout, "Call to 'connect' timed out.")
+ raise newException(TimeoutError, "Call to 'connect' timed out.")
else:
when defined(ssl):
if socket.isSSL:
@@ -904,10 +904,10 @@ proc connect*(socket: PSocket, address: string, port = TPort(0), timeout: int,
doAssert socket.handshake()
socket.fd.setBlocking(true)
-proc isSSL*(socket: PSocket): bool = return socket.isSSL
+proc isSSL*(socket: Socket): bool = return socket.isSSL
## Determines whether ``socket`` is a SSL socket.
-proc getFD*(socket: PSocket): TSocketHandle = return socket.fd
+proc getFD*(socket: Socket): TSocketHandle = return socket.fd
## Returns the socket's file descriptor
type
@@ -1042,23 +1042,23 @@ proc parseIPv4Address(address_str: string): TIpAddress =
currentByte = currentByte * 10 +
cast[uint16](ord(address_str[i]) - ord('0'))
if currentByte > 255'u16:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Value is out of range")
seperatorValid = true
elif address_str[i] == '.': # IPv4 address separator
if not seperatorValid or byteCount >= 3:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v4[byteCount] = cast[uint8](currentByte)
currentByte = 0
byteCount.inc
seperatorValid = false
else:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if byteCount != 3 or not seperatorValid:
- raise newException(EInvalidValue, "Invalid IP Address")
+ raise newException(ValueError, "Invalid IP Address")
result.address_v4[byteCount] = cast[uint8](currentByte)
proc parseIPv6Address(address_str: string): TIpAddress =
@@ -1066,7 +1066,7 @@ proc parseIPv6Address(address_str: string): TIpAddress =
## Raises EInvalidValue on errors
result.family = IpAddressFamily.IPv6
if address_str.len < 2:
- raise newException(EInvalidValue, "Invalid IP Address")
+ raise newException(ValueError, "Invalid IP Address")
var
groupCount = 0
@@ -1081,17 +1081,17 @@ proc parseIPv6Address(address_str: string): TIpAddress =
for i,c in address_str:
if c == ':':
if not seperatorValid:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address contains an invalid seperator")
if lastWasColon:
if dualColonGroup != -1:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address contains more than one \"::\" seperator")
dualColonGroup = groupCount
seperatorValid = false
elif i != 0 and i != high(address_str):
if groupCount >= 8:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
@@ -1100,17 +1100,17 @@ proc parseIPv6Address(address_str: string): TIpAddress =
if dualColonGroup != -1: seperatorValid = false
elif i == 0: # only valid if address starts with ::
if address_str[1] != ':':
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address may not start with \":\"")
else: # i == high(address_str) - only valid if address ends with ::
if address_str[high(address_str)-1] != ':':
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address may not end with \":\"")
lastWasColon = true
currentGroupStart = i + 1
elif c == '.': # Switch to parse IPv4 mode
if i < 3 or not seperatorValid or groupCount >= 7:
- raise newException(EInvalidValue, "Invalid IP Address")
+ raise newException(ValueError, "Invalid IP Address")
v4StartPos = currentGroupStart
currentShort = 0
seperatorValid = false
@@ -1123,19 +1123,19 @@ proc parseIPv6Address(address_str: string): TIpAddress =
else: # Upper case hex
currentShort = (currentShort shl 4) + cast[uint32](ord(c) - ord('A')) + 10
if currentShort > 65535'u32:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Value is out of range")
lastWasColon = false
seperatorValid = true
else:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if v4StartPos == -1: # Don't parse v4. Copy the remaining v6 stuff
if seperatorValid: # Copy remaining data
if groupCount >= 8:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
result.address_v6[groupCount*2] = cast[uint8](currentShort shr 8)
result.address_v6[groupCount*2+1] = cast[uint8](currentShort and 0xFF)
@@ -1145,32 +1145,32 @@ proc parseIPv6Address(address_str: string): TIpAddress =
if c in strutils.Digits: # Character is a number
currentShort = currentShort * 10 + cast[uint32](ord(c) - ord('0'))
if currentShort > 255'u32:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Value is out of range")
seperatorValid = true
elif c == '.': # IPv4 address separator
if not seperatorValid or byteCount >= 3:
- raise newException(EInvalidValue, "Invalid IP Address")
+ raise newException(ValueError, "Invalid IP Address")
result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
currentShort = 0
byteCount.inc()
seperatorValid = false
else: # Invalid character
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. Address contains an invalid character")
if byteCount != 3 or not seperatorValid:
- raise newException(EInvalidValue, "Invalid IP Address")
+ raise newException(ValueError, "Invalid IP Address")
result.address_v6[groupCount*2 + byteCount] = cast[uint8](currentShort)
groupCount += 2
# Shift and fill zeros in case of ::
if groupCount > 8:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
elif groupCount < 8: # must fill
if dualColonGroup == -1:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too few groups")
var toFill = 8 - groupCount # The number of groups to fill
var toShift = groupCount - dualColonGroup # Nr of known groups after ::
@@ -1179,14 +1179,14 @@ proc parseIPv6Address(address_str: string): TIpAddress =
for i in 0..2*toFill-1: # fill with 0s
result.address_v6[dualColonGroup*2+i] = 0
elif dualColonGroup != -1:
- raise newException(EInvalidValue,
+ raise newException(ValueError,
"Invalid IP Address. The address consists of too many groups")
proc parseIpAddress*(address_str: string): TIpAddress =
## Parses an IP address
## Raises EInvalidValue on error
if address_str == nil:
- raise newException(EInvalidValue, "IP Address string is nil")
+ raise newException(ValueError, "IP Address string is nil")
if address_str.contains(':'):
return parseIPv6Address(address_str)
else:
diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim
index 14a494ecf..f3517fc3c 100644
--- a/lib/pure/rawsockets.nim
+++ b/lib/pure/rawsockets.nim
@@ -14,7 +14,7 @@
import unsigned, os
-when hostos == "solaris":
+when hostOS == "solaris":
{.passl: "-lsocket -lnsl".}
const useWinVersion = defined(Windows) or defined(nimdoc)
@@ -156,7 +156,7 @@ proc newRawSocket*(domain: Domain = AF_INET, typ: SockType = SOCK_STREAM,
proc close*(socket: SocketHandle) =
## closes a socket.
when useWinVersion:
- discard winlean.closeSocket(socket)
+ discard winlean.closesocket(socket)
else:
discard posix.close(socket)
# TODO: These values should not be discarded. An EOS should be raised.
@@ -165,7 +165,7 @@ proc close*(socket: SocketHandle) =
proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint =
result = bindSocket(socket, name, namelen)
-proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [FReadIO].} =
+proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [ReadIOEffect].} =
## Marks ``socket`` as accepting connections.
## ``Backlog`` specifies the maximum length of the
## queue of pending connections.
@@ -223,7 +223,7 @@ proc htons*(x: int16): int16 =
## order, this is a no-op; otherwise, it performs a 2-byte swap operation.
result = rawsockets.ntohs(x)
-proc getServByName*(name, proto: string): Servent {.tags: [FReadIO].} =
+proc getServByName*(name, proto: string): Servent {.tags: [ReadIOEffect].} =
## Searches the database from the beginning and finds the first entry for
## which the service name specified by ``name`` matches the s_name member
## and the protocol name specified by ``proto`` matches the s_proto member.
@@ -233,13 +233,13 @@ proc getServByName*(name, proto: string): Servent {.tags: [FReadIO].} =
var s = winlean.getservbyname(name, proto)
else:
var s = posix.getservbyname(name, proto)
- if s == nil: raise newException(EOS, "Service not found.")
+ if s == nil: raise newException(OSError, "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
result.port = Port(s.s_port)
result.proto = $s.s_proto
-proc getServByPort*(port: Port, proto: string): Servent {.tags: [FReadIO].} =
+proc getServByPort*(port: Port, proto: string): Servent {.tags: [ReadIOEffect].} =
## Searches the database from the beginning and finds the first entry for
## which the port specified by ``port`` matches the s_port member and the
## protocol name specified by ``proto`` matches the s_proto member.
@@ -249,13 +249,13 @@ proc getServByPort*(port: Port, proto: string): Servent {.tags: [FReadIO].} =
var s = winlean.getservbyport(ze(int16(port)).cint, proto)
else:
var s = posix.getservbyport(ze(int16(port)).cint, proto)
- if s == nil: raise newException(EOS, "Service not found.")
+ if s == nil: raise newException(OSError, "Service not found.")
result.name = $s.s_name
result.aliases = cstringArrayToSeq(s.s_aliases)
result.port = Port(s.s_port)
result.proto = $s.s_proto
-proc getHostByAddr*(ip: string): Hostent {.tags: [FReadIO].} =
+proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
## This function will lookup the hostname of an IP Address.
var myaddr: InAddr
myaddr.s_addr = inet_addr(ip)
@@ -284,7 +284,7 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [FReadIO].} =
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
-proc getHostByName*(name: string): Hostent {.tags: [FReadIO].} =
+proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
## This function will lookup the IP address of a hostname.
when useWinVersion:
var s = winlean.gethostbyname(name)
@@ -314,28 +314,28 @@ proc getSockName*(socket: SocketHandle): Port =
name.sin_family = posix.AF_INET
#name.sin_port = htons(cint16(port))
#name.sin_addr.s_addr = htonl(INADDR_ANY)
- var namelen = sizeof(name).Socklen
+ var namelen = sizeof(name).SockLen
if getsockname(socket, cast[ptr SockAddr](addr(name)),
addr(namelen)) == -1'i32:
raiseOSError(osLastError())
result = Port(rawsockets.ntohs(name.sin_port))
proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
- tags: [FReadIO].} =
+ tags: [ReadIOEffect].} =
## getsockopt for integer options.
var res: cint
- var size = sizeof(res).Socklen
+ var size = sizeof(res).SockLen
if getsockopt(socket, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
raiseOSError(osLastError())
result = int(res)
proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {.
- tags: [FWriteIO].} =
+ tags: [WriteIOEffect].} =
## setsockopt for integer options.
var value = cint(optval)
if setsockopt(socket, cint(level), cint(optname), addr(value),
- sizeof(value).Socklen) < 0'i32:
+ sizeof(value).SockLen) < 0'i32:
raiseOSError(osLastError())
proc setBlocking*(s: SocketHandle, blocking: bool) =
@@ -361,13 +361,13 @@ proc timeValFromMilliseconds(timeout = 500): Timeval =
result.tv_sec = seconds.int32
result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
-proc createFdSet(fd: var FdSet, s: seq[SocketHandle], m: var int) =
+proc createFdSet(fd: var FD_SET, s: seq[SocketHandle], m: var int) =
FD_ZERO(fd)
for i in items(s):
m = max(m, int(i))
FD_SET(i, fd)
-proc pruneSocketSet(s: var seq[SocketHandle], fd: var FdSet) =
+proc pruneSocketSet(s: var seq[SocketHandle], fd: var FD_SET) =
var i = 0
var L = s.len
while i < L:
@@ -386,7 +386,7 @@ proc select*(readfds: var seq[SocketHandle], timeout = 500): int =
##
## A socket is removed from the specific ``seq`` when it has data waiting to
## be read/written to or has errors (``exceptfds``).
- var tv {.noInit.}: Ttimeval = timeValFromMilliseconds(timeout)
+ var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
var rd: TFdSet
var m = 0
@@ -400,7 +400,7 @@ proc select*(readfds: var seq[SocketHandle], timeout = 500): int =
pruneSocketSet(readfds, (rd))
proc selectWrite*(writefds: var seq[SocketHandle],
- timeout = 500): int {.tags: [FReadIO].} =
+ timeout = 500): int {.tags: [ReadIOEffect].} =
## When a socket in ``writefds`` is ready to be written to then a non-zero
## value will be returned specifying the count of the sockets which can be
## written to. The sockets which can be written to will also be removed
diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim
index 55ae87a1f..53284cfdc 100644
--- a/lib/windows/winlean.nim
+++ b/lib/windows/winlean.nim
@@ -425,7 +425,7 @@ type
TFdSet* {.pure, final.} = object
fd_count*: cint # unsigned
- fd_array*: array[0..FD_SETSIZE-1, TSocketHandle]
+ fd_array*: array[0..FD_SETSIZE-1, SocketHandle]
TTimeval* {.pure, final.} = object
tv_sec*, tv_usec*: int32
@@ -444,7 +444,7 @@ type
var
SOMAXCONN* {.importc, header: "Winsock2.h".}: cint
- INVALID_SOCKET* {.importc, header: "Winsock2.h".}: TSocketHandle
+ INVALID_SOCKET* {.importc, header: "Winsock2.h".}: SocketHandle
SOL_SOCKET* {.importc, header: "Winsock2.h".}: cint
SO_DEBUG* {.importc, header: "Winsock2.h".}: cint ## turn on debugging info recording
SO_ACCEPTCONN* {.importc, header: "Winsock2.h".}: cint # socket has had listen()
@@ -460,7 +460,7 @@ var
SO_EXCLUSIVEADDRUSE* {.importc, header: "Winsock2.h".}: cint # disallow local address reuse
SO_ERROR* {.importc, header: "Winsock2.h".}: cint
-proc `==`*(x, y: TSocketHandle): bool {.borrow.}
+proc `==`*(x, y: SocketHandle): bool {.borrow.}
proc getservbyname*(name, proto: cstring): ptr TServent {.
stdcall, importc: "getservbyname", dynlib: ws2dll.}
@@ -474,45 +474,45 @@ proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr Thostent {.
proc gethostbyname*(name: cstring): ptr Thostent {.
stdcall, importc: "gethostbyname", dynlib: ws2dll.}
-proc socket*(af, typ, protocol: cint): TSocketHandle {.
+proc socket*(af, typ, protocol: cint): SocketHandle {.
stdcall, importc: "socket", dynlib: ws2dll.}
-proc closesocket*(s: TSocketHandle): cint {.
+proc closesocket*(s: SocketHandle): cint {.
stdcall, importc: "closesocket", dynlib: ws2dll.}
-proc accept*(s: TSocketHandle, a: ptr TSockAddr, addrlen: ptr TSockLen): TSocketHandle {.
+proc accept*(s: SocketHandle, a: ptr TSockAddr, addrlen: ptr TSockLen): SocketHandle {.
stdcall, importc: "accept", dynlib: ws2dll.}
-proc bindSocket*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
+proc bindSocket*(s: SocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
stdcall, importc: "bind", dynlib: ws2dll.}
-proc connect*(s: TSocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
+proc connect*(s: SocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
stdcall, importc: "connect", dynlib: ws2dll.}
-proc getsockname*(s: TSocketHandle, name: ptr TSockAddr,
+proc getsockname*(s: SocketHandle, name: ptr TSockAddr,
namelen: ptr TSockLen): cint {.
stdcall, importc: "getsockname", dynlib: ws2dll.}
-proc getsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer,
+proc getsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
optlen: ptr TSockLen): cint {.
stdcall, importc: "getsockopt", dynlib: ws2dll.}
-proc setsockopt*(s: TSocketHandle, level, optname: cint, optval: pointer,
+proc setsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
optlen: TSockLen): cint {.
stdcall, importc: "setsockopt", dynlib: ws2dll.}
-proc listen*(s: TSocketHandle, backlog: cint): cint {.
+proc listen*(s: SocketHandle, backlog: cint): cint {.
stdcall, importc: "listen", dynlib: ws2dll.}
-proc recv*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {.
+proc recv*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "recv", dynlib: ws2dll.}
-proc recvfrom*(s: TSocketHandle, buf: cstring, len, flags: cint,
+proc recvfrom*(s: SocketHandle, buf: cstring, len, flags: cint,
fromm: ptr TSockAddr, fromlen: ptr TSockLen): cint {.
stdcall, importc: "recvfrom", dynlib: ws2dll.}
proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet,
timeout: ptr TTimeval): cint {.
stdcall, importc: "select", dynlib: ws2dll.}
-proc send*(s: TSocketHandle, buf: pointer, len, flags: cint): cint {.
+proc send*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "send", dynlib: ws2dll.}
-proc sendto*(s: TSocketHandle, buf: pointer, len, flags: cint,
+proc sendto*(s: SocketHandle, buf: pointer, len, flags: cint,
to: ptr TSockAddr, tolen: TSockLen): cint {.
stdcall, importc: "sendto", dynlib: ws2dll.}
-proc shutdown*(s: TSocketHandle, how: cint): cint {.
+proc shutdown*(s: SocketHandle, how: cint): cint {.
stdcall, importc: "shutdown", dynlib: ws2dll.}
proc getnameinfo*(a1: ptr TSockAddr, a2: TSockLen,
@@ -523,13 +523,13 @@ proc getnameinfo*(a1: ptr TSockAddr, a2: TSockLen,
proc inet_addr*(cp: cstring): int32 {.
stdcall, importc: "inet_addr", dynlib: ws2dll.}
-proc WSAFDIsSet(s: TSocketHandle, FDSet: var TFdSet): bool {.
+proc WSAFDIsSet(s: SocketHandle, FDSet: var TFdSet): bool {.
stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll, noSideEffect.}
-proc FD_ISSET*(Socket: TSocketHandle, FDSet: var TFdSet): cint =
+proc FD_ISSET*(Socket: SocketHandle, FDSet: var TFdSet): cint =
result = if WSAFDIsSet(Socket, FDSet): 1'i32 else: 0'i32
-proc FD_SET*(Socket: TSocketHandle, FDSet: var TFdSet) =
+proc FD_SET*(Socket: SocketHandle, FDSet: var TFdSet) =
if FDSet.fd_count < FD_SETSIZE:
FDSet.fd_array[int(FDSet.fd_count)] = Socket
inc(FDSet.fd_count)
@@ -699,7 +699,7 @@ var
WSAID_GETACCEPTEXSOCKADDRS*: TGUID = TGUID(D1: 0xb5367df2'i32, D2: 0xcbac'i16, D3: 0x11cf, D4: [
0x95'i8, 0xca'i8, 0x00'i8, 0x80'i8, 0x5f'i8, 0x48'i8, 0xa1'i8, 0x92'i8])
-proc WSAIoctl*(s: TSocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
+proc WSAIoctl*(s: SocketHandle, dwIoControlCode: DWORD, lpvInBuffer: pointer,
cbInBuffer: DWORD, lpvOutBuffer: pointer, cbOutBuffer: DWORD,
lpcbBytesReturned: PDWORD, lpOverlapped: POVERLAPPED,
lpCompletionRoutine: POVERLAPPED_COMPLETION_ROUTINE): cint
@@ -710,12 +710,12 @@ type
len*: ULONG
buf*: cstring
-proc WSARecv*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
+proc WSARecv*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
bytesReceived, flags: PDWORD, lpOverlapped: POVERLAPPED,
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
stdcall, importc: "WSARecv", dynlib: "Ws2_32.dll".}
-proc WSASend*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
+proc WSASend*(s: SocketHandle, buf: ptr TWSABuf, bufCount: DWORD,
bytesSent: PDWORD, flags: DWORD, lpOverlapped: POVERLAPPED,
completionProc: POVERLAPPED_COMPLETION_ROUTINE): cint {.
stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".}
From fc5153e9b0d9d6236e4c1dda145f68049163d0c3 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 00:37:15 +0200
Subject: [PATCH 014/409] big rename
---
lib/pure/collections/sets.nim | 24 ++++++++++++------------
lib/pure/net.nim | 6 +++---
2 files changed, 15 insertions(+), 15 deletions(-)
diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim
index 994023b3f..4a5471417 100644
--- a/lib/pure/collections/sets.nim
+++ b/lib/pure/collections/sets.nim
@@ -188,7 +188,7 @@ proc incl*[A](s: var HashSet[A], key: A) =
assert s.isValid, "The set needs to be initialized."
inclImpl()
-proc incl*[A](s: var HashSet[A], other: TSet[A]) =
+proc incl*[A](s: var HashSet[A], other: HashSet[A]) =
## Includes all elements from `other` into `s`.
##
## Example:
@@ -219,7 +219,7 @@ proc excl*[A](s: var HashSet[A], key: A) =
s.data[index].slot = seDeleted
dec(s.counter)
-proc excl*[A](s: var HashSet[A], other: TSet[A]) =
+proc excl*[A](s: var HashSet[A], other: HashSet[A]) =
## Excludes everything in `other` from `s`.
##
## Example:
@@ -320,7 +320,7 @@ proc `$`*[A](s: HashSet[A]): string =
assert s.isValid, "The set needs to be initialized."
dollarImpl()
-proc union*[A](s1, s2: HashSet[A]): TSet[A] =
+proc union*[A](s1, s2: HashSet[A]): HashSet[A] =
## Returns the union of the sets `s1` and `s2`.
##
## The union of two sets is represented mathematically as *A ∪ B* and is the
@@ -337,7 +337,7 @@ proc union*[A](s1, s2: HashSet[A]): TSet[A] =
result = s1
incl(result, s2)
-proc intersection*[A](s1, s2: HashSet[A]): TSet[A] =
+proc intersection*[A](s1, s2: HashSet[A]): HashSet[A] =
## Returns the intersection of the sets `s1` and `s2`.
##
## The intersection of two sets is represented mathematically as *A ∩ B* and
@@ -356,7 +356,7 @@ proc intersection*[A](s1, s2: HashSet[A]): TSet[A] =
for item in s1:
if item in s2: incl(result, item)
-proc difference*[A](s1, s2: HashSet[A]): TSet[A] =
+proc difference*[A](s1, s2: HashSet[A]): HashSet[A] =
## Returns the difference of the sets `s1` and `s2`.
##
## The difference of two sets is represented mathematically as *A \ B* and is
@@ -376,7 +376,7 @@ proc difference*[A](s1, s2: HashSet[A]): TSet[A] =
if not contains(s2, item):
incl(result, item)
-proc symmetricDifference*[A](s1, s2: HashSet[A]): TSet[A] =
+proc symmetricDifference*[A](s1, s2: HashSet[A]): HashSet[A] =
## Returns the symmetric difference of the sets `s1` and `s2`.
##
## The symmetric difference of two sets is represented mathematically as *A â–³
@@ -395,19 +395,19 @@ proc symmetricDifference*[A](s1, s2: HashSet[A]): TSet[A] =
for item in s2:
if containsOrIncl(result, item): excl(result, item)
-proc `+`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
+proc `+`*[A](s1, s2: HashSet[A]): HashSet[A] {.inline.} =
## Alias for `union(s1, s2) <#union>`_.
result = union(s1, s2)
-proc `*`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
+proc `*`*[A](s1, s2: HashSet[A]): HashSet[A] {.inline.} =
## Alias for `intersection(s1, s2) <#intersection>`_.
result = intersection(s1, s2)
-proc `-`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
+proc `-`*[A](s1, s2: HashSet[A]): HashSet[A] {.inline.} =
## Alias for `difference(s1, s2) <#difference>`_.
result = difference(s1, s2)
-proc `-+-`*[A](s1, s2: HashSet[A]): TSet[A] {.inline.} =
+proc `-+-`*[A](s1, s2: HashSet[A]): HashSet[A] {.inline.} =
## Alias for `symmetricDifference(s1, s2) <#symmetricDifference>`_.
result = symmetricDifference(s1, s2)
@@ -477,7 +477,7 @@ proc `==`*[A](s, t: HashSet[A]): bool =
## assert a == b
s.counter == t.counter and s <= t
-proc map*[A, B](data: HashSet[A], op: proc (x: A): B {.closure.}): TSet[B] =
+proc map*[A, B](data: HashSet[A], op: proc (x: A): B {.closure.}): HashSet[B] =
## Returns a new set after applying `op` on each of the elements of `data`.
##
## You can use this proc to transform the elements from a set. Example:
@@ -621,7 +621,7 @@ proc incl*[A](s: var OrderedSet[A], key: A) =
assert s.isValid, "The set needs to be initialized."
inclImpl()
-proc incl*[A](s: var HashSet[A], other: TOrderedSet[A]) =
+proc incl*[A](s: var HashSet[A], other: OrderedSet[A]) =
## Includes all elements from `other` into `s`.
##
## Example:
diff --git a/lib/pure/net.nim b/lib/pure/net.nim
index a64294a77..ff3c1e683 100644
--- a/lib/pure/net.nim
+++ b/lib/pure/net.nim
@@ -625,7 +625,7 @@ proc waitFor(socket: Socket, waited: var float, timeout, size: int,
waited += (epochTime() - startTime)
proc recv*(socket: Socket, data: pointer, size: int, timeout: int): int {.
- tags: [ReadIOEffect, FTime].} =
+ tags: [ReadIOEffect, TimeEffect].} =
## overload with a ``timeout`` parameter in miliseconds.
var waited = 0.0 # number of seconds already waited
@@ -688,7 +688,7 @@ proc peekChar(socket: Socket, c: var char): int {.tags: [ReadIOEffect].} =
proc readLine*(socket: Socket, line: var TaintedString, timeout = -1,
flags = {SocketFlag.SafeDisconn}) {.
- tags: [ReadIOEffect, FTime].} =
+ tags: [ReadIOEffect, TimeEffect].} =
## Reads a line of data from ``socket``.
##
## If a full line is read ``\r\L`` is not
@@ -886,7 +886,7 @@ proc connectAsync(socket: Socket, name: string, port = Port(0),
if not success: raiseOSError(lastError)
proc connect*(socket: Socket, address: string, port = Port(0), timeout: int,
- af: Domain = AF_INET) {.tags: [ReadIOEffect, FWriteIO].} =
+ af: Domain = AF_INET) {.tags: [ReadIOEffect, WriteIOEffect].} =
## Connects to server as specified by ``address`` on port specified by ``port``.
##
## The ``timeout`` paremeter specifies the time in miliseconds to allow for
From dcffbb052a88bebf3acfc1b5410a9737f2aa7719 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 01:17:21 +0200
Subject: [PATCH 015/409] big rename
---
lib/posix/posix.nim | 157 +++++++++++++++++++++-------------------
lib/pure/os.nim | 2 +-
lib/pure/rawsockets.nim | 34 ++++-----
lib/pure/uri.nim | 2 +-
lib/windows/winlean.nim | 109 +++++++++++++++-------------
5 files changed, 158 insertions(+), 146 deletions(-)
diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim
index 43139389b..d8f329e34 100644
--- a/lib/posix/posix.nim
+++ b/lib/posix/posix.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -384,12 +384,12 @@ type
sched_ss_max_repl*: cint ## Maximum pending replenishments for
## sporadic server.
- Ttimeval* {.importc: "struct timeval", header: "",
- final, pure.} = object ## struct timeval
+ Timeval* {.importc: "struct timeval", header: "",
+ final, pure.} = object ## struct timeval
tv_sec*: int ## Seconds.
tv_usec*: int ## Microseconds.
- TFdSet* {.importc: "fd_set", header: "",
- final, pure.} = object
+ FdSet* {.importc: "fd_set", header: "",
+ final, pure.} = object
Tmcontext* {.importc: "mcontext_t", header: "",
final, pure.} = object
Tucontext* {.importc: "ucontext_t", header: "",
@@ -422,11 +422,11 @@ when hasSpawnH:
header: "", final, pure.} = object
type
- TSocklen* {.importc: "socklen_t", header: "".} = cuint
+ Socklen* {.importc: "socklen_t", header: "".} = cuint
TSa_Family* {.importc: "sa_family_t", header: "".} = cint
- TSockAddr* {.importc: "struct sockaddr", header: "",
- pure, final.} = object ## struct sockaddr
+ SockAddr* {.importc: "struct sockaddr", header: "",
+ pure, final.} = object ## struct sockaddr
sa_family*: TSa_Family ## Address family.
sa_data*: array [0..255, char] ## Socket address (variable-length data).
@@ -474,15 +474,15 @@ type
TInAddrT* {.importc: "in_addr_t", pure, final,
header: "".} = int32 ## unsigned!
- TInAddr* {.importc: "struct in_addr", pure, final,
+ InAddr* {.importc: "struct in_addr", pure, final,
header: "".} = object ## struct in_addr
s_addr*: TInAddrScalar
- Tsockaddr_in* {.importc: "struct sockaddr_in", pure, final,
+ Sockaddr_in* {.importc: "struct sockaddr_in", pure, final,
header: "".} = object ## struct sockaddr_in
sin_family*: TSa_Family ## AF_INET.
sin_port*: TInPort ## Port number.
- sin_addr*: TInAddr ## IP address.
+ sin_addr*: InAddr ## IP address.
TIn6Addr* {.importc: "struct in6_addr", pure, final,
header: "".} = object ## struct in6_addr
@@ -501,7 +501,7 @@ type
ipv6mr_multiaddr*: TIn6Addr ## IPv6 multicast address.
ipv6mr_interface*: cint ## Interface index.
- Thostent* {.importc: "struct hostent", pure, final,
+ Hostent* {.importc: "struct hostent", pure, final,
header: "".} = object ## struct hostent
h_name*: cstring ## Official name of the host.
h_aliases*: cstringArray ## A pointer to an array of pointers to
@@ -531,8 +531,8 @@ type
## a null pointer.
p_proto*: cint ## The protocol number.
- TServent* {.importc: "struct servent", pure, final,
- header: "".} = object ## struct servent
+ Servent* {.importc: "struct servent", pure, final,
+ header: "".} = object ## struct servent
s_name*: cstring ## Official name of the service.
s_aliases*: cstringArray ## A pointer to an array of pointers to
## alternative service names, terminated by
@@ -542,16 +542,16 @@ type
s_proto*: cstring ## The name of the protocol to use when
## contacting the service.
- Taddrinfo* {.importc: "struct addrinfo", pure, final,
+ AddrInfo* {.importc: "struct addrinfo", pure, final,
header: "".} = object ## struct addrinfo
ai_flags*: cint ## Input flags.
ai_family*: cint ## Address family of socket.
ai_socktype*: cint ## Socket type.
ai_protocol*: cint ## Protocol of socket.
- ai_addrlen*: TSocklen ## Length of socket address.
- ai_addr*: ptr TSockAddr ## Socket address of socket.
+ ai_addrlen*: Socklen ## Length of socket address.
+ ai_addr*: ptr SockAddr ## Socket address of socket.
ai_canonname*: cstring ## Canonical name of service location.
- ai_next*: ptr Taddrinfo ## Pointer to next in list.
+ ai_next*: ptr AddrInfo ## Pointer to next in list.
TPollfd* {.importc: "struct pollfd", pure, final,
header: "".} = object ## struct pollfd
@@ -561,6 +561,11 @@ type
Tnfds* {.importc: "nfds_t", header: "".} = cint
+{.deprecated: [TSockaddr_in: Sockaddr_in, TAddrinfo: AddrInfo,
+ TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval,
+ TFdSet: FdSet, Thostent: Hostent, TServent: Servent,
+ TInAddr: InAddr, Tin6_addr: In6_addr, Tsockaddr_in6: Sockaddr_in6].}
+
var
errno* {.importc, header: "".}: cint ## error variable
h_errno* {.importc, header: "".}: cint
@@ -1787,18 +1792,18 @@ proc ntohl*(a1: int32): int32 {.importc, header: "".}
proc ntohs*(a1: int16): int16 {.importc, header: "".}
proc inet_addr*(a1: cstring): TInAddrT {.importc, header: "".}
-proc inet_ntoa*(a1: TInAddr): cstring {.importc, header: "".}
+proc inet_ntoa*(a1: InAddr): cstring {.importc, header: "".}
proc inet_ntop*(a1: cint, a2: pointer, a3: cstring, a4: int32): cstring {.
importc, header: "".}
proc inet_pton*(a1: cint, a2: cstring, a3: pointer): cint {.
importc, header: "".}
var
- in6addr_any* {.importc, header: "".}: TIn6Addr
- in6addr_loopback* {.importc, header: "".}: TIn6Addr
+ in6addr_any* {.importc, header: "".}: In6_addr
+ in6addr_loopback* {.importc, header: "".}: In6_addr
-proc IN6ADDR_ANY_INIT* (): TIn6Addr {.importc, header: "".}
-proc IN6ADDR_LOOPBACK_INIT* (): TIn6Addr {.importc, header: "".}
+proc IN6ADDR_ANY_INIT* (): In6_addr {.importc, header: "".}
+proc IN6ADDR_LOOPBACK_INIT* (): In6_addr {.importc, header: "".}
# dirent.h
proc closedir*(a1: ptr TDIR): cint {.importc, header: "".}
@@ -1817,7 +1822,7 @@ proc dlopen*(a1: cstring, a2: cint): pointer {.importc, header: "".}
proc dlsym*(a1: pointer, a2: cstring): pointer {.importc, header: "".}
proc creat*(a1: cstring, a2: TMode): cint {.importc, header: "".}
-proc fcntl*(a1: cint | TSocketHandle, a2: cint): cint {.varargs, importc, header: "".}
+proc fcntl*(a1: cint | SocketHandle, a2: cint): cint {.varargs, importc, header: "".}
proc open*(a1: cstring, a2: cint): cint {.varargs, importc, header: "".}
proc posix_fadvise*(a1: cint, a2, a3: TOff, a4: cint): cint {.
importc, header: "".}
@@ -2095,7 +2100,7 @@ proc access*(a1: cstring, a2: cint): cint {.importc, header: "".}
proc alarm*(a1: cint): cint {.importc, header: "".}
proc chdir*(a1: cstring): cint {.importc, header: "".}
proc chown*(a1: cstring, a2: Tuid, a3: TGid): cint {.importc, header: "".}
-proc close*(a1: cint | TSocketHandle): cint {.importc, header: "".}
+proc close*(a1: cint | SocketHandle): cint {.importc, header: "".}
proc confstr*(a1: cint, a2: cstring, a3: int): int {.importc, header: "".}
proc crypt*(a1, a2: cstring): cstring {.importc, header: "".}
proc ctermid*(a1: cstring): cstring {.importc, header: "".}
@@ -2374,15 +2379,15 @@ proc sched_yield*(): cint {.importc, header: "".}
proc strerror*(errnum: cint): cstring {.importc, header: "".}
proc hstrerror*(herrnum: cint): cstring {.importc, header: "".}
-proc FD_CLR*(a1: cint, a2: var TFdSet) {.importc, header: "".}
-proc FD_ISSET*(a1: cint | TSocketHandle, a2: var TFdSet): cint {.
+proc FD_CLR*(a1: cint, a2: var FdSet) {.importc, header: "".}
+proc FD_ISSET*(a1: cint | SocketHandle, a2: var FdSet): cint {.
importc, header: "".}
-proc FD_SET*(a1: cint | TSocketHandle, a2: var TFdSet) {.importc, header: "".}
-proc FD_ZERO*(a1: var TFdSet) {.importc, header: "".}
+proc fdSet*(a1: cint | SocketHandle, a2: var FdSet) {.importc, header: "".}
+proc FD_ZERO*(a1: var FdSet) {.importc, header: "".}
-proc pselect*(a1: cint, a2, a3, a4: ptr TFdSet, a5: ptr Ttimespec,
+proc pselect*(a1: cint, a2, a3, a4: ptr FdSet, a5: ptr Ttimespec,
a6: var Tsigset): cint {.importc, header: "".}
-proc select*(a1: cint | TSocketHandle, a2, a3, a4: ptr TFdSet, a5: ptr Ttimeval): cint {.
+proc select*(a1: cint | SocketHandle, a2, a3, a4: ptr FdSet, a5: ptr Timeval): cint {.
importc, header: "".}
when hasSpawnH:
@@ -2458,48 +2463,48 @@ proc CMSG_FIRSTHDR*(mhdr: ptr Tmsghdr): ptr Tcmsghdr {.
importc, header: "".}
const
- INVALID_SOCKET* = TSocketHandle(-1)
+ INVALID_SOCKET* = SocketHandle(-1)
-proc `==`*(x, y: TSocketHandle): bool {.borrow.}
+proc `==`*(x, y: SocketHandle): bool {.borrow.}
-proc accept*(a1: TSocketHandle, a2: ptr TSockAddr, a3: ptr TSocklen): TSocketHandle {.
+proc accept*(a1: SocketHandle, a2: ptr SockAddr, a3: ptr Socklen): SocketHandle {.
importc, header: "".}
-proc bindSocket*(a1: TSocketHandle, a2: ptr TSockAddr, a3: TSocklen): cint {.
+proc bindSocket*(a1: SocketHandle, a2: ptr SockAddr, a3: Socklen): cint {.
importc: "bind", header: "".}
## is Posix's ``bind``, because ``bind`` is a reserved word
-proc connect*(a1: TSocketHandle, a2: ptr TSockAddr, a3: TSocklen): cint {.
+proc connect*(a1: SocketHandle, a2: ptr SockAddr, a3: Socklen): cint {.
importc, header: "".}
-proc getpeername*(a1: TSocketHandle, a2: ptr TSockAddr, a3: ptr TSocklen): cint {.
+proc getpeername*(a1: SocketHandle, a2: ptr SockAddr, a3: ptr Socklen): cint {.
importc, header: "".}
-proc getsockname*(a1: TSocketHandle, a2: ptr TSockAddr, a3: ptr TSocklen): cint {.
+proc getsockname*(a1: SocketHandle, a2: ptr SockAddr, a3: ptr Socklen): cint {.
importc, header: "".}
-proc getsockopt*(a1: TSocketHandle, a2, a3: cint, a4: pointer, a5: ptr TSocklen): cint {.
+proc getsockopt*(a1: SocketHandle, a2, a3: cint, a4: pointer, a5: ptr Socklen): cint {.
importc, header: "".}
-proc listen*(a1: TSocketHandle, a2: cint): cint {.
+proc listen*(a1: SocketHandle, a2: cint): cint {.
importc, header: "".}
-proc recv*(a1: TSocketHandle, a2: pointer, a3: int, a4: cint): int {.
+proc recv*(a1: SocketHandle, a2: pointer, a3: int, a4: cint): int {.
importc, header: "".}
-proc recvfrom*(a1: TSocketHandle, a2: pointer, a3: int, a4: cint,
- a5: ptr TSockAddr, a6: ptr TSocklen): int {.
+proc recvfrom*(a1: SocketHandle, a2: pointer, a3: int, a4: cint,
+ a5: ptr SockAddr, a6: ptr Socklen): int {.
importc, header: "".}
-proc recvmsg*(a1: TSocketHandle, a2: ptr Tmsghdr, a3: cint): int {.
+proc recvmsg*(a1: SocketHandle, a2: ptr Tmsghdr, a3: cint): int {.
importc, header: "".}
-proc send*(a1: TSocketHandle, a2: pointer, a3: int, a4: cint): int {.
+proc send*(a1: SocketHandle, a2: pointer, a3: int, a4: cint): int {.
importc, header: "".}
-proc sendmsg*(a1: TSocketHandle, a2: ptr Tmsghdr, a3: cint): int {.
+proc sendmsg*(a1: SocketHandle, a2: ptr Tmsghdr, a3: cint): int {.
importc, header: "".}
-proc sendto*(a1: TSocketHandle, a2: pointer, a3: int, a4: cint, a5: ptr TSockAddr,
- a6: TSocklen): int {.
+proc sendto*(a1: SocketHandle, a2: pointer, a3: int, a4: cint, a5: ptr SockAddr,
+ a6: Socklen): int {.
importc, header: "".}
-proc setsockopt*(a1: TSocketHandle, a2, a3: cint, a4: pointer, a5: TSocklen): cint {.
+proc setsockopt*(a1: SocketHandle, a2, a3: cint, a4: pointer, a5: Socklen): cint {.
importc, header: "".}
-proc shutdown*(a1: TSocketHandle, a2: cint): cint {.
+proc shutdown*(a1: SocketHandle, a2: cint): cint {.
importc, header: "".}
-proc socket*(a1, a2, a3: cint): TSocketHandle {.
+proc socket*(a1, a2, a3: cint): SocketHandle {.
importc, header: "".}
proc sockatmark*(a1: cint): cint {.
importc, header: "".}
@@ -2512,40 +2517,40 @@ proc if_indextoname*(a1: cint, a2: cstring): cstring {.
proc if_nameindex*(): ptr Tif_nameindex {.importc, header: "".}
proc if_freenameindex*(a1: ptr Tif_nameindex) {.importc, header: "".}
-proc IN6_IS_ADDR_UNSPECIFIED* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_UNSPECIFIED* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Unspecified address.
-proc IN6_IS_ADDR_LOOPBACK* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_LOOPBACK* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Loopback address.
-proc IN6_IS_ADDR_MULTICAST* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MULTICAST* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast address.
-proc IN6_IS_ADDR_LINKLOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_LINKLOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Unicast link-local address.
-proc IN6_IS_ADDR_SITELOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_SITELOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Unicast site-local address.
-proc IN6_IS_ADDR_V4MAPPED* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_V4MAPPED* (a1: ptr In6_addr): cint {.
importc, header: "".}
## IPv4 mapped address.
-proc IN6_IS_ADDR_V4COMPAT* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_V4COMPAT* (a1: ptr In6_addr): cint {.
importc, header: "".}
## IPv4-compatible address.
-proc IN6_IS_ADDR_MC_NODELOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MC_NODELOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast node-local address.
-proc IN6_IS_ADDR_MC_LINKLOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MC_LINKLOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast link-local address.
-proc IN6_IS_ADDR_MC_SITELOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MC_SITELOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast site-local address.
-proc IN6_IS_ADDR_MC_ORGLOCAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MC_ORGLOCAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast organization-local address.
-proc IN6_IS_ADDR_MC_GLOBAL* (a1: ptr TIn6Addr): cint {.
+proc IN6_IS_ADDR_MC_GLOBAL* (a1: ptr In6_addr): cint {.
importc, header: "".}
## Multicast global address.
@@ -2553,21 +2558,21 @@ proc endhostent*() {.importc, header: "".}
proc endnetent*() {.importc, header: "".}
proc endprotoent*() {.importc, header: "".}
proc endservent*() {.importc, header: "".}
-proc freeaddrinfo*(a1: ptr Taddrinfo) {.importc, header: "".}
+proc freeaddrinfo*(a1: ptr AddrInfo) {.importc, header: "".}
proc gai_strerror*(a1: cint): cstring {.importc, header: "".}
-proc getaddrinfo*(a1, a2: cstring, a3: ptr Taddrinfo,
- a4: var ptr Taddrinfo): cint {.importc, header: "".}
+proc getaddrinfo*(a1, a2: cstring, a3: ptr AddrInfo,
+ a4: var ptr AddrInfo): cint {.importc, header: "".}
-proc gethostbyaddr*(a1: pointer, a2: TSocklen, a3: cint): ptr Thostent {.
+proc gethostbyaddr*(a1: pointer, a2: Socklen, a3: cint): ptr Hostent {.
importc, header: "".}
-proc gethostbyname*(a1: cstring): ptr Thostent {.importc, header: "".}
-proc gethostent*(): ptr Thostent {.importc, header: "".}
+proc gethostbyname*(a1: cstring): ptr Hostent {.importc, header: "".}
+proc gethostent*(): ptr Hostent {.importc, header: "".}
-proc getnameinfo*(a1: ptr TSockAddr, a2: TSocklen,
- a3: cstring, a4: TSocklen, a5: cstring,
- a6: TSocklen, a7: cint): cint {.importc, header: "".}
+proc getnameinfo*(a1: ptr SockAddr, a2: Socklen,
+ a3: cstring, a4: Socklen, a5: cstring,
+ a6: Socklen, a7: cint): cint {.importc, header: "".}
proc getnetbyaddr*(a1: int32, a2: cint): ptr Tnetent {.importc, header: "".}
proc getnetbyname*(a1: cstring): ptr Tnetent {.importc, header: "".}
@@ -2577,10 +2582,10 @@ proc getprotobyname*(a1: cstring): ptr TProtoent {.importc, header: "".
proc getprotobynumber*(a1: cint): ptr TProtoent {.importc, header: "".}
proc getprotoent*(): ptr TProtoent {.importc, header: "".}
-proc getservbyname*(a1, a2: cstring): ptr TServent {.importc, header: "".}
-proc getservbyport*(a1: cint, a2: cstring): ptr TServent {.
+proc getservbyname*(a1, a2: cstring): ptr Servent {.importc, header: "".}
+proc getservbyport*(a1: cint, a2: cstring): ptr Servent {.
importc, header: "".}
-proc getservent*(): ptr TServent {.importc, header: "".}
+proc getservent*(): ptr Servent {.importc, header: "".}
proc sethostent*(a1: cint) {.importc, header: "".}
proc setnetent*(a1: cint) {.importc, header: "".}
@@ -2593,7 +2598,7 @@ proc poll*(a1: ptr TPollfd, a2: Tnfds, a3: int): cint {.
proc realpath*(name, resolved: cstring): cstring {.
importc: "realpath", header: "".}
-proc utimes*(path: cstring, times: ptr array [2, Ttimeval]): int {.
+proc utimes*(path: cstring, times: ptr array [2, Timeval]): int {.
importc: "utimes", header: "".}
## Sets file access and modification times.
##
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index 76100deba..d348497a9 100644
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -1814,7 +1814,7 @@ proc sleep*(milsecs: int) {.rtl, extern: "nos$1", tags: [TimeEffect].} =
winlean.sleep(int32(milsecs))
else:
var a, b: Ttimespec
- a.tv_sec = TTime(milsecs div 1000)
+ a.tv_sec = Time(milsecs div 1000)
a.tv_nsec = (milsecs mod 1000) * 1000 * 1000
discard posix.nanosleep(a, b)
diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim
index f3517fc3c..45634c4ec 100644
--- a/lib/pure/rawsockets.nim
+++ b/lib/pure/rawsockets.nim
@@ -162,7 +162,7 @@ proc close*(socket: SocketHandle) =
# TODO: These values should not be discarded. An EOS should be raised.
# http://stackoverflow.com/questions/12463473/what-happens-if-you-call-close-on-a-bsd-socket-multiple-times
-proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint =
+proc bindAddr*(socket: SocketHandle, name: ptr SockAddr, namelen: Socklen): cint =
result = bindSocket(socket, name, namelen)
proc listen*(socket: SocketHandle, backlog = SOMAXCONN): cint {.tags: [ReadIOEffect].} =
@@ -184,12 +184,12 @@ proc getAddrInfo*(address: string, port: Port, af: Domain = AF_INET, typ: SockTy
hints.ai_family = toInt(af)
hints.ai_socktype = toInt(typ)
hints.ai_protocol = toInt(prot)
- var gaiResult = getAddrInfo(address, $port, addr(hints), result)
+ var gaiResult = getaddrinfo(address, $port, addr(hints), result)
if gaiResult != 0'i32:
when useWinVersion:
raiseOSError(osLastError())
else:
- raise newException(EOS, $gai_strerror(gaiResult))
+ raise newException(OSError, $gai_strerror(gaiResult))
proc dealloc*(ai: ptr AddrInfo) =
freeaddrinfo(ai)
@@ -268,7 +268,7 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
var s = posix.gethostbyaddr(addr(myaddr), sizeof(myaddr).Socklen,
cint(posix.AF_INET))
if s == nil:
- raise newException(EOS, $hstrerror(h_errno))
+ raise newException(OSError, $hstrerror(h_errno))
result.name = $s.h_name
result.aliases = cstringArrayToSeq(s.h_aliases)
@@ -280,7 +280,7 @@ proc getHostByAddr*(ip: string): Hostent {.tags: [ReadIOEffect].} =
elif s.h_addrtype == posix.AF_INET6:
result.addrtype = AF_INET6
else:
- raise newException(EOS, "unknown h_addrtype")
+ raise newException(OSError, "unknown h_addrtype")
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
@@ -301,7 +301,7 @@ proc getHostByName*(name: string): Hostent {.tags: [ReadIOEffect].} =
elif s.h_addrtype == posix.AF_INET6:
result.addrtype = AF_INET6
else:
- raise newException(EOS, "unknown h_addrtype")
+ raise newException(OSError, "unknown h_addrtype")
result.addrList = cstringArrayToSeq(s.h_addr_list)
result.length = int(s.h_length)
@@ -314,7 +314,7 @@ proc getSockName*(socket: SocketHandle): Port =
name.sin_family = posix.AF_INET
#name.sin_port = htons(cint16(port))
#name.sin_addr.s_addr = htonl(INADDR_ANY)
- var namelen = sizeof(name).SockLen
+ var namelen = sizeof(name).Socklen
if getsockname(socket, cast[ptr SockAddr](addr(name)),
addr(namelen)) == -1'i32:
raiseOSError(osLastError())
@@ -324,7 +324,7 @@ proc getSockOptInt*(socket: SocketHandle, level, optname: int): int {.
tags: [ReadIOEffect].} =
## getsockopt for integer options.
var res: cint
- var size = sizeof(res).SockLen
+ var size = sizeof(res).Socklen
if getsockopt(socket, cint(level), cint(optname),
addr(res), addr(size)) < 0'i32:
raiseOSError(osLastError())
@@ -335,7 +335,7 @@ proc setSockOptInt*(socket: SocketHandle, level, optname, optval: int) {.
## setsockopt for integer options.
var value = cint(optval)
if setsockopt(socket, cint(level), cint(optname), addr(value),
- sizeof(value).SockLen) < 0'i32:
+ sizeof(value).Socklen) < 0'i32:
raiseOSError(osLastError())
proc setBlocking*(s: SocketHandle, blocking: bool) =
@@ -361,13 +361,13 @@ proc timeValFromMilliseconds(timeout = 500): Timeval =
result.tv_sec = seconds.int32
result.tv_usec = ((timeout - seconds * 1000) * 1000).int32
-proc createFdSet(fd: var FD_SET, s: seq[SocketHandle], m: var int) =
+proc createFdSet(fd: var FdSet, s: seq[SocketHandle], m: var int) =
FD_ZERO(fd)
for i in items(s):
m = max(m, int(i))
- FD_SET(i, fd)
+ fdSet(i, fd)
-proc pruneSocketSet(s: var seq[SocketHandle], fd: var FD_SET) =
+proc pruneSocketSet(s: var seq[SocketHandle], fd: var FdSet) =
var i = 0
var L = s.len
while i < L:
@@ -386,9 +386,9 @@ proc select*(readfds: var seq[SocketHandle], timeout = 500): int =
##
## A socket is removed from the specific ``seq`` when it has data waiting to
## be read/written to or has errors (``exceptfds``).
- var tv {.noInit.}: TTimeval = timeValFromMilliseconds(timeout)
+ var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
- var rd: TFdSet
+ var rd: FdSet
var m = 0
createFdSet((rd), readfds, m)
@@ -410,7 +410,7 @@ proc selectWrite*(writefds: var seq[SocketHandle],
## an unlimited time.
var tv {.noInit.}: Timeval = timeValFromMilliseconds(timeout)
- var wr: TFdSet
+ var wr: FdSet
var m = 0
createFdSet((wr), writefds, m)
@@ -422,5 +422,5 @@ proc selectWrite*(writefds: var seq[SocketHandle],
pruneSocketSet(writefds, (wr))
when defined(Windows):
- var wsa: WSADATA
- if WSAStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())
+ var wsa: WSAData
+ if wsaStartup(0x0101'i16, addr wsa) != 0: raiseOSError(osLastError())
diff --git a/lib/pure/uri.nim b/lib/pure/uri.nim
index ed1059cc2..2c65d071e 100644
--- a/lib/pure/uri.nim
+++ b/lib/pure/uri.nim
@@ -70,7 +70,7 @@ proc parsePath(uri: string, i: var int, result: var TUri) =
i.inc parseUntil(uri, result.path, {'?', '#'}, i)
# The 'mailto' scheme's PATH actually contains the hostname/username
- if result.scheme.ToLower() == "mailto":
+ if result.scheme.toLower == "mailto":
parseAuthority(result.path, result)
result.path = ""
diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim
index 53284cfdc..0da6cb1ff 100644
--- a/lib/windows/winlean.nim
+++ b/lib/windows/winlean.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -368,45 +368,45 @@ type
{.deprecated: [TSocketHandle: SocketHandle].}
type
- TWSAData* {.pure, final, importc: "WSADATA", header: "Winsock2.h".} = object
+ WSAData* {.importc: "WSADATA", header: "Winsock2.h".} = object
wVersion, wHighVersion: int16
szDescription: array[0..WSADESCRIPTION_LEN, char]
szSystemStatus: array[0..WSASYS_STATUS_LEN, char]
iMaxSockets, iMaxUdpDg: int16
lpVendorInfo: cstring
- TSockAddr* {.pure, final, importc: "SOCKADDR", header: "Winsock2.h".} = object
+ SockAddr* {.importc: "SOCKADDR", header: "Winsock2.h".} = object
sa_family*: int16 # unsigned
sa_data: array[0..13, char]
- TInAddr* {.pure, final, importc: "IN_ADDR", header: "Winsock2.h".} = object
+ InAddr* {.importc: "IN_ADDR", header: "Winsock2.h".} = object
s_addr*: int32 # IP address
- Tsockaddr_in* {.pure, final, importc: "SOCKADDR_IN",
+ Sockaddr_in* {.importc: "SOCKADDR_IN",
header: "Winsock2.h".} = object
sin_family*: int16
sin_port*: int16 # unsigned
- sin_addr*: TInAddr
+ sin_addr*: InAddr
sin_zero*: array[0..7, char]
- Tin6_addr* {.pure, final, importc: "IN6_ADDR", header: "Winsock2.h".} = object
+ In6_addr* {.importc: "IN6_ADDR", header: "Winsock2.h".} = object
bytes*: array[0..15, char]
- Tsockaddr_in6* {.pure, final, importc: "SOCKADDR_IN6",
+ Sockaddr_in6* {.importc: "SOCKADDR_IN6",
header: "Winsock2.h".} = object
sin6_family*: int16
sin6_port*: int16 # unsigned
sin6_flowinfo*: int32 # unsigned
- sin6_addr*: Tin6_addr
+ sin6_addr*: In6_addr
sin6_scope_id*: int32 # unsigned
- Tsockaddr_in6_old* {.pure, final.} = object
+ Sockaddr_in6_old* = object
sin6_family*: int16
sin6_port*: int16 # unsigned
sin6_flowinfo*: int32 # unsigned
- sin6_addr*: Tin6_addr
+ sin6_addr*: In6_addr
- TServent* {.pure, final.} = object
+ Servent* = object
s_name*: cstring
s_aliases*: cstringArray
when defined(cpu64):
@@ -416,31 +416,38 @@ type
s_port*: int16
s_proto*: cstring
- Thostent* {.pure, final.} = object
+ Hostent* = object
h_name*: cstring
h_aliases*: cstringArray
h_addrtype*: int16
h_length*: int16
h_addr_list*: cstringArray
- TFdSet* {.pure, final.} = object
+ FdSet* = object
fd_count*: cint # unsigned
fd_array*: array[0..FD_SETSIZE-1, SocketHandle]
- TTimeval* {.pure, final.} = object
+ Timeval* = object
tv_sec*, tv_usec*: int32
- TAddrInfo* {.pure, final.} = object
+ AddrInfo* = object
ai_flags*: cint ## Input flags.
ai_family*: cint ## Address family of socket.
ai_socktype*: cint ## Socket type.
ai_protocol*: cint ## Protocol of socket.
ai_addrlen*: int ## Length of socket address.
ai_canonname*: cstring ## Canonical name of service location.
- ai_addr*: ptr TSockAddr ## Socket address of socket.
- ai_next*: ptr TAddrInfo ## Pointer to next in list.
+ ai_addr*: ptr SockAddr ## Socket address of socket.
+ ai_next*: ptr AddrInfo ## Pointer to next in list.
+
+ SockLen* = cuint
+
+{.deprecated: [TSockaddr_in: Sockaddr_in, TAddrinfo: AddrInfo,
+ TSockAddr: SockAddr, TSockLen: SockLen, TTimeval: Timeval,
+ TWSADATA: WSADATA, TFdSet: FdSet, Thostent: Hostent, TServent: Servent,
+ TInAddr: InAddr, Tin6_addr: In6_addr, Tsockaddr_in6: Sockaddr_in6,
+ Tsockaddr_in6_old: Sockaddr_in6_old].}
- TSockLen* = cuint
var
SOMAXCONN* {.importc, header: "Winsock2.h".}: cint
@@ -462,16 +469,16 @@ var
proc `==`*(x, y: SocketHandle): bool {.borrow.}
-proc getservbyname*(name, proto: cstring): ptr TServent {.
+proc getservbyname*(name, proto: cstring): ptr Servent {.
stdcall, importc: "getservbyname", dynlib: ws2dll.}
-proc getservbyport*(port: cint, proto: cstring): ptr TServent {.
+proc getservbyport*(port: cint, proto: cstring): ptr Servent {.
stdcall, importc: "getservbyport", dynlib: ws2dll.}
-proc gethostbyaddr*(ip: ptr TInAddr, len: cuint, theType: cint): ptr Thostent {.
+proc gethostbyaddr*(ip: ptr InAddr, len: cuint, theType: cint): ptr Hostent {.
stdcall, importc: "gethostbyaddr", dynlib: ws2dll.}
-proc gethostbyname*(name: cstring): ptr Thostent {.
+proc gethostbyname*(name: cstring): ptr Hostent {.
stdcall, importc: "gethostbyname", dynlib: ws2dll.}
proc socket*(af, typ, protocol: cint): SocketHandle {.
@@ -480,20 +487,20 @@ proc socket*(af, typ, protocol: cint): SocketHandle {.
proc closesocket*(s: SocketHandle): cint {.
stdcall, importc: "closesocket", dynlib: ws2dll.}
-proc accept*(s: SocketHandle, a: ptr TSockAddr, addrlen: ptr TSockLen): SocketHandle {.
+proc accept*(s: SocketHandle, a: ptr SockAddr, addrlen: ptr SockLen): SocketHandle {.
stdcall, importc: "accept", dynlib: ws2dll.}
-proc bindSocket*(s: SocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
+proc bindSocket*(s: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint {.
stdcall, importc: "bind", dynlib: ws2dll.}
-proc connect*(s: SocketHandle, name: ptr TSockAddr, namelen: TSockLen): cint {.
+proc connect*(s: SocketHandle, name: ptr SockAddr, namelen: SockLen): cint {.
stdcall, importc: "connect", dynlib: ws2dll.}
-proc getsockname*(s: SocketHandle, name: ptr TSockAddr,
- namelen: ptr TSockLen): cint {.
+proc getsockname*(s: SocketHandle, name: ptr SockAddr,
+ namelen: ptr SockLen): cint {.
stdcall, importc: "getsockname", dynlib: ws2dll.}
proc getsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
- optlen: ptr TSockLen): cint {.
+ optlen: ptr SockLen): cint {.
stdcall, importc: "getsockopt", dynlib: ws2dll.}
proc setsockopt*(s: SocketHandle, level, optname: cint, optval: pointer,
- optlen: TSockLen): cint {.
+ optlen: SockLen): cint {.
stdcall, importc: "setsockopt", dynlib: ws2dll.}
proc listen*(s: SocketHandle, backlog: cint): cint {.
@@ -501,53 +508,53 @@ proc listen*(s: SocketHandle, backlog: cint): cint {.
proc recv*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "recv", dynlib: ws2dll.}
proc recvfrom*(s: SocketHandle, buf: cstring, len, flags: cint,
- fromm: ptr TSockAddr, fromlen: ptr TSockLen): cint {.
+ fromm: ptr SockAddr, fromlen: ptr SockLen): cint {.
stdcall, importc: "recvfrom", dynlib: ws2dll.}
-proc select*(nfds: cint, readfds, writefds, exceptfds: ptr TFdSet,
- timeout: ptr TTimeval): cint {.
+proc select*(nfds: cint, readfds, writefds, exceptfds: ptr FdSet,
+ timeout: ptr Timeval): cint {.
stdcall, importc: "select", dynlib: ws2dll.}
proc send*(s: SocketHandle, buf: pointer, len, flags: cint): cint {.
stdcall, importc: "send", dynlib: ws2dll.}
proc sendto*(s: SocketHandle, buf: pointer, len, flags: cint,
- to: ptr TSockAddr, tolen: TSockLen): cint {.
+ to: ptr SockAddr, tolen: SockLen): cint {.
stdcall, importc: "sendto", dynlib: ws2dll.}
proc shutdown*(s: SocketHandle, how: cint): cint {.
stdcall, importc: "shutdown", dynlib: ws2dll.}
-proc getnameinfo*(a1: ptr TSockAddr, a2: TSockLen,
- a3: cstring, a4: TSockLen, a5: cstring,
- a6: TSockLen, a7: cint): cint {.
+proc getnameinfo*(a1: ptr SockAddr, a2: SockLen,
+ a3: cstring, a4: SockLen, a5: cstring,
+ a6: SockLen, a7: cint): cint {.
stdcall, importc: "getnameinfo", dynlib: ws2dll.}
proc inet_addr*(cp: cstring): int32 {.
stdcall, importc: "inet_addr", dynlib: ws2dll.}
-proc WSAFDIsSet(s: SocketHandle, FDSet: var TFdSet): bool {.
+proc WSAFDIsSet(s: SocketHandle, set: var FdSet): bool {.
stdcall, importc: "__WSAFDIsSet", dynlib: ws2dll, noSideEffect.}
-proc FD_ISSET*(Socket: SocketHandle, FDSet: var TFdSet): cint =
- result = if WSAFDIsSet(Socket, FDSet): 1'i32 else: 0'i32
+proc FD_ISSET*(Socket: SocketHandle, set: var FdSet): cint =
+ result = if WSAFDIsSet(Socket, set): 1'i32 else: 0'i32
-proc FD_SET*(Socket: SocketHandle, FDSet: var TFdSet) =
- if FDSet.fd_count < FD_SETSIZE:
- FDSet.fd_array[int(FDSet.fd_count)] = Socket
- inc(FDSet.fd_count)
+proc fdSet*(socket: SocketHandle, s: var FdSet) =
+ if s.fd_count < FD_SETSIZE:
+ s.fd_array[int(s.fd_count)] = socket
+ inc(s.fd_count)
-proc FD_ZERO*(FDSet: var TFdSet) =
- FDSet.fd_count = 0
+proc FD_ZERO*(s: var FdSet) =
+ s.fd_count = 0
-proc wsaStartup*(wVersionRequired: int16, WSData: ptr TWSAData): cint {.
+proc wsaStartup*(wVersionRequired: int16, WSData: ptr WSAData): cint {.
stdcall, importc: "WSAStartup", dynlib: ws2dll.}
-proc getaddrinfo*(nodename, servname: cstring, hints: ptr TAddrInfo,
- res: var ptr TAddrInfo): cint {.
+proc getaddrinfo*(nodename, servname: cstring, hints: ptr AddrInfo,
+ res: var ptr AddrInfo): cint {.
stdcall, importc: "getaddrinfo", dynlib: ws2dll.}
-proc freeaddrinfo*(ai: ptr TAddrInfo) {.
+proc freeaddrinfo*(ai: ptr AddrInfo) {.
stdcall, importc: "freeaddrinfo", dynlib: ws2dll.}
-proc inet_ntoa*(i: TInAddr): cstring {.
+proc inet_ntoa*(i: InAddr): cstring {.
stdcall, importc, dynlib: ws2dll.}
const
From d69e8f4de48320783f1a4aeafb43c452499ffe06 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 01:19:17 +0200
Subject: [PATCH 016/409] updated base64.nim
---
lib/pure/base64.nim | 254 ++++++++++++++++++++++----------------------
1 file changed, 127 insertions(+), 127 deletions(-)
diff --git a/lib/pure/base64.nim b/lib/pure/base64.nim
index 3d3cea25c..72c49142d 100644
--- a/lib/pure/base64.nim
+++ b/lib/pure/base64.nim
@@ -1,127 +1,127 @@
-#
-#
-# Nim's Runtime Library
-# (c) Copyright 2010 Andreas Rumpf
-#
-# See the file "copying.txt", included in this
-# distribution, for details about the copyright.
-#
-
-## This module implements a base64 encoder and decoder.
-
-const
- cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
-
-template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediate.} =
- ## encodes `s` into base64 representation. After `lineLen` characters, a
- ## `newline` is added.
- var total = ((len(s) + 2) div 3) * 4
- var numLines = (total + lineLen - 1) div lineLen
- if numLines > 0: inc(total, (numLines-1) * newLine.len)
-
- result = newString(total)
- var i = 0
- var r = 0
- var currLine = 0
- while i < s.len - 2:
- var a = ord(s[i])
- var b = ord(s[i+1])
- var c = ord(s[i+2])
- result[r] = cb64[a shr 2]
- result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
- result[r+2] = cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)]
- result[r+3] = cb64[c and 0x3F]
- inc(r, 4)
- inc(i, 3)
- inc(currLine, 4)
- if currLine >= lineLen and i != s.len-2:
- for x in items(newLine):
- result[r] = x
- inc(r)
- currLine = 0
-
- if i < s.len-1:
- var a = ord(s[i])
- var b = ord(s[i+1])
- result[r] = cb64[a shr 2]
- result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
- result[r+2] = cb64[((b and 0x0F) shl 2)]
- result[r+3] = '='
- if r+4 != result.len:
- setLen(result, r+4)
- elif i < s.len:
- var a = ord(s[i])
- result[r] = cb64[a shr 2]
- result[r+1] = cb64[(a and 3) shl 4]
- result[r+2] = '='
- result[r+3] = '='
- if r+4 != result.len:
- setLen(result, r+4)
- else:
- #assert(r == result.len)
-
-proc encode*[T:TInteger|char](s: openarray[T], lineLen = 75, newLine="\13\10"): string =
- ## encodes `s` into base64 representation. After `lineLen` characters, a
- ## `newline` is added.
- encodeInternal(s, lineLen, newLine)
-
-proc encode*(s: string, lineLen = 75, newLine="\13\10"): string =
- ## encodes `s` into base64 representation. After `lineLen` characters, a
- ## `newline` is added.
- encodeInternal(s, lineLen, newLine)
-
-proc decodeByte(b: char): int {.inline.} =
- case b
- of '+': result = ord('>')
- of '0'..'9': result = ord(b) + 4
- of 'A'..'Z': result = ord(b) - ord('A')
- of 'a'..'z': result = ord(b) - 71
- else: result = 63
-
-proc decode*(s: string): string =
- ## decodes a string in base64 representation back into its original form.
- ## Whitespace is skipped.
- const Whitespace = {' ', '\t', '\v', '\r', '\l', '\f'}
- var total = ((len(s) + 3) div 4) * 3
- # total is an upper bound, as we will skip arbitrary whitespace:
- result = newString(total)
-
- var i = 0
- var r = 0
- while true:
- while s[i] in Whitespace: inc(i)
- if i < s.len-3:
- var a = s[i].decodeByte
- var b = s[i+1].decodeByte
- var c = s[i+2].decodeByte
- var d = s[i+3].decodeByte
-
- result[r] = chr((a shl 2) and 0xff or ((b shr 4) and 0x03))
- result[r+1] = chr((b shl 4) and 0xff or ((c shr 2) and 0x0F))
- result[r+2] = chr((c shl 6) and 0xff or (d and 0x3F))
- inc(r, 3)
- inc(i, 4)
- else: break
- assert i == s.len
- # adjust the length:
- if i > 0 and s[i-1] == '=':
- dec(r)
- if i > 1 and s[i-2] == '=': dec(r)
- setLen(result, r)
-
-when isMainModule:
- assert encode("leasure.") == "bGVhc3VyZS4="
- assert encode("easure.") == "ZWFzdXJlLg=="
- assert encode("asure.") == "YXN1cmUu"
- assert encode("sure.") == "c3VyZS4="
-
- const longText = """Man is distinguished, not only by his reason, but by this
- singular passion from other animals, which is a lust of the mind,
- that by a perseverance of delight in the continued and indefatigable
- generation of knowledge, exceeds the short vehemence of any carnal
- pleasure."""
- const tests = ["", "abc", "xyz", "man", "leasure.", "sure.", "easure.",
- "asure.", longText]
- for t in items(tests):
- assert decode(encode(t)) == t
-
+#
+#
+# Nim's Runtime Library
+# (c) Copyright 2010 Andreas Rumpf
+#
+# See the file "copying.txt", included in this
+# distribution, for details about the copyright.
+#
+
+## This module implements a base64 encoder and decoder.
+
+const
+ cb64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+
+template encodeInternal(s: expr, lineLen: int, newLine: string): stmt {.immediate.} =
+ ## encodes `s` into base64 representation. After `lineLen` characters, a
+ ## `newline` is added.
+ var total = ((len(s) + 2) div 3) * 4
+ var numLines = (total + lineLen - 1) div lineLen
+ if numLines > 0: inc(total, (numLines-1) * newLine.len)
+
+ result = newString(total)
+ var i = 0
+ var r = 0
+ var currLine = 0
+ while i < s.len - 2:
+ var a = ord(s[i])
+ var b = ord(s[i+1])
+ var c = ord(s[i+2])
+ result[r] = cb64[a shr 2]
+ result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
+ result[r+2] = cb64[((b and 0x0F) shl 2) or ((c and 0xC0) shr 6)]
+ result[r+3] = cb64[c and 0x3F]
+ inc(r, 4)
+ inc(i, 3)
+ inc(currLine, 4)
+ if currLine >= lineLen and i != s.len-2:
+ for x in items(newLine):
+ result[r] = x
+ inc(r)
+ currLine = 0
+
+ if i < s.len-1:
+ var a = ord(s[i])
+ var b = ord(s[i+1])
+ result[r] = cb64[a shr 2]
+ result[r+1] = cb64[((a and 3) shl 4) or ((b and 0xF0) shr 4)]
+ result[r+2] = cb64[((b and 0x0F) shl 2)]
+ result[r+3] = '='
+ if r+4 != result.len:
+ setLen(result, r+4)
+ elif i < s.len:
+ var a = ord(s[i])
+ result[r] = cb64[a shr 2]
+ result[r+1] = cb64[(a and 3) shl 4]
+ result[r+2] = '='
+ result[r+3] = '='
+ if r+4 != result.len:
+ setLen(result, r+4)
+ else:
+ #assert(r == result.len)
+
+proc encode*[T:SomeInteger|char](s: openarray[T], lineLen = 75, newLine="\13\10"): string =
+ ## encodes `s` into base64 representation. After `lineLen` characters, a
+ ## `newline` is added.
+ encodeInternal(s, lineLen, newLine)
+
+proc encode*(s: string, lineLen = 75, newLine="\13\10"): string =
+ ## encodes `s` into base64 representation. After `lineLen` characters, a
+ ## `newline` is added.
+ encodeInternal(s, lineLen, newLine)
+
+proc decodeByte(b: char): int {.inline.} =
+ case b
+ of '+': result = ord('>')
+ of '0'..'9': result = ord(b) + 4
+ of 'A'..'Z': result = ord(b) - ord('A')
+ of 'a'..'z': result = ord(b) - 71
+ else: result = 63
+
+proc decode*(s: string): string =
+ ## decodes a string in base64 representation back into its original form.
+ ## Whitespace is skipped.
+ const Whitespace = {' ', '\t', '\v', '\r', '\l', '\f'}
+ var total = ((len(s) + 3) div 4) * 3
+ # total is an upper bound, as we will skip arbitrary whitespace:
+ result = newString(total)
+
+ var i = 0
+ var r = 0
+ while true:
+ while s[i] in Whitespace: inc(i)
+ if i < s.len-3:
+ var a = s[i].decodeByte
+ var b = s[i+1].decodeByte
+ var c = s[i+2].decodeByte
+ var d = s[i+3].decodeByte
+
+ result[r] = chr((a shl 2) and 0xff or ((b shr 4) and 0x03))
+ result[r+1] = chr((b shl 4) and 0xff or ((c shr 2) and 0x0F))
+ result[r+2] = chr((c shl 6) and 0xff or (d and 0x3F))
+ inc(r, 3)
+ inc(i, 4)
+ else: break
+ assert i == s.len
+ # adjust the length:
+ if i > 0 and s[i-1] == '=':
+ dec(r)
+ if i > 1 and s[i-2] == '=': dec(r)
+ setLen(result, r)
+
+when isMainModule:
+ assert encode("leasure.") == "bGVhc3VyZS4="
+ assert encode("easure.") == "ZWFzdXJlLg=="
+ assert encode("asure.") == "YXN1cmUu"
+ assert encode("sure.") == "c3VyZS4="
+
+ const longText = """Man is distinguished, not only by his reason, but by this
+ singular passion from other animals, which is a lust of the mind,
+ that by a perseverance of delight in the continued and indefatigable
+ generation of knowledge, exceeds the short vehemence of any carnal
+ pleasure."""
+ const tests = ["", "abc", "xyz", "man", "leasure.", "sure.", "easure.",
+ "asure.", longText]
+ for t in items(tests):
+ assert decode(encode(t)) == t
+
From a6211058c5b23d1a1985ac8b59989e0f7895949c Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 01:27:36 +0200
Subject: [PATCH 017/409] updated basic2d, basic3d modules
---
lib/pure/basic2d.nim | 26 +++++++++++++-------------
lib/pure/basic3d.nim | 24 ++++++++++++------------
2 files changed, 25 insertions(+), 25 deletions(-)
diff --git a/lib/pure/basic2d.nim b/lib/pure/basic2d.nim
index 40f59db74..f2fc1566b 100644
--- a/lib/pure/basic2d.nim
+++ b/lib/pure/basic2d.nim
@@ -92,7 +92,7 @@ proc point2d*(x,y:float):TPoint2d {.noInit,inline.}
let
IDMATRIX*:TMatrix2d=matrix2d(1.0,0.0,0.0,1.0,0.0,0.0)
## Quick access to an identity matrix
- ORIGO*:TPoint2d=Point2d(0.0,0.0)
+ ORIGO*:TPoint2d=point2d(0.0,0.0)
## Quick acces to point (0,0)
XAXIS*:TVector2d=vector2d(1.0,0.0)
## Quick acces to an 2d x-axis unit vector
@@ -212,7 +212,7 @@ proc mirror*(v:TVector2d):TMatrix2d {.noInit.} =
xy2=v.x*v.y*2.0*nd
sqd=nd*(sqx-sqy)
- if nd==inf or nd==neginf:
+ if nd==Inf or nd==NegInf:
return IDMATRIX #mirroring around a zero vector is arbitrary=>just use identity
result.setElements(
@@ -231,7 +231,7 @@ proc mirror*(org:TPoint2d,v:TVector2d):TMatrix2d {.noInit.} =
xy2=v.x*v.y*2.0*nd
sqd=nd*(sqx-sqy)
- if nd==inf or nd==neginf:
+ if nd==Inf or nd==NegInf:
return IDMATRIX #mirroring around a zero vector is arbitrary=>just use identity
result.setElements(
@@ -285,7 +285,7 @@ proc inverse*(m:TMatrix2d):TMatrix2d {.noInit.} =
## will be raised.
let d=m.determinant
if d==0.0:
- raise newException(EDivByZero,"Cannot invert a zero determinant matrix")
+ raise newException(DivByZeroError,"Cannot invert a zero determinant matrix")
result.setElements(
m.by/d,-m.ay/d,
@@ -360,7 +360,7 @@ proc `len=`*(v:var TVector2d,newlen:float) {.noInit.} =
v.y=0.0
return
- if fac==inf or fac==neginf:
+ if fac==Inf or fac==NegInf:
#to short for float accuracy
#do as good as possible:
v.x=newlen
@@ -431,7 +431,7 @@ proc normalize*(v:var TVector2d) {.inline.}=
## Modifies `v` to have a length of 1.0, keeping its angle.
## If `v` has zero length, an EDivByZero will be raised.
if not tryNormalize(v):
- raise newException(EDivByZero,"Cannot normalize zero length vector")
+ raise newException(DivByZeroError,"Cannot normalize zero length vector")
proc transformNorm*(v:var TVector2d,t:TMatrix2d)=
## Applies a normal direction transformation `t` onto `v` in place.
@@ -447,7 +447,7 @@ proc transformNorm*(v:var TVector2d,t:TMatrix2d)=
# | | 0 0 1 | |
let d=t.determinant
if(d==0.0):
- raise newException(EDivByZero,"Matrix is not invertible")
+ raise newException(DivByZeroError,"Matrix is not invertible")
let newx = (t.by*v.x-t.ay*v.y)/d
v.y = (t.ax*v.y-t.bx*v.x)/d
v.x = newx
@@ -461,7 +461,7 @@ proc transformInv*(v:var TVector2d,t:TMatrix2d)=
let d=t.determinant
if(d==0.0):
- raise newException(EDivByZero,"Matrix is not invertible")
+ raise newException(DivByZeroError,"Matrix is not invertible")
let newx=(t.by*v.x-t.bx*v.y)/d
v.y = (t.ax*v.y-t.ay*v.x)/d
@@ -531,7 +531,7 @@ proc mirror*(v:var TVector2d,mirrvec:TVector2d)=
xy2=mirrvec.x*mirrvec.y*2.0*nd
sqd=nd*(sqx-sqy)
- if nd==inf or nd==neginf:
+ if nd==Inf or nd==NegInf:
return #mirroring around a zero vector is arbitrary=>keep as is is fastest
let newx=xy2*v.y+sqd*v.x
@@ -703,7 +703,7 @@ proc transformInv*(p:var TPoint2d,t:TMatrix2d){.inline.}=
# | TX TY 1 |
let d=t.determinant
if d==0.0:
- raise newException(EDivByZero,"Cannot invert a zero determinant matrix")
+ raise newException(DivByZeroError,"Cannot invert a zero determinant matrix")
let
newx= (t.bx*t.ty-t.by*t.tx+p.x*t.by-p.y*t.bx)/d
p.y = -(t.ax*t.ty-t.ay*t.tx+p.x*t.ay-p.y*t.ax)/d
@@ -820,11 +820,11 @@ proc closestPoint*(p:TPoint2d,pts:varargs[TPoint2d]):TPoint2d=
var
bestidx=0
- bestdist=p.sqrdist(pts[0])
+ bestdist=p.sqrDist(pts[0])
curdist:float
for idx in 1..high(pts):
- curdist=p.sqrdist(pts[idx])
+ curdist=p.sqrDist(pts[idx])
if curdist
Date: Thu, 28 Aug 2014 01:30:12 +0200
Subject: [PATCH 018/409] more modules updated
---
lib/pure/cgi.nim | 16 ++++----
lib/pure/complex.nim | 88 ++++++++++++++++++++++----------------------
lib/pure/strtabs.nim | 36 +++++++++---------
3 files changed, 70 insertions(+), 70 deletions(-)
diff --git a/lib/pure/cgi.nim b/lib/pure/cgi.nim
index bb7934faa..bfa94a238 100644
--- a/lib/pure/cgi.nim
+++ b/lib/pure/cgi.nim
@@ -103,12 +103,12 @@ type
proc cgiError*(msg: string) {.noreturn.} =
## raises an ECgi exception with message `msg`.
- var e: ref ECgi
+ var e: ref CgiError
new(e)
e.msg = msg
raise e
-proc getEncodedData(allowedMethods: set[TRequestMethod]): string =
+proc getEncodedData(allowedMethods: set[RequestMethod]): string =
case getEnv("REQUEST_METHOD").string
of "POST":
if methodPost notin allowedMethods:
@@ -167,7 +167,7 @@ iterator decodeData*(data: string): tuple[key, value: TaintedString] =
elif data[i] == '\0': break
else: cgiError("'&' expected")
-iterator decodeData*(allowedMethods: set[TRequestMethod] =
+iterator decodeData*(allowedMethods: set[RequestMethod] =
{methodNone, methodPost, methodGet}): tuple[key, value: TaintedString] =
## Reads and decodes CGI data and yields the (name, value) pairs the
## data consists of. If the client does not use a method listed in the
@@ -177,15 +177,15 @@ iterator decodeData*(allowedMethods: set[TRequestMethod] =
for key, value in decodeData(data):
yield (key, value)
-proc readData*(allowedMethods: set[TRequestMethod] =
- {methodNone, methodPost, methodGet}): PStringTable =
+proc readData*(allowedMethods: set[RequestMethod] =
+ {methodNone, methodPost, methodGet}): StringTableRef =
## Read CGI data. If the client does not use a method listed in the
## `allowedMethods` set, an `ECgi` exception is raised.
result = newStringTable()
for name, value in decodeData(allowedMethods):
result[name.string] = value.string
-proc validateData*(data: PStringTable, validKeys: varargs[string]) =
+proc validateData*(data: StringTableRef, validKeys: varargs[string]) =
## validates data; raises `ECgi` if this fails. This checks that each variable
## name of the CGI `data` occurs in the `validKeys` array.
for key, val in pairs(data):
@@ -393,5 +393,5 @@ proc existsCookie*(name: string): bool =
when isMainModule:
const test1 = "abc\L+def xyz"
- assert UrlEncode(test1) == "abc%0A%2Bdef+xyz"
- assert UrlDecode(UrlEncode(test1)) == test1
+ assert URLencode(test1) == "abc%0A%2Bdef+xyz"
+ assert URLdecode(URLencode(test1)) == test1
diff --git a/lib/pure/complex.nim b/lib/pure/complex.nim
index d31d56f83..a8709e098 100644
--- a/lib/pure/complex.nim
+++ b/lib/pure/complex.nim
@@ -30,50 +30,50 @@ type
{.deprecated: [TComplex: Complex].}
-proc `==` *(x, y: TComplex): bool =
+proc `==` *(x, y: Complex): bool =
## Compare two complex numbers `x` and `y` for equality.
result = x.re == y.re and x.im == y.im
-proc `=~` *(x, y: TComplex): bool =
+proc `=~` *(x, y: Complex): bool =
## Compare two complex numbers `x` and `y` approximately.
result = abs(x.re-y.re)= 0: result = t.data[index].val
else: result = ""
-proc mget*(t: PStringTable, key: string): var string {.
+proc mget*(t: StringTableRef, key: string): var string {.
rtl, extern: "nstTake".} =
## retrieves the location at ``t[key]``. If `key` is not in `t`, the
## ``EInvalidKey`` exception is raised.
@@ -117,25 +117,25 @@ proc mget*(t: PStringTable, key: string): var string {.
if index >= 0: result = t.data[index].val
else: raise newException(KeyError, "key does not exist: " & key)
-proc hasKey*(t: PStringTable, key: string): bool {.rtl, extern: "nst$1".} =
+proc hasKey*(t: StringTableRef, key: string): bool {.rtl, extern: "nst$1".} =
## returns true iff `key` is in the table `t`.
result = rawGet(t, key) >= 0
-proc rawInsert(t: PStringTable, data: var KeyValuePairSeq, key, val: string) =
+proc rawInsert(t: StringTableRef, data: var KeyValuePairSeq, key, val: string) =
var h: THash = myhash(t, key) and high(data)
while not isNil(data[h].key):
h = nextTry(h, high(data))
data[h].key = key
data[h].val = val
-proc enlarge(t: PStringTable) =
+proc enlarge(t: StringTableRef) =
var n: KeyValuePairSeq
newSeq(n, len(t.data) * growthFactor)
for i in countup(0, high(t.data)):
if not isNil(t.data[i].key): rawInsert(t, n, t.data[i].key, t.data[i].val)
swap(t.data, n)
-proc `[]=`*(t: PStringTable, key, val: string) {.rtl, extern: "nstPut".} =
+proc `[]=`*(t: StringTableRef, key, val: string) {.rtl, extern: "nstPut".} =
## puts a (key, value)-pair into `t`.
var index = rawGet(t, key)
if index >= 0:
@@ -151,7 +151,7 @@ proc raiseFormatException(s: string) =
e.msg = "format string: key not found: " & s
raise e
-proc getValue(t: PStringTable, flags: set[TFormatFlag], key: string): string =
+proc getValue(t: StringTableRef, flags: set[FormatFlag], key: string): string =
if hasKey(t, key): return t[key]
# hm difficult: assume safety in taint mode here. XXX This is dangerous!
if useEnvironment in flags: result = os.getEnv(key).string
@@ -160,7 +160,7 @@ proc getValue(t: PStringTable, flags: set[TFormatFlag], key: string): string =
if useKey in flags: result = '$' & key
elif not (useEmpty in flags): raiseFormatException(key)
-proc newStringTable*(mode: TStringTableMode): PStringTable {.
+proc newStringTable*(mode: StringTableMode): StringTableRef {.
rtl, extern: "nst$1".} =
## creates a new string table that is empty.
new(result)
@@ -169,7 +169,7 @@ proc newStringTable*(mode: TStringTableMode): PStringTable {.
newSeq(result.data, startSize)
proc newStringTable*(keyValuePairs: varargs[string],
- mode: TStringTableMode): PStringTable {.
+ mode: StringTableMode): StringTableRef {.
rtl, extern: "nst$1WithPairs".} =
## creates a new string table with given key value pairs.
## Example::
@@ -182,7 +182,7 @@ proc newStringTable*(keyValuePairs: varargs[string],
inc(i, 2)
proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]],
- mode: StringTableMode = modeCaseSensitive): PStringTable {.
+ mode: StringTableMode = modeCaseSensitive): StringTableRef {.
rtl, extern: "nst$1WithTableConstr".} =
## creates a new string table with given key value pairs.
## Example::
@@ -191,7 +191,7 @@ proc newStringTable*(keyValuePairs: varargs[tuple[key, val: string]],
result = newStringTable(mode)
for key, val in items(keyValuePairs): result[key] = val
-proc `%`*(f: string, t: PStringTable, flags: set[TFormatFlag] = {}): string {.
+proc `%`*(f: string, t: StringTableRef, flags: set[FormatFlag] = {}): string {.
rtl, extern: "nstFormat".} =
## The `%` operator for string tables.
const
@@ -221,7 +221,7 @@ proc `%`*(f: string, t: PStringTable, flags: set[TFormatFlag] = {}): string {.
add(result, f[i])
inc(i)
-proc `$`*(t: PStringTable): string {.rtl, extern: "nstDollar".} =
+proc `$`*(t: StringTableRef): string {.rtl, extern: "nstDollar".} =
## The `$` operator for string tables.
if t.len == 0:
result = "{:}"
From 12d2a37519abfb490c39a5018ea4eb93eaeb3b29 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 01:39:45 +0200
Subject: [PATCH 019/409] more modules updated
---
lib/pure/dynlib.nim | 24 ++++++++---------
lib/pure/encodings.nim | 18 ++++++-------
lib/pure/events.nim | 22 ++++++++--------
lib/pure/gentabs.nim | 4 +--
lib/pure/parsexml.nim | 16 ++++++------
lib/pure/xmltree.nim | 58 +++++++++++++++++++++---------------------
6 files changed, 71 insertions(+), 71 deletions(-)
diff --git a/lib/pure/dynlib.nim b/lib/pure/dynlib.nim
index 77ef20ad9..617fbc66f 100644
--- a/lib/pure/dynlib.nim
+++ b/lib/pure/dynlib.nim
@@ -16,29 +16,29 @@ type
{.deprecated: [TLibHandle: LibHandle].}
-proc loadLib*(path: string, global_symbols=false): TLibHandle
+proc loadLib*(path: string, global_symbols=false): LibHandle
## loads a library from `path`. Returns nil if the library could not
## be loaded.
-proc loadLib*(): TLibHandle
+proc loadLib*(): LibHandle
## gets the handle from the current executable. Returns nil if the
## library could not be loaded.
-proc unloadLib*(lib: TLibHandle)
+proc unloadLib*(lib: LibHandle)
## unloads the library `lib`
proc raiseInvalidLibrary*(name: cstring) {.noinline, noreturn.} =
## raises an `EInvalidLibrary` exception.
- var e: ref EInvalidLibrary
+ var e: ref LibraryError
new(e)
e.msg = "could not find symbol: " & $name
raise e
-proc symAddr*(lib: TLibHandle, name: cstring): pointer
+proc symAddr*(lib: LibHandle, name: cstring): pointer
## retrieves the address of a procedure/variable from `lib`. Returns nil
## if the symbol could not be found.
-proc checkedSymAddr*(lib: TLibHandle, name: cstring): pointer =
+proc checkedSymAddr*(lib: LibHandle, name: cstring): pointer =
## retrieves the address of a procedure/variable from `lib`. Raises
## `EInvalidLibrary` if the symbol could not be found.
result = symAddr(lib, name)
@@ -87,13 +87,13 @@ elif defined(windows) or defined(dos):
proc getProcAddress(lib: THINSTANCE, name: cstring): pointer {.
importc: "GetProcAddress", header: "", stdcall.}
- proc loadLib(path: string, global_symbols=false): TLibHandle =
- result = cast[TLibHandle](winLoadLibrary(path))
- proc loadLib(): TLibHandle =
- result = cast[TLibHandle](winLoadLibrary(nil))
- proc unloadLib(lib: TLibHandle) = FreeLibrary(cast[THINSTANCE](lib))
+ proc loadLib(path: string, global_symbols=false): LibHandle =
+ result = cast[LibHandle](winLoadLibrary(path))
+ proc loadLib(): LibHandle =
+ result = cast[LibHandle](winLoadLibrary(nil))
+ proc unloadLib(lib: LibHandle) = FreeLibrary(cast[THINSTANCE](lib))
- proc symAddr(lib: TLibHandle, name: cstring): pointer =
+ proc symAddr(lib: LibHandle, name: cstring): pointer =
result = getProcAddress(cast[THINSTANCE](lib), name)
else:
diff --git a/lib/pure/encodings.nim b/lib/pure/encodings.nim
index f10c4e40b..8cc668359 100644
--- a/lib/pure/encodings.nim
+++ b/lib/pure/encodings.nim
@@ -36,7 +36,7 @@ when defined(windows):
while i < a.len and j < b.len:
if a[i] in {'-', '_'}: inc i
if b[j] in {'-', '_'}: inc j
- if a[i].tolower != b[j].tolower: return false
+ if a[i].toLower != b[j].toLower: return false
inc i
inc j
result = i == a.len and j == b.len
@@ -295,11 +295,11 @@ else:
proc getCurrentEncoding*(): string =
## retrieves the current encoding. On Unix, always "UTF-8" is returned.
when defined(windows):
- result = codePageToName(GetACP())
+ result = codePageToName(getACP())
else:
result = "UTF-8"
-proc open*(destEncoding = "UTF-8", srcEncoding = "CP1252"): PConverter =
+proc open*(destEncoding = "UTF-8", srcEncoding = "CP1252"): EncodingConverter =
## opens a converter that can convert from `srcEncoding` to `destEncoding`.
## Raises `EIO` if it cannot fullfill the request.
when not defined(windows):
@@ -312,19 +312,19 @@ proc open*(destEncoding = "UTF-8", srcEncoding = "CP1252"): PConverter =
result.dest = nameToCodePage(destEncoding)
result.src = nameToCodePage(srcEncoding)
if int(result.dest) == -1:
- raise newException(EInvalidEncoding,
+ raise newException(EncodingError,
"cannot find encoding " & destEncoding)
if int(result.src) == -1:
- raise newException(EInvalidEncoding,
+ raise newException(EncodingError,
"cannot find encoding " & srcEncoding)
-proc close*(c: PConverter) =
+proc close*(c: EncodingConverter) =
## frees the resources the converter `c` holds.
when not defined(windows):
iconvClose(c)
when defined(windows):
- proc convert*(c: PConverter, s: string): string =
+ proc convert*(c: EncodingConverter, s: string): string =
## converts `s` to `destEncoding` that was given to the converter `c`. It
## assumed that `s` is in `srcEncoding`.
@@ -354,7 +354,7 @@ when defined(windows):
cbMultiByte = cint(s.len),
lpWideCharStr = cstring(result),
cchWideChar = cint(cap))
- if m == 0: osError(osLastError())
+ if m == 0: raiseOSError(osLastError())
setLen(result, m*2)
elif m <= cap:
setLen(result, m*2)
@@ -391,7 +391,7 @@ when defined(windows):
cchWideChar = cint(result.len div 2),
lpMultiByteStr = cstring(res),
cbMultiByte = cap.cint)
- if m == 0: osError(osLastError())
+ if m == 0: raiseOSError(osLastError())
setLen(res, m)
result = res
elif m <= cap:
diff --git a/lib/pure/events.nim b/lib/pure/events.nim
index 7868050d1..47dc6ba3f 100644
--- a/lib/pure/events.nim
+++ b/lib/pure/events.nim
@@ -46,37 +46,37 @@ type
{.deprecated: [TEventArgs: EventArgs, TEventHandler: EventHandler,
TEventEmitter: EventEmitter, EInvalidEvent: EventError].}
-proc initEventHandler*(name: string): TEventHandler =
+proc initEventHandler*(name: string): EventHandler =
## Initializes an EventHandler with the specified name and returns it.
result.handlers = @[]
result.name = name
-proc addHandler*(handler: var TEventHandler, func: proc(e: TEventArgs) {.closure.}) =
+proc addHandler*(handler: var EventHandler, func: proc(e: EventArgs) {.closure.}) =
## Adds the callback to the specified event handler.
handler.handlers.add(func)
-proc removeHandler*(handler: var TEventHandler, func: proc(e: TEventArgs) {.closure.}) =
+proc removeHandler*(handler: var EventHandler, func: proc(e: EventArgs) {.closure.}) =
## Removes the callback from the specified event handler.
for i in countup(0, len(handler.handlers) -1):
if func == handler.handlers[i]:
handler.handlers.del(i)
break
-proc containsHandler*(handler: var TEventHandler, func: proc(e: TEventArgs) {.closure.}): bool =
+proc containsHandler*(handler: var EventHandler, func: proc(e: EventArgs) {.closure.}): bool =
## Checks if a callback is registered to this event handler.
return handler.handlers.contains(func)
-proc clearHandlers*(handler: var TEventHandler) =
+proc clearHandlers*(handler: var EventHandler) =
## Clears all of the callbacks from the event handler.
setLen(handler.handlers, 0)
-proc getEventHandler(emitter: var TEventEmitter, event: string): int =
+proc getEventHandler(emitter: var EventEmitter, event: string): int =
for k in 0..high(emitter.s):
if emitter.s[k].name == event: return k
return -1
-proc on*(emitter: var TEventEmitter, event: string, func: proc(e: TEventArgs) {.closure.}) =
+proc on*(emitter: var EventEmitter, event: string, func: proc(e: EventArgs) {.closure.}) =
## Assigns a event handler with the specified callback. If the event
## doesn't exist, it will be created.
var i = getEventHandler(emitter, event)
@@ -87,17 +87,17 @@ proc on*(emitter: var TEventEmitter, event: string, func: proc(e: TEventArgs) {.
else:
addHandler(emitter.s[i], func)
-proc emit*(emitter: var TEventEmitter, eventhandler: var TEventHandler,
- args: TEventArgs) =
+proc emit*(emitter: var EventEmitter, eventhandler: var EventHandler,
+ args: EventArgs) =
## Fires an event handler with specified event arguments.
for func in items(eventhandler.handlers): func(args)
-proc emit*(emitter: var TEventEmitter, event: string, args: TEventArgs) =
+proc emit*(emitter: var EventEmitter, event: string, args: EventArgs) =
## Fires an event handler with specified event arguments.
var i = getEventHandler(emitter, event)
if i >= 0:
emit(emitter, emitter.s[i], args)
-proc initEventEmitter*(): TEventEmitter =
+proc initEventEmitter*(): EventEmitter =
## Creates and returns a new EventEmitter.
result.s = @[]
diff --git a/lib/pure/gentabs.nim b/lib/pure/gentabs.nim
index 87a55ea1e..c371809a0 100644
--- a/lib/pure/gentabs.nim
+++ b/lib/pure/gentabs.nim
@@ -25,7 +25,7 @@ type
TGenKeyValuePair[T] = tuple[key: string, val: T]
TGenKeyValuePairSeq[T] = seq[TGenKeyValuePair[T]]
- TGenTable*[T] = object of TObject
+ TGenTable*[T] = object of RootObj
counter: int
data: TGenKeyValuePairSeq[T]
mode: TGenTableMode
@@ -78,7 +78,7 @@ proc RawGet[T](tbl: PGenTable[T], key: string): int =
var h: THash
h = myhash(tbl, key) and high(tbl.data) # start with real hash value
while not isNil(tbl.data[h].key):
- if mycmp(tbl, tbl.data[h].key, key):
+ if myCmp(tbl, tbl.data[h].key, key):
return h
h = nextTry(h, high(tbl.data))
result = - 1
diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim
index 2d944917f..cc7575563 100644
--- a/lib/pure/parsexml.nim
+++ b/lib/pure/parsexml.nim
@@ -98,11 +98,11 @@ type
filename: string
options: set[XmlParseOption]
-{.deprecated: [TXmlParser: XmlParser, TXmlParseOptions: XmlParseOptions,
+{.deprecated: [TXmlParser: XmlParser, TXmlParseOptions: XmlParseOption,
TXmlError: XmlErrorKind, TXmlEventKind: XmlEventKind].}
const
- errorMessages: array[XmlError, string] = [
+ errorMessages: array[XmlErrorKind, string] = [
"no error",
"']]>' expected",
"name expected",
@@ -235,11 +235,11 @@ proc parseCDATA(my: var TXMLParser) =
markError(my, errEndOfCDataExpected)
break
of '\c':
- pos = lexbase.HandleCR(my, pos)
+ pos = lexbase.handleCR(my, pos)
buf = my.buf
add(my.a, '\L')
of '\L':
- pos = lexbase.HandleLF(my, pos)
+ pos = lexbase.handleLF(my, pos)
buf = my.buf
add(my.a, '\L')
else:
@@ -263,11 +263,11 @@ proc parseComment(my: var TXMLParser) =
markError(my, errEndOfCommentExpected)
break
of '\c':
- pos = lexbase.HandleCR(my, pos)
+ pos = lexbase.handleCR(my, pos)
buf = my.buf
if my.options.contains(reportComments): add(my.a, '\L')
of '\L':
- pos = lexbase.HandleLF(my, pos)
+ pos = lexbase.handleLF(my, pos)
buf = my.buf
if my.options.contains(reportComments): add(my.a, '\L')
else:
@@ -286,11 +286,11 @@ proc parseWhitespace(my: var TXmlParser, skip=False) =
Inc(pos)
of '\c':
# the specification says that CR-LF, CR are to be transformed to LF
- pos = lexbase.HandleCR(my, pos)
+ pos = lexbase.handleCR(my, pos)
buf = my.buf
if not skip: add(my.a, '\L')
of '\L':
- pos = lexbase.HandleLF(my, pos)
+ pos = lexbase.handleLF(my, pos)
buf = my.buf
if not skip: add(my.a, '\L')
else:
diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim
index 6007232c5..c15c2e148 100644
--- a/lib/pure/xmltree.nim
+++ b/lib/pure/xmltree.nim
@@ -12,7 +12,7 @@
import macros, strtabs
type
- XmlNode* = ref TXmlNode ## an XML tree consists of ``PXmlNode``'s.
+ XmlNode* = ref XmlNodeObj ## an XML tree consists of ``PXmlNode``'s.
XmlNodeKind* = enum ## different kinds of ``PXmlNode``'s
xnText, ## a text element
@@ -48,43 +48,43 @@ proc newElement*(tag: string): XmlNode =
result.s = @[]
# init attributes lazily to safe memory
-proc newText*(text: string): PXmlNode =
+proc newText*(text: string): XmlNode =
## creates a new ``PXmlNode`` of kind ``xnText`` with the text `text`.
result = newXmlNode(xnText)
result.fText = text
-proc newComment*(comment: string): PXmlNode =
+proc newComment*(comment: string): XmlNode =
## creates a new ``PXmlNode`` of kind ``xnComment`` with the text `comment`.
result = newXmlNode(xnComment)
result.fText = comment
-proc newCData*(cdata: string): PXmlNode =
+proc newCData*(cdata: string): XmlNode =
## creates a new ``PXmlNode`` of kind ``xnComment`` with the text `cdata`.
result = newXmlNode(xnCData)
result.fText = cdata
-proc newEntity*(entity: string): PXmlNode =
+proc newEntity*(entity: string): XmlNode =
## creates a new ``PXmlNode`` of kind ``xnEntity`` with the text `entity`.
result = newXmlNode(xnCData)
result.fText = entity
-proc text*(n: PXmlNode): string {.inline.} =
+proc text*(n: XmlNode): string {.inline.} =
## gets the associated text with the node `n`. `n` can be a CDATA, Text,
## comment, or entity node.
assert n.k in {xnText, xnComment, xnCData, xnEntity}
result = n.fText
-proc rawText*(n: PXmlNode): string {.inline.} =
+proc rawText*(n: XmlNode): string {.inline.} =
## returns the underlying 'text' string by reference.
## This is only used for speed hacks.
shallowCopy(result, n.fText)
-proc rawTag*(n: PXmlNode): string {.inline.} =
+proc rawTag*(n: XmlNode): string {.inline.} =
## returns the underlying 'tag' string by reference.
## This is only used for speed hacks.
shallowCopy(result, n.fTag)
-proc innerText*(n: PXmlNode): string =
+proc innerText*(n: XmlNode): string =
## gets the inner text of `n`. `n` has to be an ``xnElement`` node. Only
## ``xnText`` and ``xnEntity`` nodes are considered part of `n`'s inner text,
## other child nodes are silently ignored.
@@ -93,55 +93,55 @@ proc innerText*(n: PXmlNode): string =
for i in 0 .. n.s.len-1:
if n.s[i].k in {xnText, xnEntity}: result.add(n.s[i].fText)
-proc tag*(n: PXmlNode): string {.inline.} =
+proc tag*(n: XmlNode): string {.inline.} =
## gets the tag name of `n`. `n` has to be an ``xnElement`` node.
assert n.k == xnElement
result = n.fTag
-proc add*(father, son: PXmlNode) {.inline.} =
+proc add*(father, son: XmlNode) {.inline.} =
## adds the child `son` to `father`.
add(father.s, son)
-proc len*(n: PXmlNode): int {.inline.} =
+proc len*(n: XmlNode): int {.inline.} =
## returns the number `n`'s children.
if n.k == xnElement: result = len(n.s)
-proc kind*(n: PXmlNode): TXmlNodeKind {.inline.} =
+proc kind*(n: XmlNode): XmlNodeKind {.inline.} =
## returns `n`'s kind.
result = n.k
-proc `[]`* (n: PXmlNode, i: int): PXmlNode {.inline.} =
+proc `[]`* (n: XmlNode, i: int): XmlNode {.inline.} =
## returns the `i`'th child of `n`.
assert n.k == xnElement
result = n.s[i]
-iterator items*(n: PXmlNode): PXmlNode {.inline.} =
+iterator items*(n: XmlNode): XmlNode {.inline.} =
## iterates over any child of `n`.
assert n.k == xnElement
for i in 0 .. n.len-1: yield n[i]
-proc attrs*(n: PXmlNode): PXmlAttributes {.inline.} =
+proc attrs*(n: XmlNode): XmlAttributes {.inline.} =
## gets the attributes belonging to `n`.
## Returns `nil` if attributes have not been initialised for this node.
assert n.k == xnElement
result = n.fAttr
-proc `attrs=`*(n: PXmlNode, attr: PXmlAttributes) {.inline.} =
+proc `attrs=`*(n: XmlNode, attr: XmlAttributes) {.inline.} =
## sets the attributes belonging to `n`.
assert n.k == xnElement
n.fAttr = attr
-proc attrsLen*(n: PXmlNode): int {.inline.} =
+proc attrsLen*(n: XmlNode): int {.inline.} =
## returns the number of `n`'s attributes.
assert n.k == xnElement
if not isNil(n.fAttr): result = len(n.fAttr)
-proc clientData*(n: PXmlNode): int {.inline.} =
+proc clientData*(n: XmlNode): int {.inline.} =
## gets the client data of `n`. The client data field is used by the HTML
## parser and generator.
result = n.fClientData
-proc `clientData=`*(n: PXmlNode, data: int) {.inline.} =
+proc `clientData=`*(n: XmlNode, data: int) {.inline.} =
## sets the client data of `n`. The client data field is used by the HTML
## parser and generator.
n.fClientData = data
@@ -175,13 +175,13 @@ proc addIndent(result: var string, indent: int) =
result.add("\n")
for i in 1..indent: result.add(' ')
-proc noWhitespace(n: PXmlNode): bool =
+proc noWhitespace(n: XmlNode): bool =
#for i in 1..n.len-1:
# if n[i].kind != n[0].kind: return true
for i in 0..n.len-1:
if n[i].kind in {xnText, xnEntity}: return true
-proc add*(result: var string, n: PXmlNode, indent = 0, indWidth = 2) =
+proc add*(result: var string, n: XmlNode, indent = 0, indWidth = 2) =
## adds the textual representation of `n` to `result`.
if n == nil: return
case n.k
@@ -234,14 +234,14 @@ const
xmlHeader* = "\n"
## header to use for complete XML output
-proc `$`*(n: PXmlNode): string =
+proc `$`*(n: XmlNode): string =
## converts `n` into its string representation. No ``<$xml ...$>`` declaration
## is produced, so that the produced XML fragments are composable.
result = ""
result.add(n)
-proc newXmlTree*(tag: string, children: openArray[PXmlNode],
- attributes: PXmlAttributes = nil): PXmlNode =
+proc newXmlTree*(tag: string, children: openArray[XmlNode],
+ attributes: XmlAttributes = nil): XmlNode =
## creates a new XML tree with `tag`, `children` and `attributes`
result = newXmlNode(xnElement)
result.fTag = tag
@@ -285,7 +285,7 @@ macro `<>`*(x: expr): expr {.immediate.} =
let x = callsite()
result = xmlConstructor(x)
-proc child*(n: PXmlNode, name: string): PXmlNode =
+proc child*(n: XmlNode, name: string): XmlNode =
## Finds the first child element of `n` with a name of `name`.
## Returns `nil` on failure.
assert n.kind == xnElement
@@ -294,14 +294,14 @@ proc child*(n: PXmlNode, name: string): PXmlNode =
if i.tag == name:
return i
-proc attr*(n: PXmlNode, name: string): string =
+proc attr*(n: XmlNode, name: string): string =
## Finds the first attribute of `n` with a name of `name`.
## Returns "" on failure.
assert n.kind == xnElement
if n.attrs == nil: return ""
return n.attrs[name]
-proc findAll*(n: PXmlNode, tag: string, result: var seq[PXmlNode]) =
+proc findAll*(n: XmlNode, tag: string, result: var seq[XmlNode]) =
## Iterates over all the children of `n` returning those matching `tag`.
##
## Found nodes satisfying the condition will be appended to the `result`
@@ -326,7 +326,7 @@ proc findAll*(n: PXmlNode, tag: string, result: var seq[PXmlNode]) =
elif child.k == xnElement:
child.findAll(tag, result)
-proc findAll*(n: PXmlNode, tag: string): seq[PXmlNode] =
+proc findAll*(n: XmlNode, tag: string): seq[XmlNode] =
## Shortcut version to assign in let blocks. Example:
##
## .. code-block::
From e07b8334396b70b9a6ded6adc27ee1bcbc60c7d6 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 01:41:41 +0200
Subject: [PATCH 020/409] more modules updated
---
lib/pure/lexbase.nim | 32 ++++++++--------
lib/pure/parsexml.nim | 86 +++++++++++++++++++++----------------------
2 files changed, 59 insertions(+), 59 deletions(-)
diff --git a/lib/pure/lexbase.nim b/lib/pure/lexbase.nim
index 63c2599b9..a3a3d7b5c 100644
--- a/lib/pure/lexbase.nim
+++ b/lib/pure/lexbase.nim
@@ -30,7 +30,7 @@ type
bufpos*: int ## the current position within the buffer
buf*: cstring ## the buffer itself
bufLen*: int ## length of buffer in characters
- input: PStream ## the input stream
+ input: Stream ## the input stream
lineNumber*: int ## the current line number
sentinel: int
lineStart: int # index of last line start in buffer
@@ -38,23 +38,23 @@ type
{.deprecated: [TBaseLexer: BaseLexer].}
-proc open*(L: var TBaseLexer, input: PStream, bufLen: int = 8192)
+proc open*(L: var BaseLexer, input: Stream, bufLen: int = 8192)
## inits the TBaseLexer with a stream to read from
-proc close*(L: var TBaseLexer)
+proc close*(L: var BaseLexer)
## closes the base lexer. This closes `L`'s associated stream too.
-proc getCurrentLine*(L: TBaseLexer, marker: bool = true): string
+proc getCurrentLine*(L: BaseLexer, marker: bool = true): string
## retrieves the current line.
-proc getColNumber*(L: TBaseLexer, pos: int): int
+proc getColNumber*(L: BaseLexer, pos: int): int
## retrieves the current column.
-proc handleCR*(L: var TBaseLexer, pos: int): int
+proc handleCR*(L: var BaseLexer, pos: int): int
## Call this if you scanned over '\c' in the buffer; it returns the the
## position to continue the scanning from. `pos` must be the position
## of the '\c'.
-proc handleLF*(L: var TBaseLexer, pos: int): int
+proc handleLF*(L: var BaseLexer, pos: int): int
## Call this if you scanned over '\L' in the buffer; it returns the the
## position to continue the scanning from. `pos` must be the position
## of the '\L'.
@@ -64,11 +64,11 @@ proc handleLF*(L: var TBaseLexer, pos: int): int
const
chrSize = sizeof(char)
-proc close(L: var TBaseLexer) =
+proc close(L: var BaseLexer) =
dealloc(L.buf)
close(L.input)
-proc fillBuffer(L: var TBaseLexer) =
+proc fillBuffer(L: var BaseLexer) =
var
charsRead, toCopy, s: int # all are in characters,
# not bytes (in case this
@@ -113,7 +113,7 @@ proc fillBuffer(L: var TBaseLexer) =
break
s = L.bufLen - 1
-proc fillBaseLexer(L: var TBaseLexer, pos: int): int =
+proc fillBaseLexer(L: var BaseLexer, pos: int): int =
assert(pos <= L.sentinel)
if pos < L.sentinel:
result = pos + 1 # nothing to do
@@ -123,24 +123,24 @@ proc fillBaseLexer(L: var TBaseLexer, pos: int): int =
result = 0
L.lineStart = result
-proc handleCR(L: var TBaseLexer, pos: int): int =
+proc handleCR(L: var BaseLexer, pos: int): int =
assert(L.buf[pos] == '\c')
inc(L.lineNumber)
result = fillBaseLexer(L, pos)
if L.buf[result] == '\L':
result = fillBaseLexer(L, result)
-proc handleLF(L: var TBaseLexer, pos: int): int =
+proc handleLF(L: var BaseLexer, pos: int): int =
assert(L.buf[pos] == '\L')
inc(L.lineNumber)
result = fillBaseLexer(L, pos) #L.lastNL := result-1; // BUGFIX: was: result;
-proc skipUtf8Bom(L: var TBaseLexer) =
+proc skipUtf8Bom(L: var BaseLexer) =
if (L.buf[0] == '\xEF') and (L.buf[1] == '\xBB') and (L.buf[2] == '\xBF'):
inc(L.bufpos, 3)
inc(L.lineStart, 3)
-proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) =
+proc open(L: var BaseLexer, input: Stream, bufLen: int = 8192) =
assert(bufLen > 0)
assert(input != nil)
L.input = input
@@ -153,10 +153,10 @@ proc open(L: var TBaseLexer, input: PStream, bufLen: int = 8192) =
fillBuffer(L)
skipUtf8Bom(L)
-proc getColNumber(L: TBaseLexer, pos: int): int =
+proc getColNumber(L: BaseLexer, pos: int): int =
result = abs(pos - L.lineStart)
-proc getCurrentLine(L: TBaseLexer, marker: bool = true): string =
+proc getCurrentLine(L: BaseLexer, marker: bool = true): string =
var i: int
result = ""
i = L.lineStart
diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim
index cc7575563..f4f46e4f4 100644
--- a/lib/pure/parsexml.nim
+++ b/lib/pure/parsexml.nim
@@ -90,7 +90,7 @@ type
reportWhitespace, ## report whitespace
reportComments ## report comments
- XmlParser* = object of TBaseLexer ## the parser object.
+ XmlParser* = object of BaseLexer ## the parser object.
a, b, c: string
kind: XmlEventKind
err: XmlErrorKind
@@ -134,93 +134,93 @@ proc close*(my: var XmlParser) {.inline.} =
## closes the parser `my` and its associated input stream.
lexbase.close(my)
-proc kind*(my: TXmlParser): TXmlEventKind {.inline.} =
+proc kind*(my: XmlParser): XmlEventKind {.inline.} =
## returns the current event type for the XML parser
return my.kind
-proc charData*(my: TXmlParser): string {.inline.} =
+proc charData*(my: XmlParser): string {.inline.} =
## returns the character data for the events: ``xmlCharData``,
## ``xmlWhitespace``, ``xmlComment``, ``xmlCData``, ``xmlSpecial``
assert(my.kind in {xmlCharData, xmlWhitespace, xmlComment, xmlCData,
xmlSpecial})
return my.a
-proc elementName*(my: TXmlParser): string {.inline.} =
+proc elementName*(my: XmlParser): string {.inline.} =
## returns the element name for the events: ``xmlElementStart``,
## ``xmlElementEnd``, ``xmlElementOpen``
assert(my.kind in {xmlElementStart, xmlElementEnd, xmlElementOpen})
return my.a
-proc entityName*(my: TXmlParser): string {.inline.} =
+proc entityName*(my: XmlParser): string {.inline.} =
## returns the entity name for the event: ``xmlEntity``
assert(my.kind == xmlEntity)
return my.a
-proc attrKey*(my: TXmlParser): string {.inline.} =
+proc attrKey*(my: XmlParser): string {.inline.} =
## returns the attribute key for the event ``xmlAttribute``
assert(my.kind == xmlAttribute)
return my.a
-proc attrValue*(my: TXmlParser): string {.inline.} =
+proc attrValue*(my: XmlParser): string {.inline.} =
## returns the attribute value for the event ``xmlAttribute``
assert(my.kind == xmlAttribute)
return my.b
-proc PIName*(my: TXmlParser): string {.inline.} =
+proc PIName*(my: XmlParser): string {.inline.} =
## returns the processing instruction name for the event ``xmlPI``
assert(my.kind == xmlPI)
return my.a
-proc PIRest*(my: TXmlParser): string {.inline.} =
+proc PIRest*(my: XmlParser): string {.inline.} =
## returns the rest of the processing instruction for the event ``xmlPI``
assert(my.kind == xmlPI)
return my.b
-proc rawData*(my: TXmlParser): string {.inline.} =
+proc rawData*(my: XmlParser): string {.inline.} =
## returns the underlying 'data' string by reference.
## This is only used for speed hacks.
shallowCopy(result, my.a)
-proc rawData2*(my: TXmlParser): string {.inline.} =
+proc rawData2*(my: XmlParser): string {.inline.} =
## returns the underlying second 'data' string by reference.
## This is only used for speed hacks.
shallowCopy(result, my.b)
-proc getColumn*(my: TXmlParser): int {.inline.} =
+proc getColumn*(my: XmlParser): int {.inline.} =
## get the current column the parser has arrived at.
- result = getColNumber(my, my.bufPos)
+ result = getColNumber(my, my.bufpos)
-proc getLine*(my: TXmlParser): int {.inline.} =
+proc getLine*(my: XmlParser): int {.inline.} =
## get the current line the parser has arrived at.
- result = my.linenumber
+ result = my.lineNumber
-proc getFilename*(my: TXmlParser): string {.inline.} =
+proc getFilename*(my: XmlParser): string {.inline.} =
## get the filename of the file that the parser processes.
result = my.filename
-proc errorMsg*(my: TXmlParser): string =
+proc errorMsg*(my: XmlParser): string =
## returns a helpful error message for the event ``xmlError``
assert(my.kind == xmlError)
result = "$1($2, $3) Error: $4" % [
my.filename, $getLine(my), $getColumn(my), errorMessages[my.err]]
-proc errorMsgExpected*(my: TXmlParser, tag: string): string =
+proc errorMsgExpected*(my: XmlParser, tag: string): string =
## returns an error message " expected" in the same format as the
## other error messages
result = "$1($2, $3) Error: $4" % [
my.filename, $getLine(my), $getColumn(my), "<$1> expected" % tag]
-proc errorMsg*(my: TXmlParser, msg: string): string =
+proc errorMsg*(my: XmlParser, msg: string): string =
## returns an error message with text `msg` in the same format as the
## other error messages
result = "$1($2, $3) Error: $4" % [
my.filename, $getLine(my), $getColumn(my), msg]
-proc markError(my: var TXmlParser, kind: TXmlError) {.inline.} =
+proc markError(my: var XmlParser, kind: XmlErrorKind) {.inline.} =
my.err = kind
my.state = stateError
-proc parseCDATA(my: var TXMLParser) =
+proc parseCDATA(my: var XmlParser) =
var pos = my.bufpos + len("
Date: Thu, 28 Aug 2014 01:54:36 +0200
Subject: [PATCH 021/409] more modules updated
---
lib/pure/json.nim | 116 +++++++++++++++++++++---------------------
lib/pure/terminal.nim | 4 +-
lib/pure/unittest.nim | 4 +-
3 files changed, 62 insertions(+), 62 deletions(-)
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index b2c0db3d1..d90ddebf1 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -82,7 +82,7 @@ type
stateEof, stateStart, stateObject, stateArray, stateExpectArrayComma,
stateExpectObjectComma, stateExpectColon, stateExpectValue
- JsonParser* = object of TBaseLexer ## the parser object.
+ JsonParser* = object of BaseLexer ## the parser object.
a: string
tok: TTokKind
kind: JsonEventKind
@@ -119,7 +119,7 @@ const
"{", "}", "[", "]", ":", ","
]
-proc open*(my: var JsonParser, input: PStream, filename: string) =
+proc open*(my: var JsonParser, input: Stream, filename: string) =
## initializes the parser with an input stream. `Filename` is only used
## for nice error messages.
lexbase.open(my, input)
@@ -224,7 +224,7 @@ proc parseString(my: var JsonParser): TTokKind =
if handleHexChar(buf[pos], r): inc(pos)
if handleHexChar(buf[pos], r): inc(pos)
if handleHexChar(buf[pos], r): inc(pos)
- add(my.a, toUTF8(TRune(r)))
+ add(my.a, toUTF8(Rune(r)))
else:
# don't bother with the error
add(my.a, buf[pos])
@@ -402,7 +402,7 @@ proc next*(my: var JsonParser) =
case tk
of tkString, tkInt, tkFloat, tkTrue, tkFalse, tkNull:
my.state[i] = stateEof # expect EOF next!
- my.kind = TJsonEventKind(ord(tk))
+ my.kind = JsonEventKind(ord(tk))
of tkBracketLe:
my.state.add(stateArray) # we expect any
my.kind = jsonArrayStart
@@ -418,7 +418,7 @@ proc next*(my: var JsonParser) =
case tk
of tkString, tkInt, tkFloat, tkTrue, tkFalse, tkNull:
my.state.add(stateExpectColon)
- my.kind = TJsonEventKind(ord(tk))
+ my.kind = JsonEventKind(ord(tk))
of tkBracketLe:
my.state.add(stateExpectColon)
my.state.add(stateArray)
@@ -437,7 +437,7 @@ proc next*(my: var JsonParser) =
case tk
of tkString, tkInt, tkFloat, tkTrue, tkFalse, tkNull:
my.state.add(stateExpectArrayComma) # expect value next!
- my.kind = TJsonEventKind(ord(tk))
+ my.kind = JsonEventKind(ord(tk))
of tkBracketLe:
my.state.add(stateExpectArrayComma)
my.state.add(stateArray)
@@ -488,7 +488,7 @@ proc next*(my: var JsonParser) =
case tk
of tkString, tkInt, tkFloat, tkTrue, tkFalse, tkNull:
my.state[i] = stateExpectObjectComma
- my.kind = TJsonEventKind(ord(tk))
+ my.kind = JsonEventKind(ord(tk))
of tkBracketLe:
my.state[i] = stateExpectObjectComma
my.state.add(stateArray)
@@ -505,7 +505,7 @@ proc next*(my: var JsonParser) =
# ------------- higher level interface ---------------------------------------
type
- TJsonNodeKind* = enum ## possible JSON node types
+ JsonNodeKind* = enum ## possible JSON node types
JNull,
JBool,
JInt,
@@ -514,9 +514,9 @@ type
JObject,
JArray
- PJsonNode* = ref TJsonNode ## JSON node
- TJsonNode* {.final, pure, acyclic.} = object
- case kind*: TJsonNodeKind
+ JsonNode* = ref JsonNodeObj ## JSON node
+ JsonNodeObj* {.acyclic.} = object
+ case kind*: JsonNodeKind
of JString:
str*: string
of JInt:
@@ -528,104 +528,104 @@ type
of JNull:
nil
of JObject:
- fields*: seq[tuple[key: string, val: PJsonNode]]
+ fields*: seq[tuple[key: string, val: JsonNode]]
of JArray:
- elems*: seq[PJsonNode]
+ elems*: seq[JsonNode]
JsonParsingError* = object of ValueError ## is raised for a JSON error
{.deprecated: [EJsonParsingError: JsonParsingError, TJsonNode: JsonNodeObj,
PJsonNode: JsonNode, TJsonNodeKind: JsonNodeKind].}
-proc raiseParseErr*(p: TJsonParser, msg: string) {.noinline, noreturn.} =
+proc raiseParseErr*(p: JsonParser, msg: string) {.noinline, noreturn.} =
## raises an `EJsonParsingError` exception.
- raise newException(EJsonParsingError, errorMsgExpected(p, msg))
+ raise newException(JsonParsingError, errorMsgExpected(p, msg))
-proc newJString*(s: string): PJsonNode =
+proc newJString*(s: string): JsonNode =
## Creates a new `JString PJsonNode`.
new(result)
result.kind = JString
result.str = s
-proc newJStringMove(s: string): PJsonNode =
+proc newJStringMove(s: string): JsonNode =
new(result)
result.kind = JString
shallowCopy(result.str, s)
-proc newJInt*(n: BiggestInt): PJsonNode =
+proc newJInt*(n: BiggestInt): JsonNode =
## Creates a new `JInt PJsonNode`.
new(result)
result.kind = JInt
result.num = n
-proc newJFloat*(n: float): PJsonNode =
+proc newJFloat*(n: float): JsonNode =
## Creates a new `JFloat PJsonNode`.
new(result)
result.kind = JFloat
result.fnum = n
-proc newJBool*(b: bool): PJsonNode =
+proc newJBool*(b: bool): JsonNode =
## Creates a new `JBool PJsonNode`.
new(result)
result.kind = JBool
result.bval = b
-proc newJNull*(): PJsonNode =
+proc newJNull*(): JsonNode =
## Creates a new `JNull PJsonNode`.
new(result)
-proc newJObject*(): PJsonNode =
+proc newJObject*(): JsonNode =
## Creates a new `JObject PJsonNode`
new(result)
result.kind = JObject
result.fields = @[]
-proc newJArray*(): PJsonNode =
+proc newJArray*(): JsonNode =
## Creates a new `JArray PJsonNode`
new(result)
result.kind = JArray
result.elems = @[]
-proc `%`*(s: string): PJsonNode =
+proc `%`*(s: string): JsonNode =
## Generic constructor for JSON data. Creates a new `JString PJsonNode`.
new(result)
result.kind = JString
result.str = s
-proc `%`*(n: BiggestInt): PJsonNode =
+proc `%`*(n: BiggestInt): JsonNode =
## Generic constructor for JSON data. Creates a new `JInt PJsonNode`.
new(result)
result.kind = JInt
result.num = n
-proc `%`*(n: float): PJsonNode =
+proc `%`*(n: float): JsonNode =
## Generic constructor for JSON data. Creates a new `JFloat PJsonNode`.
new(result)
result.kind = JFloat
result.fnum = n
-proc `%`*(b: bool): PJsonNode =
+proc `%`*(b: bool): JsonNode =
## Generic constructor for JSON data. Creates a new `JBool PJsonNode`.
new(result)
result.kind = JBool
result.bval = b
-proc `%`*(keyVals: openArray[tuple[key: string, val: PJsonNode]]): PJsonNode =
+proc `%`*(keyVals: openArray[tuple[key: string, val: JsonNode]]): JsonNode =
## Generic constructor for JSON data. Creates a new `JObject PJsonNode`
new(result)
result.kind = JObject
newSeq(result.fields, keyVals.len)
for i, p in pairs(keyVals): result.fields[i] = p
-proc `%`*(elements: openArray[PJsonNode]): PJsonNode =
+proc `%`*(elements: openArray[JsonNode]): JsonNode =
## Generic constructor for JSON data. Creates a new `JArray PJsonNode`
new(result)
result.kind = JArray
newSeq(result.elems, elements.len)
for i, p in pairs(elements): result.elems[i] = p
-proc `==`* (a,b: PJsonNode): bool =
+proc `==`* (a,b: JsonNode): bool =
## Check two nodes for equality
if a.isNil:
if b.isNil: return true
@@ -649,7 +649,7 @@ proc `==`* (a,b: PJsonNode): bool =
of JObject:
a.fields == b.fields
-proc hash* (n:PJsonNode): THash =
+proc hash* (n:JsonNode): THash =
## Compute the hash for a JSON node
case n.kind
of JArray:
@@ -667,7 +667,7 @@ proc hash* (n:PJsonNode): THash =
of JNull:
result = hash(0)
-proc len*(n: PJsonNode): int =
+proc len*(n: JsonNode): int =
## If `n` is a `JArray`, it returns the number of elements.
## If `n` is a `JObject`, it returns the number of pairs.
## Else it returns 0.
@@ -676,7 +676,7 @@ proc len*(n: PJsonNode): int =
of JObject: result = n.fields.len
else: discard
-proc `[]`*(node: PJsonNode, name: string): PJsonNode =
+proc `[]`*(node: JsonNode, name: string): JsonNode =
## Gets a field from a `JObject`, which must not be nil.
## If the value at `name` does not exist, returns nil
assert(not isNil(node))
@@ -686,35 +686,35 @@ proc `[]`*(node: PJsonNode, name: string): PJsonNode =
return item
return nil
-proc `[]`*(node: PJsonNode, index: int): PJsonNode =
+proc `[]`*(node: JsonNode, index: int): JsonNode =
## Gets the node at `index` in an Array. Result is undefined if `index`
## is out of bounds
assert(not isNil(node))
assert(node.kind == JArray)
return node.elems[index]
-proc hasKey*(node: PJsonNode, key: string): bool =
+proc hasKey*(node: JsonNode, key: string): bool =
## Checks if `key` exists in `node`.
assert(node.kind == JObject)
for k, item in items(node.fields):
if k == key: return true
-proc existsKey*(node: PJsonNode, key: string): bool {.deprecated.} = node.hasKey(key)
+proc existsKey*(node: JsonNode, key: string): bool {.deprecated.} = node.hasKey(key)
## Deprecated for `hasKey`
-proc add*(father, child: PJsonNode) =
+proc add*(father, child: JsonNode) =
## Adds `child` to a JArray node `father`.
assert father.kind == JArray
father.elems.add(child)
-proc add*(obj: PJsonNode, key: string, val: PJsonNode) =
+proc add*(obj: JsonNode, key: string, val: JsonNode) =
## Adds ``(key, val)`` pair to the JObject node `obj`. For speed
## reasons no check for duplicate keys is performed!
## But ``[]=`` performs the check.
assert obj.kind == JObject
obj.fields.add((key, val))
-proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) =
+proc `[]=`*(obj: JsonNode, key: string, val: JsonNode) =
## Sets a field from a `JObject`. Performs a check for duplicate keys.
assert(obj.kind == JObject)
for i in 0..obj.fields.len-1:
@@ -723,14 +723,14 @@ proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) =
return
obj.fields.add((key, val))
-proc `{}`*(node: PJsonNode, key: string): PJsonNode =
+proc `{}`*(node: JsonNode, key: string): JsonNode =
## Transverses the node and gets the given value. If any of the
## names does not exist, returns nil
result = node
if isNil(node): return nil
result = result[key]
-proc `{}=`*(node: PJsonNode, names: varargs[string], value: PJsonNode) =
+proc `{}=`*(node: JsonNode, names: varargs[string], value: JsonNode) =
## Transverses the node and tries to set the value at the given location
## to `value` If any of the names are missing, they are added
var node = node
@@ -740,7 +740,7 @@ proc `{}=`*(node: PJsonNode, names: varargs[string], value: PJsonNode) =
node = node[names[i]]
node[names[names.len-1]] = value
-proc delete*(obj: PJsonNode, key: string) =
+proc delete*(obj: JsonNode, key: string) =
## Deletes ``obj[key]`` preserving the order of the other (key, value)-pairs.
assert(obj.kind == JObject)
for i in 0..obj.fields.len-1:
@@ -749,7 +749,7 @@ proc delete*(obj: PJsonNode, key: string) =
return
raise newException(IndexError, "key not in object")
-proc copy*(p: PJsonNode): PJsonNode =
+proc copy*(p: JsonNode): JsonNode =
## Performs a deep copy of `a`.
case p.kind
of JString:
@@ -800,7 +800,7 @@ proc escapeJson*(s: string): string =
result.add(toHex(r, 4))
result.add("\"")
-proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = true,
+proc toPretty(result: var string, node: JsonNode, indent = 2, ml = true,
lstArr = false, currIndent = 0) =
case node.kind
of JObject:
@@ -855,34 +855,34 @@ proc toPretty(result: var string, node: PJsonNode, indent = 2, ml = true,
if lstArr: result.indent(currIndent)
result.add("null")
-proc pretty*(node: PJsonNode, indent = 2): string =
+proc pretty*(node: JsonNode, indent = 2): string =
## Converts `node` to its JSON Representation, with indentation and
## on multiple lines.
result = ""
toPretty(result, node, indent)
-proc `$`*(node: PJsonNode): string =
+proc `$`*(node: JsonNode): string =
## Converts `node` to its JSON Representation on one line.
result = ""
toPretty(result, node, 1, false)
-iterator items*(node: PJsonNode): PJsonNode =
+iterator items*(node: JsonNode): JsonNode =
## Iterator for the items of `node`. `node` has to be a JArray.
assert node.kind == JArray
for i in items(node.elems):
yield i
-iterator pairs*(node: PJsonNode): tuple[key: string, val: PJsonNode] =
+iterator pairs*(node: JsonNode): tuple[key: string, val: JsonNode] =
## Iterator for the child elements of `node`. `node` has to be a JObject.
assert node.kind == JObject
for key, val in items(node.fields):
yield (key, val)
-proc eat(p: var TJsonParser, tok: TTokKind) =
+proc eat(p: var JsonParser, tok: TTokKind) =
if p.tok == tok: discard getTok(p)
else: raiseParseErr(p, tokToStr[tok])
-proc parseJson(p: var TJsonParser): PJsonNode =
+proc parseJson(p: var JsonParser): JsonNode =
## Parses JSON from a JSON Parser `p`.
case p.tok
of tkString:
@@ -931,20 +931,20 @@ proc parseJson(p: var TJsonParser): PJsonNode =
raiseParseErr(p, "{")
when not defined(js):
- proc parseJson*(s: PStream, filename: string): PJsonNode =
+ proc parseJson*(s: Stream, filename: string): JsonNode =
## Parses from a stream `s` into a `PJsonNode`. `filename` is only needed
## for nice error messages.
- var p: TJsonParser
+ var p: JsonParser
p.open(s, filename)
discard getTok(p) # read first token
result = p.parseJson()
p.close()
- proc parseJson*(buffer: string): PJsonNode =
+ proc parseJson*(buffer: string): JsonNode =
## Parses JSON from `buffer`.
result = parseJson(newStringStream(buffer), "input")
- proc parseFile*(filename: string): PJsonNode =
+ proc parseFile*(filename: string): JsonNode =
## Parses `file` into a `PJsonNode`.
var stream = newFileStream(filename, fmRead)
if stream == nil:
@@ -1062,8 +1062,8 @@ when isMainModule:
echo(pretty(parsed2))
try:
echo(parsed["key2"][12123])
- raise newException(EInvalidValue, "That line was expected to fail")
- except EInvalidIndex: echo()
+ raise newException(ValueError, "That line was expected to fail")
+ except IndexError: echo()
let testJson = parseJson"""{ "a": [1, 2, 3, 4], "b": "asd" }"""
# nil passthrough
@@ -1075,12 +1075,12 @@ when isMainModule:
try:
let a = testJson["a"][9]
assert(false, "EInvalidIndex not thrown")
- except EInvalidIndex:
+ except IndexError:
discard
try:
let a = testJson["a"][-1]
assert(false, "EInvalidIndex not thrown")
- except EInvalidIndex:
+ except IndexError:
discard
try:
assert(testJson["a"][0].num == 1, "Index doesn't correspond to its value")
diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim
index 0ebe8a39e..19635ee68 100644
--- a/lib/pure/terminal.nim
+++ b/lib/pure/terminal.nim
@@ -216,7 +216,7 @@ when not defined(windows):
gFG = 0
gBG = 0
-proc setStyle*(style: set[TStyle]) =
+proc setStyle*(style: set[Style]) =
## sets the terminal style
when defined(windows):
var a = 0'i16
@@ -229,7 +229,7 @@ proc setStyle*(style: set[TStyle]) =
for s in items(style):
stdout.write("\e[" & $ord(s) & 'm')
-proc writeStyled*(txt: string, style: set[TStyle] = {styleBright}) =
+proc writeStyled*(txt: string, style: set[Style] = {styleBright}) =
## writes the text `txt` in a given `style`.
when defined(windows):
var old = getAttributes()
diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim
index f26d8c3e6..372c02f4e 100644
--- a/lib/pure/unittest.nim
+++ b/lib/pure/unittest.nim
@@ -58,7 +58,7 @@ template suite*(name: expr, body: stmt): stmt {.immediate, dirty.} =
proc testDone(name: string, s: TestStatus) =
if s == FAILED:
- program_result += 1
+ programResult += 1
if OutputLevel != PRINT_NONE and (OutputLevel == PRINT_ALL or s == FAILED):
template rawPrint() = echo("[", $s, "] ", name, "\n")
@@ -105,7 +105,7 @@ template fail* =
when declared(TestStatusIMPL):
TestStatusIMPL = FAILED
else:
- program_result += 1
+ programResult += 1
checkpoints = @[]
From 42f5a838a396a05c8931c41498ff8026620d4f30 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 02:06:11 +0200
Subject: [PATCH 022/409] more modules updated
---
lib/core/typeinfo.nim | 148 +++----
lib/pure/collections/intsets.nim | 26 +-
lib/pure/logging.nim | 40 +-
lib/pure/marshal.nim | 638 +++++++++++++++----------------
4 files changed, 426 insertions(+), 426 deletions(-)
diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim
index 8df1b3dfb..848388c2b 100644
--- a/lib/core/typeinfo.nim
+++ b/lib/core/typeinfo.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Dominik Picheta, Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -68,20 +68,20 @@ type
const
GenericSeqSize = (2 * sizeof(int))
-proc genericAssign(dest, src: Pointer, mt: PNimType) {.importCompilerProc.}
-proc genericShallowAssign(dest, src: Pointer, mt: PNimType) {.
+proc genericAssign(dest, src: pointer, mt: PNimType) {.importCompilerProc.}
+proc genericShallowAssign(dest, src: pointer, mt: PNimType) {.
importCompilerProc.}
proc incrSeq(seq: PGenSeq, elemSize: int): PGenSeq {.importCompilerProc.}
proc newObj(typ: PNimType, size: int): pointer {.importCompilerProc.}
proc newSeq(typ: PNimType, len: int): pointer {.importCompilerProc.}
-proc objectInit(dest: Pointer, typ: PNimType) {.importCompilerProc.}
+proc objectInit(dest: pointer, typ: PNimType) {.importCompilerProc.}
-template `+!!`(a, b: expr): expr = cast[pointer](cast[TAddress](a) + b)
+template `+!!`(a, b: expr): expr = cast[pointer](cast[ByteAddress](a) + b)
-proc getDiscriminant(aa: Pointer, n: ptr TNimNode): int =
+proc getDiscriminant(aa: pointer, n: ptr TNimNode): int =
assert(n.kind == nkCase)
var d: int
- var a = cast[TAddress](aa)
+ var a = cast[ByteAddress](aa)
case n.typ.size
of 1: d = ze(cast[ptr int8](a +% n.offset)[])
of 2: d = ze(cast[ptr int16](a +% n.offset)[])
@@ -89,7 +89,7 @@ proc getDiscriminant(aa: Pointer, n: ptr TNimNode): int =
else: assert(false)
return d
-proc selectBranch(aa: Pointer, n: ptr TNimNode): ptr TNimNode =
+proc selectBranch(aa: pointer, n: ptr TNimNode): ptr TNimNode =
var discr = getDiscriminant(aa, n)
if discr <% n.len:
result = n.sons[discr]
@@ -174,14 +174,14 @@ proc `[]`*(x: TAny, i: int): TAny =
of tyArray:
var bs = x.rawType.base.size
if i >=% x.rawType.size div bs:
- raise newException(EInvalidIndex, "index out of bounds")
+ raise newException(IndexError, "index out of bounds")
return newAny(x.value +!! i*bs, x.rawType.base)
of tySequence:
var s = cast[ppointer](x.value)[]
- if s == nil: raise newException(EInvalidValue, "sequence is nil")
+ if s == nil: raise newException(ValueError, "sequence is nil")
var bs = x.rawType.base.size
if i >=% cast[PGenSeq](s).len:
- raise newException(EInvalidIndex, "index out of bounds")
+ raise newException(IndexError, "index out of bounds")
return newAny(s +!! (GenericSeqSize+i*bs), x.rawType.base)
else: assert false
@@ -191,15 +191,15 @@ proc `[]=`*(x: TAny, i: int, y: TAny) =
of tyArray:
var bs = x.rawType.base.size
if i >=% x.rawType.size div bs:
- raise newException(EInvalidIndex, "index out of bounds")
+ raise newException(IndexError, "index out of bounds")
assert y.rawType == x.rawType.base
genericAssign(x.value +!! i*bs, y.value, y.rawType)
of tySequence:
var s = cast[ppointer](x.value)[]
- if s == nil: raise newException(EInvalidValue, "sequence is nil")
+ if s == nil: raise newException(ValueError, "sequence is nil")
var bs = x.rawType.base.size
if i >=% cast[PGenSeq](s).len:
- raise newException(EInvalidIndex, "index out of bounds")
+ raise newException(IndexError, "index out of bounds")
assert y.rawType == x.rawType.base
genericAssign(s +!! (GenericSeqSize+i*bs), y.value, y.rawType)
else: assert false
@@ -276,7 +276,7 @@ proc cmpIgnoreStyle(a, b: cstring): int {.noSideEffect.} =
else: result = c
var i = 0
var j = 0
- while True:
+ while true:
while a[i] == '_': inc(i)
while b[j] == '_': inc(j) # BUGFIX: typo
var aa = toLower(a[i])
@@ -311,12 +311,12 @@ proc `[]=`*(x: TAny, fieldName: string, value: TAny) =
when false:
if x.rawType.kind == tyObject: t = cast[ptr PNimType](x.value)[]
assert x.rawType.kind in {tyTuple, tyObject}
- var n = getFieldNode(x.value, t.node, fieldname)
+ var n = getFieldNode(x.value, t.node, fieldName)
if n != nil:
assert n.typ == value.rawType
genericAssign(x.value +!! n.offset, value.value, value.rawType)
else:
- raise newException(EInvalidValue, "invalid field name: " & fieldName)
+ raise newException(ValueError, "invalid field name: " & fieldName)
proc `[]`*(x: TAny, fieldName: string): TAny =
## gets a field of `x`; `x` represents an object or a tuple.
@@ -325,80 +325,80 @@ proc `[]`*(x: TAny, fieldName: string): TAny =
when false:
if x.rawType.kind == tyObject: t = cast[ptr PNimType](x.value)[]
assert x.rawType.kind in {tyTuple, tyObject}
- var n = getFieldNode(x.value, t.node, fieldname)
+ var n = getFieldNode(x.value, t.node, fieldName)
if n != nil:
result.value = x.value +!! n.offset
result.rawType = n.typ
else:
- raise newException(EInvalidValue, "invalid field name: " & fieldName)
+ raise newException(ValueError, "invalid field name: " & fieldName)
proc `[]`*(x: TAny): TAny =
## dereference operation for the any `x` that represents a ptr or a ref.
- assert x.rawtype.kind in {tyRef, tyPtr}
+ assert x.rawType.kind in {tyRef, tyPtr}
result.value = cast[ppointer](x.value)[]
result.rawType = x.rawType.base
proc `[]=`*(x, y: TAny) =
## dereference operation for the any `x` that represents a ptr or a ref.
- assert x.rawtype.kind in {tyRef, tyPtr}
+ assert x.rawType.kind in {tyRef, tyPtr}
assert y.rawType == x.rawType.base
genericAssign(cast[ppointer](x.value)[], y.value, y.rawType)
proc getInt*(x: TAny): int =
## retrieve the int value out of `x`. `x` needs to represent an int.
- assert skipRange(x.rawtype).kind == tyInt
+ assert skipRange(x.rawType).kind == tyInt
result = cast[ptr int](x.value)[]
proc getInt8*(x: TAny): int8 =
## retrieve the int8 value out of `x`. `x` needs to represent an int8.
- assert skipRange(x.rawtype).kind == tyInt8
+ assert skipRange(x.rawType).kind == tyInt8
result = cast[ptr int8](x.value)[]
proc getInt16*(x: TAny): int16 =
## retrieve the int16 value out of `x`. `x` needs to represent an int16.
- assert skipRange(x.rawtype).kind == tyInt16
+ assert skipRange(x.rawType).kind == tyInt16
result = cast[ptr int16](x.value)[]
proc getInt32*(x: TAny): int32 =
## retrieve the int32 value out of `x`. `x` needs to represent an int32.
- assert skipRange(x.rawtype).kind == tyInt32
+ assert skipRange(x.rawType).kind == tyInt32
result = cast[ptr int32](x.value)[]
proc getInt64*(x: TAny): int64 =
## retrieve the int64 value out of `x`. `x` needs to represent an int64.
- assert skipRange(x.rawtype).kind == tyInt64
+ assert skipRange(x.rawType).kind == tyInt64
result = cast[ptr int64](x.value)[]
-proc getBiggestInt*(x: TAny): biggestInt =
+proc getBiggestInt*(x: TAny): BiggestInt =
## retrieve the integer value out of `x`. `x` needs to represent
## some integer, a bool, a char, an enum or a small enough bit set.
- ## The value might be sign-extended to ``biggestInt``.
- var t = skipRange(x.rawtype)
+ ## The value might be sign-extended to ``BiggestInt``.
+ var t = skipRange(x.rawType)
case t.kind
- of tyInt: result = biggestInt(cast[ptr int](x.value)[])
- of tyInt8: result = biggestInt(cast[ptr int8](x.value)[])
- of tyInt16: result = biggestInt(cast[ptr int16](x.value)[])
- of tyInt32: result = biggestInt(cast[ptr int32](x.value)[])
- of tyInt64, tyUInt64: result = biggestInt(cast[ptr int64](x.value)[])
- of tyBool: result = biggestInt(cast[ptr bool](x.value)[])
- of tyChar: result = biggestInt(cast[ptr char](x.value)[])
+ of tyInt: result = BiggestInt(cast[ptr int](x.value)[])
+ of tyInt8: result = BiggestInt(cast[ptr int8](x.value)[])
+ of tyInt16: result = BiggestInt(cast[ptr int16](x.value)[])
+ of tyInt32: result = BiggestInt(cast[ptr int32](x.value)[])
+ of tyInt64, tyUInt64: result = BiggestInt(cast[ptr int64](x.value)[])
+ of tyBool: result = BiggestInt(cast[ptr bool](x.value)[])
+ of tyChar: result = BiggestInt(cast[ptr char](x.value)[])
of tyEnum, tySet:
case t.size
of 1: result = ze64(cast[ptr int8](x.value)[])
of 2: result = ze64(cast[ptr int16](x.value)[])
- of 4: result = biggestInt(cast[ptr int32](x.value)[])
- of 8: result = biggestInt(cast[ptr int64](x.value)[])
+ of 4: result = BiggestInt(cast[ptr int32](x.value)[])
+ of 8: result = BiggestInt(cast[ptr int64](x.value)[])
else: assert false
- of tyUInt: result = biggestInt(cast[ptr uint](x.value)[])
- of tyUInt8: result = biggestInt(cast[ptr uint8](x.value)[])
- of tyUInt16: result = biggestInt(cast[ptr uint16](x.value)[])
- of tyUInt32: result = biggestInt(cast[ptr uint32](x.value)[])
+ of tyUInt: result = BiggestInt(cast[ptr uint](x.value)[])
+ of tyUInt8: result = BiggestInt(cast[ptr uint8](x.value)[])
+ of tyUInt16: result = BiggestInt(cast[ptr uint16](x.value)[])
+ of tyUInt32: result = BiggestInt(cast[ptr uint32](x.value)[])
else: assert false
-proc setBiggestInt*(x: TAny, y: biggestInt) =
+proc setBiggestInt*(x: TAny, y: BiggestInt) =
## sets the integer value of `x`. `x` needs to represent
## some integer, a bool, a char, an enum or a small enough bit set.
- var t = skipRange(x.rawtype)
+ var t = skipRange(x.rawType)
case t.kind
of tyInt: cast[ptr int](x.value)[] = int(y)
of tyInt8: cast[ptr int8](x.value)[] = int8(y)
@@ -422,37 +422,37 @@ proc setBiggestInt*(x: TAny, y: biggestInt) =
proc getUInt*(x: TAny): uint =
## retrieve the uint value out of `x`, `x` needs to represent an uint.
- assert skipRange(x.rawtype).kind == tyUInt
+ assert skipRange(x.rawType).kind == tyUInt
result = cast[ptr uint](x.value)[]
proc getUInt8*(x: TAny): uint8 =
## retrieve the uint8 value out of `x`, `x` needs to represent an
## uint8.
- assert skipRange(x.rawtype).kind == tyUInt8
+ assert skipRange(x.rawType).kind == tyUInt8
result = cast[ptr uint8](x.value)[]
proc getUInt16*(x: TAny): uint16 =
## retrieve the uint16 value out of `x`, `x` needs to represent an
## uint16.
- assert skipRange(x.rawtype).kind == tyUInt16
+ assert skipRange(x.rawType).kind == tyUInt16
result = cast[ptr uint16](x.value)[]
proc getUInt32*(x: TAny): uint32 =
## retrieve the uint32 value out of `x`, `x` needs to represent an
## uint32.
- assert skipRange(x.rawtype).kind == tyUInt32
+ assert skipRange(x.rawType).kind == tyUInt32
result = cast[ptr uint32](x.value)[]
proc getUInt64*(x: TAny): uint64 =
## retrieve the uint64 value out of `x`, `x` needs to represent an
## uint64.
- assert skipRange(x.rawtype).kind == tyUInt64
+ assert skipRange(x.rawType).kind == tyUInt64
result = cast[ptr uint64](x.value)[]
proc getBiggestUint*(x: TAny): uint64 =
## retrieve the unsigned integer value out of `x`. `x` needs to
## represent an unsigned integer.
- var t = skipRange(x.rawtype)
+ var t = skipRange(x.rawType)
case t.kind
of tyUInt: result = uint64(cast[ptr uint](x.value)[])
of tyUInt8: result = uint64(cast[ptr uint8](x.value)[])
@@ -464,7 +464,7 @@ proc getBiggestUint*(x: TAny): uint64 =
proc setBiggestUint*(x: TAny; y: uint64) =
## sets the unsigned integer value of `c`. `c` needs to represent an
## unsigned integer.
- var t = skipRange(x.rawtype)
+ var t = skipRange(x.rawType)
case t.kind:
of tyUInt: cast[ptr uint](x.value)[] = uint(y)
of tyUInt8: cast[ptr uint8](x.value)[] = uint8(y)
@@ -475,13 +475,13 @@ proc setBiggestUint*(x: TAny; y: uint64) =
proc getChar*(x: TAny): char =
## retrieve the char value out of `x`. `x` needs to represent a char.
- var t = skipRange(x.rawtype)
+ var t = skipRange(x.rawType)
assert t.kind == tyChar
result = cast[ptr char](x.value)[]
proc getBool*(x: TAny): bool =
## retrieve the bool value out of `x`. `x` needs to represent a bool.
- var t = skipRange(x.rawtype)
+ var t = skipRange(x.rawType)
assert t.kind == tyBool
result = cast[ptr bool](x.value)[]
@@ -495,7 +495,7 @@ proc getEnumOrdinal*(x: TAny, name: string): int =
## gets the enum field ordinal from `name`. `x` needs to represent an enum
## but is only used to access the type information. In case of an error
## ``low(int)`` is returned.
- var typ = skipRange(x.rawtype)
+ var typ = skipRange(x.rawType)
assert typ.kind == tyEnum
var n = typ.node
var s = n.sons
@@ -511,7 +511,7 @@ proc getEnumField*(x: TAny, ordinalValue: int): string =
## gets the enum field name as a string. `x` needs to represent an enum
## but is only used to access the type information. The field name of
## `ordinalValue` is returned.
- var typ = skipRange(x.rawtype)
+ var typ = skipRange(x.rawType)
assert typ.kind == tyEnum
var e = ordinalValue
if ntfEnumHole notin typ.flags:
@@ -531,51 +531,51 @@ proc getEnumField*(x: TAny): string =
proc getFloat*(x: TAny): float =
## retrieve the float value out of `x`. `x` needs to represent an float.
- assert skipRange(x.rawtype).kind == tyFloat
+ assert skipRange(x.rawType).kind == tyFloat
result = cast[ptr float](x.value)[]
proc getFloat32*(x: TAny): float32 =
## retrieve the float32 value out of `x`. `x` needs to represent an float32.
- assert skipRange(x.rawtype).kind == tyFloat32
+ assert skipRange(x.rawType).kind == tyFloat32
result = cast[ptr float32](x.value)[]
proc getFloat64*(x: TAny): float64 =
## retrieve the float64 value out of `x`. `x` needs to represent an float64.
- assert skipRange(x.rawtype).kind == tyFloat64
+ assert skipRange(x.rawType).kind == tyFloat64
result = cast[ptr float64](x.value)[]
-proc getBiggestFloat*(x: TAny): biggestFloat =
+proc getBiggestFloat*(x: TAny): BiggestFloat =
## retrieve the float value out of `x`. `x` needs to represent
- ## some float. The value is extended to ``biggestFloat``.
- case skipRange(x.rawtype).kind
- of tyFloat: result = biggestFloat(cast[ptr Float](x.value)[])
- of tyFloat32: result = biggestFloat(cast[ptr Float32](x.value)[])
- of tyFloat64: result = biggestFloat(cast[ptr Float64](x.value)[])
+ ## some float. The value is extended to ``BiggestFloat``.
+ case skipRange(x.rawType).kind
+ of tyFloat: result = BiggestFloat(cast[ptr float](x.value)[])
+ of tyFloat32: result = BiggestFloat(cast[ptr float32](x.value)[])
+ of tyFloat64: result = BiggestFloat(cast[ptr float64](x.value)[])
else: assert false
-proc setBiggestFloat*(x: TAny, y: biggestFloat) =
+proc setBiggestFloat*(x: TAny, y: BiggestFloat) =
## sets the float value of `x`. `x` needs to represent
## some float.
- case skipRange(x.rawtype).kind
- of tyFloat: cast[ptr Float](x.value)[] = y
- of tyFloat32: cast[ptr Float32](x.value)[] = y.float32
- of tyFloat64: cast[ptr Float64](x.value)[] = y
+ case skipRange(x.rawType).kind
+ of tyFloat: cast[ptr float](x.value)[] = y
+ of tyFloat32: cast[ptr float32](x.value)[] = y.float32
+ of tyFloat64: cast[ptr float64](x.value)[] = y
else: assert false
proc getString*(x: TAny): string =
## retrieve the string value out of `x`. `x` needs to represent a string.
- assert x.rawtype.kind == tyString
+ assert x.rawType.kind == tyString
if not isNil(cast[ptr pointer](x.value)[]):
result = cast[ptr string](x.value)[]
proc setString*(x: TAny, y: string) =
## sets the string value of `x`. `x` needs to represent a string.
- assert x.rawtype.kind == tyString
+ assert x.rawType.kind == tyString
cast[ptr string](x.value)[] = y
proc getCString*(x: TAny): cstring =
## retrieve the cstring value out of `x`. `x` needs to represent a cstring.
- assert x.rawtype.kind == tyCString
+ assert x.rawType.kind == tyCString
result = cast[ptr cstring](x.value)[]
proc assign*(x, y: TAny) =
@@ -587,7 +587,7 @@ proc assign*(x, y: TAny) =
iterator elements*(x: TAny): int =
## iterates over every element of `x` that represents a Nimrod bitset.
assert x.rawType.kind == tySet
- var typ = x.rawtype
+ var typ = x.rawType
var p = x.value
# "typ.slots.len" field is for sets the "first" field
var u: int64
@@ -609,7 +609,7 @@ iterator elements*(x: TAny): int =
proc inclSetElement*(x: TAny, elem: int) =
## includes an element `elem` in `x`. `x` needs to represent a Nimrod bitset.
assert x.rawType.kind == tySet
- var typ = x.rawtype
+ var typ = x.rawType
var p = x.value
# "typ.slots.len" field is for sets the "first" field
var e = elem - typ.node.len
diff --git a/lib/pure/collections/intsets.nim b/lib/pure/collections/intsets.nim
index 678c428c1..5d9c3f445 100644
--- a/lib/pure/collections/intsets.nim
+++ b/lib/pure/collections/intsets.nim
@@ -51,7 +51,7 @@ proc mustRehash(length, counter: int): bool {.inline.} =
proc nextTry(h, maxHash: THash): THash {.inline.} =
result = ((5 * h) + 1) and maxHash
-proc intSetGet(t: TIntSet, key: int): PTrunk =
+proc intSetGet(t: IntSet, key: int): PTrunk =
var h = key and t.max
while t.data[h] != nil:
if t.data[h].key == key:
@@ -59,7 +59,7 @@ proc intSetGet(t: TIntSet, key: int): PTrunk =
h = nextTry(h, t.max)
result = nil
-proc intSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) =
+proc intSetRawInsert(t: IntSet, data: var TTrunkSeq, desc: PTrunk) =
var h = desc.key and t.max
while data[h] != nil:
assert(data[h] != desc)
@@ -67,7 +67,7 @@ proc intSetRawInsert(t: TIntSet, data: var TTrunkSeq, desc: PTrunk) =
assert(data[h] == nil)
data[h] = desc
-proc intSetEnlarge(t: var TIntSet) =
+proc intSetEnlarge(t: var IntSet) =
var n: TTrunkSeq
var oldMax = t.max
t.max = ((t.max + 1) * 2) - 1
@@ -76,7 +76,7 @@ proc intSetEnlarge(t: var TIntSet) =
if t.data[i] != nil: intSetRawInsert(t, n, t.data[i])
swap(t.data, n)
-proc intSetPut(t: var TIntSet, key: int): PTrunk =
+proc intSetPut(t: var IntSet, key: int): PTrunk =
var h = key and t.max
while t.data[h] != nil:
if t.data[h].key == key:
@@ -93,7 +93,7 @@ proc intSetPut(t: var TIntSet, key: int): PTrunk =
t.head = result
t.data[h] = result
-proc contains*(s: TIntSet, key: int): bool =
+proc contains*(s: IntSet, key: int): bool =
## returns true iff `key` is in `s`.
var t = intSetGet(s, `shr`(key, TrunkShift))
if t != nil:
@@ -102,14 +102,14 @@ proc contains*(s: TIntSet, key: int): bool =
else:
result = false
-proc incl*(s: var TIntSet, key: int) =
+proc incl*(s: var IntSet, key: int) =
## includes an element `key` in `s`.
var t = intSetPut(s, `shr`(key, TrunkShift))
var u = key and TrunkMask
t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] or
`shl`(1, u and IntMask)
-proc excl*(s: var TIntSet, key: int) =
+proc excl*(s: var IntSet, key: int) =
## excludes `key` from the set `s`.
var t = intSetGet(s, `shr`(key, TrunkShift))
if t != nil:
@@ -117,7 +117,7 @@ proc excl*(s: var TIntSet, key: int) =
t.bits[`shr`(u, IntShift)] = t.bits[`shr`(u, IntShift)] and
not `shl`(1, u and IntMask)
-proc containsOrIncl*(s: var TIntSet, key: int): bool =
+proc containsOrIncl*(s: var IntSet, key: int): bool =
## returns true if `s` contains `key`, otherwise `key` is included in `s`
## and false is returned.
var t = intSetGet(s, `shr`(key, TrunkShift))
@@ -131,14 +131,14 @@ proc containsOrIncl*(s: var TIntSet, key: int): bool =
incl(s, key)
result = false
-proc initIntSet*: TIntSet =
+proc initIntSet*: IntSet =
## creates a new int set that is empty.
newSeq(result.data, InitIntSetSize)
result.max = InitIntSetSize-1
result.counter = 0
result.head = nil
-proc assign*(dest: var TIntSet, src: TIntSet) =
+proc assign*(dest: var IntSet, src: IntSet) =
## copies `src` to `dest`. `dest` does not need to be initialized by
## `initIntSet`.
dest.counter = src.counter
@@ -162,7 +162,7 @@ proc assign*(dest: var TIntSet, src: TIntSet) =
it = it.next
-iterator items*(s: TIntSet): int {.inline.} =
+iterator items*(s: IntSet): int {.inline.} =
## iterates over any included element of `s`.
var r = s.head
while r != nil:
@@ -187,11 +187,11 @@ template dollarImpl(): stmt =
result.add($key)
result.add("}")
-proc `$`*(s: TIntSet): string =
+proc `$`*(s: IntSet): string =
## The `$` operator for int sets.
dollarImpl()
-proc empty*(s: TIntSet): bool {.inline.} =
+proc empty*(s: IntSet): bool {.inline.} =
## returns true if `s` is empty. This is safe to call even before
## the set has been initialized with `initIntSet`.
result = s.counter == 0
diff --git a/lib/pure/logging.nim b/lib/pure/logging.nim
index a0773f40b..bd5e1bf42 100644
--- a/lib/pure/logging.nim
+++ b/lib/pure/logging.nim
@@ -61,15 +61,15 @@ const
type
Logger* = ref object of RootObj ## abstract logger; the base type of all loggers
- levelThreshold*: Leve l ## only messages of level >= levelThreshold
- ## should be processed
+ levelThreshold*: Level ## only messages of level >= levelThreshold
+ ## should be processed
fmtStr: string ## = defaultFmtStr by default, see substituteLog for $date etc.
ConsoleLogger* = ref object of Logger ## logger that writes the messages to the
## console
FileLogger* = ref object of Logger ## logger that writes the messages to a file
- f: TFile
+ f: File
RollingFileLogger* = ref object of FileLogger ## logger that writes the
## messages to a file and
@@ -109,19 +109,19 @@ proc substituteLog(frmt: string): string =
of "appname": result.add(app.splitFile.name)
method log*(logger: Logger, level: Level,
- frmt: string, args: varargs[string, `$`]) {.raises: [EBase], tags: [FTime, FWriteIO, FReadIO].} =
+ frmt: string, args: varargs[string, `$`]) {.raises: [Exception], tags: [FTime, FWriteIO, FReadIO].} =
## Override this method in custom loggers. Default implementation does
## nothing.
discard
-method log*(logger: PConsoleLogger, level: TLevel,
+method log*(logger: ConsoleLogger, level: Level,
frmt: string, args: varargs[string, `$`]) =
## Logs to the console using ``logger`` only.
if level >= logger.levelThreshold:
writeln(stdout, LevelNames[level], " ", substituteLog(logger.fmtStr),
frmt % args)
-method log*(logger: PFileLogger, level: TLevel,
+method log*(logger: FileLogger, level: Level,
frmt: string, args: varargs[string, `$`]) =
## Logs to a file using ``logger`` only.
if level >= logger.levelThreshold:
@@ -133,16 +133,16 @@ proc defaultFilename*(): string =
var (path, name, ext) = splitFile(getAppFilename())
result = changeFileExt(path / name, "log")
-proc newConsoleLogger*(levelThreshold = lvlAll, fmtStr = defaultFmtStr): PConsoleLogger =
+proc newConsoleLogger*(levelThreshold = lvlAll, fmtStr = defaultFmtStr): ConsoleLogger =
## Creates a new console logger. This logger logs to the console.
new result
result.fmtStr = fmtStr
result.levelThreshold = levelThreshold
proc newFileLogger*(filename = defaultFilename(),
- mode: TFileMode = fmAppend,
+ mode: FileMode = fmAppend,
levelThreshold = lvlAll,
- fmtStr = defaultFmtStr): PFileLogger =
+ fmtStr = defaultFmtStr): FileLogger =
## Creates a new file logger. This logger logs to a file.
new(result)
result.levelThreshold = levelThreshold
@@ -151,7 +151,7 @@ proc newFileLogger*(filename = defaultFilename(),
# ------
-proc countLogLines(logger: PRollingFileLogger): int =
+proc countLogLines(logger: RollingFileLogger): int =
result = 0
for line in logger.f.lines():
result.inc()
@@ -169,13 +169,13 @@ proc countFiles(filename: string): int =
let num = parseInt(numS)
if num > result:
result = num
- except EInvalidValue: discard
+ except ValueError: discard
proc newRollingFileLogger*(filename = defaultFilename(),
- mode: TFileMode = fmReadWrite,
+ mode: FileMode = fmReadWrite,
levelThreshold = lvlAll,
fmtStr = defaultFmtStr,
- maxLines = 1000): PRollingFileLogger =
+ maxLines = 1000): RollingFileLogger =
## Creates a new rolling file logger. Once a file reaches ``maxLines`` lines
## a new log file will be started and the old will be renamed.
new(result)
@@ -193,14 +193,14 @@ proc newRollingFileLogger*(filename = defaultFilename(),
# We need to get a line count because we will be appending to the file.
result.curLine = countLogLines(result)
-proc rotate(logger: PRollingFileLogger) =
+proc rotate(logger: RollingFileLogger) =
let (dir, name, ext) = splitFile(logger.baseName)
for i in countdown(logger.logFiles, 0):
let srcSuff = if i != 0: ExtSep & $i else: ""
moveFile(dir / (name & ext & srcSuff),
dir / (name & ext & ExtSep & $(i+1)))
-method log*(logger: PRollingFileLogger, level: TLevel,
+method log*(logger: RollingFileLogger, level: Level,
frmt: string, args: varargs[string, `$`]) =
## Logs to a file using rolling ``logger`` only.
if level >= logger.levelThreshold:
@@ -218,20 +218,20 @@ method log*(logger: PRollingFileLogger, level: TLevel,
var
level* = lvlAll ## global log filter
- handlers*: seq[PLogger] = @[] ## handlers with their own log levels
+ handlers*: seq[Logger] = @[] ## handlers with their own log levels
-proc logLoop(level: TLevel, frmt: string, args: varargs[string, `$`]) =
+proc logLoop(level: Level, frmt: string, args: varargs[string, `$`]) =
for logger in items(handlers):
if level >= logger.levelThreshold:
log(logger, level, frmt, args)
-template log*(level: TLevel, frmt: string, args: varargs[string, `$`]) =
+template log*(level: Level, frmt: string, args: varargs[string, `$`]) =
## Logs a message to all registered handlers at the given level.
bind logLoop
bind `%`
- bind logging.Level
+ bind logging.level
- if level >= logging.Level:
+ if level >= logging.level:
logLoop(level, frmt, args)
template debug*(frmt: string, args: varargs[string, `$`]) =
diff --git a/lib/pure/marshal.nim b/lib/pure/marshal.nim
index 7857e9a94..fc63605a9 100644
--- a/lib/pure/marshal.nim
+++ b/lib/pure/marshal.nim
@@ -1,319 +1,319 @@
-#
-#
-# Nim's Runtime Library
-# (c) Copyright 2014 Andreas Rumpf
-#
-# See the file "copying.txt", included in this
-# distribution, for details about the copyright.
-#
-
-## This module contains procs for serialization and deseralization of
-## arbitrary Nim data structures. The serialization format uses JSON.
-##
-## **Restriction**: For objects their type is **not** serialized. This means
-## essentially that it does not work if the object has some other runtime
-## type than its compiletime type:
-##
-## .. code-block:: nim
-##
-## type
-## TA = object
-## TB = object of TA
-## f: int
-##
-## var
-## a: ref TA
-## b: ref TB
-##
-## new(b)
-## a = b
-## echo($$a[]) # produces "{}", not "{f: 0}"
-
-import streams, typeinfo, json, intsets, tables
-
-proc ptrToInt(x: pointer): int {.inline.} =
- result = cast[int](x) # don't skip alignment
-
-proc storeAny(s: PStream, a: TAny, stored: var TIntSet) =
- case a.kind
- of akNone: assert false
- of akBool: s.write($getBool(a))
- of akChar: s.write(escapeJson($getChar(a)))
- of akArray, akSequence:
- if a.kind == akSequence and isNil(a): s.write("null")
- else:
- s.write("[")
- for i in 0 .. a.len-1:
- if i > 0: s.write(", ")
- storeAny(s, a[i], stored)
- s.write("]")
- of akObject, akTuple:
- s.write("{")
- var i = 0
- for key, val in fields(a):
- if i > 0: s.write(", ")
- s.write(escapeJson(key))
- s.write(": ")
- storeAny(s, val, stored)
- inc(i)
- s.write("}")
- of akSet:
- s.write("[")
- var i = 0
- for e in elements(a):
- if i > 0: s.write(", ")
- s.write($e)
- inc(i)
- s.write("]")
- of akRange: storeAny(s, skipRange(a), stored)
- of akEnum: s.write(getEnumField(a).escapeJson)
- of akPtr, akRef:
- var x = a.getPointer
- if isNil(x): s.write("null")
- elif stored.containsOrIncl(x.ptrToInt):
- # already stored, so we simply write out the pointer as an int:
- s.write($x.ptrToInt)
- else:
- # else as a [value, key] pair:
- # (reversed order for convenient x[0] access!)
- s.write("[")
- s.write($x.ptrToInt)
- s.write(", ")
- storeAny(s, a[], stored)
- s.write("]")
- of akProc, akPointer, akCString: s.write($a.getPointer.ptrToInt)
- of akString:
- var x = getString(a)
- if IsNil(x): s.write("null")
- else: s.write(escapeJson(x))
- of akInt..akInt64, akUInt..akUInt64: s.write($getBiggestInt(a))
- of akFloat..akFloat128: s.write($getBiggestFloat(a))
-
-proc loadAny(p: var TJsonParser, a: TAny, t: var TTable[biggestInt, pointer]) =
- case a.kind
- of akNone: assert false
- of akBool:
- case p.kind
- of jsonFalse: setBiggestInt(a, 0)
- of jsonTrue: setBiggestInt(a, 1)
- else: raiseParseErr(p, "'true' or 'false' expected for a bool")
- next(p)
- of akChar:
- if p.kind == jsonString:
- var x = p.str
- if x.len == 1:
- setBiggestInt(a, ord(x[0]))
- next(p)
- return
- raiseParseErr(p, "string of length 1 expected for a char")
- of akEnum:
- if p.kind == jsonString:
- setBiggestInt(a, getEnumOrdinal(a, p.str))
- next(p)
- return
- raiseParseErr(p, "string expected for an enum")
- of akArray:
- if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for an array")
- next(p)
- var i = 0
- while p.kind != jsonArrayEnd and p.kind != jsonEof:
- loadAny(p, a[i], t)
- inc(i)
- if p.kind == jsonArrayEnd: next(p)
- else: raiseParseErr(p, "']' end of array expected")
- of akSequence:
- case p.kind
- of jsonNull:
- setPointer(a, nil)
- next(p)
- of jsonArrayStart:
- next(p)
- invokeNewSeq(a, 0)
- var i = 0
- while p.kind != jsonArrayEnd and p.kind != jsonEof:
- extendSeq(a)
- loadAny(p, a[i], t)
- inc(i)
- if p.kind == jsonArrayEnd: next(p)
- else: raiseParseErr(p, "")
- else:
- raiseParseErr(p, "'[' expected for a seq")
- of akObject, akTuple:
- if a.kind == akObject: setObjectRuntimeType(a)
- if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
- next(p)
- while p.kind != jsonObjectEnd and p.kind != jsonEof:
- if p.kind != jsonString:
- raiseParseErr(p, "string expected for a field name")
- var fieldName = p.str
- next(p)
- loadAny(p, a[fieldName], t)
- if p.kind == jsonObjectEnd: next(p)
- else: raiseParseErr(p, "'}' end of object expected")
- of akSet:
- if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
- next(p)
- while p.kind != jsonArrayEnd and p.kind != jsonEof:
- if p.kind != jsonInt: raiseParseErr(p, "int expected for a set")
- inclSetElement(a, p.getInt.int)
- next(p)
- if p.kind == jsonArrayEnd: next(p)
- else: raiseParseErr(p, "']' end of array expected")
- of akPtr, akRef:
- case p.kind
- of jsonNull:
- setPointer(a, nil)
- next(p)
- of jsonInt:
- setPointer(a, t[p.getInt])
- next(p)
- of jsonArrayStart:
- next(p)
- if a.kind == akRef: invokeNew(a)
- else: setPointer(a, alloc0(a.baseTypeSize))
- if p.kind == jsonInt:
- t[p.getInt] = getPointer(a)
- next(p)
- else: raiseParseErr(p, "index for ref type expected")
- loadAny(p, a[], t)
- if p.kind == jsonArrayEnd: next(p)
- else: raiseParseErr(p, "']' end of ref-address pair expected")
- else: raiseParseErr(p, "int for pointer type expected")
- of akProc, akPointer, akCString:
- case p.kind
- of jsonNull:
- setPointer(a, nil)
- next(p)
- of jsonInt:
- setPointer(a, cast[pointer](p.getInt.int))
- next(p)
- else: raiseParseErr(p, "int for pointer type expected")
- of akString:
- case p.kind
- of jsonNull:
- setPointer(a, nil)
- next(p)
- of jsonString:
- setString(a, p.str)
- next(p)
- else: raiseParseErr(p, "string expected")
- of akInt..akInt64, akUInt..akUInt64:
- if p.kind == jsonInt:
- setBiggestInt(a, getInt(p))
- next(p)
- return
- raiseParseErr(p, "int expected")
- of akFloat..akFloat128:
- if p.kind == jsonFloat:
- setBiggestFloat(a, getFloat(p))
- next(p)
- return
- raiseParseErr(p, "float expected")
- of akRange: loadAny(p, a.skipRange, t)
-
-proc loadAny(s: PStream, a: TAny, t: var TTable[BiggestInt, pointer]) =
- var p: TJsonParser
- open(p, s, "unknown file")
- next(p)
- loadAny(p, a, t)
- close(p)
-
-proc load*[T](s: PStream, data: var T) =
- ## loads `data` from the stream `s`. Raises `EIO` in case of an error.
- var tab = initTable[biggestInt, pointer]()
- loadAny(s, toAny(data), tab)
-
-proc store*[T](s: PStream, data: T) =
- ## stores `data` into the stream `s`. Raises `EIO` in case of an error.
- var stored = initIntSet()
- var d: T
- shallowCopy(d, data)
- storeAny(s, toAny(d), stored)
-
-proc `$$`*[T](x: T): string =
- ## returns a string representation of `x`.
- var stored = initIntSet()
- var d: T
- shallowCopy(d, x)
- var s = newStringStream()
- storeAny(s, toAny(d), stored)
- result = s.data
-
-proc to*[T](data: string): T =
- ## reads data and transforms it to a ``T``.
- var tab = initTable[biggestInt, pointer]()
- loadAny(newStringStream(data), toAny(result), tab)
-
-when isMainModule:
- template testit(x: expr) = echo($$to[type(x)]($$x))
-
- var x: array[0..4, array[0..4, string]] = [
- ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
- ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
- ["test", "1", "2", "3", "4"]]
- testit(x)
- var test2: tuple[name: string, s: uint] = ("tuple test", 56u)
- testit(test2)
-
- type
- TE = enum
- blah, blah2
-
- TestObj = object
- test, asd: int
- case test2: TE
- of blah:
- help: string
- else:
- nil
-
- PNode = ref TNode
- TNode = object
- next, prev: PNode
- data: string
-
- proc buildList(): PNode =
- new(result)
- new(result.next)
- new(result.prev)
- result.data = "middle"
- result.next.data = "next"
- result.prev.data = "prev"
- result.next.next = result.prev
- result.next.prev = result
- result.prev.next = result
- result.prev.prev = result.next
-
- var test3: TestObj
- test3.test = 42
- test3.test2 = blah
- testit(test3)
-
- var test4: ref tuple[a, b: string]
- new(test4)
- test4.a = "ref string test: A"
- test4.b = "ref string test: B"
- testit(test4)
-
- var test5 = @[(0,1),(2,3),(4,5)]
- testit(test5)
-
- var test6: set[char] = {'A'..'Z', '_'}
- testit(test6)
-
- var test7 = buildList()
- echo($$test7)
- testit(test7)
-
- type
- TA {.inheritable.} = object
- TB = object of TA
- f: int
-
- var
- a: ref TA
- b: ref TB
- new(b)
- a = b
- echo($$a[]) # produces "{}", not "{f: 0}"
-
+#
+#
+# Nim's Runtime Library
+# (c) Copyright 2014 Andreas Rumpf
+#
+# See the file "copying.txt", included in this
+# distribution, for details about the copyright.
+#
+
+## This module contains procs for serialization and deseralization of
+## arbitrary Nim data structures. The serialization format uses JSON.
+##
+## **Restriction**: For objects their type is **not** serialized. This means
+## essentially that it does not work if the object has some other runtime
+## type than its compiletime type:
+##
+## .. code-block:: nim
+##
+## type
+## TA = object
+## TB = object of TA
+## f: int
+##
+## var
+## a: ref TA
+## b: ref TB
+##
+## new(b)
+## a = b
+## echo($$a[]) # produces "{}", not "{f: 0}"
+
+import streams, typeinfo, json, intsets, tables
+
+proc ptrToInt(x: pointer): int {.inline.} =
+ result = cast[int](x) # don't skip alignment
+
+proc storeAny(s: Stream, a: TAny, stored: var IntSet) =
+ case a.kind
+ of akNone: assert false
+ of akBool: s.write($getBool(a))
+ of akChar: s.write(escapeJson($getChar(a)))
+ of akArray, akSequence:
+ if a.kind == akSequence and isNil(a): s.write("null")
+ else:
+ s.write("[")
+ for i in 0 .. a.len-1:
+ if i > 0: s.write(", ")
+ storeAny(s, a[i], stored)
+ s.write("]")
+ of akObject, akTuple:
+ s.write("{")
+ var i = 0
+ for key, val in fields(a):
+ if i > 0: s.write(", ")
+ s.write(escapeJson(key))
+ s.write(": ")
+ storeAny(s, val, stored)
+ inc(i)
+ s.write("}")
+ of akSet:
+ s.write("[")
+ var i = 0
+ for e in elements(a):
+ if i > 0: s.write(", ")
+ s.write($e)
+ inc(i)
+ s.write("]")
+ of akRange: storeAny(s, skipRange(a), stored)
+ of akEnum: s.write(getEnumField(a).escapeJson)
+ of akPtr, akRef:
+ var x = a.getPointer
+ if isNil(x): s.write("null")
+ elif stored.containsOrIncl(x.ptrToInt):
+ # already stored, so we simply write out the pointer as an int:
+ s.write($x.ptrToInt)
+ else:
+ # else as a [value, key] pair:
+ # (reversed order for convenient x[0] access!)
+ s.write("[")
+ s.write($x.ptrToInt)
+ s.write(", ")
+ storeAny(s, a[], stored)
+ s.write("]")
+ of akProc, akPointer, akCString: s.write($a.getPointer.ptrToInt)
+ of akString:
+ var x = getString(a)
+ if isNil(x): s.write("null")
+ else: s.write(escapeJson(x))
+ of akInt..akInt64, akUInt..akUInt64: s.write($getBiggestInt(a))
+ of akFloat..akFloat128: s.write($getBiggestFloat(a))
+
+proc loadAny(p: var JsonParser, a: TAny, t: var Table[BiggestInt, pointer]) =
+ case a.kind
+ of akNone: assert false
+ of akBool:
+ case p.kind
+ of jsonFalse: setBiggestInt(a, 0)
+ of jsonTrue: setBiggestInt(a, 1)
+ else: raiseParseErr(p, "'true' or 'false' expected for a bool")
+ next(p)
+ of akChar:
+ if p.kind == jsonString:
+ var x = p.str
+ if x.len == 1:
+ setBiggestInt(a, ord(x[0]))
+ next(p)
+ return
+ raiseParseErr(p, "string of length 1 expected for a char")
+ of akEnum:
+ if p.kind == jsonString:
+ setBiggestInt(a, getEnumOrdinal(a, p.str))
+ next(p)
+ return
+ raiseParseErr(p, "string expected for an enum")
+ of akArray:
+ if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for an array")
+ next(p)
+ var i = 0
+ while p.kind != jsonArrayEnd and p.kind != jsonEof:
+ loadAny(p, a[i], t)
+ inc(i)
+ if p.kind == jsonArrayEnd: next(p)
+ else: raiseParseErr(p, "']' end of array expected")
+ of akSequence:
+ case p.kind
+ of jsonNull:
+ setPointer(a, nil)
+ next(p)
+ of jsonArrayStart:
+ next(p)
+ invokeNewSeq(a, 0)
+ var i = 0
+ while p.kind != jsonArrayEnd and p.kind != jsonEof:
+ extendSeq(a)
+ loadAny(p, a[i], t)
+ inc(i)
+ if p.kind == jsonArrayEnd: next(p)
+ else: raiseParseErr(p, "")
+ else:
+ raiseParseErr(p, "'[' expected for a seq")
+ of akObject, akTuple:
+ if a.kind == akObject: setObjectRuntimeType(a)
+ if p.kind != jsonObjectStart: raiseParseErr(p, "'{' expected for an object")
+ next(p)
+ while p.kind != jsonObjectEnd and p.kind != jsonEof:
+ if p.kind != jsonString:
+ raiseParseErr(p, "string expected for a field name")
+ var fieldName = p.str
+ next(p)
+ loadAny(p, a[fieldName], t)
+ if p.kind == jsonObjectEnd: next(p)
+ else: raiseParseErr(p, "'}' end of object expected")
+ of akSet:
+ if p.kind != jsonArrayStart: raiseParseErr(p, "'[' expected for a set")
+ next(p)
+ while p.kind != jsonArrayEnd and p.kind != jsonEof:
+ if p.kind != jsonInt: raiseParseErr(p, "int expected for a set")
+ inclSetElement(a, p.getInt.int)
+ next(p)
+ if p.kind == jsonArrayEnd: next(p)
+ else: raiseParseErr(p, "']' end of array expected")
+ of akPtr, akRef:
+ case p.kind
+ of jsonNull:
+ setPointer(a, nil)
+ next(p)
+ of jsonInt:
+ setPointer(a, t[p.getInt])
+ next(p)
+ of jsonArrayStart:
+ next(p)
+ if a.kind == akRef: invokeNew(a)
+ else: setPointer(a, alloc0(a.baseTypeSize))
+ if p.kind == jsonInt:
+ t[p.getInt] = getPointer(a)
+ next(p)
+ else: raiseParseErr(p, "index for ref type expected")
+ loadAny(p, a[], t)
+ if p.kind == jsonArrayEnd: next(p)
+ else: raiseParseErr(p, "']' end of ref-address pair expected")
+ else: raiseParseErr(p, "int for pointer type expected")
+ of akProc, akPointer, akCString:
+ case p.kind
+ of jsonNull:
+ setPointer(a, nil)
+ next(p)
+ of jsonInt:
+ setPointer(a, cast[pointer](p.getInt.int))
+ next(p)
+ else: raiseParseErr(p, "int for pointer type expected")
+ of akString:
+ case p.kind
+ of jsonNull:
+ setPointer(a, nil)
+ next(p)
+ of jsonString:
+ setString(a, p.str)
+ next(p)
+ else: raiseParseErr(p, "string expected")
+ of akInt..akInt64, akUInt..akUInt64:
+ if p.kind == jsonInt:
+ setBiggestInt(a, getInt(p))
+ next(p)
+ return
+ raiseParseErr(p, "int expected")
+ of akFloat..akFloat128:
+ if p.kind == jsonFloat:
+ setBiggestFloat(a, getFloat(p))
+ next(p)
+ return
+ raiseParseErr(p, "float expected")
+ of akRange: loadAny(p, a.skipRange, t)
+
+proc loadAny(s: Stream, a: TAny, t: var Table[BiggestInt, pointer]) =
+ var p: JsonParser
+ open(p, s, "unknown file")
+ next(p)
+ loadAny(p, a, t)
+ close(p)
+
+proc load*[T](s: Stream, data: var T) =
+ ## loads `data` from the stream `s`. Raises `EIO` in case of an error.
+ var tab = initTable[BiggestInt, pointer]()
+ loadAny(s, toAny(data), tab)
+
+proc store*[T](s: Stream, data: T) =
+ ## stores `data` into the stream `s`. Raises `EIO` in case of an error.
+ var stored = initIntSet()
+ var d: T
+ shallowCopy(d, data)
+ storeAny(s, toAny(d), stored)
+
+proc `$$`*[T](x: T): string =
+ ## returns a string representation of `x`.
+ var stored = initIntSet()
+ var d: T
+ shallowCopy(d, x)
+ var s = newStringStream()
+ storeAny(s, toAny(d), stored)
+ result = s.data
+
+proc to*[T](data: string): T =
+ ## reads data and transforms it to a ``T``.
+ var tab = initTable[BiggestInt, pointer]()
+ loadAny(newStringStream(data), toAny(result), tab)
+
+when isMainModule:
+ template testit(x: expr) = echo($$to[type(x)]($$x))
+
+ var x: array[0..4, array[0..4, string]] = [
+ ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+ ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+ ["test", "1", "2", "3", "4"]]
+ testit(x)
+ var test2: tuple[name: string, s: uint] = ("tuple test", 56u)
+ testit(test2)
+
+ type
+ TE = enum
+ blah, blah2
+
+ TestObj = object
+ test, asd: int
+ case test2: TE
+ of blah:
+ help: string
+ else:
+ nil
+
+ PNode = ref TNode
+ TNode = object
+ next, prev: PNode
+ data: string
+
+ proc buildList(): PNode =
+ new(result)
+ new(result.next)
+ new(result.prev)
+ result.data = "middle"
+ result.next.data = "next"
+ result.prev.data = "prev"
+ result.next.next = result.prev
+ result.next.prev = result
+ result.prev.next = result
+ result.prev.prev = result.next
+
+ var test3: TestObj
+ test3.test = 42
+ test3.test2 = blah
+ testit(test3)
+
+ var test4: ref tuple[a, b: string]
+ new(test4)
+ test4.a = "ref string test: A"
+ test4.b = "ref string test: B"
+ testit(test4)
+
+ var test5 = @[(0,1),(2,3),(4,5)]
+ testit(test5)
+
+ var test6: set[char] = {'A'..'Z', '_'}
+ testit(test6)
+
+ var test7 = buildList()
+ echo($$test7)
+ testit(test7)
+
+ type
+ TA {.inheritable.} = object
+ TB = object of TA
+ f: int
+
+ var
+ a: ref TA
+ b: ref TB
+ new(b)
+ a = b
+ echo($$a[]) # produces "{}", not "{f: 0}"
+
From 00f50f27973ff33217eabe0b5f02cab49a0d8601 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 02:12:49 +0200
Subject: [PATCH 023/409] more modules updated
---
lib/pure/matchers.nim | 4 ++--
lib/pure/strutils.nim | 10 +++++-----
2 files changed, 7 insertions(+), 7 deletions(-)
diff --git a/lib/pure/matchers.nim b/lib/pure/matchers.nim
index c3ad7235f..46fc9985c 100644
--- a/lib/pure/matchers.nim
+++ b/lib/pure/matchers.nim
@@ -31,8 +31,8 @@ proc validEmailAddress*(s: string): bool {.noSideEffect,
inc(i)
if s[i] != '@': return false
var j = len(s)-1
- if s[j] notin letters: return false
- while j >= i and s[j] in letters: dec(j)
+ if s[j] notin Letters: return false
+ while j >= i and s[j] in Letters: dec(j)
inc(i) # skip '@'
while s[i] in {'0'..'9', 'a'..'z', '-', '.'}: inc(i)
if s[i] != '\0': return false
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 2af973b6e..5153455e2 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -130,7 +130,7 @@ proc normalize*(s: string): string {.noSideEffect, procvar,
if j != s.len: setLen(result, j)
proc cmpIgnoreCase*(a, b: string): int {.noSideEffect,
- rtl, extern: "nsuCmpIgnoreCase", procvar, operator: 4.} =
+ rtl, extern: "nsuCmpIgnoreCase", procvar.} =
## Compares two strings in a case insensitive manner. Returns:
##
## | 0 iff a == b
@@ -148,7 +148,7 @@ proc cmpIgnoreCase*(a, b: string): int {.noSideEffect,
# thus we compile without checks here
proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect,
- rtl, extern: "nsuCmpIgnoreStyle", procvar, operator: 3.} =
+ rtl, extern: "nsuCmpIgnoreStyle", procvar.} =
## Compares two strings normalized (i.e. case and
## underscores do not matter). Returns:
##
@@ -170,7 +170,7 @@ proc cmpIgnoreStyle*(a, b: string): int {.noSideEffect,
{.pop.}
proc strip*(s: string, leading = true, trailing = true): string {.noSideEffect,
- rtl, extern: "nsuStrip", operator: 5.} =
+ rtl, extern: "nsuStrip".} =
## Strips whitespace from `s` and returns the resulting string.
##
## If `leading` is true, leading whitespace is stripped.
@@ -1147,7 +1147,7 @@ type
proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
precision: range[0..32] = 16): string {.
- noSideEffect, operator: 2, rtl, extern: "nsu$1".} =
+ noSideEffect, rtl, extern: "nsu$1".} =
## Converts a floating point value `f` to a string.
##
## If ``format == ffDecimal`` then precision is the number of digits to
@@ -1178,7 +1178,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
proc formatFloat*(f: float, format: FloatFormatMode = ffDefault,
precision: range[0..32] = 16): string {.
- noSideEffect, operator: 2, rtl, extern: "nsu$1".} =
+ noSideEffect, rtl, extern: "nsu$1".} =
## Converts a floating point value `f` to a string.
##
## If ``format == ffDecimal`` then precision is the number of digits to
From 2b6277c9649fb8672984cc8afc2068afd6c331a1 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 02:14:25 +0200
Subject: [PATCH 024/409] more modules updated
---
lib/pure/nimprof.nim | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/lib/pure/nimprof.nim b/lib/pure/nimprof.nim
index 6b8fe1ce5..3598cdd3a 100644
--- a/lib/pure/nimprof.nim
+++ b/lib/pure/nimprof.nim
@@ -132,9 +132,9 @@ else:
proc hook(st: TStackTrace) {.nimcall.} =
if interval == 0:
hookAux(st, 1)
- elif getticks() - t0 > interval:
+ elif getTicks() - t0 > interval:
hookAux(st, 1)
- t0 = getticks()
+ t0 = getTicks()
proc getTotal(x: ptr TProfileEntry): int =
result = if isNil(x): 0 else: x.total
@@ -150,7 +150,7 @@ proc writeProfile() {.noconv.} =
system.profilerHook = nil
const filename = "profile_results.txt"
echo "writing " & filename & "..."
- var f: TFile
+ var f: File
if open(f, filename, fmWrite):
sort(profileData, cmpEntries)
writeln(f, "total executions of each stack trace:")
From bf9764e563c4ec84ad29eaf12112a8f10d336681 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 02:21:49 +0200
Subject: [PATCH 025/409] several modules changed
---
lib/pure/oids.nim | 2 +-
lib/pure/parsecfg.nim | 9 ++-
lib/pure/parsecsv.nim | 2 +-
lib/pure/parseopt.nim | 2 +-
lib/pure/parseopt2.nim | 6 +-
lib/pure/parsesql.nim | 126 ++++++++++++++++++++---------------------
lib/pure/parseurl.nim | 14 ++---
7 files changed, 80 insertions(+), 81 deletions(-)
diff --git a/lib/pure/oids.nim b/lib/pure/oids.nim
index c0bfb7c08..7c58a2dda 100644
--- a/lib/pure/oids.nim
+++ b/lib/pure/oids.nim
@@ -89,5 +89,5 @@ proc generatedTime*(oid: Oid): Time =
result = Time(tmp)
when isMainModule:
- let xo = genOID()
+ let xo = genOid()
echo xo.generatedTime
diff --git a/lib/pure/parsecfg.nim b/lib/pure/parsecfg.nim
index c340bf98b..a45976d86 100644
--- a/lib/pure/parsecfg.nim
+++ b/lib/pure/parsecfg.nim
@@ -38,7 +38,7 @@ type
cfgError ## an error ocurred during parsing
CfgEvent* = object of RootObj ## describes a parsing event
- case kind*: TCfgEventKind ## the kind of the event
+ case kind*: CfgEventKind ## the kind of the event
of cfgEof: nil
of cfgSectionStart:
section*: string ## `section` contains the name of the
@@ -70,12 +70,11 @@ type
# implementation
const
- SymChars: CharSet = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.',
- '/', '\\'}
+ SymChars = {'a'..'z', 'A'..'Z', '0'..'9', '_', '\x80'..'\xFF', '.', '/', '\\'}
proc rawGetTok(c: var CfgParser, tok: var Token) {.gcsafe.}
-proc open*(c: var CfgParser, input: PStream, filename: string,
+proc open*(c: var CfgParser, input: Stream, filename: string,
lineOffset = 0) {.rtl, extern: "npc$1".} =
## initializes the parser with an input stream. `Filename` is only used
## for nice error messages. `lineOffset` can be used to influence the line
@@ -122,7 +121,7 @@ proc handleDecChars(c: var CfgParser, xi: var int) =
xi = (xi * 10) + (ord(c.buf[c.bufpos]) - ord('0'))
inc(c.bufpos)
-proc getEscapedChar(c: var CfgParser, tok: var TToken) =
+proc getEscapedChar(c: var CfgParser, tok: var Token) =
inc(c.bufpos) # skip '\'
case c.buf[c.bufpos]
of 'n', 'N':
diff --git a/lib/pure/parsecsv.nim b/lib/pure/parsecsv.nim
index d267906a3..c8abdca4f 100644
--- a/lib/pure/parsecsv.nim
+++ b/lib/pure/parsecsv.nim
@@ -155,7 +155,7 @@ proc readRow*(my: var CsvParser, columns = 0): bool =
else: error(my, my.bufpos, my.sep & " expected")
break
- setlen(my.row, col)
+ setLen(my.row, col)
result = col > 0
if result and col != columns and columns > 0:
error(my, oldpos+1, $columns & " columns expected, but found " &
diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim
index b325bd1f5..de00bc76d 100644
--- a/lib/pure/parseopt.nim
+++ b/lib/pure/parseopt.nim
@@ -59,7 +59,7 @@ when declared(os.paramCount):
result.val = TaintedString""
proc parseWord(s: string, i: int, w: var string,
- delim: CharSet = {'\x09', ' ', '\0'}): int =
+ delim: set[char] = {'\x09', ' ', '\0'}): int =
result = i
if s[result] == '\"':
inc(result)
diff --git a/lib/pure/parseopt2.nim b/lib/pure/parseopt2.nim
index c283a5edf..5b1f50958 100644
--- a/lib/pure/parseopt2.nim
+++ b/lib/pure/parseopt2.nim
@@ -31,7 +31,7 @@ type
cmdLongOption, ## a long option ``--option`` detected
cmdShortOption ## a short option ``-c`` detected
OptParser* =
- object of TObject ## this object implements the command line parser
+ object of RootObj ## this object implements the command line parser
cmd: seq[string]
pos: int
remainingShortOptions: string
@@ -102,10 +102,10 @@ proc next(p: var OptParser) =
let token = p.cmd[p.pos]
p.pos += 1
- if token.startswith("--"):
+ if token.startsWith("--"):
p.kind = cmdLongOption
nextOption(p, token[2..token.len-1], allowEmpty=true)
- elif token.startswith("-"):
+ elif token.startsWith("-"):
p.kind = cmdShortOption
nextOption(p, token[1..token.len-1], allowEmpty=true)
else:
diff --git a/lib/pure/parsesql.nim b/lib/pure/parsesql.nim
index fcca0aa44..bb4ede779 100644
--- a/lib/pure/parsesql.nim
+++ b/lib/pure/parsesql.nim
@@ -64,12 +64,12 @@ proc close(L: var SqlLexer) =
proc getColumn(L: SqlLexer): int =
## get the current column the parser has arrived at.
- result = getColNumber(L, L.bufPos)
+ result = getColNumber(L, L.bufpos)
proc getLine(L: SqlLexer): int =
- result = L.linenumber
+ result = L.lineNumber
-proc handleHexChar(c: var TSqlLexer, xi: var int) =
+proc handleHexChar(c: var SqlLexer, xi: var int) =
case c.buf[c.bufpos]
of '0'..'9':
xi = (xi shl 4) or (ord(c.buf[c.bufpos]) - ord('0'))
@@ -83,76 +83,76 @@ proc handleHexChar(c: var TSqlLexer, xi: var int) =
else:
discard
-proc handleOctChar(c: var TSqlLexer, xi: var int) =
+proc handleOctChar(c: var SqlLexer, xi: var int) =
if c.buf[c.bufpos] in {'0'..'7'}:
xi = (xi shl 3) or (ord(c.buf[c.bufpos]) - ord('0'))
inc(c.bufpos)
-proc getEscapedChar(c: var TSqlLexer, tok: var TToken) =
+proc getEscapedChar(c: var SqlLexer, tok: var Token) =
inc(c.bufpos)
case c.buf[c.bufpos]
of 'n', 'N':
add(tok.literal, '\L')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'r', 'R', 'c', 'C':
add(tok.literal, '\c')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'l', 'L':
add(tok.literal, '\L')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'f', 'F':
add(tok.literal, '\f')
inc(c.bufpos)
of 'e', 'E':
add(tok.literal, '\e')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'a', 'A':
add(tok.literal, '\a')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'b', 'B':
add(tok.literal, '\b')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'v', 'V':
add(tok.literal, '\v')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 't', 'T':
add(tok.literal, '\t')
- Inc(c.bufpos)
+ inc(c.bufpos)
of '\'', '\"':
add(tok.literal, c.buf[c.bufpos])
- Inc(c.bufpos)
+ inc(c.bufpos)
of '\\':
add(tok.literal, '\\')
- Inc(c.bufpos)
+ inc(c.bufpos)
of 'x', 'X':
inc(c.bufpos)
var xi = 0
handleHexChar(c, xi)
handleHexChar(c, xi)
- add(tok.literal, Chr(xi))
+ add(tok.literal, chr(xi))
of '0'..'7':
var xi = 0
handleOctChar(c, xi)
handleOctChar(c, xi)
handleOctChar(c, xi)
- if (xi <= 255): add(tok.literal, Chr(xi))
+ if (xi <= 255): add(tok.literal, chr(xi))
else: tok.kind = tkInvalid
else: tok.kind = tkInvalid
-proc handleCRLF(c: var TSqlLexer, pos: int): int =
+proc handleCRLF(c: var SqlLexer, pos: int): int =
case c.buf[pos]
of '\c': result = lexbase.handleCR(c, pos)
of '\L': result = lexbase.handleLF(c, pos)
else: result = pos
-proc skip(c: var TSqlLexer) =
+proc skip(c: var SqlLexer) =
var pos = c.bufpos
var buf = c.buf
var nested = 0
while true:
case buf[pos]
of ' ', '\t':
- Inc(pos)
+ inc(pos)
of '-':
if buf[pos+1] == '-':
while not (buf[pos] in {'\c', '\L', lexbase.EndOfFile}): inc(pos)
@@ -189,8 +189,8 @@ proc skip(c: var TSqlLexer) =
break # EndOfFile also leaves the loop
c.bufpos = pos
-proc getString(c: var TSqlLexer, tok: var TToken, kind: TokKind) =
- var pos = c.bufPos + 1
+proc getString(c: var SqlLexer, tok: var Token, kind: TokKind) =
+ var pos = c.bufpos + 1
var buf = c.buf
tok.kind = kind
block parseLoop:
@@ -208,16 +208,16 @@ proc getString(c: var TSqlLexer, tok: var TToken, kind: TokKind) =
tok.kind = tkInvalid
break parseLoop
elif (ch == '\\') and kind == tkEscapeConstant:
- c.bufPos = pos
+ c.bufpos = pos
getEscapedChar(c, tok)
- pos = c.bufPos
+ pos = c.bufpos
else:
add(tok.literal, ch)
- Inc(pos)
+ inc(pos)
c.bufpos = pos
- var line = c.linenumber
+ var line = c.lineNumber
skip(c)
- if c.linenumber > line:
+ if c.lineNumber > line:
# a new line whitespace has been parsed, so we check if the string
# continues after the whitespace:
buf = c.buf # may have been reallocated
@@ -227,8 +227,8 @@ proc getString(c: var TSqlLexer, tok: var TToken, kind: TokKind) =
else: break parseLoop
c.bufpos = pos
-proc getDollarString(c: var TSqlLexer, tok: var TToken) =
- var pos = c.bufPos + 1
+proc getDollarString(c: var SqlLexer, tok: var Token) =
+ var pos = c.bufpos + 1
var buf = c.buf
tok.kind = tkDollarQuotedConstant
var tag = "$"
@@ -242,7 +242,7 @@ proc getDollarString(c: var TSqlLexer, tok: var TToken) =
while true:
case buf[pos]
of '\c', '\L':
- pos = HandleCRLF(c, pos)
+ pos = handleCRLF(c, pos)
buf = c.buf
add(tok.literal, "\L")
of '\0':
@@ -263,19 +263,19 @@ proc getDollarString(c: var TSqlLexer, tok: var TToken) =
inc(pos)
c.bufpos = pos
-proc getSymbol(c: var TSqlLexer, tok: var TToken) =
+proc getSymbol(c: var SqlLexer, tok: var Token) =
var pos = c.bufpos
var buf = c.buf
while true:
add(tok.literal, buf[pos])
- Inc(pos)
+ inc(pos)
if buf[pos] notin {'a'..'z','A'..'Z','0'..'9','_','$', '\128'..'\255'}:
break
c.bufpos = pos
tok.kind = tkIdentifier
-proc getQuotedIdentifier(c: var TSqlLexer, tok: var TToken) =
- var pos = c.bufPos + 1
+proc getQuotedIdentifier(c: var SqlLexer, tok: var Token) =
+ var pos = c.bufpos + 1
var buf = c.buf
tok.kind = tkQuotedIdentifier
while true:
@@ -292,11 +292,11 @@ proc getQuotedIdentifier(c: var TSqlLexer, tok: var TToken) =
break
else:
add(tok.literal, ch)
- Inc(pos)
+ inc(pos)
c.bufpos = pos
-proc getBitHexString(c: var TSqlLexer, tok: var TToken, validChars: TCharSet) =
- var pos = c.bufPos + 1
+proc getBitHexString(c: var SqlLexer, tok: var Token, validChars: set[char]) =
+ var pos = c.bufpos + 1
var buf = c.buf
block parseLoop:
while true:
@@ -304,7 +304,7 @@ proc getBitHexString(c: var TSqlLexer, tok: var TToken, validChars: TCharSet) =
var ch = buf[pos]
if ch in validChars:
add(tok.literal, ch)
- Inc(pos)
+ inc(pos)
elif ch == '\'':
inc(pos)
break
@@ -312,9 +312,9 @@ proc getBitHexString(c: var TSqlLexer, tok: var TToken, validChars: TCharSet) =
tok.kind = tkInvalid
break parseLoop
c.bufpos = pos
- var line = c.linenumber
+ var line = c.lineNumber
skip(c)
- if c.linenumber > line:
+ if c.lineNumber > line:
# a new line whitespace has been parsed, so we check if the string
# continues after the whitespace:
buf = c.buf # may have been reallocated
@@ -324,9 +324,9 @@ proc getBitHexString(c: var TSqlLexer, tok: var TToken, validChars: TCharSet) =
else: break parseLoop
c.bufpos = pos
-proc getNumeric(c: var TSqlLexer, tok: var TToken) =
+proc getNumeric(c: var SqlLexer, tok: var Token) =
tok.kind = tkInteger
- var pos = c.bufPos
+ var pos = c.bufpos
var buf = c.buf
while buf[pos] in Digits:
add(tok.literal, buf[pos])
@@ -355,11 +355,11 @@ proc getNumeric(c: var TSqlLexer, tok: var TToken) =
tok.kind = tkInvalid
c.bufpos = pos
-proc getOperator(c: var TSqlLexer, tok: var TToken) =
+proc getOperator(c: var SqlLexer, tok: var Token) =
const operators = {'+', '-', '*', '/', '<', '>', '=', '~', '!', '@', '#', '%',
'^', '&', '|', '`', '?'}
tok.kind = tkOperator
- var pos = c.bufPos
+ var pos = c.bufpos
var buf = c.buf
var trailingPlusMinus = false
while true:
@@ -381,14 +381,14 @@ proc getOperator(c: var TSqlLexer, tok: var TToken) =
inc(pos)
c.bufpos = pos
-proc getTok(c: var TSqlLexer, tok: var TToken) =
+proc getTok(c: var SqlLexer, tok: var Token) =
tok.kind = tkInvalid
- setlen(tok.literal, 0)
+ setLen(tok.literal, 0)
skip(c)
case c.buf[c.bufpos]
of ';':
- tok.kind = tkSemiColon
- inc(c.bufPos)
+ tok.kind = tkSemicolon
+ inc(c.bufpos)
add(tok.literal, ';')
of ',':
tok.kind = tkComma
@@ -399,19 +399,19 @@ proc getTok(c: var TSqlLexer, tok: var TToken) =
inc(c.bufpos)
add(tok.literal, ':')
of 'e', 'E':
- if c.buf[c.bufPos + 1] == '\'':
- Inc(c.bufPos)
+ if c.buf[c.bufpos + 1] == '\'':
+ inc(c.bufpos)
getString(c, tok, tkEscapeConstant)
else:
getSymbol(c, tok)
of 'b', 'B':
- if c.buf[c.bufPos + 1] == '\'':
+ if c.buf[c.bufpos + 1] == '\'':
tok.kind = tkBitStringConstant
getBitHexString(c, tok, {'0'..'1'})
else:
getSymbol(c, tok)
of 'x', 'X':
- if c.buf[c.bufPos + 1] == '\'':
+ if c.buf[c.bufpos + 1] == '\'':
tok.kind = tkHexStringConstant
getBitHexString(c, tok, {'a'..'f','A'..'F','0'..'9'})
else:
@@ -423,18 +423,18 @@ proc getTok(c: var TSqlLexer, tok: var TToken) =
add(tok.literal, '[')
of ']':
tok.kind = tkBracketRi
- Inc(c.bufpos)
+ inc(c.bufpos)
add(tok.literal, ']')
of '(':
tok.kind = tkParLe
- Inc(c.bufpos)
+ inc(c.bufpos)
add(tok.literal, '(')
of ')':
tok.kind = tkParRi
- Inc(c.bufpos)
+ inc(c.bufpos)
add(tok.literal, ')')
of '.':
- if c.buf[c.bufPos + 1] in Digits:
+ if c.buf[c.bufpos + 1] in Digits:
getNumeric(c, tok)
else:
tok.kind = tkDot
@@ -456,7 +456,7 @@ proc getTok(c: var TSqlLexer, tok: var TToken) =
add(tok.literal, c.buf[c.bufpos])
inc(c.bufpos)
-proc errorStr(L: TSqlLexer, msg: string): string =
+proc errorStr(L: SqlLexer, msg: string): string =
result = "$1($2, $3) Error: $4" % [L.filename, $getLine(L), $getColumn(L), msg]
@@ -819,7 +819,7 @@ proc parseColumnDef(p: var SqlParser): SqlNode =
result.add(parseDataType(p))
parseColumnConstraints(p, result)
-proc parseIfNotExists(p: var SqlParser, k: TSqlNodeKind): SqlNode =
+proc parseIfNotExists(p: var SqlParser, k: SqlNodeKind): SqlNode =
getTok(p)
if isKeyw(p, "if"):
getTok(p)
@@ -1076,10 +1076,10 @@ proc parseStmt(p: var SqlParser): SqlNode =
else:
sqlError(p, "CREATE expected")
-proc open(p: var SqlParser, input: PStream, filename: string) =
+proc open(p: var SqlParser, input: Stream, filename: string) =
## opens the parser `p` and assigns the input stream `input` to it.
## `filename` is only used for error messages.
- open(TSqlLexer(p), input, filename)
+ open(SqlLexer(p), input, filename)
p.tok.kind = tkInvalid
p.tok.literal = ""
getTok(p)
@@ -1090,16 +1090,16 @@ proc parse(p: var SqlParser): SqlNode =
result = newNode(nkStmtList)
while p.tok.kind != tkEof:
var s = parseStmt(p)
- eat(p, tkSemiColon)
+ eat(p, tkSemicolon)
result.add(s)
if result.len == 1:
result = result.sons[0]
proc close(p: var SqlParser) =
## closes the parser `p`. The associated input stream is closed too.
- close(TSqlLexer(p))
+ close(SqlLexer(p))
-proc parseSQL*(input: PStream, filename: string): SqlNode =
+proc parseSQL*(input: Stream, filename: string): SqlNode =
## parses the SQL from `input` into an AST and returns the AST.
## `filename` is only used for error messages.
## Syntax errors raise an `EInvalidSql` exception.
diff --git a/lib/pure/parseurl.nim b/lib/pure/parseurl.nim
index 2637a879d..32e69b89a 100644
--- a/lib/pure/parseurl.nim
+++ b/lib/pure/parseurl.nim
@@ -31,12 +31,12 @@ proc parseUrl*(url: string): Url {.deprecated.} =
var temp = ""
if url[i] != '/': # url isn't a relative path
- while True:
+ while true:
# Scheme
if url[i] == ':':
if url[i+1] == '/' and url[i+2] == '/':
scheme = temp
- temp.setlen(0)
+ temp.setLen(0)
inc(i, 3) # Skip the //
# Authority(username, password)
if url[i] == '@':
@@ -45,7 +45,7 @@ proc parseUrl*(url: string): Url {.deprecated.} =
if colon >= 0:
password = username.substr(colon+1)
username = username.substr(0, colon-1)
- temp.setlen(0)
+ temp.setLen(0)
inc(i) #Skip the @
# hostname(subdomain, domain, port)
if url[i] == '/' or url[i] == '\0':
@@ -55,7 +55,7 @@ proc parseUrl*(url: string): Url {.deprecated.} =
port = hostname.substr(colon+1)
hostname = hostname.substr(0, colon-1)
- temp.setlen(0)
+ temp.setLen(0)
break
temp.add(url[i])
@@ -63,16 +63,16 @@ proc parseUrl*(url: string): Url {.deprecated.} =
if url[i] == '/': inc(i) # Skip the '/'
# Path
- while True:
+ while true:
if url[i] == '?':
path = temp
- temp.setlen(0)
+ temp.setLen(0)
if url[i] == '#':
if temp[0] == '?':
query = temp
else:
path = temp
- temp.setlen(0)
+ temp.setLen(0)
if url[i] == '\0':
if temp[0] == '?':
From cca8887ba072f99e52f45d66f2855272817d2123 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 02:26:22 +0200
Subject: [PATCH 026/409] updated pegs module
---
lib/pure/pegs.nim | 76 +++++++++++++++++++++++------------------------
1 file changed, 38 insertions(+), 38 deletions(-)
diff --git a/lib/pure/pegs.nim b/lib/pure/pegs.nim
index 8bd307c7d..b2d8a2a4f 100644
--- a/lib/pure/pegs.nim
+++ b/lib/pure/pegs.nim
@@ -81,7 +81,7 @@ type
of pkTerminal, pkTerminalIgnoreCase, pkTerminalIgnoreStyle: term: string
of pkChar, pkGreedyRepChar: ch: char
of pkCharChoice, pkGreedyRepSet: charChoice: ref set[char]
- of pkNonTerminal: nt: PNonTerminal
+ of pkNonTerminal: nt: NonTerminal
of pkBackRef..pkBackRefIgnoreStyle: index: range[0..MaxSubpatterns]
else: sons: seq[TNode]
NonTerminal* = ref NonTerminalObj
@@ -237,7 +237,7 @@ proc anyRune*: Peg {.inline.} =
proc newLine*: Peg {.inline.} =
## constructs the PEG `newline`:idx: (``\n``)
- result.kind = pkNewline
+ result.kind = pkNewLine
proc unicodeLetter*: Peg {.inline.} =
## constructs the PEG ``\letter`` which matches any Unicode letter.
@@ -273,21 +273,21 @@ proc capture*(a: Peg): Peg {.nosideEffect, rtl, extern: "npegsCapture".} =
result.kind = pkCapture
result.sons = @[a]
-proc backref*(index: range[1..MaxSubPatterns]): Peg {.
+proc backref*(index: range[1..MaxSubpatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a back reference of the given `index`. `index` starts counting
## from 1.
result.kind = pkBackRef
result.index = index-1
-proc backrefIgnoreCase*(index: range[1..MaxSubPatterns]): Peg {.
+proc backrefIgnoreCase*(index: range[1..MaxSubpatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a back reference of the given `index`. `index` starts counting
## from 1. Ignores case for matching.
result.kind = pkBackRefIgnoreCase
result.index = index-1
-proc backrefIgnoreStyle*(index: range[1..MaxSubPatterns]): Peg {.
+proc backrefIgnoreStyle*(index: range[1..MaxSubpatterns]): Peg {.
nosideEffect, rtl, extern: "npegs$1".}=
## constructs a back reference of the given `index`. `index` starts counting
## from 1. Ignores style for matching.
@@ -309,7 +309,7 @@ proc spaceCost(n: Peg): int =
inc(result, spaceCost(n.sons[i]))
if result >= InlineThreshold: break
-proc nonterminal*(n: PNonTerminal): Peg {.
+proc nonterminal*(n: NonTerminal): Peg {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a PEG that consists of the nonterminal symbol
assert n != nil
@@ -320,7 +320,7 @@ proc nonterminal*(n: PNonTerminal): Peg {.
result.kind = pkNonTerminal
result.nt = n
-proc newNonTerminal*(name: string, line, column: int): PNonTerminal {.
+proc newNonTerminal*(name: string, line, column: int): NonTerminal {.
nosideEffect, rtl, extern: "npegs$1".} =
## constructs a nonterminal symbol
new(result)
@@ -416,7 +416,7 @@ proc toStrAux(r: Peg, res: var string) =
of pkTitle: add(res, "\\title")
of pkWhitespace: add(res, "\\white")
- of pkNewline: add(res, "\\n")
+ of pkNewLine: add(res, "\\n")
of pkTerminal: add(res, singleQuoteEsc(r.term))
of pkTerminalIgnoreCase:
add(res, 'i')
@@ -500,14 +500,14 @@ proc `$` *(r: Peg): string {.nosideEffect, rtl, extern: "npegsToString".} =
type
Captures* = object ## contains the captured substrings.
- matches: array[0..maxSubpatterns-1, tuple[first, last: int]]
+ matches: array[0..MaxSubpatterns-1, tuple[first, last: int]]
ml: int
origStart: int
{.deprecated: [TCaptures: Captures].}
proc bounds*(c: Captures,
- i: range[0..maxSubpatterns-1]): tuple[first, last: int] =
+ i: range[0..MaxSubpatterns-1]): tuple[first, last: int] =
## returns the bounds ``[first..last]`` of the `i`'th capture.
result = c.matches[i]
@@ -543,7 +543,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
result = -1
of pkLetter:
if s[start] != '\0':
- var a: TRune
+ var a: Rune
result = start
fastRuneAt(s, result, a)
if isAlpha(a): dec(result, start)
@@ -552,7 +552,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
result = -1
of pkLower:
if s[start] != '\0':
- var a: TRune
+ var a: Rune
result = start
fastRuneAt(s, result, a)
if isLower(a): dec(result, start)
@@ -561,7 +561,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
result = -1
of pkUpper:
if s[start] != '\0':
- var a: TRune
+ var a: Rune
result = start
fastRuneAt(s, result, a)
if isUpper(a): dec(result, start)
@@ -570,7 +570,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
result = -1
of pkTitle:
if s[start] != '\0':
- var a: TRune
+ var a: Rune
result = start
fastRuneAt(s, result, a)
if isTitle(a): dec(result, start)
@@ -579,7 +579,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
result = -1
of pkWhitespace:
if s[start] != '\0':
- var a: TRune
+ var a: Rune
result = start
fastRuneAt(s, result, a)
if isWhiteSpace(a): dec(result, start)
@@ -603,7 +603,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
of pkTerminalIgnoreCase:
var
i = 0
- a, b: TRune
+ a, b: Rune
result = start
while i < len(p.term):
fastRuneAt(p.term, i, a)
@@ -615,15 +615,15 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
of pkTerminalIgnoreStyle:
var
i = 0
- a, b: TRune
+ a, b: Rune
result = start
while i < len(p.term):
while true:
fastRuneAt(p.term, i, a)
- if a != TRune('_'): break
+ if a != Rune('_'): break
while true:
fastRuneAt(s, result, b)
- if b != TRune('_'): break
+ if b != Rune('_'): break
if toLower(a) != toLower(b):
result = -1
break
@@ -674,7 +674,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
while start+result < s.len:
var x = rawMatch(s, p.sons[0], start+result, c)
if x >= 0:
- if idx < maxSubpatterns:
+ if idx < MaxSubpatterns:
c.matches[idx] = (start, start+result-1)
#else: silently ignore the capture
inc(result, x)
@@ -718,7 +718,7 @@ proc rawMatch*(s: string, p: Peg, start: int, c: var Captures): int {.
inc(c.ml)
result = rawMatch(s, p.sons[0], start, c)
if result >= 0:
- if idx < maxSubpatterns:
+ if idx < MaxSubpatterns:
c.matches[idx] = (start, start+result-1)
#else: silently ignore the capture
else:
@@ -861,7 +861,7 @@ template `=~`*(s: string, pattern: Peg): bool =
## else:
## echo("syntax error")
##
- bind maxSubpatterns
+ bind MaxSubpatterns
when not declaredInScope(matches):
var matches {.inject.}: array[0..MaxSubpatterns-1, string]
match(s, pattern, matches)
@@ -906,7 +906,7 @@ proc replacef*(s: string, sub: Peg, by: string): string {.
## "var1<-keykey; val2<-key2key2"
result = ""
var i = 0
- var caps: array[0..maxSubpatterns-1, string]
+ var caps: array[0..MaxSubpatterns-1, string]
var c: Captures
while i < s.len:
c.ml = 0
@@ -945,7 +945,7 @@ proc parallelReplace*(s: string, subs: varargs[
result = ""
var i = 0
var c: Captures
- var caps: array[0..maxSubpatterns-1, string]
+ var caps: array[0..MaxSubpatterns-1, string]
while i < s.len:
block searchSubs:
for j in 0..high(subs):
@@ -1055,7 +1055,7 @@ type
PegLexer {.inheritable.} = object ## the lexer object.
bufpos: int ## the current position within the buffer
buf: cstring ## the buffer itself
- LineNumber: int ## the current line number
+ lineNumber: int ## the current line number
lineStart: int ## index of last line start in buffer
colOffset: int ## column to add
filename: string
@@ -1070,14 +1070,14 @@ const
proc handleCR(L: var PegLexer, pos: int): int =
assert(L.buf[pos] == '\c')
- inc(L.linenumber)
+ inc(L.lineNumber)
result = pos+1
if L.buf[result] == '\L': inc(result)
L.lineStart = result
proc handleLF(L: var PegLexer, pos: int): int =
assert(L.buf[pos] == '\L')
- inc(L.linenumber)
+ inc(L.lineNumber)
result = pos+1
L.lineStart = result
@@ -1093,7 +1093,7 @@ proc getColumn(L: PegLexer): int {.inline.} =
result = abs(L.bufpos - L.lineStart) + L.colOffset
proc getLine(L: PegLexer): int {.inline.} =
- result = L.linenumber
+ result = L.lineNumber
proc errorStr(L: PegLexer, msg: string, line = -1, col = -1): string =
var line = if line < 0: getLine(L) else: line
@@ -1159,7 +1159,7 @@ proc getEscapedChar(c: var PegLexer, tok: var TToken) =
else: tok.kind = tkInvalid
of '\0'..'\31':
tok.kind = tkInvalid
- elif c.buf[c.bufpos] in strutils.letters:
+ elif c.buf[c.bufpos] in strutils.Letters:
tok.kind = tkInvalid
else:
add(tok.literal, c.buf[c.bufpos])
@@ -1186,7 +1186,7 @@ proc skip(c: var PegLexer) =
proc getString(c: var PegLexer, tok: var TToken) =
tok.kind = tkStringLit
- var pos = c.bufPos + 1
+ var pos = c.bufpos + 1
var buf = c.buf
var quote = buf[pos-1]
while true:
@@ -1207,7 +1207,7 @@ proc getString(c: var PegLexer, tok: var TToken) =
c.bufpos = pos
proc getDollar(c: var PegLexer, tok: var TToken) =
- var pos = c.bufPos + 1
+ var pos = c.bufpos + 1
var buf = c.buf
if buf[pos] in {'0'..'9'}:
tok.kind = tkBackref
@@ -1222,7 +1222,7 @@ proc getDollar(c: var PegLexer, tok: var TToken) =
proc getCharSet(c: var PegLexer, tok: var TToken) =
tok.kind = tkCharSet
tok.charset = {}
- var pos = c.bufPos + 1
+ var pos = c.bufpos + 1
var buf = c.buf
var caret = false
if buf[pos] == '^':
@@ -1404,11 +1404,11 @@ proc arrowIsNextTok(c: PegLexer): bool =
# ----------------------------- parser ----------------------------------------
type
- EInvalidPeg* = object of EInvalidValue ## raised if an invalid
+ EInvalidPeg* = object of ValueError ## raised if an invalid
## PEG has been detected
PegParser = object of PegLexer ## the PEG parser object
tok: TToken
- nonterms: seq[PNonTerminal]
+ nonterms: seq[NonTerminal]
modifier: TModifier
captures: int
identIsVerbatim: bool
@@ -1430,7 +1430,7 @@ proc eat(p: var PegParser, kind: TTokKind) =
proc parseExpr(p: var PegParser): Peg
-proc getNonTerminal(p: var PegParser, name: string): PNonTerminal =
+proc getNonTerminal(p: var PegParser, name: string): NonTerminal =
for i in 0..high(p.nonterms):
result = p.nonterms[i]
if cmpIgnoreStyle(result.name, name) == 0: return
@@ -1567,7 +1567,7 @@ proc seqExpr(p: var PegParser): Peg =
result = primary(p)
while true:
case p.tok.kind
- of tkAmp, tkNot, tkAt, tkStringLit, tkCharset, tkParLe, tkCurlyLe,
+ of tkAmp, tkNot, tkAt, tkStringLit, tkCharSet, tkParLe, tkCurlyLe,
tkAny, tkAnyRune, tkBuiltin, tkEscaped, tkDollar, tkBackref,
tkHat, tkCurlyAt:
result = sequence(result, primary(p))
@@ -1583,7 +1583,7 @@ proc parseExpr(p: var PegParser): Peg =
getTok(p)
result = result / seqExpr(p)
-proc parseRule(p: var PegParser): PNonTerminal =
+proc parseRule(p: var PegParser): NonTerminal =
if p.tok.kind == tkIdentifier and arrowIsNextTok(p):
result = getNonTerminal(p, p.tok.literal)
if ntDeclared in result.flags:
@@ -1712,7 +1712,7 @@ when isMainModule:
assert match("_______ana", peg"A <- 'ana' / . A")
assert match("abcs%%%", peg"A <- ..A / .A / '%'")
- var matches: array[0..maxSubpatterns-1, string]
+ var matches: array[0..MaxSubpatterns-1, string]
if "abc" =~ peg"{'a'}'bc' 'xyz' / {\ident}":
assert matches[0] == "abc"
else:
From 649dfa09c4fcef2d8174cf4f997aa482600a718e Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 08:50:01 +0200
Subject: [PATCH 027/409] updated poly.nim
---
lib/pure/poly.nim | 62 +++++++++++++++++++++----------------------
lib/pure/terminal.nim | 24 +++++++++++------
2 files changed, 47 insertions(+), 39 deletions(-)
diff --git a/lib/pure/poly.nim b/lib/pure/poly.nim
index 19bed2aca..286e5a8fd 100644
--- a/lib/pure/poly.nim
+++ b/lib/pure/poly.nim
@@ -17,13 +17,13 @@ type
{.deprecated: [TPoly: Poly].}
-proc degree*(p:TPoly):int=
+proc degree*(p:Poly):int=
## Returns the degree of the polynomial,
## that is the number of coefficients-1
return p.cofs.len-1
-proc eval*(p:TPoly,x:float):float=
+proc eval*(p:Poly,x:float):float=
## Evaluates a polynomial function value for `x`
## quickly using Horners method
var n=p.degree
@@ -33,7 +33,7 @@ proc eval*(p:TPoly,x:float):float=
result = result*x+p.cofs[n]
dec n
-proc `[]` *(p:TPoly;idx:int):float=
+proc `[]` *(p:Poly;idx:int):float=
## Gets a coefficient of the polynomial.
## p[2] will returns the quadric term, p[3] the cubic etc.
## Out of bounds index will return 0.0.
@@ -41,7 +41,7 @@ proc `[]` *(p:TPoly;idx:int):float=
return 0.0
return p.cofs[idx]
-proc `[]=` *(p:var TPoly;idx:int,v:float)=
+proc `[]=` *(p:var Poly;idx:int,v:float)=
## Sets an coefficient of the polynomial by index.
## p[2] set the quadric term, p[3] the cubic etc.
## If index is out of range for the coefficients,
@@ -57,14 +57,14 @@ proc `[]=` *(p:var TPoly;idx:int,v:float)=
p.cofs[idx]=v
-iterator items*(p:TPoly):float=
+iterator items*(p:Poly):float=
## Iterates through the corfficients of the polynomial.
var i=p.degree
while i>=0:
yield p[i]
dec i
-proc clean*(p:var TPoly;zerotol=0.0)=
+proc clean*(p:var Poly;zerotol=0.0)=
## Removes leading zero coefficients of the polynomial.
## An optional tolerance can be given for what's considered zero.
var n=p.degree
@@ -77,7 +77,7 @@ proc clean*(p:var TPoly;zerotol=0.0)=
if relen: p.cofs.setLen(n+1)
-proc `$` *(p:TPoly):string =
+proc `$` *(p:Poly):string =
## Gets a somewhat reasonable string representation of the polynomial
## The format should be compatible with most online function plotters,
## for example directly in google search
@@ -105,13 +105,13 @@ proc `$` *(p:TPoly):string =
result="0"
-proc derivative*(p: TPoly): TPoly=
+proc derivative*(p: Poly): Poly=
## Returns a new polynomial, which is the derivative of `p`
newSeq[float](result.cofs,p.degree)
for idx in 0..high(result.cofs):
result.cofs[idx]=p.cofs[idx+1]*float(idx+1)
-proc diff*(p:TPoly,x:float):float=
+proc diff*(p:Poly,x:float):float=
## Evaluates the differentiation of a polynomial with
## respect to `x` quickly using a modifed Horners method
var n=p.degree
@@ -121,7 +121,7 @@ proc diff*(p:TPoly,x:float):float=
result = result*x+p[n]*float(n)
dec n
-proc integral*(p:TPoly):TPoly=
+proc integral*(p:Poly):Poly=
## Returns a new polynomial which is the indefinite
## integral of `p`. The constant term is set to 0.0
newSeq(result.cofs,p.cofs.len+1)
@@ -130,7 +130,7 @@ proc integral*(p:TPoly):TPoly=
result.cofs[i]=p.cofs[i-1]/float(i)
-proc integrate*(p:TPoly;xmin,xmax:float):float=
+proc integrate*(p:Poly;xmin,xmax:float):float=
## Computes the definite integral of `p` between `xmin` and `xmax`
## quickly using a modified version of Horners method
var
@@ -148,7 +148,7 @@ proc integrate*(p:TPoly;xmin,xmax:float):float=
result=s2*xmax-s1*xmin
-proc initPoly*(cofs:varargs[float]):TPoly=
+proc initPoly*(cofs:varargs[float]):Poly=
## Initializes a polynomial with given coefficients.
## The most significant coefficient is first, so to create x^2-2x+3:
## intiPoly(1.0,-2.0,3.0)
@@ -164,7 +164,7 @@ proc initPoly*(cofs:varargs[float]):TPoly=
result.clean #remove leading zero terms
-proc divMod*(p,d:TPoly;q,r:var TPoly)=
+proc divMod*(p,d:Poly;q,r:var Poly)=
## Divides `p` with `d`, and stores the quotinent in `q` and
## the remainder in `d`
var
@@ -192,7 +192,7 @@ proc divMod*(p,d:TPoly;q,r:var TPoly)=
r.clean # drop zero coefficients in remainder
-proc `+` *(p1:TPoly,p2:TPoly):TPoly=
+proc `+` *(p1:Poly,p2:Poly):Poly=
## Adds two polynomials
var n=max(p1.cofs.len,p2.cofs.len)
newSeq(result.cofs,n)
@@ -202,7 +202,7 @@ proc `+` *(p1:TPoly,p2:TPoly):TPoly=
result.clean # drop zero coefficients in remainder
-proc `*` *(p1:TPoly,p2:TPoly):TPoly=
+proc `*` *(p1:Poly,p2:Poly):Poly=
## Multiplies the polynomial `p1` with `p2`
var
d1=p1.degree
@@ -219,24 +219,24 @@ proc `*` *(p1:TPoly,p2:TPoly):TPoly=
result.clean
-proc `*` *(p:TPoly,f:float):TPoly=
+proc `*` *(p:Poly,f:float):Poly=
## Multiplies the polynomial `p` with a real number
newSeq(result.cofs,p.cofs.len)
for i in 0..high(p.cofs):
result[i]=p.cofs[i]*f
result.clean
-proc `*` *(f:float,p:TPoly):TPoly=
+proc `*` *(f:float,p:Poly):Poly=
## Multiplies a real number with a polynomial
return p*f
-proc `-`*(p:TPoly):TPoly=
+proc `-`*(p:Poly):Poly=
## Negates a polynomial
result=p
for i in countup(0, no roots
return @[linrt]
elif p.degree==2:
diff --git a/lib/pure/terminal.nim b/lib/pure/terminal.nim
index 19635ee68..323b8b216 100644
--- a/lib/pure/terminal.nim
+++ b/lib/pure/terminal.nim
@@ -31,7 +31,8 @@ when defined(windows):
proc getCursorPos(): tuple [x,y: int] =
var c: TCONSOLESCREENBUFFERINFO
- if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0: raiseOSError(osLastError())
+ if GetConsoleScreenBufferInfo(conHandle, addr(c)) == 0:
+ raiseOSError(osLastError())
return (int(c.dwCursorPosition.x), int(c.dwCursorPosition.y))
proc getAttributes(): int16 =
@@ -61,10 +62,12 @@ proc setCursorXPos*(x: int) =
when defined(windows):
var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
+ raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.x = int16(x)
- if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0:
+ raiseOSError(osLastError())
else:
stdout.write("\e[" & $x & 'G')
@@ -75,10 +78,12 @@ when defined(windows):
when defined(windows):
var scrbuf: TCONSOLESCREENBUFFERINFO
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
+ raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.y = int16(y)
- if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0:
+ raiseOSError(osLastError())
else:
discard
@@ -155,10 +160,12 @@ proc eraseLine* =
var scrbuf: TCONSOLESCREENBUFFERINFO
var numwrote: DWORD
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
+ raiseOSError(osLastError())
var origin = scrbuf.dwCursorPosition
origin.x = 0'i16
- if SetConsoleCursorPosition(conHandle, origin) == 0: raiseOSError(osLastError())
+ if SetConsoleCursorPosition(conHandle, origin) == 0:
+ raiseOSError(osLastError())
var ht = scrbuf.dwSize.Y - origin.Y
var wt = scrbuf.dwSize.X - origin.X
if FillConsoleOutputCharacter(hStdout,' ', ht*wt,
@@ -178,7 +185,8 @@ proc eraseScreen* =
var numwrote: DWORD
var origin: TCOORD # is inititalized to 0, 0
var hStdout = conHandle
- if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0: raiseOSError(osLastError())
+ if GetConsoleScreenBufferInfo(hStdout, addr(scrbuf)) == 0:
+ raiseOSError(osLastError())
if FillConsoleOutputCharacter(hStdout, ' ', scrbuf.dwSize.X*scrbuf.dwSize.Y,
origin, addr(numwrote)) == 0:
raiseOSError(osLastError())
From 2781fea9e2a67e86f37277f5e2808fc444a1173a Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 09:38:14 +0200
Subject: [PATCH 028/409] Nimrod renamed to Nim
---
compiler/aliases.nim | 2 +-
compiler/ast.nim | 2 +-
compiler/astalgo.nim | 2 +-
compiler/babelcmd.nim | 4 ++--
compiler/bitsets.nim | 6 +++---
compiler/canonicalizer.nim | 4 ++--
compiler/ccgcalls.nim | 2 +-
compiler/ccgexprs.nim | 8 ++++----
compiler/ccgmerge.nim | 2 +-
compiler/ccgstmts.nim | 4 ++--
compiler/ccgthreadvars.nim | 2 +-
compiler/ccgtrav.nim | 2 +-
compiler/ccgtypes.nim | 2 +-
compiler/ccgutils.nim | 2 +-
compiler/cgen.nim | 8 ++++----
compiler/cgendata.nim | 4 ++--
compiler/cgmeth.nim | 2 +-
compiler/commands.nim | 4 ++--
compiler/condsyms.nim | 2 +-
compiler/crc.nim | 2 +-
compiler/depends.nim | 2 +-
compiler/docgen.nim | 2 +-
compiler/docgen2.nim | 2 +-
compiler/evalffi.nim | 4 ++--
compiler/evaltempl.nim | 2 +-
compiler/extccomp.nim | 2 +-
compiler/filter_tmpl.nim | 6 +++---
compiler/filters.nim | 4 ++--
compiler/guards.nim | 2 +-
compiler/hlo.nim | 2 +-
compiler/idents.nim | 2 +-
compiler/idgen.nim | 2 +-
compiler/importer.nim | 2 +-
compiler/jsgen.nim | 4 ++--
compiler/jstypes.nim | 2 +-
compiler/lambdalifting.nim | 2 +-
compiler/lexer.nim | 6 +++---
compiler/lists.nim | 2 +-
compiler/llstream.nim | 2 +-
compiler/lowerings.nim | 2 +-
compiler/main.nim | 2 +-
compiler/modules.nim | 4 ++--
compiler/msgs.nim | 2 +-
compiler/nimconf.nim | 4 ++--
compiler/nimeval.nim | 4 ++--
compiler/nimlexbase.nim | 2 +-
compiler/nimrod.ini | 12 ++++++------
compiler/nimrod.nim | 2 +-
compiler/nimrod.nimrod.cfg | 2 +-
compiler/nimsets.nim | 4 ++--
compiler/nversion.nim | 4 ++--
compiler/options.nim | 4 ++--
compiler/parampatterns.nim | 2 +-
compiler/parser.nim | 4 ++--
compiler/passaux.nim | 2 +-
compiler/passes.nim | 2 +-
compiler/patterns.nim | 2 +-
compiler/pbraces.nim | 2 +-
compiler/procfind.nim | 2 +-
compiler/readme.txt | 4 ++--
compiler/renderer.nim | 4 ++--
compiler/rodread.nim | 2 +-
compiler/rodutils.nim | 2 +-
compiler/rodwrite.nim | 4 ++--
compiler/ropes.nim | 4 ++--
compiler/saturate.nim | 2 +-
compiler/sem.nim | 2 +-
compiler/semcall.nim | 2 +-
compiler/semdata.nim | 2 +-
compiler/semdestruct.nim | 2 +-
compiler/semgnrc.nim | 2 +-
compiler/seminst.nim | 2 +-
compiler/semmacrosanity.nim | 2 +-
compiler/semmagic.nim | 2 +-
compiler/semparallel.nim | 2 +-
compiler/sempass2.nim | 2 +-
compiler/semstmts.nim | 2 +-
compiler/semtempl.nim | 2 +-
compiler/service.nim | 2 +-
compiler/sigmatch.nim | 2 +-
compiler/suggest.nim | 2 +-
compiler/syntaxes.nim | 2 +-
compiler/tccgen.nim | 2 +-
compiler/transf.nim | 2 +-
compiler/trees.nim | 2 +-
compiler/treetab.nim | 2 +-
compiler/types.nim | 2 +-
compiler/vmdeps.nim | 2 +-
compiler/wordrecg.nim | 2 +-
89 files changed, 125 insertions(+), 125 deletions(-)
diff --git a/compiler/aliases.nim b/compiler/aliases.nim
index a26b94303..d68c9360a 100644
--- a/compiler/aliases.nim
+++ b/compiler/aliases.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ast.nim b/compiler/ast.nim
index b6878c56e..2ba9cdb2e 100644
--- a/compiler/ast.nim
+++ b/compiler/ast.nim
@@ -476,7 +476,7 @@ type
# and first phase symbol lookup in generics
skConditional, # symbol for the preprocessor (may become obsolete)
skDynLib, # symbol represents a dynamic library; this is used
- # internally; it does not exist in Nimrod code
+ # internally; it does not exist in Nim code
skParam, # a parameter
skGenericParam, # a generic parameter; eq in ``proc x[eq=`==`]()``
skTemp, # a temporary variable (introduced by compiler)
diff --git a/compiler/astalgo.nim b/compiler/astalgo.nim
index e95dbf7c8..ad5393dbd 100644
--- a/compiler/astalgo.nim
+++ b/compiler/astalgo.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/babelcmd.nim b/compiler/babelcmd.nim
index 7fa233732..d67b1dab5 100644
--- a/compiler/babelcmd.nim
+++ b/compiler/babelcmd.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## Implements some helper procs for Babel (Nimrod's package manager) support.
+## Implements some helper procs for Babel (Nim's package manager) support.
import parseutils, strutils, strtabs, os, options, msgs, lists
diff --git a/compiler/bitsets.nim b/compiler/bitsets.nim
index 740bdd5ef..a2324f4e2 100644
--- a/compiler/bitsets.nim
+++ b/compiler/bitsets.nim
@@ -1,14 +1,14 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# this unit handles Nimrod sets; it implements bit sets
-# the code here should be reused in the Nimrod standard library
+# this unit handles Nim sets; it implements bit sets
+# the code here should be reused in the Nim standard library
type
TBitSet* = seq[int8] # we use byte here to avoid issues with
diff --git a/compiler/canonicalizer.nim b/compiler/canonicalizer.nim
index 3bc4eb029..14448f0e8 100644
--- a/compiler/canonicalizer.nim
+++ b/compiler/canonicalizer.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -370,7 +370,7 @@ proc encodeSym(w: PRodWriter, s: PSym, result: var string) =
# the last entry of a symbol:
if s.ast != nil:
# we used to attempt to save space here by only storing a dummy AST if
- # it is not necessary, but Nimrod's heavy compile-time evaluation features
+ # it is not necessary, but Nim's heavy compile-time evaluation features
# make that unfeasible nowadays:
encodeNode(w, s.info, s.ast, result)
diff --git a/compiler/ccgcalls.nim b/compiler/ccgcalls.nim
index adcc95e84..753d375af 100644
--- a/compiler/ccgcalls.nim
+++ b/compiler/ccgcalls.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim
index b5817de05..8914ad0de 100644
--- a/compiler/ccgexprs.nim
+++ b/compiler/ccgexprs.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -15,7 +15,7 @@ proc intLiteral(i: BiggestInt): PRope =
if (i > low(int32)) and (i <= high(int32)):
result = toRope(i)
elif i == low(int32):
- # Nimrod has the same bug for the same reasons :-)
+ # Nim has the same bug for the same reasons :-)
result = ~"(-2147483647 -1)"
elif i > low(int64):
result = rfmt(nil, "IL64($1)", toRope(i))
@@ -908,7 +908,7 @@ proc gcUsage(n: PNode) =
if gSelectedGC == gcNone: message(n.info, warnGcMem, n.renderTree)
proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
- #
+ #
# s = 'Hello ' & name & ', how do you feel?' & 'z'
#
#
@@ -951,7 +951,7 @@ proc genStrConcat(p: BProc, e: PNode, d: var TLoc) =
gcUsage(e)
proc genStrAppend(p: BProc, e: PNode, d: var TLoc) =
- #
+ #
# s &= 'Hello ' & name & ', how do you feel?' & 'z'
# // BUG: what if s is on the left side too?
#
diff --git a/compiler/ccgmerge.nim b/compiler/ccgmerge.nim
index 2d27257ce..69c41ff59 100644
--- a/compiler/ccgmerge.nim
+++ b/compiler/ccgmerge.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim
index 0c3d35f7b..66bfbba8c 100644
--- a/compiler/ccgstmts.nim
+++ b/compiler/ccgstmts.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -547,7 +547,7 @@ proc genCaseSecondPass(p: BProc, t: PNode, d: var TLoc,
proc genIfForCaseUntil(p: BProc, t: PNode, d: var TLoc,
rangeFormat, eqFormat: TFormatStr,
until: int, a: TLoc): TLabel =
- # generate a C-if statement for a Nimrod case statement
+ # generate a C-if statement for a Nim case statement
var labId = p.labels
for i in 1..until:
inc(p.labels)
diff --git a/compiler/ccgthreadvars.nim b/compiler/ccgthreadvars.nim
index c00b931ef..60bc0fc4b 100644
--- a/compiler/ccgthreadvars.nim
+++ b/compiler/ccgthreadvars.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ccgtrav.nim b/compiler/ccgtrav.nim
index a5bf9e7a7..16ec564e8 100644
--- a/compiler/ccgtrav.nim
+++ b/compiler/ccgtrav.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim
index 0bd96e89f..8c2e99339 100644
--- a/compiler/ccgtypes.nim
+++ b/compiler/ccgtypes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/ccgutils.nim b/compiler/ccgutils.nim
index 48fdacf46..54af3c705 100644
--- a/compiler/ccgutils.nim
+++ b/compiler/ccgutils.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/cgen.nim b/compiler/cgen.nim
index deccf9ced..7c694f245 100644
--- a/compiler/cgen.nim
+++ b/compiler/cgen.nim
@@ -917,18 +917,18 @@ proc addIntTypes(result: var PRope) {.inline.} =
proc getCopyright(cfilenoext: string): PRope =
if optCompileOnly in gGlobalOptions:
- result = ropeff("/* Generated by Nimrod Compiler v$1 */$N" &
+ result = ropeff("/* Generated by Nim Compiler v$1 */$N" &
"/* (c) 2014 Andreas Rumpf */$N" &
"/* The generated code is subject to the original license. */$N",
- "; Generated by Nimrod Compiler v$1$N" &
+ "; Generated by Nim Compiler v$1$N" &
"; (c) 2012 Andreas Rumpf$N", [toRope(VersionAsString)])
else:
- result = ropeff("/* Generated by Nimrod Compiler v$1 */$N" &
+ result = ropeff("/* Generated by Nim Compiler v$1 */$N" &
"/* (c) 2014 Andreas Rumpf */$N" &
"/* The generated code is subject to the original license. */$N" &
"/* Compiled for: $2, $3, $4 */$N" &
"/* Command for C compiler:$n $5 */$N",
- "; Generated by Nimrod Compiler v$1$N" &
+ "; Generated by Nim Compiler v$1$N" &
"; (c) 2014 Andreas Rumpf$N" &
"; Compiled for: $2, $3, $4$N" &
"; Command for LLVM compiler:$N $5$N", [toRope(VersionAsString),
diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim
index 12041c55b..ea8f32974 100644
--- a/compiler/cgendata.nim
+++ b/compiler/cgendata.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -62,7 +62,7 @@ type
frameLen*: int16
TCProc{.final.} = object # represents C proc that is currently generated
- prc*: PSym # the Nimrod proc that this C proc belongs to
+ prc*: PSym # the Nim proc that this C proc belongs to
beforeRetNeeded*: bool # true iff 'BeforeRet' label for proc is needed
threadVarAccessed*: bool # true if the proc already accessed some threadvar
nestedTryStmts*: seq[PNode] # in how many nested try statements we are
diff --git a/compiler/cgmeth.nim b/compiler/cgmeth.nim
index 948541302..1d0cb82ad 100644
--- a/compiler/cgmeth.nim
+++ b/compiler/cgmeth.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/commands.nim b/compiler/commands.nim
index 712e0e1c5..fff860de9 100644
--- a/compiler/commands.nim
+++ b/compiler/commands.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -51,7 +51,7 @@ proc processSwitch*(switch, arg: string, pass: TCmdLinePass, info: TLineInfo)
# implementation
const
- HelpMessage = "Nimrod Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" &
+ HelpMessage = "Nim Compiler Version $1 (" & CompileDate & ") [$2: $3]\n" &
"Copyright (c) 2006-2014 by Andreas Rumpf\n"
const
diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim
index 6b93b1c12..28288ed39 100644
--- a/compiler/condsyms.nim
+++ b/compiler/condsyms.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/crc.nim b/compiler/crc.nim
index 22b1d1b69..a8b61f2a5 100644
--- a/compiler/crc.nim
+++ b/compiler/crc.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/depends.nim b/compiler/depends.nim
index a43eaf844..115a98f84 100644
--- a/compiler/depends.nim
+++ b/compiler/depends.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/docgen.nim b/compiler/docgen.nim
index 7d9a11fbc..5c851118d 100644
--- a/compiler/docgen.nim
+++ b/compiler/docgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/docgen2.nim b/compiler/docgen2.nim
index 1bff89b55..aa832b6df 100644
--- a/compiler/docgen2.nim
+++ b/compiler/docgen2.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/evalffi.nim b/compiler/evalffi.nim
index f798a43ac..d6b3a1aa5 100644
--- a/compiler/evalffi.nim
+++ b/compiler/evalffi.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## This file implements the FFI part of the evaluator for Nimrod code.
+## This file implements the FFI part of the evaluator for Nim code.
import ast, astalgo, ropes, types, options, tables, dynlib, libffi, msgs, os
diff --git a/compiler/evaltempl.nim b/compiler/evaltempl.nim
index 78cdbb45f..78cc691c0 100644
--- a/compiler/evaltempl.nim
+++ b/compiler/evaltempl.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/extccomp.nim b/compiler/extccomp.nim
index 8dc399f43..7a213aea4 100644
--- a/compiler/extccomp.nim
+++ b/compiler/extccomp.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/filter_tmpl.nim b/compiler/filter_tmpl.nim
index 0014e9c78..7b975dbaa 100644
--- a/compiler/filter_tmpl.nim
+++ b/compiler/filter_tmpl.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# This module implements Nimrod's standard template filter.
+# This module implements Nim's standard template filter.
import
llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options,
@@ -148,7 +148,7 @@ proc parseLine(p: var TTmplParser) =
inc(j)
else:
if p.x[j] == p.subsChar:
- # parse Nimrod expression:
+ # parse Nim expression:
inc(j)
case p.x[j]
of '{':
diff --git a/compiler/filters.nim b/compiler/filters.nim
index ce0ffd196..783a320a4 100644
--- a/compiler/filters.nim
+++ b/compiler/filters.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# This module implements Nimrod's simple filters and helpers for filters.
+# This module implements Nim's simple filters and helpers for filters.
import
llstream, os, wordrecg, idents, strutils, ast, astalgo, msgs, options,
diff --git a/compiler/guards.nim b/compiler/guards.nim
index 431de6156..05128f409 100644
--- a/compiler/guards.nim
+++ b/compiler/guards.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/hlo.nim b/compiler/hlo.nim
index c75d6519f..363d100be 100644
--- a/compiler/hlo.nim
+++ b/compiler/hlo.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/idents.nim b/compiler/idents.nim
index c37d94362..775bffa00 100644
--- a/compiler/idents.nim
+++ b/compiler/idents.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/idgen.nim b/compiler/idgen.nim
index 7f137b885..3c5669b54 100644
--- a/compiler/idgen.nim
+++ b/compiler/idgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/importer.nim b/compiler/importer.nim
index b4cae017e..538957887 100644
--- a/compiler/importer.nim
+++ b/compiler/importer.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim
index dfe498e47..c97adffb1 100644
--- a/compiler/jsgen.nim
+++ b/compiler/jsgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -1664,7 +1664,7 @@ proc newModule(module: PSym): BModule =
if globals == nil: globals = newGlobals()
proc genHeader(): PRope =
- result = ropef("/* Generated by the Nimrod Compiler v$1 */$n" &
+ result = ropef("/* Generated by the Nim Compiler v$1 */$n" &
"/* (c) 2014 Andreas Rumpf */$n$n" &
"$nvar Globals = this;$n" &
"var framePtr = null;$n" &
diff --git a/compiler/jstypes.nim b/compiler/jstypes.nim
index 009fc7935..8b032c3ce 100644
--- a/compiler/jstypes.nim
+++ b/compiler/jstypes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/lambdalifting.nim b/compiler/lambdalifting.nim
index c29d20a0a..2a9b1e886 100644
--- a/compiler/lambdalifting.nim
+++ b/compiler/lambdalifting.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/lexer.nim b/compiler/lexer.nim
index abc491bfe..e0b3b76ce 100644
--- a/compiler/lexer.nim
+++ b/compiler/lexer.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -102,7 +102,7 @@ type
# so that it is the correct default value
base2, base8, base16
- TToken* = object # a Nimrod token
+ TToken* = object # a Nim token
tokType*: TTokType # the type of the token
indent*: int # the indentation; != -1 if the token has been
# preceeded with indentation
@@ -148,7 +148,7 @@ proc lexMessage*(L: TLexer, msg: TMsgKind, arg = "")
proc isKeyword(kind: TTokType): bool =
result = (kind >= tokKeywordLow) and (kind <= tokKeywordHigh)
-proc isNimrodIdentifier*(s: string): bool =
+proc isNimIdentifier*(s: string): bool =
if s[0] in SymStartChars:
var i = 1
while i < s.len:
diff --git a/compiler/lists.nim b/compiler/lists.nim
index 2b3a9f3fc..1b2b91bff 100644
--- a/compiler/lists.nim
+++ b/compiler/lists.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/llstream.nim b/compiler/llstream.nim
index 8dc3dcea3..be469548d 100644
--- a/compiler/llstream.nim
+++ b/compiler/llstream.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/lowerings.nim b/compiler/lowerings.nim
index c4155724f..e90ef9376 100644
--- a/compiler/lowerings.nim
+++ b/compiler/lowerings.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/main.nim b/compiler/main.nim
index b4af49248..58833f60c 100644
--- a/compiler/main.nim
+++ b/compiler/main.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/modules.nim b/compiler/modules.nim
index 65c438cc3..8939afd5a 100644
--- a/compiler/modules.nim
+++ b/compiler/modules.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -117,7 +117,7 @@ proc newModule(fileIdx: int32): PSym =
result.kind = skModule
let filename = fileIdx.toFullPath
result.name = getIdent(splitFile(filename).name)
- if not isNimrodIdentifier(result.name.s):
+ if not isNimIdentifier(result.name.s):
rawMessage(errInvalidModuleName, result.name.s)
result.info = newLineInfo(fileIdx, 1, 1)
diff --git a/compiler/msgs.nim b/compiler/msgs.nim
index 00f80a438..43b3b6c8e 100644
--- a/compiler/msgs.nim
+++ b/compiler/msgs.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/nimconf.nim b/compiler/nimconf.nim
index 136a0d454..d23c7f1be 100644
--- a/compiler/nimconf.nim
+++ b/compiler/nimconf.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -14,7 +14,7 @@ import
options, idents, wordrecg
# ---------------- configuration file parser -----------------------------
-# we use Nimrod's scanner here to safe space and work
+# we use Nim's scanner here to safe space and work
proc ppGetTok(L: var TLexer, tok: var TToken) =
# simple filter
diff --git a/compiler/nimeval.nim b/compiler/nimeval.nim
index 0ee108d48..5693cbe91 100644
--- a/compiler/nimeval.nim
+++ b/compiler/nimeval.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## exposes the Nimrod VM to clients.
+## exposes the Nim VM to clients.
import
ast, modules, passes, passaux, condsyms,
diff --git a/compiler/nimlexbase.nim b/compiler/nimlexbase.nim
index cabcac390..e18e1c22a 100644
--- a/compiler/nimlexbase.nim
+++ b/compiler/nimlexbase.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/nimrod.ini b/compiler/nimrod.ini
index 44e16cec8..8bd00e891 100644
--- a/compiler/nimrod.ini
+++ b/compiler/nimrod.ini
@@ -1,5 +1,5 @@
[Project]
-Name: "Nimrod"
+Name: "Nim"
Version: "$version"
Platforms: """
windows: i386;amd64
@@ -13,15 +13,15 @@ Platforms: """
"""
Authors: "Andreas Rumpf"
-Description: """This is the Nimrod Compiler. Nimrod is a new statically typed,
+Description: """This is the Nim Compiler. Nim is a new statically typed,
imperative programming language, that supports procedural, functional, object
oriented and generic programming styles while remaining simple and efficient.
-A special feature that Nimrod inherited from Lisp is that Nimrod's abstract
+A special feature that Nim inherited from Lisp is that Nim's abstract
syntax tree (AST) is part of the specification - this allows a powerful macro
system which can be used to create domain specific languages.
-Nimrod is a compiled, garbage-collected systems programming language
-which has an excellent productivity/performance ratio. Nimrod's design
+Nim is a compiled, garbage-collected systems programming language
+which has an excellent productivity/performance ratio. Nim's design
focuses on the 3E: efficiency, expressiveness, elegance (in the order of
priority)."""
@@ -149,6 +149,6 @@ flags = "-w"
[deb]
buildDepends: "gcc (>= 4:4.3.2)"
pkgDepends: "gcc (>= 4:4.3.2)"
-shortDesc: "The Nimrod Compiler"
+shortDesc: "The Nim Compiler"
licenses: "bin/nimrod,MIT;lib/*,MIT;"
diff --git a/compiler/nimrod.nim b/compiler/nimrod.nim
index 69cb8bb99..27222ca57 100644
--- a/compiler/nimrod.nim
+++ b/compiler/nimrod.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/nimrod.nimrod.cfg b/compiler/nimrod.nimrod.cfg
index 2c6e6f249..c9e4b248b 100644
--- a/compiler/nimrod.nimrod.cfg
+++ b/compiler/nimrod.nimrod.cfg
@@ -1,4 +1,4 @@
-# Special configuration file for the Nimrod project
+# Special configuration file for the Nim project
mainModule:"nimrod.nim"
diff --git a/compiler/nimsets.nim b/compiler/nimsets.nim
index d65618e0a..aa7686d30 100644
--- a/compiler/nimsets.nim
+++ b/compiler/nimsets.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# this unit handles Nimrod sets; it implements symbolic sets
+# this unit handles Nim sets; it implements symbolic sets
import
ast, astalgo, trees, nversion, msgs, platform, bitsets, types, renderer
diff --git a/compiler/nversion.nim b/compiler/nversion.nim
index 3c868ed2a..7f0f93782 100644
--- a/compiler/nversion.nim
+++ b/compiler/nversion.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# This module contains Nimrod's version. It is the only place where it needs
+# This module contains Nim's version. It is the only place where it needs
# to be changed.
const
diff --git a/compiler/options.nim b/compiler/options.nim
index 8acf9e830..e30080e8f 100644
--- a/compiler/options.nim
+++ b/compiler/options.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -68,7 +68,7 @@ type # please make sure we have under 32 options
# also: generate header file
TGlobalOptions* = set[TGlobalOption]
- TCommands* = enum # Nimrod's commands
+ TCommands* = enum # Nim's commands
# **keep binary compatible**
cmdNone, cmdCompileToC, cmdCompileToCpp, cmdCompileToOC,
cmdCompileToJS, cmdCompileToLLVM, cmdInterpret, cmdPretty, cmdDoc,
diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim
index bbdba8c22..300abea1e 100644
--- a/compiler/parampatterns.nim
+++ b/compiler/parampatterns.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/parser.nim b/compiler/parser.nim
index 548084974..20c037c00 100644
--- a/compiler/parser.nim
+++ b/compiler/parser.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# This module implements the parser of the standard Nimrod syntax.
+# This module implements the parser of the standard Nim syntax.
# The parser strictly reflects the grammar ("doc/grammar.txt"); however
# it uses several helper routines to keep the parser small. A special
# efficient algorithm is used for the precedence levels. The parser here can
diff --git a/compiler/passaux.nim b/compiler/passaux.nim
index 0ba9f22d0..f754c80e5 100644
--- a/compiler/passaux.nim
+++ b/compiler/passaux.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/passes.nim b/compiler/passes.nim
index 1af9739bd..a63e29b35 100644
--- a/compiler/passes.nim
+++ b/compiler/passes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/patterns.nim b/compiler/patterns.nim
index 5e21289b5..3d71aa4d1 100644
--- a/compiler/patterns.nim
+++ b/compiler/patterns.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/pbraces.nim b/compiler/pbraces.nim
index ce6e0d9a9..cf4dbffc5 100644
--- a/compiler/pbraces.nim
+++ b/compiler/pbraces.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/procfind.nim b/compiler/procfind.nim
index 0354d585d..e88524634 100644
--- a/compiler/procfind.nim
+++ b/compiler/procfind.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/readme.txt b/compiler/readme.txt
index 3d3cf4b29..c4934e031 100644
--- a/compiler/readme.txt
+++ b/compiler/readme.txt
@@ -1,4 +1,4 @@
-This directory contains the Nimrod compiler written in Nimrod. Note that this
+This directory contains the Nim compiler written in Nim. Note that this
code has been translated from a bootstrapping version written in Pascal, so
-the code is **not** a poster child of good Nimrod code.
+the code is **not** a poster child of good Nim code.
diff --git a/compiler/renderer.nim b/compiler/renderer.nim
index e01916920..29f581573 100644
--- a/compiler/renderer.nim
+++ b/compiler/renderer.nim
@@ -1,13 +1,13 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-# This module implements the renderer of the standard Nimrod representation.
+# This module implements the renderer of the standard Nim representation.
import
lexer, options, idents, strutils, ast, msgs, lists
diff --git a/compiler/rodread.nim b/compiler/rodread.nim
index 47020253f..acccc1abb 100644
--- a/compiler/rodread.nim
+++ b/compiler/rodread.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim
index 09b92cd8a..e0ef3c397 100644
--- a/compiler/rodutils.nim
+++ b/compiler/rodutils.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/rodwrite.nim b/compiler/rodwrite.nim
index 4948c8fc2..7eacb0883 100644
--- a/compiler/rodwrite.nim
+++ b/compiler/rodwrite.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -297,7 +297,7 @@ proc encodeSym(w: PRodWriter, s: PSym, result: var string) =
# the last entry of a symbol:
if s.ast != nil:
# we used to attempt to save space here by only storing a dummy AST if
- # it is not necessary, but Nimrod's heavy compile-time evaluation features
+ # it is not necessary, but Nim's heavy compile-time evaluation features
# make that unfeasible nowadays:
encodeNode(w, s.info, s.ast, result)
when false:
diff --git a/compiler/ropes.nim b/compiler/ropes.nim
index 6eb3673b4..b14081694 100644
--- a/compiler/ropes.nim
+++ b/compiler/ropes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -12,7 +12,7 @@
# Ropes are a data structure that represents a very long string
# efficiently; especially concatenation is done in O(1) instead of O(N).
# Ropes make use a lazy evaluation: They are essentially concatenation
-# trees that are only flattened when converting to a native Nimrod
+# trees that are only flattened when converting to a native Nim
# string or when written to disk. The empty string is represented by a
# nil pointer.
# A little picture makes everything clear:
diff --git a/compiler/saturate.nim b/compiler/saturate.nim
index ed197bdd1..f4fe29a20 100644
--- a/compiler/saturate.nim
+++ b/compiler/saturate.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/sem.nim b/compiler/sem.nim
index 26a59334c..be71ebef8 100644
--- a/compiler/sem.nim
+++ b/compiler/sem.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semcall.nim b/compiler/semcall.nim
index 927b23cf2..3ce88651f 100644
--- a/compiler/semcall.nim
+++ b/compiler/semcall.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semdata.nim b/compiler/semdata.nim
index abecc1b6d..c57ce2c26 100644
--- a/compiler/semdata.nim
+++ b/compiler/semdata.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semdestruct.nim b/compiler/semdestruct.nim
index 3c30dc1bd..4ce610bf9 100644
--- a/compiler/semdestruct.nim
+++ b/compiler/semdestruct.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim
index 224168528..8d8067195 100644
--- a/compiler/semgnrc.nim
+++ b/compiler/semgnrc.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/seminst.nim b/compiler/seminst.nim
index b205eb09a..8ac3849b4 100644
--- a/compiler/seminst.nim
+++ b/compiler/seminst.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semmacrosanity.nim b/compiler/semmacrosanity.nim
index 8106aa179..c685d602d 100644
--- a/compiler/semmacrosanity.nim
+++ b/compiler/semmacrosanity.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim
index f943e7006..7b612c806 100644
--- a/compiler/semmagic.nim
+++ b/compiler/semmagic.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semparallel.nim b/compiler/semparallel.nim
index 5571d1bed..fe735c9f2 100644
--- a/compiler/semparallel.nim
+++ b/compiler/semparallel.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim
index 332b74155..fee70af15 100644
--- a/compiler/sempass2.nim
+++ b/compiler/sempass2.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim
index 583185048..89acb2e98 100644
--- a/compiler/semstmts.nim
+++ b/compiler/semstmts.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semtempl.nim b/compiler/semtempl.nim
index ee8b1ccb8..880e37fef 100644
--- a/compiler/semtempl.nim
+++ b/compiler/semtempl.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/service.nim b/compiler/service.nim
index 22f5c6e33..8e1c9cf1b 100644
--- a/compiler/service.nim
+++ b/compiler/service.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim
index e5bf08097..588628c9a 100644
--- a/compiler/sigmatch.nim
+++ b/compiler/sigmatch.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/suggest.nim b/compiler/suggest.nim
index c2bdfc5c3..650e5b3fb 100644
--- a/compiler/suggest.nim
+++ b/compiler/suggest.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/syntaxes.nim b/compiler/syntaxes.nim
index 8de6dcd91..61677a641 100644
--- a/compiler/syntaxes.nim
+++ b/compiler/syntaxes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/tccgen.nim b/compiler/tccgen.nim
index a571d416e..0082dfcbb 100644
--- a/compiler/tccgen.nim
+++ b/compiler/tccgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/transf.nim b/compiler/transf.nim
index 00fe03ab6..bab719ba1 100644
--- a/compiler/transf.nim
+++ b/compiler/transf.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/trees.nim b/compiler/trees.nim
index 35e9334cc..b1edd21f3 100644
--- a/compiler/trees.nim
+++ b/compiler/trees.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/treetab.nim b/compiler/treetab.nim
index ecb8fb083..63f3fc6e2 100644
--- a/compiler/treetab.nim
+++ b/compiler/treetab.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/types.nim b/compiler/types.nim
index ba796b6c3..c810dc025 100644
--- a/compiler/types.nim
+++ b/compiler/types.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim
index c0916fbd8..831e2ddce 100644
--- a/compiler/vmdeps.nim
+++ b/compiler/vmdeps.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/wordrecg.nim b/compiler/wordrecg.nim
index 96056eb6f..e3b4b3062 100644
--- a/compiler/wordrecg.nim
+++ b/compiler/wordrecg.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
From d05df2173b95155a53e9c731f1c78b754eb2410c Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 09:50:51 +0200
Subject: [PATCH 029/409] Nimrod renamed to Nim
---
lib/core/locks.nim | 8 ++--
lib/core/macros.nim | 2 +-
lib/core/typeinfo.nim | 4 +-
lib/core/unsigned.nim | 2 +-
lib/impure/db_mysql.nim | 2 +-
lib/impure/db_postgres.nim | 2 +-
lib/impure/db_sqlite.nim | 2 +-
lib/impure/dialogs.nim | 4 +-
lib/impure/graphics.nim | 4 +-
lib/impure/rdstdin.nim | 2 +-
lib/impure/re.nim | 6 +--
lib/impure/ssl.nim | 2 +-
lib/impure/web.nim | 2 +-
lib/impure/zipfiles.nim | 2 +-
lib/js/dom.nim | 2 +-
lib/nimrtl.nim | 2 +-
lib/packages/docutils/rst.nim | 4 +-
lib/packages/docutils/rstast.nim | 2 +-
lib/posix/epoll.nim | 2 +-
lib/posix/inotify.nim | 2 +-
lib/posix/posix.nim | 6 +--
lib/prelude.nim | 2 +-
lib/pure/actors.nim | 2 +-
lib/pure/algorithm.nim | 4 +-
lib/pure/cgi.nim | 8 ++--
lib/pure/concurrency/cpuinfo.nim | 2 +-
lib/pure/concurrency/threadpool.nim | 2 +-
lib/pure/ftpclient.nim | 2 +-
lib/pure/gentabs.nim | 2 +-
lib/pure/httpserver.nim | 2 +-
lib/pure/math.nim | 6 +--
lib/pure/memfiles.nim | 2 +-
lib/pure/os.nim | 4 +-
lib/pure/osproc.nim | 2 +-
lib/pure/parsecfg.nim | 2 +-
lib/pure/ropes.nim | 2 +-
lib/pure/streams.nim | 4 +-
lib/pure/strutils.nim | 6 +--
lib/pure/typetraits.nim | 2 +-
lib/pure/unittest.nim | 2 +-
lib/pure/xmltree.nim | 8 ++--
lib/system.nim | 74 ++++++++++++++---------------
lib/windows/mmsystem.nim | 2 +-
lib/windows/nb30.nim | 2 +-
lib/windows/psapi.nim | 2 +-
lib/windows/shellapi.nim | 2 +-
lib/windows/shfolder.nim | 2 +-
lib/windows/windows.nim | 2 +-
lib/windows/winlean.nim | 2 +-
lib/wrappers/libsvm.nim | 2 +-
lib/wrappers/mysql.nim | 2 +-
lib/wrappers/sphinx.nim | 2 +-
lib/wrappers/sqlite3.nim | 2 +-
lib/wrappers/tinyc.nim | 2 +-
lib/wrappers/zip/libzip.nim | 2 +-
lib/wrappers/zip/zzip.nim | 2 +-
56 files changed, 116 insertions(+), 116 deletions(-)
diff --git a/lib/core/locks.nim b/lib/core/locks.nim
index 894965a85..d865c78c5 100644
--- a/lib/core/locks.nim
+++ b/lib/core/locks.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## This module contains Nimrod's support for locks and condition vars.
+## This module contains Nim's support for locks and condition vars.
## If the symbol ``preventDeadlocks`` is defined
## (compiled with ``-d:preventDeadlocks``) special logic is added to
## every ``acquire``, ``tryAcquire`` and ``release`` action that ensures at
@@ -18,10 +18,10 @@
include "system/syslocks"
type
- TLock* = TSysLock ## Nimrod lock; whether this is re-entrant
+ TLock* = TSysLock ## Nim lock; whether this is re-entrant
## or not is unspecified! However, compilation
## in preventDeadlocks-mode guarantees re-entrancy.
- TCond* = TSysCond ## Nimrod condition variable
+ TCond* = TSysCond ## Nim condition variable
FLock* = object of TEffect ## effect that denotes that some lock operation
## is performed
diff --git a/lib/core/macros.nim b/lib/core/macros.nim
index 0acd948fe..41ba030f9 100644
--- a/lib/core/macros.nim
+++ b/lib/core/macros.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim
index 848388c2b..5ca101919 100644
--- a/lib/core/typeinfo.nim
+++ b/lib/core/typeinfo.nim
@@ -585,7 +585,7 @@ proc assign*(x, y: TAny) =
genericAssign(x.value, y.value, y.rawType)
iterator elements*(x: TAny): int =
- ## iterates over every element of `x` that represents a Nimrod bitset.
+ ## iterates over every element of `x` that represents a Nim bitset.
assert x.rawType.kind == tySet
var typ = x.rawType
var p = x.value
@@ -607,7 +607,7 @@ iterator elements*(x: TAny): int =
yield i+typ.node.len
proc inclSetElement*(x: TAny, elem: int) =
- ## includes an element `elem` in `x`. `x` needs to represent a Nimrod bitset.
+ ## includes an element `elem` in `x`. `x` needs to represent a Nim bitset.
assert x.rawType.kind == tySet
var typ = x.rawType
var p = x.value
diff --git a/lib/core/unsigned.nim b/lib/core/unsigned.nim
index a3ddd4125..7acdf1439 100644
--- a/lib/core/unsigned.nim
+++ b/lib/core/unsigned.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim
index eec4daf00..709e899e8 100644
--- a/lib/impure/db_mysql.nim
+++ b/lib/impure/db_mysql.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/db_postgres.nim b/lib/impure/db_postgres.nim
index f6ae93303..6658dc0e0 100644
--- a/lib/impure/db_postgres.nim
+++ b/lib/impure/db_postgres.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/db_sqlite.nim b/lib/impure/db_sqlite.nim
index 809ee7039..844e5d07e 100644
--- a/lib/impure/db_sqlite.nim
+++ b/lib/impure/db_sqlite.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/dialogs.nim b/lib/impure/dialogs.nim
index 00ba2663e..bbed99239 100644
--- a/lib/impure/dialogs.nim
+++ b/lib/impure/dialogs.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -8,7 +8,7 @@
#
-## This module implements portable dialogs for Nimrod; the implementation
+## This module implements portable dialogs for Nim; the implementation
## builds on the GTK interface. On Windows, native dialogs are shown instead.
import
diff --git a/lib/impure/graphics.nim b/lib/impure/graphics.nim
index 2c8e96460..dda7626ba 100644
--- a/lib/impure/graphics.nim
+++ b/lib/impure/graphics.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf, Dominik Picheta
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## This module implements graphical output for Nimrod; the current
+## This module implements graphical output for Nim; the current
## implementation uses SDL but the interface is meant to support multiple
## backends some day. There is no need to init SDL as this module does that
## implicitly.
diff --git a/lib/impure/rdstdin.nim b/lib/impure/rdstdin.nim
index 1037d3bda..9153d2360 100644
--- a/lib/impure/rdstdin.nim
+++ b/lib/impure/rdstdin.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/re.nim b/lib/impure/re.nim
index ac07b2d6b..0624fbf43 100644
--- a/lib/impure/re.nim
+++ b/lib/impure/re.nim
@@ -1,13 +1,13 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
-## Regular expression support for Nimrod. Consider using the pegs module
+## Regular expression support for Nim. Consider using the pegs module
## instead.
## This module is implemented by providing a wrapper around the
## `PRCE (Perl-Compatible Regular Expressions) `_
@@ -68,7 +68,7 @@ proc finalizeRegEx(x: TRegex) =
pcre.free_substring(cast[cstring](x.e))
proc re*(s: string, flags = {reExtended, reStudy}): TRegex =
- ## Constructor of regular expressions. Note that Nimrod's
+ ## Constructor of regular expressions. Note that Nim's
## extended raw string literals support this syntax ``re"[abc]"`` as
## a short form for ``re(r"[abc]")``.
new(result, finalizeRegEx)
diff --git a/lib/impure/ssl.nim b/lib/impure/ssl.nim
index 54d524c7b..8a091a0d9 100644
--- a/lib/impure/ssl.nim
+++ b/lib/impure/ssl.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Dominik Picheta
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/web.nim b/lib/impure/web.nim
index 5f04422d1..abd7e2498 100644
--- a/lib/impure/web.nim
+++ b/lib/impure/web.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/impure/zipfiles.nim b/lib/impure/zipfiles.nim
index 1726449d8..b7df30d89 100644
--- a/lib/impure/zipfiles.nim
+++ b/lib/impure/zipfiles.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/js/dom.nim b/lib/js/dom.nim
index 951d8e835..2051ef294 100644
--- a/lib/js/dom.nim
+++ b/lib/js/dom.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/nimrtl.nim b/lib/nimrtl.nim
index 68b7d7bd9..96dab1284 100644
--- a/lib/nimrtl.nim
+++ b/lib/nimrtl.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/packages/docutils/rst.nim b/lib/packages/docutils/rst.nim
index 27d520493..f685a97e1 100644
--- a/lib/packages/docutils/rst.nim
+++ b/lib/packages/docutils/rst.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
@@ -17,7 +17,7 @@ import
type
TRstParseOption* = enum ## options for the RST parser
roSkipPounds, ## skip ``#`` at line beginning (documentation
- ## embedded in Nimrod comments)
+ ## embedded in Nim comments)
roSupportSmilies, ## make the RST parser support smilies like ``:)``
roSupportRawDirective, ## support the ``raw`` directive (don't support
## it for sandboxing)
diff --git a/lib/packages/docutils/rstast.nim b/lib/packages/docutils/rstast.nim
index 8f946d973..7b781ad6a 100644
--- a/lib/packages/docutils/rstast.nim
+++ b/lib/packages/docutils/rstast.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/posix/epoll.nim b/lib/posix/epoll.nim
index ee04348e8..5565a5ae8 100644
--- a/lib/posix/epoll.nim
+++ b/lib/posix/epoll.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Dominik Picheta
#
# See the file "copying.txt", included in this
diff --git a/lib/posix/inotify.nim b/lib/posix/inotify.nim
index 852eb12fa..c6f0633ff 100644
--- a/lib/posix/inotify.nim
+++ b/lib/posix/inotify.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Dominik Picheta
#
# See the file "copying.txt", included in this
diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim
index d8f329e34..430d82429 100644
--- a/lib/posix/posix.nim
+++ b/lib/posix/posix.nim
@@ -13,14 +13,14 @@
# net/if, sys/socket, sys/uio, netinet/in, netinet/tcp, netdb
## This is a raw POSIX interface module. It does not not provide any
-## convenience: cstrings are used instead of proper Nimrod strings and
+## convenience: cstrings are used instead of proper Nim strings and
## return codes indicate errors. If you want exceptions
-## and a proper Nimrod-like interface, use the OS module or write a wrapper.
+## and a proper Nim-like interface, use the OS module or write a wrapper.
## Coding conventions:
## ALL types are named the same as in the POSIX standard except that they start
## with 'T' or 'P' (if they are pointers) and without the '_t' suffix to be
-## consistent with Nimrod conventions. If an identifier is a Nimrod keyword
+## consistent with Nim conventions. If an identifier is a Nim keyword
## the \`identifier\` notation is used.
##
## This library relies on the header files of your C compiler. The
diff --git a/lib/prelude.nim b/lib/prelude.nim
index 50b4d4092..60d9c0925 100644
--- a/lib/prelude.nim
+++ b/lib/prelude.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/actors.nim b/lib/pure/actors.nim
index 8a8d8b51b..18299d687 100644
--- a/lib/pure/actors.nim
+++ b/lib/pure/actors.nim
@@ -7,7 +7,7 @@
# distribution, for details about the copyright.
#
-## `Actor`:idx: support for Nimrod. An actor is implemented as a thread with
+## `Actor`:idx: support for Nim. An actor is implemented as a thread with
## a channel as its inbox. This module requires the ``--threads:on``
## command line switch.
##
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim
index dd9131c05..3993a4172 100644
--- a/lib/pure/algorithm.nim
+++ b/lib/pure/algorithm.nim
@@ -151,11 +151,11 @@ proc merge[T](a, b: var openArray[T], lo, m, hi: int,
proc sort*[T](a: var openArray[T],
cmp: proc (x, y: T): int {.closure.},
order = SortOrder.Ascending) =
- ## Default Nimrod sort. The sorting is guaranteed to be stable and
+ ## Default Nim sort. The sorting is guaranteed to be stable and
## the worst case is guaranteed to be O(n log n).
## The current implementation uses an iterative
## mergesort to achieve this. It uses a temporary sequence of
- ## length ``a.len div 2``. Currently Nimrod does not support a
+ ## length ``a.len div 2``. Currently Nim does not support a
## sensible default argument for ``cmp``, so you have to provide one
## of your own. However, the ``system.cmp`` procs can be used:
##
diff --git a/lib/pure/cgi.nim b/lib/pure/cgi.nim
index bfa94a238..b30f8dd33 100644
--- a/lib/pure/cgi.nim
+++ b/lib/pure/cgi.nim
@@ -325,7 +325,7 @@ proc setTestData*(keysvalues: varargs[string]) =
## This can only simulate the 'GET' request method. `keysvalues` should
## provide embedded (name, value)-pairs. Example:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## setTestData("name", "Hanz", "password", "12345")
putEnv("REQUEST_METHOD", "GET")
var i = 0
@@ -342,7 +342,7 @@ proc writeContentType*() =
## call this before starting to send your HTML data to `stdout`. This
## implements this part of the CGI protocol:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## write(stdout, "Content-type: text/html\n\n")
write(stdout, "Content-type: text/html\n\n")
@@ -366,11 +366,11 @@ proc writeErrorMessage*(data: string) =
stdout.write(data)
proc setStackTraceStdout*() =
- ## Makes Nimrod output stacktraces to stdout, instead of server log.
+ ## Makes Nim output stacktraces to stdout, instead of server log.
errorMessageWriter = writeErrorMessage
proc setStackTraceNewLine*() {.deprecated.} =
- ## Makes Nimrod output stacktraces to stdout, instead of server log.
+ ## Makes Nim output stacktraces to stdout, instead of server log.
## Depracated alias for setStackTraceStdout.
setStackTraceStdout()
diff --git a/lib/pure/concurrency/cpuinfo.nim b/lib/pure/concurrency/cpuinfo.nim
index dfa819f64..e55786c3e 100644
--- a/lib/pure/concurrency/cpuinfo.nim
+++ b/lib/pure/concurrency/cpuinfo.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim
index dfde610f2..fe08e94fc 100644
--- a/lib/pure/concurrency/threadpool.nim
+++ b/lib/pure/concurrency/threadpool.nim
@@ -189,7 +189,7 @@ proc nimFlowVarSignal(fv: FlowVarBase) {.compilerProc.} =
proc awaitAndThen*[T](fv: FlowVar[T]; action: proc (x: T) {.closure.}) =
## blocks until the ``fv`` is available and then passes its value
- ## to ``action``. Note that due to Nimrod's parameter passing semantics this
+ ## to ``action``. Note that due to Nim's parameter passing semantics this
## means that ``T`` doesn't need to be copied and so ``awaitAndThen`` can
## sometimes be more efficient than ``^``.
await(fv)
diff --git a/lib/pure/ftpclient.nim b/lib/pure/ftpclient.nim
index ccb0929f6..5a8cf50b2 100644
--- a/lib/pure/ftpclient.nim
+++ b/lib/pure/ftpclient.nim
@@ -39,7 +39,7 @@ type
csock: Socket # Command connection socket
dsock: Socket # Data connection socket
else:
- dummyA, dummyB: pointer # workaround a Nimrod API issue
+ dummyA, dummyB: pointer # workaround a Nim API issue
asyncCSock: AsyncSocket
asyncDSock: AsyncSocket
handleEvent*: proc (ftp: AsyncFTPClient, ev: FTPEvent){.closure,gcsafe.}
diff --git a/lib/pure/gentabs.nim b/lib/pure/gentabs.nim
index c371809a0..694bfb542 100644
--- a/lib/pure/gentabs.nim
+++ b/lib/pure/gentabs.nim
@@ -9,7 +9,7 @@
## The ``gentabs`` module implements an efficient hash table that is a
## key-value mapping. The keys are required to be strings, but the values
-## may be any Nimrod or user defined type. This module supports matching
+## may be any Nim or user defined type. This module supports matching
## of keys in case-sensitive, case-insensitive and style-insensitive modes.
{.deprecated.}
diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim
index a41dc9450..4bbdbb5a1 100644
--- a/lib/pure/httpserver.nim
+++ b/lib/pure/httpserver.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf, Dominik Picheta
#
# See the file "copying.txt", included in this
diff --git a/lib/pure/math.nim b/lib/pure/math.nim
index c6a0305d2..32bae18c2 100644
--- a/lib/pure/math.nim
+++ b/lib/pure/math.nim
@@ -30,15 +30,15 @@ const
E* = 2.71828182845904523536028747 ## Euler's number
MaxFloat64Precision* = 16 ## maximum number of meaningful digits
- ## after the decimal point for Nimrod's
+ ## after the decimal point for Nim's
## ``float64`` type.
MaxFloat32Precision* = 8 ## maximum number of meaningful digits
- ## after the decimal point for Nimrod's
+ ## after the decimal point for Nim's
## ``float32`` type.
MaxFloatPrecision* = MaxFloat64Precision ## maximum number of
## meaningful digits
## after the decimal point
- ## for Nimrod's ``float`` type.
+ ## for Nim's ``float`` type.
type
FloatClass* = enum ## describes the class a floating point value belongs to.
diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim
index c85c2b498..24dbfb6d3 100644
--- a/lib/pure/memfiles.nim
+++ b/lib/pure/memfiles.nim
@@ -1,7 +1,7 @@
#
#
# Nim's Runtime Library
-# (c) Copyright 2014 Nimrod Contributors
+# (c) Copyright 2014 Nim Contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index d348497a9..ae352c26f 100644
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -1245,7 +1245,7 @@ iterator walkDir*(dir: string): tuple[kind: TPathComponent, path: string] {.
##
## and this code:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## for kind, path in walkDir("dirA"):
## echo(path)
##
@@ -1657,7 +1657,7 @@ when defined(nimdoc):
## # Do something else!
elif defined(windows):
- # Since we support GUI applications with Nimrod, we sometimes generate
+ # Since we support GUI applications with Nim, we sometimes generate
# a WinMain entry proc. But a WinMain proc has no access to the parsed
# command line arguments. The way to get them differs. Thus we parse them
# ourselves. This has the additional benefit that the program's behaviour
diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim
index 957a91d06..884774f1f 100644
--- a/lib/pure/osproc.nim
+++ b/lib/pure/osproc.nim
@@ -287,7 +287,7 @@ proc execProcesses*(cmds: openArray[string],
close(p)
proc select*(readfds: var seq[PProcess], timeout = 500): int
- ## `select` with a sensible Nimrod interface. `timeout` is in miliseconds.
+ ## `select` with a sensible Nim interface. `timeout` is in miliseconds.
## Specify -1 for no timeout. Returns the number of processes that are
## ready to read from. The processes that are ready to be read from are
## removed from `readfds`.
diff --git a/lib/pure/parsecfg.nim b/lib/pure/parsecfg.nim
index a45976d86..bb9d2aed2 100644
--- a/lib/pure/parsecfg.nim
+++ b/lib/pure/parsecfg.nim
@@ -11,7 +11,7 @@
## parser. The configuration file's syntax is similar to the Windows ``.ini``
## format, but much more powerful, as it is not a line based parser. String
## literals, raw string literals and triple quoted string literals are supported
-## as in the Nimrod programming language.
+## as in the Nim programming language.
## This is an example of how a configuration file may look like:
##
diff --git a/lib/pure/ropes.nim b/lib/pure/ropes.nim
index 8205203ba..8b0661063 100644
--- a/lib/pure/ropes.nim
+++ b/lib/pure/ropes.nim
@@ -10,7 +10,7 @@
## This module contains support for a `rope`:idx: data type.
## Ropes can represent very long strings efficiently; especially concatenation
## is done in O(1) instead of O(n). They are essentially concatenation
-## trees that are only flattened when converting to a native Nimrod
+## trees that are only flattened when converting to a native Nim
## string. The empty string is represented by ``nil``. Ropes are immutable and
## subtrees can be shared without copying.
## Leaves can be cached for better memory efficiency at the cost of
diff --git a/lib/pure/streams.nim b/lib/pure/streams.nim
index bc0f1c540..31aa7497d 100644
--- a/lib/pure/streams.nim
+++ b/lib/pure/streams.nim
@@ -9,7 +9,7 @@
## This module provides a stream interface and two implementations thereof:
## the `FileStream` and the `StringStream` which implement the stream
-## interface for Nimrod file objects (`File`) and strings. Other modules
+## interface for Nim file objects (`File`) and strings. Other modules
## may provide other implementations for this standard stream interface.
include "system/inclrtl"
@@ -98,7 +98,7 @@ proc writeData*(s, unused: Stream, buffer: pointer,
proc write*[T](s: Stream, x: T) =
## generic write procedure. Writes `x` to the stream `s`. Implementation:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
##
## s.writeData(s, addr(x), sizeof(x))
var y: T
diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim
index 5153455e2..2fdf72011 100644
--- a/lib/pure/strutils.nim
+++ b/lib/pure/strutils.nim
@@ -117,7 +117,7 @@ proc normalize*(s: string): string {.noSideEffect, procvar,
## Normalizes the string `s`.
##
## That means to convert it to lower case and remove any '_'. This is needed
- ## for Nimrod identifiers for example.
+ ## for Nim identifiers for example.
result = newString(s.len)
var j = 0
for i in 0..len(s) - 1:
@@ -1155,7 +1155,7 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault,
## If ``format == ffScientific`` then precision is the maximum number
## of significant digits to be printed.
## `precision`'s default value is the maximum number of meaningful digits
- ## after the decimal point for Nimrod's ``biggestFloat`` type.
+ ## after the decimal point for Nim's ``biggestFloat`` type.
##
## If ``precision == 0``, it tries to format it nicely.
const floatFormatToChar: array[FloatFormatMode, char] = ['g', 'f', 'e']
@@ -1186,7 +1186,7 @@ proc formatFloat*(f: float, format: FloatFormatMode = ffDefault,
## If ``format == ffScientific`` then precision is the maximum number
## of significant digits to be printed.
## `precision`'s default value is the maximum number of meaningful digits
- ## after the decimal point for Nimrod's ``float`` type.
+ ## after the decimal point for Nim's ``float`` type.
result = formatBiggestFloat(f, format, precision)
proc formatSize*(bytes: BiggestInt, decimalSep = '.'): string =
diff --git a/lib/pure/typetraits.nim b/lib/pure/typetraits.nim
index 1180b98f0..2c3d872df 100644
--- a/lib/pure/typetraits.nim
+++ b/lib/pure/typetraits.nim
@@ -1,7 +1,7 @@
#
#
# Nim's Runtime Library
-# (c) Copyright 2012 Nimrod Contributors
+# (c) Copyright 2012 Nim Contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
diff --git a/lib/pure/unittest.nim b/lib/pure/unittest.nim
index 372c02f4e..bbd074390 100644
--- a/lib/pure/unittest.nim
+++ b/lib/pure/unittest.nim
@@ -1,7 +1,7 @@
#
#
# Nim's Runtime Library
-# (c) Copyright 2012 Nimrod Contributors
+# (c) Copyright 2012 Nim Contributors
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim
index c15c2e148..2caa65023 100644
--- a/lib/pure/xmltree.nim
+++ b/lib/pure/xmltree.nim
@@ -276,11 +276,11 @@ macro `<>`*(x: expr): expr {.immediate.} =
## Constructor macro for XML. Example usage:
##
## .. code-block:: nimrod
- ## <>a(href="http://nimrod-code.org", newText("Nimrod rules."))
+ ## <>a(href="http://nimrod-code.org", newText("Nim rules."))
##
## Produces an XML tree for::
##
- ## Nimrod rules.
+ ## Nim rules.
##
let x = callsite()
result = xmlConstructor(x)
@@ -339,5 +339,5 @@ proc findAll*(n: XmlNode, tag: string): seq[XmlNode] =
findAll(n, tag, result)
when isMainModule:
- assert """Nimrod rules.""" ==
- $(<>a(href="http://nimrod-code.org", newText("Nimrod rules.")))
+ assert """Nim rules.""" ==
+ $(<>a(href="http://nimrod-code.org", newText("Nim rules.")))
diff --git a/lib/system.nim b/lib/system.nim
index 0e9712c24..b07fa76e2 100644
--- a/lib/system.nim
+++ b/lib/system.nim
@@ -103,7 +103,7 @@ proc defined*(x: expr): bool {.magic: "Defined", noSideEffect.}
## `-d:x switch `_ to enable build time
## conditionals:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## when not defined(release):
## # Do here programmer friendly expensive sanity checks.
## # Put here the normal code
@@ -123,7 +123,7 @@ proc declared*(x: expr): bool {.magic: "Defined", noSideEffect.}
## This can be used to check whether a library provides a certain
## feature or not:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## when not defined(strutils.toUpper):
## # provide our own toUpper proc here, because strutils is
## # missing it.
@@ -320,7 +320,7 @@ type
## of an int. This type is often useful for documentation and debugging.
RootObj* {.exportc: "TNimObject", inheritable.} =
- object ## the root of Nimrod's object hierarchy. Objects should
+ object ## the root of Nim's object hierarchy. Objects should
## inherit from TObject or one of its descendants. However,
## objects that have no ancestor are allowed.
RootRef* = ref RootObj ## reference to RootObj
@@ -465,7 +465,7 @@ type
## The operation produced a result that cannot be represented with infinite
## precision -- for example: ``2.0 / 3.0, log(1.1)``
##
- ## **NOTE**: Nimrod currently does not detect these! See the full
+ ## **NOTE**: Nim currently does not detect these! See the full
## `exception hierarchy`_.
DeadThreadError* = object of Exception ## \
## Raised if it is attempted to send a message to a dead thread.
@@ -691,7 +691,7 @@ proc `div` *(x, y: int32): int32 {.magic: "DivI", noSideEffect.}
proc `div` *(x, y: int64): int64 {.magic: "DivI64", noSideEffect.}
## computes the integer division. This is roughly the same as
## ``floor(x/y)``.
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## 1 div 2 == 0
## 2 div 2 == 1
## 3 div 2 == 1
@@ -710,7 +710,7 @@ proc `shr` *(x, y: int16): int16 {.magic: "ShrI", noSideEffect.}
proc `shr` *(x, y: int32): int32 {.magic: "ShrI", noSideEffect.}
proc `shr` *(x, y: int64): int64 {.magic: "ShrI64", noSideEffect.}
## computes the `shift right` operation of `x` and `y`.
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## 0b0001_0000'i8 shr 2 == 0b0100_0000'i8
## 0b1000_0000'i8 shr 2 == 0b0000_0000'i8
## 0b0000_0001'i8 shr 9 == 0b0000_0000'i8
@@ -849,12 +849,12 @@ proc contains*[T](x: set[T], y: T): bool {.magic: "InSet", noSideEffect.}
## One should overload this proc if one wants to overload the ``in`` operator.
## The parameters are in reverse order! ``a in b`` is a template for
## ``contains(b, a)``.
- ## This is because the unification algorithm that Nimrod uses for overload
+ ## This is because the unification algorithm that Nim uses for overload
## resolution works from left to right.
## But for the ``in`` operator that would be the wrong direction for this
## piece of code:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## var s: set[range['a'..'z']] = {'a'..'c'}
## writeln(stdout, 'b' in s)
##
@@ -868,7 +868,7 @@ proc contains*[T](s: Slice[T], value: T): bool {.noSideEffect, inline.} =
## Checks if `value` is withing the range of `s`; returns true iff
## `value >= s.a and value <= s.b`
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert((1..3).contains(1) == true)
## assert((1..3).contains(2) == true)
## assert((1..3).contains(4) == false)
@@ -877,20 +877,20 @@ proc contains*[T](s: Slice[T], value: T): bool {.noSideEffect, inline.} =
template `in` * (x, y: expr): expr {.immediate.} = contains(y, x)
## Sugar for contains
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(1 in (1..3) == true)
## assert(5 in (1..3) == false)
template `notin` * (x, y: expr): expr {.immediate.} = not contains(y, x)
## Sugar for not containing
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(1 notin (1..3) == false)
## assert(5 notin (1..3) == true)
proc `is` *[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
## Checks if T is of the same type as S
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## proc test[T](a: T): int =
## when (T is int):
## return a
@@ -905,7 +905,7 @@ template `isnot` *(x, y: expr): expr {.immediate.} = not (x is y)
proc `of` *[T, S](x: T, y: S): bool {.magic: "Of", noSideEffect.}
## Checks if `x` has a type of `y`
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(EFloatingPoint of EBase)
## assert(EIO of ESystem)
## assert(EDivByZero of EBase)
@@ -961,25 +961,25 @@ proc `&` * (x: string, y: char): string {.
magic: "ConStrStr", noSideEffect, merge.}
## Concatenates `x` with `y`
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert("ab" & 'c' == "abc")
proc `&` * (x: char, y: char): string {.
magic: "ConStrStr", noSideEffect, merge.}
## Concatenates `x` and `y` into a string
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert('a' & 'b' == "ab")
proc `&` * (x, y: string): string {.
magic: "ConStrStr", noSideEffect, merge.}
## Concatenates `x` and `y`
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert("ab" & "cd" == "abcd")
proc `&` * (x: char, y: string): string {.
magic: "ConStrStr", noSideEffect, merge.}
## Concatenates `x` with `y`
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert('a' & "bc" == "abc")
# implementation note: These must all have the same magic value "ConStrStr" so
@@ -988,7 +988,7 @@ proc `&` * (x: char, y: string): string {.
proc add*(x: var string, y: char) {.magic: "AppendStrCh", noSideEffect.}
## Appends `y` to `x` in place
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## var tmp = ""
## tmp.add('a')
## tmp.add('b')
@@ -996,7 +996,7 @@ proc add*(x: var string, y: char) {.magic: "AppendStrCh", noSideEffect.}
proc add*(x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.}
## Concatenates `x` and `y` in place
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## var tmp = ""
## tmp.add("ab")
## tmp.add("cd")
@@ -1020,19 +1020,19 @@ const
## ``HH:MM:SS``. This works thanks to compiler magic.
NimVersion* {.magic: "NimrodVersion"}: string = "0.0.0"
- ## is the version of Nimrod as a string.
+ ## is the version of Nim as a string.
## This works thanks to compiler magic.
NimMajor* {.magic: "NimrodMajor"}: int = 0
- ## is the major number of Nimrod's version.
+ ## is the major number of Nim's version.
## This works thanks to compiler magic.
NimMinor* {.magic: "NimrodMinor"}: int = 0
- ## is the minor number of Nimrod's version.
+ ## is the minor number of Nim's version.
## This works thanks to compiler magic.
NimPatch* {.magic: "NimrodPatch"}: int = 0
- ## is the patch number of Nimrod's version.
+ ## is the patch number of Nim's version.
## This works thanks to compiler magic.
cpuEndian* {.magic: "CpuEndian"}: Endianness = littleEndian
@@ -1145,7 +1145,7 @@ proc add *[T](x: var seq[T], y: openArray[T]) {.noSideEffect.} =
## Generic proc for adding a data item `y` to a container `x`.
## For containers that have an order, `add` means *append*. New generic
## containers should also call their adding proc `add` for consistency.
- ## Generic code becomes much easier to write if the Nimrod naming scheme is
+ ## Generic code becomes much easier to write if the Nim naming scheme is
## respected.
let xl = x.len
setLen(x, xl + y.len)
@@ -1183,7 +1183,7 @@ proc insert*[T](x: var seq[T], item: T, i = 0) {.noSideEffect.} =
x[i] = item
proc repr*[T](x: T): string {.magic: "Repr", noSideEffect.}
- ## takes any Nimrod variable and returns its string representation. It
+ ## takes any Nim variable and returns its string representation. It
## works even for complex data graphs with cycles. This is a great
## debugging tool.
@@ -1193,12 +1193,12 @@ type
## pointers to integer addresses for readability.
BiggestInt* = int64
- ## is an alias for the biggest signed integer type the Nimrod compiler
+ ## is an alias for the biggest signed integer type the Nim compiler
## supports. Currently this is ``int64``, but it is platform-dependant
## in general.
BiggestFloat* = float64
- ## is an alias for the biggest floating point type the Nimrod
+ ## is an alias for the biggest floating point type the Nim
## compiler supports. Currently this is ``float64``, but it is
## platform-dependant in general.
@@ -1236,7 +1236,7 @@ type # these work for most platforms:
## This is the same as the type ``double`` in *C*.
clongdouble* {.importc: "long double", nodecl.} = BiggestFloat
## This is the same as the type ``long double`` in *C*.
- ## This C type is not supported by Nimrod's code generator
+ ## This C type is not supported by Nim's code generator
cuchar* {.importc: "unsigned char", nodecl.} = char
## This is the same as the type ``unsigned char`` in *C*.
@@ -1590,7 +1590,7 @@ iterator `||`*[S, T](a: S, b: T, annotation=""): T {.
## Note that the compiler maps that to
## the ``#pragma omp parallel for`` construct of `OpenMP`:idx: and as
## such isn't aware of the parallelism in your code! Be careful! Later
- ## versions of ``||`` will get proper support by Nimrod's code generator
+ ## versions of ``||`` will get proper support by Nim's code generator
## and GC.
discard
@@ -1642,7 +1642,7 @@ proc max*(x, y: float): float {.magic: "MaxF64", noSideEffect.} =
proc clamp*[T](x, a, b: T): T =
## limits the value ``x`` within the interval [a, b]
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert((1.4).clamp(0.0, 1.0) == 1.0)
## assert((0.5).clamp(0.0, 1.0) == 0.5)
if x < a: return a
@@ -1746,7 +1746,7 @@ proc `&` *[T](x, y: seq[T]): seq[T] {.noSideEffect.} =
## Concatenates two sequences.
## Requires copying of the sequences.
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(@[1, 2, 3, 4] & @[5, 6] == @[1, 2, 3, 4, 5, 6])
newSeq(result, x.len + y.len)
for i in 0..x.len-1:
@@ -1758,7 +1758,7 @@ proc `&` *[T](x: seq[T], y: T): seq[T] {.noSideEffect.} =
## Appends element y to the end of the sequence.
## Requires copying of the sequence
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(@[1, 2, 3] & 4 == @[1, 2, 3, 4])
newSeq(result, x.len + 1)
for i in 0..x.len-1:
@@ -1769,7 +1769,7 @@ proc `&` *[T](x: T, y: seq[T]): seq[T] {.noSideEffect.} =
## Prepends the element x to the beginning of the sequence.
## Requires copying of the sequence
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## assert(1 & @[2, 3, 4] == @[1, 2, 3, 4])
newSeq(result, y.len + 1)
result[0] = x
@@ -1883,7 +1883,7 @@ iterator fieldPairs*[T: tuple|object](x: T): RootObj {.
## you want to run for each type. To perform the comparison use the `is
## operator `_. Example:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
##
## type
## Custom = object
@@ -2946,7 +2946,7 @@ when true:
template assert*(cond: bool, msg = "") =
## Raises ``EAssertionFailure`` with `msg` if `cond` is false.
##
- ## Provides a means to implement `programming by contracts`:idx: in Nimrod.
+ ## Provides a means to implement `programming by contracts`:idx: in Nim.
## ``assert`` evaluates expression ``cond`` and if ``cond`` is false, it
## raises an ``EAssertionFailure`` exception. However, the compiler may not
## generate any code at all for ``assert`` if it is advised to do so through
@@ -3031,7 +3031,7 @@ proc shallow*(s: var string) {.noSideEffect, inline.} =
type
TNimrodNode {.final.} = object
PNimrodNode* {.magic: "PNimrodNode".} = ref TNimrodNode
- ## represents a Nimrod AST node. Macros operate on this type.
+ ## represents a Nim AST node. Macros operate on this type.
when false:
template eval*(blk: stmt): stmt =
@@ -3060,7 +3060,7 @@ proc compiles*(x): bool {.magic: "Compiles", noSideEffect.} =
## without any semantic error.
## This can be used to check whether a type supports some operation:
##
- ## .. code-block:: Nimrod
+ ## .. code-block:: Nim
## when not compiles(3 + 4):
## echo "'+' for integers is available"
discard
diff --git a/lib/windows/mmsystem.nim b/lib/windows/mmsystem.nim
index 91279a5ef..632a6e557 100644
--- a/lib/windows/mmsystem.nim
+++ b/lib/windows/mmsystem.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2006 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/nb30.nim b/lib/windows/nb30.nim
index a7fd526aa..be4a0616c 100644
--- a/lib/windows/nb30.nim
+++ b/lib/windows/nb30.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2006 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/psapi.nim b/lib/windows/psapi.nim
index 7d53cf7ca..fd1dcada8 100644
--- a/lib/windows/psapi.nim
+++ b/lib/windows/psapi.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2009 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/shellapi.nim b/lib/windows/shellapi.nim
index 41f2a60d5..9a280f551 100644
--- a/lib/windows/shellapi.nim
+++ b/lib/windows/shellapi.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2006 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/shfolder.nim b/lib/windows/shfolder.nim
index 253b1c77a..886d757eb 100644
--- a/lib/windows/shfolder.nim
+++ b/lib/windows/shfolder.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2006 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim
index 5fd9127b3..32641b8fe 100644
--- a/lib/windows/windows.nim
+++ b/lib/windows/windows.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim
index 0da6cb1ff..18a565ffc 100644
--- a/lib/windows/winlean.nim
+++ b/lib/windows/winlean.nim
@@ -8,7 +8,7 @@
#
## This module implements a small wrapper for some needed Win API procedures,
-## so that the Nimrod compiler does not depend on the huge Windows module.
+## so that the Nim compiler does not depend on the huge Windows module.
const
useWinUnicode* = not defined(useWinAnsi)
diff --git a/lib/wrappers/libsvm.nim b/lib/wrappers/libsvm.nim
index 8dec05bcf..00d5ac73c 100644
--- a/lib/wrappers/libsvm.nim
+++ b/lib/wrappers/libsvm.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/wrappers/mysql.nim b/lib/wrappers/mysql.nim
index 84d70287f..9871d4a7a 100644
--- a/lib/wrappers/mysql.nim
+++ b/lib/wrappers/mysql.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/wrappers/sphinx.nim b/lib/wrappers/sphinx.nim
index b4e127c65..e4a282968 100644
--- a/lib/wrappers/sphinx.nim
+++ b/lib/wrappers/sphinx.nim
@@ -12,7 +12,7 @@
# did not, you can find it at http://www.gnu.org/
#
-## Nimrod wrapper for ``sphinx``.
+## Nim wrapper for ``sphinx``.
{.deadCodeElim: on.}
when defined(windows):
diff --git a/lib/wrappers/sqlite3.nim b/lib/wrappers/sqlite3.nim
index 7b7f0874e..e817cd9ee 100644
--- a/lib/wrappers/sqlite3.nim
+++ b/lib/wrappers/sqlite3.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/wrappers/tinyc.nim b/lib/wrappers/tinyc.nim
index f685c714d..ac6cb70f1 100644
--- a/lib/wrappers/tinyc.nim
+++ b/lib/wrappers/tinyc.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2010 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/wrappers/zip/libzip.nim b/lib/wrappers/zip/libzip.nim
index 0b8d2b3ec..ebd74c7fd 100644
--- a/lib/wrappers/zip/libzip.nim
+++ b/lib/wrappers/zip/libzip.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/lib/wrappers/zip/zzip.nim b/lib/wrappers/zip/zzip.nim
index a656322ee..73fd53c34 100644
--- a/lib/wrappers/zip/zzip.nim
+++ b/lib/wrappers/zip/zzip.nim
@@ -1,6 +1,6 @@
#
#
-# Nimrod's Runtime Library
+# Nim's Runtime Library
# (c) Copyright 2008 Andreas Rumpf
#
# See the file "copying.txt", included in this
From 4523b29d7af0ac88754eec29981306022a0d642b Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 09:59:26 +0200
Subject: [PATCH 030/409] Nimrod renamed to Nim
---
lib/core/macros.nim | 20 +++++------
lib/core/typeinfo.nim | 2 +-
lib/impure/db_postgres.nim | 4 +--
lib/impure/re.nim | 14 ++++----
lib/impure/ssl.nim | 2 +-
lib/impure/web.nim | 2 +-
lib/prelude.nim | 4 +--
lib/pure/actors.nim | 2 +-
lib/pure/algorithm.nim | 4 +--
lib/pure/asyncnet.nim | 2 +-
lib/pure/collections/LockFreeHash.nim | 2 +-
lib/pure/future.nim | 4 +--
lib/pure/httpclient.nim | 6 ++--
lib/pure/httpserver.nim | 2 +-
lib/pure/json.nim | 4 +--
lib/pure/os.nim | 30 ++++++++--------
lib/pure/osproc.nim | 2 +-
lib/pure/parseopt.nim | 2 +-
lib/pure/parseutils.nim | 4 +--
lib/pure/parsexml.nim | 4 +--
lib/pure/times.nim | 2 +-
lib/pure/xmltree.nim | 10 +++---
lib/system.nim | 52 +++++++++++++--------------
23 files changed, 90 insertions(+), 90 deletions(-)
diff --git a/lib/core/macros.nim b/lib/core/macros.nim
index 41ba030f9..32e74aebf 100644
--- a/lib/core/macros.nim
+++ b/lib/core/macros.nim
@@ -261,7 +261,7 @@ proc getAst*(macroOrTemplate: expr): PNimrodNode {.magic: "ExpandToAst", noSideE
## Obtains the AST nodes returned from a macro or template invocation.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## macro FooMacro() =
## var ast = getAst(BarTemplate())
@@ -278,7 +278,7 @@ proc quote*(bl: stmt, op = "``"): PNimrodNode {.magic: "QuoteAst", noSideEffect.
##
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## macro check(ex: expr): stmt =
## # this is a simplified version of the check macro from the
@@ -422,7 +422,7 @@ proc lispRepr*(n: PNimrodNode): string {.compileTime.} =
add(result, ")")
macro dumpTree*(s: stmt): stmt {.immediate.} = echo s.treeRepr
- ## Accepts a block of nimrod code and prints the parsed abstract syntax
+ ## Accepts a block of nim code and prints the parsed abstract syntax
## tree using the `toTree` function. Printing is done *at compile time*.
##
## You can use this as a tool to explore the Nimrod's abstract syntax
@@ -430,7 +430,7 @@ macro dumpTree*(s: stmt): stmt {.immediate.} = echo s.treeRepr
## a certain expression/statement.
macro dumpLisp*(s: stmt): stmt {.immediate.} = echo s.lispRepr
- ## Accepts a block of nimrod code and prints the parsed abstract syntax
+ ## Accepts a block of nim code and prints the parsed abstract syntax
## tree using the `toLisp` function. Printing is done *at compile time*.
##
## See `dumpTree`.
@@ -489,7 +489,7 @@ proc newIdentDefs*(name, kind: PNimrodNode;
## ``let`` or ``var`` blocks may have an empty ``kind`` node if the
## identifier is being assigned a value. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## var varSection = newNimNode(nnkVarSection).add(
## newIdentDefs(ident("a"), ident("string")),
@@ -501,7 +501,7 @@ proc newIdentDefs*(name, kind: PNimrodNode;
## If you need to create multiple identifiers you need to use the lower level
## ``newNimNode``:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## result = newNimNode(nnkIdentDefs).add(
## ident("a"), ident("b"), ident("c"), ident("string"),
@@ -549,7 +549,7 @@ proc newIfStmt*(branches: varargs[tuple[cond, body: PNimrodNode]]):
PNimrodNode {.compiletime.} =
## Constructor for ``if`` statements.
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## newIfStmt(
## (Ident, StmtList),
@@ -643,7 +643,7 @@ template findChild*(n: PNimrodNode; cond: expr): PNimrodNode {.
immediate, dirty.} =
## Find the first child node matching condition (or nil).
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var res = findChild(n, it.kind == nnkPostfix and
## it.basename.ident == !"foo")
block:
@@ -738,11 +738,11 @@ proc addIdentIfAbsent*(dest: PNimrodNode, ident: string) {.compiletime.} =
when not defined(booting):
template emit*(e: static[string]): stmt =
- ## accepts a single string argument and treats it as nimrod code
+ ## accepts a single string argument and treats it as nim code
## that should be inserted verbatim in the program
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## emit("echo " & '"' & "hello world".toUpper & '"')
##
macro payload: stmt {.gensym.} =
diff --git a/lib/core/typeinfo.nim b/lib/core/typeinfo.nim
index 5ca101919..842a944e1 100644
--- a/lib/core/typeinfo.nim
+++ b/lib/core/typeinfo.nim
@@ -50,7 +50,7 @@ type
akUInt32 = 43, ## any represents an unsigned int32
akUInt64 = 44, ## any represents an unsigned int64
- TAny* = object {.pure.} ## can represent any nimrod value; NOTE: the wrapped
+ TAny* = object {.pure.} ## can represent any nim value; NOTE: the wrapped
## value can be modified with its wrapper! This means
## that ``TAny`` keeps a non-traced pointer to its
## wrapped value and **must not** live longer than
diff --git a/lib/impure/db_postgres.nim b/lib/impure/db_postgres.nim
index 6658dc0e0..4b7e20d0a 100644
--- a/lib/impure/db_postgres.nim
+++ b/lib/impure/db_postgres.nim
@@ -186,7 +186,7 @@ proc open*(connection, user, password, database: string): TDbConn {.
##
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## con = Open("", "", "", "host=localhost port=5432 dbname=mydb")
##
@@ -194,7 +194,7 @@ proc open*(connection, user, password, database: string): TDbConn {.
## for more information.
##
## Note that the connection parameter is not used but exists to maintain
- ## the nimrod db api.
+ ## the nim db api.
result = PQsetdbLogin(nil, nil, nil, nil, database, user, password)
if PQStatus(result) != CONNECTION_OK: dbError(result) # result = nil
diff --git a/lib/impure/re.nim b/lib/impure/re.nim
index 0624fbf43..a129a5eba 100644
--- a/lib/impure/re.nim
+++ b/lib/impure/re.nim
@@ -228,7 +228,7 @@ template `=~` *(s: string, pattern: TRegex): expr =
## This calls ``match`` with an implicit declared ``matches`` array that
## can be used in the scope of the ``=~`` call:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## if line =~ re"\s*(\w+)\s*\=\s*(\w+)":
## # matches a key=value pair:
@@ -271,12 +271,12 @@ proc replace*(s: string, sub: TRegex, by = ""): string =
## Replaces `sub` in `s` by the string `by`. Captures cannot be
## accessed in `by`. Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "var1=key; var2=key2".replace(re"(\w+)'='(\w+)")
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## "; "
result = ""
@@ -293,12 +293,12 @@ proc replacef*(s: string, sub: TRegex, by: string): string =
## Replaces `sub` in `s` by the string `by`. Captures can be accessed in `by`
## with the notation ``$i`` and ``$#`` (see strutils.`%`). Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "var1=key; var2=key2".replacef(re"(\w+)'='(\w+)", "$1<-$2$2")
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## "var1<-keykey; val2<-key2key2"
result = ""
@@ -360,13 +360,13 @@ iterator split*(s: string, sep: TRegex): string =
## Substrings are separated by the regular expression `sep`.
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for word in split("00232this02939is39an22example111", re"\d+"):
## writeln(stdout, word)
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "this"
## "is"
## "an"
diff --git a/lib/impure/ssl.nim b/lib/impure/ssl.nim
index 8a091a0d9..cae9990b9 100644
--- a/lib/impure/ssl.nim
+++ b/lib/impure/ssl.nim
@@ -8,7 +8,7 @@
#
## This module provides an easy to use sockets-style
-## nimrod interface to the OpenSSL library.
+## nim interface to the OpenSSL library.
{.deprecated.}
diff --git a/lib/impure/web.nim b/lib/impure/web.nim
index abd7e2498..f0c19b367 100644
--- a/lib/impure/web.nim
+++ b/lib/impure/web.nim
@@ -59,5 +59,5 @@ proc URLretrieveString*(url: string): TaintedString =
result = stream.data.TaintedString
when isMainModule:
- echo URLretrieveString("http://nimrod-code.org/")
+ echo URLretrieveString("http://nim-code.org/")
diff --git a/lib/prelude.nim b/lib/prelude.nim
index 60d9c0925..940864207 100644
--- a/lib/prelude.nim
+++ b/lib/prelude.nim
@@ -10,12 +10,12 @@
## This is an include file that simply imports common modules for your
## convenience:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## include prelude
##
## Same as:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## import os, strutils, times, parseutils, parseopt, hashes, tables, sets
import os, strutils, times, parseutils, parseopt, hashes, tables, sets
diff --git a/lib/pure/actors.nim b/lib/pure/actors.nim
index 18299d687..f2c50ce4c 100644
--- a/lib/pure/actors.nim
+++ b/lib/pure/actors.nim
@@ -13,7 +13,7 @@
##
## Example:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
##
## var
## a: TActorPool[int, void]
diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim
index 3993a4172..0358a9a81 100644
--- a/lib/pure/algorithm.nim
+++ b/lib/pure/algorithm.nim
@@ -159,7 +159,7 @@ proc sort*[T](a: var openArray[T],
## sensible default argument for ``cmp``, so you have to provide one
## of your own. However, the ``system.cmp`` procs can be used:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## sort(myIntArray, system.cmp[int])
##
@@ -170,7 +170,7 @@ proc sort*[T](a: var openArray[T],
## You can inline adhoc comparison procs with the `do notation
## `_. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## people.sort do (x, y: Person) -> int:
## result = cmp(x.surname, y.surname)
diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim
index ecaf0b9f9..695d8c07b 100644
--- a/lib/pure/asyncnet.nim
+++ b/lib/pure/asyncnet.nim
@@ -15,7 +15,7 @@
##
## The following example demonstrates a simple chat server.
##
-## .. code-block::nimrod
+## .. code-block::nim
##
## import asyncnet, asyncdispatch
##
diff --git a/lib/pure/collections/LockFreeHash.nim b/lib/pure/collections/LockFreeHash.nim
index 57beb83c9..5640838b1 100644
--- a/lib/pure/collections/LockFreeHash.nim
+++ b/lib/pure/collections/LockFreeHash.nim
@@ -1,4 +1,4 @@
-#nimrod c -t:-march=i686 --cpu:amd64 --threads:on -d:release lockfreehash.nim
+#nim c -t:-march=i686 --cpu:amd64 --threads:on -d:release lockfreehash.nim
import unsigned, math, hashes
diff --git a/lib/pure/future.nim b/lib/pure/future.nim
index c467d2c73..7d791e16c 100644
--- a/lib/pure/future.nim
+++ b/lib/pure/future.nim
@@ -53,7 +53,7 @@ proc createProcType(p, b: PNimrodNode): PNimrodNode {.compileTime.} =
macro `=>`*(p, b: expr): expr {.immediate.} =
## Syntax sugar for anonymous procedures.
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## proc passTwoAndTwo(f: (int, int) -> int): int =
## f(2, 2)
@@ -104,7 +104,7 @@ macro `=>`*(p, b: expr): expr {.immediate.} =
macro `->`*(p, b: expr): expr {.immediate.} =
## Syntax sugar for procedure types.
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## proc pass2(f: (float, float) -> float): float =
## f(2, 2)
diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim
index 3fbb04fc8..a0e8c6b05 100644
--- a/lib/pure/httpclient.nim
+++ b/lib/pure/httpclient.nim
@@ -656,17 +656,17 @@ when isMainModule:
resp = await client.request("http://picheta.me/aboutme.html")
echo("Got response: ", resp.status)
- resp = await client.request("http://nimrod-lang.org/")
+ resp = await client.request("http://nim-lang.org/")
echo("Got response: ", resp.status)
- resp = await client.request("http://nimrod-lang.org/download.html")
+ resp = await client.request("http://nim-lang.org/download.html")
echo("Got response: ", resp.status)
asyncCheck main()
runForever()
else:
- #downloadFile("http://force7.de/nimrod/index.html", "nimrodindex.html")
+ #downloadFile("http://force7.de/nim/index.html", "nimindex.html")
#downloadFile("http://www.httpwatch.com/", "ChunkTest.html")
#downloadFile("http://validator.w3.org/check?uri=http%3A%2F%2Fgoogle.com",
# "validator.html")
diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim
index 4bbdbb5a1..b850815c9 100644
--- a/lib/pure/httpserver.nim
+++ b/lib/pure/httpserver.nim
@@ -11,7 +11,7 @@
##
## Example:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## import strutils, sockets, httpserver
##
## var counter = 0
diff --git a/lib/pure/json.nim b/lib/pure/json.nim
index d90ddebf1..8bd05ad55 100644
--- a/lib/pure/json.nim
+++ b/lib/pure/json.nim
@@ -16,7 +16,7 @@
##
## Usage example:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## let
## small_json = """{"test": 1.3, "key2": true}"""
## jobj = parseJson(small_json)
@@ -26,7 +26,7 @@
##
## Results in:
##
-## .. code-block:: nimrod
+## .. code-block:: nim
##
## 1.3000000000000000e+00
## true
diff --git a/lib/pure/os.nim b/lib/pure/os.nim
index ae352c26f..c4b694406 100644
--- a/lib/pure/os.nim
+++ b/lib/pure/os.nim
@@ -514,12 +514,12 @@ proc joinPath*(head, tail: string): string {.
##
## For example on Unix:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## joinPath("usr", "lib")
##
## results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## "usr/lib"
##
## If head is the empty string, tail is returned. If tail is the empty
@@ -528,7 +528,7 @@ proc joinPath*(head, tail: string): string {.
## path separators not located on boundaries won't be modified. More
## examples on Unix:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## assert joinPath("usr", "") == "usr/"
## assert joinPath("", "lib") == "lib"
## assert joinPath("", "/lib") == "/lib"
@@ -560,7 +560,7 @@ proc `/` * (head, tail: string): string {.noSideEffect.} =
##
## Here are some examples for Unix:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## assert "usr" / "" == "usr/"
## assert "" / "lib" == "lib"
## assert "" / "/lib" == "/lib"
@@ -574,7 +574,7 @@ proc splitPath*(path: string): tuple[head, tail: string] {.
##
## Examples:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## splitPath("usr/local/bin") -> ("usr/local", "bin")
## splitPath("usr/local/bin/") -> ("usr/local/bin", "")
## splitPath("bin") -> ("", "bin")
@@ -674,10 +674,10 @@ proc splitFile*(path: string): tuple[dir, name, ext: string] {.
##
## Example:
##
- ## .. code-block:: nimrod
- ## var (dir, name, ext) = splitFile("usr/local/nimrodc.html")
+ ## .. code-block:: nim
+ ## var (dir, name, ext) = splitFile("usr/local/nimc.html")
## assert dir == "usr/local"
- ## assert name == "nimrodc"
+ ## assert name == "nimc"
## assert ext == ".html"
##
## If `path` has no extension, `ext` is the empty string.
@@ -1579,7 +1579,7 @@ proc inclFilePermissions*(filename: string,
rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect].} =
## a convenience procedure for:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## setFilePermissions(filename, getFilePermissions(filename)+permissions)
setFilePermissions(filename, getFilePermissions(filename)+permissions)
@@ -1588,7 +1588,7 @@ proc exclFilePermissions*(filename: string,
rtl, extern: "nos$1", tags: [ReadDirEffect, WriteDirEffect].} =
## a convenience procedure for:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## setFilePermissions(filename, getFilePermissions(filename)-permissions)
setFilePermissions(filename, getFilePermissions(filename)-permissions)
@@ -1627,7 +1627,7 @@ when defined(nimdoc):
## can test for its availability with `declared() `_.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## when declared(paramCount):
## # Use paramCount() here
## else:
@@ -1650,7 +1650,7 @@ when defined(nimdoc):
## can test for its availability with `declared() `_.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## when declared(paramStr):
## # Use paramStr() here
## else:
@@ -1703,7 +1703,7 @@ when declared(paramCount) or defined(nimdoc):
## can test for its availability with `declared() `_.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## when declared(commandLineParams):
## # Use commandLineParams() here
## else:
@@ -1858,7 +1858,7 @@ proc expandTilde*(path: string): string =
## The behaviour of this proc is the same on the Windows platform despite not
## having this convention. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## let configFile = expandTilde("~" / "appname.cfg")
## echo configFile
## # --> C:\Users\amber\appname.cfg
@@ -1889,7 +1889,7 @@ type
creationTime*: Time # Time file was created. Not supported on all systems!
template rawToFormalFileInfo(rawInfo, formalInfo): expr =
- ## Transforms the native file info structure into the one nimrod uses.
+ ## Transforms the native file info structure into the one nim uses.
## 'rawInfo' is either a 'TBY_HANDLE_FILE_INFORMATION' structure on Windows,
## or a 'TStat' structure on posix
when defined(Windows):
diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim
index 884774f1f..5c9cf182f 100644
--- a/lib/pure/osproc.nim
+++ b/lib/pure/osproc.nim
@@ -771,7 +771,7 @@ elif not defined(useNimRtl):
proc startProcessAfterFork(data: ptr TStartProcessData) =
# Warning: no GC here!
- # Or anything that touches global structures - all called nimrod procs
+ # Or anything that touches global structures - all called nim procs
# must be marked with stackTrace:off. Inspect C code after making changes.
if not data.optionPoParentStreams:
discard close(data.pStdin[writeIdx])
diff --git a/lib/pure/parseopt.nim b/lib/pure/parseopt.nim
index de00bc76d..786744600 100644
--- a/lib/pure/parseopt.nim
+++ b/lib/pure/parseopt.nim
@@ -132,7 +132,7 @@ when declared(initOptParser):
## This is an convenience iterator for iterating over the command line.
## This uses the TOptParser object. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var
## filename = ""
## for kind, key, val in getopt():
diff --git a/lib/pure/parseutils.nim b/lib/pure/parseutils.nim
index 38a3cbc5e..8f8ca6ab3 100644
--- a/lib/pure/parseutils.nim
+++ b/lib/pure/parseutils.nim
@@ -348,13 +348,13 @@ iterator interpolatedFragments*(s: string): tuple[kind: InterpolatedKind,
##
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for k, v in interpolatedFragments(" $this is ${an example} $$"):
## echo "(", k, ", \"", v, "\")"
##
## Results in:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## (ikString, " ")
## (ikExpr, "this")
## (ikString, " is ")
diff --git a/lib/pure/parsexml.nim b/lib/pure/parsexml.nim
index f4f46e4f4..9b2814b84 100644
--- a/lib/pure/parsexml.nim
+++ b/lib/pure/parsexml.nim
@@ -33,7 +33,7 @@
## XML parser to accomplish a simple task: To determine the title of an HTML
## document.
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## :file: examples/htmltitle.nim
##
##
@@ -44,7 +44,7 @@
## XML parser to accomplish another simple task: To determine all the links
## an HTML document contains.
##
-## .. code-block:: nimrod
+## .. code-block:: nim
## :file: examples/htmlrefs.nim
##
diff --git a/lib/pure/times.nim b/lib/pure/times.nim
index 5d92218b3..dcc5617fd 100644
--- a/lib/pure/times.nim
+++ b/lib/pure/times.nim
@@ -298,7 +298,7 @@ when not defined(JS):
## To generate useful timing values, take the difference between
## the results of two ``cpuTime`` calls:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var t0 = cpuTime()
## doWork()
## echo "CPU time [s] ", cpuTime() - t0
diff --git a/lib/pure/xmltree.nim b/lib/pure/xmltree.nim
index 2caa65023..37f591f1e 100644
--- a/lib/pure/xmltree.nim
+++ b/lib/pure/xmltree.nim
@@ -275,12 +275,12 @@ proc xmlConstructor(e: PNimrodNode): PNimrodNode {.compileTime.} =
macro `<>`*(x: expr): expr {.immediate.} =
## Constructor macro for XML. Example usage:
##
- ## .. code-block:: nimrod
- ## <>a(href="http://nimrod-code.org", newText("Nim rules."))
+ ## .. code-block:: nim
+ ## <>a(href="http://nim-code.org", newText("Nim rules."))
##
## Produces an XML tree for::
##
- ## Nim rules.
+ ## Nim rules.
##
let x = callsite()
result = xmlConstructor(x)
@@ -339,5 +339,5 @@ proc findAll*(n: XmlNode, tag: string): seq[XmlNode] =
findAll(n, tag, result)
when isMainModule:
- assert """Nim rules.""" ==
- $(<>a(href="http://nimrod-code.org", newText("Nim rules.")))
+ assert """Nim rules.""" ==
+ $(<>a(href="http://nim-code.org", newText("Nim rules.")))
diff --git a/lib/system.nim b/lib/system.nim
index b07fa76e2..1de9e23c7 100644
--- a/lib/system.nim
+++ b/lib/system.nim
@@ -100,7 +100,7 @@ proc defined*(x: expr): bool {.magic: "Defined", noSideEffect.}
## Special compile-time procedure that checks whether `x` is
## defined.
## `x` is an external symbol introduced through the compiler's
- ## `-d:x switch `_ to enable build time
+ ## `-d:x switch `_ to enable build time
## conditionals:
##
## .. code-block:: Nim
@@ -509,7 +509,7 @@ proc sizeof*[T](x: T): Natural {.magic: "SizeOf", noSideEffect.}
proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect.}
## unary ``<`` that can be used for nice looking excluding ranges:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for i in 0 .. <10: echo i
##
## Semantically this is the same as ``pred``.
@@ -544,7 +544,7 @@ proc newSeq*[T](s: var seq[T], len: int) {.magic: "NewSeq", noSideEffect.}
## ``nil``. After the creation of the sequence you should assign entries to
## the sequence instead of adding them. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var inputStrings : seq[string]
## newSeq(inputStrings, 3)
## inputStrings[0] = "The fourth"
@@ -560,7 +560,7 @@ proc newSeq*[T](len = 0): seq[T] =
## ``nil``. After the creation of the sequence you should assign entries to
## the sequence instead of adding them. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var inputStrings = newSeq[string](3)
## inputStrings[0] = "The fourth"
## inputStrings[1] = "assignment"
@@ -1058,7 +1058,7 @@ proc compileOption*(option: string): bool {.
magic: "CompileOption", noSideEffect.}
## can be used to determine an on|off compile-time option. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## when compileOption("floatchecks"):
## echo "compiled with floating point NaN and Inf checks"
@@ -1066,7 +1066,7 @@ proc compileOption*(option, arg: string): bool {.
magic: "CompileOptionArg", noSideEffect.}
## can be used to determine an enum compile-time option. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## when compileOption("opt", "size") and compileOption("gc", "boehm"):
## echo "compiled with optimization for size and uses Boehm's GC"
@@ -1123,7 +1123,7 @@ proc quit*(errorcode: int = QuitSuccess) {.
## procedures. It does *not* call the garbage collector to free all the
## memory, unless a quit procedure calls ``GC_collect``.
##
- ## The proc ``quit(QuitSuccess)`` is called implicitly when your nimrod
+ ## The proc ``quit(QuitSuccess)`` is called implicitly when your nim
## program finishes without incident. A raised unhandled exception is
## equivalent to calling ``quit(QuitFailure)``.
##
@@ -1840,7 +1840,7 @@ proc map*[T, S](data: openArray[T], op: proc (x: T): S {.closure.}): seq[S] =
## Since the input is not modified you can use this version of ``map`` to
## transform the type of the elements in the input sequence. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## let
## a = @[1, 2, 3, 4]
## b = map(a, proc(x: int): string = $x)
@@ -1854,7 +1854,7 @@ proc map*[T](data: var openArray[T], op: proc (x: var T) {.closure.}) =
## Note that this version of ``map`` requires your input and output types to
## be the same, since they are modified in-place. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var a = @["1", "2", "3", "4"]
## echo repr(a)
## # --> ["1", "2", "3", "4"]
@@ -1945,7 +1945,7 @@ proc `$`*[T: tuple|object](x: T): string =
## generic ``$`` operator for tuples that is lifted from the components
## of `x`. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## $(23, 45) == "(23, 45)"
## $() == "()"
result = "("
@@ -1971,7 +1971,7 @@ proc `$`*[T](x: set[T]): string =
## generic ``$`` operator for sets that is lifted from the components
## of `x`. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## ${23, 45} == "{23, 45}"
collectionToString(x, "{", "}")
@@ -1979,7 +1979,7 @@ proc `$`*[T](x: seq[T]): string =
## generic ``$`` operator for seqs that is lifted from the components
## of `x`. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## $(@[23, 45]) == "@[23, 45]"
collectionToString(x, "@[", "]")
@@ -2078,7 +2078,7 @@ var
## writes an error message and terminates the program. `outOfMemHook` can
## be used to raise an exception in case of OOM like so:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## var gOutOfMem: ref EOutOfMemory
## new(gOutOfMem) # need to be allocated *before* OOM really happened!
@@ -2576,7 +2576,7 @@ when not defined(JS): #and not defined(NimrodVM):
## If the file does not exist `EIO` is raised. The trailing newline
## character(s) are removed from the iterated lines. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## import strutils
##
## proc transformLetters(filename: string) =
@@ -2595,7 +2595,7 @@ when not defined(JS): #and not defined(NimrodVM):
## The trailing newline character(s) are removed from the iterated lines.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## proc countZeros(filename: File): tuple[lines, zeros: int] =
## for line in filename.lines:
## for letter in line:
@@ -2645,7 +2645,7 @@ when not defined(JS): #and not defined(NimrodVM):
## platforms this can help the processor predict better which branch is
## going to be run. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for value in inputValues:
## if likely(value <= 100):
## process(value)
@@ -2659,7 +2659,7 @@ when not defined(JS): #and not defined(NimrodVM):
## platforms this can help the processor predict better which branch is
## going to be run. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## for value in inputValues:
## if unlikely(value > 100):
## echo "Value too big!"
@@ -2766,7 +2766,7 @@ when hostOS != "standalone":
## ``b.len`` is not exactly the number of elements that are referred to
## by `x`, a `splice`:idx: is performed:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## var s = "abcdef"
## s[1 .. -2] = "xyz"
## assert s == "axyzf"
@@ -2843,7 +2843,7 @@ proc slurp*(filename: string): string {.magic: "Slurp".}
proc staticRead*(filename: string): string {.magic: "Slurp".}
## Compile-time ``readFile`` proc for easy `resource`:idx: embedding:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## const myResource = staticRead"mydatafile.bin"
##
## ``slurp`` is an alias for ``staticRead``.
@@ -2858,13 +2858,13 @@ proc staticExec*(command: string, input = ""): string {.
## if `input` is not an empty string, it will be passed as a standard input
## to the executed program.
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## const buildInfo = "Revision " & staticExec("git rev-parse HEAD") &
## "\nCompiled on " & staticExec("uname -v")
##
## ``gorge`` is an alias for ``staticExec``. Note that you can use this proc
- ## inside a pragma like `passC `_ or `passL
- ## `_.
+ ## inside a pragma like `passC `_ or `passL
+ ## `_.
proc `+=`*[T: SomeOrdinal|uint|uint64](x: var T, y: T) {.magic: "Inc", noSideEffect.}
## Increments an ordinal
@@ -2906,7 +2906,7 @@ proc instantiationInfo*(index = -1, fullPaths = false): tuple[
## to retrieve information about the current filename and line number.
## Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## import strutils
##
## template testException(exception, code: expr): stmt =
@@ -2951,7 +2951,7 @@ template assert*(cond: bool, msg = "") =
## raises an ``EAssertionFailure`` exception. However, the compiler may not
## generate any code at all for ``assert`` if it is advised to do so through
## the ``-d:release`` or ``--assertions:off`` `command line switches
- ## `_.
+ ## `_.
##
## Use ``assert`` for debugging purposes only.
bind instantiationInfo
@@ -2994,7 +2994,7 @@ template onFailedAssert*(msg: expr, code: stmt): stmt {.dirty, immediate.} =
## statements following `onFailedAssert` in the current lexical scope.
## Can be defined multiple times in a single function.
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
##
## proc example(x: int): TErrorCode =
## onFailedAssert(msg):
@@ -3089,7 +3089,7 @@ proc locals*(): RootObj {.magic: "Locals", noSideEffect.} =
## the official signature says, the return type is not ``TObject`` but a
## tuple of a structure that depends on the current scope. Example:
##
- ## .. code-block:: nimrod
+ ## .. code-block:: nim
## proc testLocals() =
## var
## a = "something"
From c95e47216f790f8aac9860a8a0deae0369a2a84f Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 10:01:20 +0200
Subject: [PATCH 031/409] Nimrod renamed to Nim
---
compiler/semexprs.nim | 2 +-
compiler/semfold.nim | 2 +-
compiler/semtypes.nim | 2 +-
compiler/vm.nim | 2 +-
compiler/vmdef.nim | 2 +-
compiler/vmgen.nim | 2 +-
6 files changed, 6 insertions(+), 6 deletions(-)
diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim
index da12ec08c..b310e0869 100644
--- a/compiler/semexprs.nim
+++ b/compiler/semexprs.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semfold.nim b/compiler/semfold.nim
index 8e53fd670..6972e3f1c 100644
--- a/compiler/semfold.nim
+++ b/compiler/semfold.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim
index 53fe4e266..c3d34f2ba 100644
--- a/compiler/semtypes.nim
+++ b/compiler/semtypes.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2012 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/vm.nim b/compiler/vm.nim
index e40acca6c..af0b30faa 100644
--- a/compiler/vm.nim
+++ b/compiler/vm.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/vmdef.nim b/compiler/vmdef.nim
index cad48abea..e25fd6392 100644
--- a/compiler/vmdef.nim
+++ b/compiler/vmdef.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2013 Andreas Rumpf
#
# See the file "copying.txt", included in this
diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim
index 94afbf008..6a6f85d76 100644
--- a/compiler/vmgen.nim
+++ b/compiler/vmgen.nim
@@ -1,6 +1,6 @@
#
#
-# The Nimrod Compiler
+# The Nim Compiler
# (c) Copyright 2014 Andreas Rumpf
#
# See the file "copying.txt", included in this
From 3ea64469008c30682a0cc7b92e3f553a07f30a37 Mon Sep 17 00:00:00 2001
From: Araq
Date: Thu, 28 Aug 2014 22:36:14 +0200
Subject: [PATCH 032/409] Nimrod renamed to Nim
---
doc/advopt.txt | 6 +-
doc/apis.txt | 2 +-
doc/astspec.txt | 112 ++++++++++++++---------------
doc/backends.txt | 162 +++++++++++++++++++++---------------------
doc/basicopt.txt | 4 +-
doc/docgen.txt | 60 ++++++++--------
doc/docs.txt | 14 ++--
doc/effects.txt | 4 +-
doc/endb.txt | 18 ++---
doc/estp.txt | 20 +++---
doc/filelist.txt | 10 +--
doc/filters.txt | 14 ++--
doc/gc.txt | 10 +--
doc/idetools.txt | 60 ++++++++--------
doc/intern.txt | 72 +++++++++----------
doc/koch.txt | 42 +++++------
doc/nimgrep.txt | 4 +-
doc/niminst.txt | 10 +--
doc/overview.txt | 4 +-
doc/pegdocs.txt | 8 +--
doc/readme.txt | 4 +-
doc/regexprs.txt | 4 +-
doc/rst.txt | 22 +++---
doc/sets_fragment.txt | 2 +-
doc/spawn.txt | 8 +--
doc/subexes.txt | 2 +-
doc/tools.txt | 14 ++--
doc/tut2.txt | 2 +-
readme.md | 32 ++++-----
readme.txt | 32 ++++-----
30 files changed, 379 insertions(+), 379 deletions(-)
diff --git a/doc/advopt.txt b/doc/advopt.txt
index 7a11e9041..18cea8a79 100644
--- a/doc/advopt.txt
+++ b/doc/advopt.txt
@@ -50,7 +50,7 @@ Advanced options:
--os:SYMBOL set the target operating system (cross-compilation)
--cpu:SYMBOL set the target processor (cross-compilation)
--debuginfo enables debug information
- --debugger:on|off turn Embedded Nimrod Debugger on|off
+ --debugger:on|off turn Embedded Nim Debugger on|off
-t, --passC:OPTION pass an option to the C compiler
-l, --passL:OPTION pass an option to the linker
--cincludes:DIR modify the C compiler header search path
@@ -58,7 +58,7 @@ Advanced options:
--clib:LIBNAME link an additional C library
(you should omit platform-specific extensions)
--genMapping generate a mapping file containing
- (Nimrod, mangled) identifier pairs
+ (Nim, mangled) identifier pairs
--project document the whole project (doc2)
--docSeeSrcUrl:url activate 'see source' for doc and doc2 commands
(see doc.item.seesrc in config/nimdoc.cfg)
@@ -89,7 +89,7 @@ Advanced options:
--listCmd list the commands used to execute external programs
--parallelBuild=0|1|... perform a parallel build
value = number of processors (0 for auto-detect)
- --verbosity:0|1|2|3 set Nimrod's verbosity level (1 is default)
+ --verbosity:0|1|2|3 set Nim's verbosity level (1 is default)
--cs:none|partial set case sensitivity level (default: none);
do not use! this setting affects the whole language
-v, --version show detailed version information
diff --git a/doc/apis.txt b/doc/apis.txt
index 9906f6bbc..e0510d85f 100644
--- a/doc/apis.txt
+++ b/doc/apis.txt
@@ -84,5 +84,5 @@ indentation indent
Coding Guidelines
=================
-For coding guidelines see the `Internals of the Nimrod Compiler
+For coding guidelines see the `Internals of the Nim Compiler
`_ documentation.
diff --git a/doc/astspec.txt b/doc/astspec.txt
index 6b6242614..5c4274093 100644
--- a/doc/astspec.txt
+++ b/doc/astspec.txt
@@ -1,11 +1,11 @@
-The AST in Nimrod
+The AST in Nim
=================
-This section describes how the AST is modelled with Nimrod's type system.
+This section describes how the AST is modelled with Nim's type system.
The AST consists of nodes (``PNimrodNode``) with a variable number of
children. Each node has a field named ``kind`` which describes what the node
contains:
-.. code-block:: nimrod
+.. code-block:: nim
type
TNimrodNodeKind = enum ## kind of a node; only explanatory
@@ -39,7 +39,7 @@ contains:
For the ``PNimrodNode`` type, the ``[]`` operator has been overloaded:
``n[i]`` is ``n``'s ``i``-th child.
-To specify the AST for the different Nimrod constructs, the notation
+To specify the AST for the different Nim constructs, the notation
``nodekind(son1, son2, ...)`` or ``nodekind(value)`` or
``nodekind(field=value)`` is used.
@@ -53,7 +53,7 @@ A leaf of the AST often corresponds to a terminal symbol in the concrete
syntax.
----------------- ---------------------------------------------
-Nimrod expression corresponding AST
+Nim expression corresponding AST
----------------- ---------------------------------------------
``42`` ``nnkIntLit(intVal = 42)``
``42'i8`` ``nnkInt8Lit(intVal = 42)``
@@ -87,12 +87,12 @@ Command call
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
echo "abc", "xyz"
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCommand(nnkIdent(!"echo"), nnkStrLit("abc"), nnkStrLit("xyz"))
@@ -101,12 +101,12 @@ Call with ``()``
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
echo("abc", "xyz")
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCall(nnkIdent(!"echo"), nnkStrLit("abc"), nnkStrLit("xyz"))
@@ -115,12 +115,12 @@ Infix operator call
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
"abc" & "xyz"
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkInfix(nnkIdent(!"&"), nnkStrLit("abc"), nnkStrLit("xyz"))
@@ -129,29 +129,29 @@ Prefix operator call
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
? "xyz"
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkPrefix(nnkIdent(!"?"), nnkStrLit("abc"))
Postfix operator call
---------------------
-**Note:** There are no postfix operators in Nimrod. However, the
+**Note:** There are no postfix operators in Nim. However, the
``nnkPostfix`` node is used for the *asterisk export marker* ``*``:
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
identifier*
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkPostfix(nnkIdent(!"*"), nnkIdent(!"identifier"))
@@ -160,12 +160,12 @@ Call with named arguments
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
writeln(file=stdout, "hallo")
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCall(nnkIdent(!"writeln"),
nnkExprEqExpr(nnkIdent(!"file"), nnkIdent(!"stdout")),
nnkStrLit("hallo"))
@@ -176,12 +176,12 @@ Dereference operator ``^``
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
x^
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkDerefExpr(nnkIdent(!"x"))
@@ -190,12 +190,12 @@ Addr operator
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
addr(x)
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkAddr(nnkIdent(!"x"))
@@ -204,12 +204,12 @@ Cast operator
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
cast[T](x)
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCast(nnkIdent(!"T"), nnkIdent(!"x"))
@@ -218,12 +218,12 @@ Object access operator ``.``
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
x.y
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkDotExpr(nnkIdent(!"x"), nnkIdent(!"y"))
@@ -232,12 +232,12 @@ Array access operator ``[]``
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
x[y]
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkBracketExpr(nnkIdent(!"x"), nnkIdent(!"y"))
@@ -249,12 +249,12 @@ are built with the ``nnkPar`` node.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
(1, 2, (3))
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkPar(nnkIntLit(1), nnkIntLit(2), nnkPar(nnkIntLit(3)))
@@ -265,12 +265,12 @@ Curly braces are used as the set constructor.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
{1, 2, 3}
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCurly(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3))
@@ -281,12 +281,12 @@ Brackets are used as the array constructor.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
[1, 2, 3]
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkBracket(nnkIntLit(1), nnkIntLit(2), nnkIntLit(3))
@@ -297,12 +297,12 @@ Ranges occur in set constructors, case statement branches or array slices.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
1..3
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkRange(nnkIntLit(1), nnkIntLit(3))
@@ -313,12 +313,12 @@ The representation of the if expression is subtle, but easy to traverse.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
if cond1: expr1 elif cond2: expr2 else: expr3
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkIfExpr(
nnkElifExpr(cond1, expr1),
nnkElifExpr(cond2, expr2),
@@ -337,7 +337,7 @@ there is no ``else`` branch, no ``nnkElse`` child exists.
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
if cond1:
stmt1
elif cond2:
@@ -349,7 +349,7 @@ Concrete syntax:
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkIfStmt(
nnkElifBranch(cond1, stmt1),
nnkElifBranch(cond2, stmt2),
@@ -369,12 +369,12 @@ Assignment
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
x = 42
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkAsgn(nnkIdent(!"x"), nnkIntLit(42))
@@ -383,14 +383,14 @@ Statement list
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
stmt1
stmt2
stmt3
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkStmtList(stmt1, stmt2, stmt3)
@@ -399,7 +399,7 @@ Case statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
case expr1
of expr2, expr3..expr4:
stmt1
@@ -412,7 +412,7 @@ Concrete syntax:
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkCaseStmt(
expr1,
nnkOfBranch(expr2, nnkRange(expr3, expr4), stmt1),
@@ -429,13 +429,13 @@ While statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
while expr1:
stmt1
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkWhileStmt(expr1, stmt1)
@@ -444,13 +444,13 @@ For statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
for ident1, ident2 in expr1:
stmt1
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkForStmt(ident1, ident2, expr1, stmt1)
@@ -459,7 +459,7 @@ Try statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
try:
stmt1
except e1, e2:
@@ -473,7 +473,7 @@ Concrete syntax:
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkTryStmt(
stmt1,
nnkExceptBranch(e1, e2, stmt2),
@@ -488,12 +488,12 @@ Return statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
return expr1
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkReturnStmt(expr1)
@@ -514,12 +514,12 @@ Continue statement
Concrete syntax:
-.. code-block:: nimrod
+.. code-block:: nim
continue
AST:
-.. code-block:: nimrod
+.. code-block:: nim
nnkContinueStmt()
Var section
diff --git a/doc/backends.txt b/doc/backends.txt
index c2dbb0af6..307f141b2 100644
--- a/doc/backends.txt
+++ b/doc/backends.txt
@@ -1,9 +1,9 @@
================================
- Nimrod Backend Integration
+ Nim Backend Integration
================================
:Author: Puppet Master
-:Version: |nimrodversion|
+:Version: |nimversion|
.. contents::
"Heresy grows from idleness." -- Unknown.
@@ -12,20 +12,20 @@
Introduction
============
-The `Nimrod Compiler User Guide `_ documents the typical
+The `Nim Compiler User Guide `_ documents the typical
compiler invocation, using the ``compile`` or ``c`` command to transform a
``.nim`` file into one or more ``.c`` files which are then compiled with the
platform's C compiler into a static binary. However there are other commands
to compile to C++, Objective-C or JavaScript. This document tries to
concentrate in a single place all the backend and interfacing options.
-The Nimrod compiler supports mainly two backend families: the C, C++ and
+The Nim compiler supports mainly two backend families: the C, C++ and
Objective-C targets and the JavaScript target. `The C like targets`_ creates
source files which can be compiled into a library or a final executable. `The
JavaScript target`_ can generate a ``.js`` file which you reference from an
HTML file or create a `standalone nodejs program `_.
-On top of generating libraries or standalone applications, Nimrod offers
+On top of generating libraries or standalone applications, Nim offers
bidirectional interfacing with the backend targets through generic and
specific pragmas.
@@ -49,25 +49,25 @@ project. This allows you to take the generated code and place it directly
into a project using any of these languages. Here are some typical command
line invocations::
- $ nimrod c hallo.nim
- $ nimrod cpp hallo.nim
- $ nimrod objc hallo.nim
+ $ nim c hallo.nim
+ $ nim cpp hallo.nim
+ $ nim objc hallo.nim
The compiler commands select the target backend, but if needed you can
`specify additional switches for cross compilation
-`_ to select the target CPU, operative system
+`_ to select the target CPU, operative system
or compiler/linker commands.
The JavaScript target
---------------------
-Nimrod can also generate `JavaScript`:idx: code through the ``js`` command.
+Nim can also generate `JavaScript`:idx: code through the ``js`` command.
However, the JavaScript code generator is experimental!
-Nimrod targets JavaScript 1.5 which is supported by any widely used browser.
+Nim targets JavaScript 1.5 which is supported by any widely used browser.
Since JavaScript does not have a portable means to include another module,
-Nimrod just generates a long ``.js`` file.
+Nim just generates a long ``.js`` file.
Features or modules that the JavaScript platform does not support are not
available. This includes:
@@ -83,35 +83,35 @@ However, the modules `strutils `_, `math `_, and
`times `_ are available! To access the DOM, use the `dom
`_ module that is only available for the JavaScript platform.
-To compile a Nimrod module into a ``.js`` file use the ``js`` command; the
+To compile a Nim module into a ``.js`` file use the ``js`` command; the
default is a ``.js`` file that is supposed to be referenced in an ``.html``
file. However, you can also run the code with `nodejs`:idx:, a `software
platform for easily building fast, scalable network applications