From 1f7fc7f279a4a1c5f4854f7c7a39a58bb2cca805 Mon Sep 17 00:00:00 2001 From: Arne Döring Date: Mon, 29 May 2017 17:53:20 +0200 Subject: arrays can now be printed --- lib/system/repr.nim | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/system') diff --git a/lib/system/repr.nim b/lib/system/repr.nim index ab02c58a2..fcf65dd0e 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -18,7 +18,7 @@ proc reprFloat(x: float): string {.compilerproc.} = return $x proc reprPointer(x: pointer): string {.compilerproc.} = var buf: array[0..59, char] discard c_sprintf(buf, "%p", x) - return $buf + return newString(buf) proc `$`(x: uint64): string = if x == 0: @@ -36,7 +36,7 @@ proc `$`(x: uint64): string = let half = i div 2 # Reverse for t in 0 .. < half: swap(buf[t], buf[i-t-1]) - result = $buf + result = newString(buf) proc reprStrAux(result: var string, s: cstring; len: int) = if cast[pointer](s) == nil: -- cgit 1.4.1-2-gfad0 From 0852be2dec72406c8d9c93e094a8907b52d1aa5a Mon Sep 17 00:00:00 2001 From: Arne Döring Date: Wed, 31 May 2017 14:05:45 +0200 Subject: remove $ for ptr/ref, prefer using string over array of char --- compiler/rodutils.nim | 8 ++++---- lib/system.nim | 30 ++++++++++++------------------ lib/system/repr.nim | 14 +++++++------- 3 files changed, 23 insertions(+), 29 deletions(-) (limited to 'lib/system') diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 03d5c95eb..1352afadb 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -10,7 +10,7 @@ ## Serialization utilities for the compiler. import strutils -proc c_sprintf(buf, frmt: cstring) {.importc: "sprintf", header: "", nodecl, varargs.} +proc c_snprintf(s: cstring; n:uint; frmt: cstring): cint {.importc: "snprintf", header: "", nodecl, varargs.} proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string = if f != f: @@ -21,9 +21,9 @@ proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string = if f > 0.0: result = "INF" else: result = "-INF" else: - var buf: array[0..80, char] - c_sprintf(buf, "%#.16e" & literalPostfix, f) - result = newString(buf) + result = newString(80) + let newLen = c_snprintf(result[0].addr, 81, "%#.16e" & literalPostfix, f) + result.setLen(newLen) proc encodeStr*(s: string, result: var string) = for i in countup(0, len(s) - 1): diff --git a/lib/system.nim b/lib/system.nim index 3dc892c44..b5008129d 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1872,26 +1872,20 @@ proc `$` *[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.} ## a ``$`` operator for a concrete enumeration is provided, this is ## used instead. (In other words: *Overwriting* is possible.) -proc `$`*[T: ref](arg: T): string = - ## The stringify operator to handle the nil value of all ref types. - ## Then it forwards to stringify operator of the underlying (value) type. - if arg.isNil: - "nil" - else: - "ref " & $arg[] - -proc `$`*[T: ptr](arg: T): string = - ## The stringify operator to handle the nil value of all ptr types. - ## Then it forwards to stringify operator of the underlying (value) type. - if arg.isNil: - "nil" - else: - "ptr " & $arg[] - -proc newString*[N](data: array[N, char]): string = +proc newString*[N](data: array[N, char]): string {.noSideEffect.} = ## Construct a string from an array of characters. The `data` is ## expected to be a null terminated string as it is often used in C. - $(cast[cstring](data[0].unsafeAddr)) + when nimvm: + # cannot cast on the vm + # not recommended to use this procedure on the vm at all, but at least it doesn't fail. + result = "" + for c in data: + if c == '\0': + return + else: + result.add c + else: + result = $(cast[cstring](data[0].unsafeAddr)) # undocumented: proc getRefcount*[T](x: ref T): int {.importc: "getRefcount", noSideEffect.} diff --git a/lib/system/repr.nim b/lib/system/repr.nim index fcf65dd0e..2775b1b3e 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -16,27 +16,27 @@ proc reprInt(x: int64): string {.compilerproc.} = return $x proc reprFloat(x: float): string {.compilerproc.} = return $x proc reprPointer(x: pointer): string {.compilerproc.} = - var buf: array[0..59, char] - discard c_sprintf(buf, "%p", x) - return newString(buf) + result = newString(60) + let newLen = c_sprintf(result[0].addr, "%p", x) + result.setLen newLen proc `$`(x: uint64): string = if x == 0: result = "0" else: - var buf: array[60, char] + result = newString(60) var i = 0 var n = x while n != 0: let nn = n div 10'u64 - buf[i] = char(n - 10'u64 * nn + ord('0')) + result[i] = char(n - 10'u64 * nn + ord('0')) inc i n = nn + result.setLen i let half = i div 2 # Reverse - for t in 0 .. < half: swap(buf[t], buf[i-t-1]) - result = newString(buf) + for t in 0 .. < half: swap(result[t], result[i-t-1]) proc reprStrAux(result: var string, s: cstring; len: int) = if cast[pointer](s) == nil: -- cgit 1.4.1-2-gfad0 From ddea990a70606aaa19513510ae4b47ada7e49fe9 Mon Sep 17 00:00:00 2001 From: Arne Döring Date: Tue, 6 Jun 2017 21:19:50 +0200 Subject: removed newString proc again, reverted some unnecesary changes --- compiler/rodutils.nim | 6 +++--- lib/pure/nativesockets.nim | 4 ++-- lib/pure/os.nim | 2 +- lib/system.nim | 15 --------------- lib/system/repr.nim | 6 +++--- tests/async/tnewasyncudp.nim | 6 +++--- tests/misc/treadx.nim | 3 +-- tests/system/toString.nim | 12 +++--------- 8 files changed, 16 insertions(+), 38 deletions(-) (limited to 'lib/system') diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 1352afadb..3a90a207c 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -21,9 +21,9 @@ proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string = if f > 0.0: result = "INF" else: result = "-INF" else: - result = newString(80) - let newLen = c_snprintf(result[0].addr, 81, "%#.16e" & literalPostfix, f) - result.setLen(newLen) + var buf: array[0..80, char] + let newLen = c_snprintf(buf.cstring, buf.len.uint, "%#.16e%s", f, literalPostfix.cstring) + result = $buf.cstring proc encodeStr*(s: string, result: var string) = for i in countup(0, len(s) - 1): diff --git a/lib/pure/nativesockets.nim b/lib/pure/nativesockets.nim index 7568408a6..a33836458 100644 --- a/lib/pure/nativesockets.nim +++ b/lib/pure/nativesockets.nim @@ -500,7 +500,7 @@ proc getLocalAddr*(socket: SocketHandle, domain: Domain): (string, Port) = if inet_ntop(name.sin6_family.cint, addr name, buf.cstring, sizeof(buf).int32).isNil: raiseOSError(osLastError()) - result = ($buf, Port(nativesockets.ntohs(name.sin6_port))) + result = ($buf.cstring, Port(nativesockets.ntohs(name.sin6_port))) else: raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr") @@ -536,7 +536,7 @@ proc getPeerAddr*(socket: SocketHandle, domain: Domain): (string, Port) = if inet_ntop(name.sin6_family.cint, addr name, buf.cstring, sizeof(buf).int32).isNil: raiseOSError(osLastError()) - result = ($buf, Port(nativesockets.ntohs(name.sin6_port))) + result = ($buf.cstring, Port(nativesockets.ntohs(name.sin6_port))) else: raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr") diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 5211bc00c..a227e9f32 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -1010,7 +1010,7 @@ iterator walkDir*(dir: string; relative=false): tuple[kind: PathComponent, path: while true: var x = readdir(d) if x == nil: break - var y = newString(x.d_name) + var y = $x.d_name.cstring if y != "." and y != "..": var s: Stat if not relative: diff --git a/lib/system.nim b/lib/system.nim index b5008129d..014538098 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -1872,21 +1872,6 @@ proc `$` *[Enum: enum](x: Enum): string {.magic: "EnumToStr", noSideEffect.} ## a ``$`` operator for a concrete enumeration is provided, this is ## used instead. (In other words: *Overwriting* is possible.) -proc newString*[N](data: array[N, char]): string {.noSideEffect.} = - ## Construct a string from an array of characters. The `data` is - ## expected to be a null terminated string as it is often used in C. - when nimvm: - # cannot cast on the vm - # not recommended to use this procedure on the vm at all, but at least it doesn't fail. - result = "" - for c in data: - if c == '\0': - return - else: - result.add c - else: - result = $(cast[cstring](data[0].unsafeAddr)) - # undocumented: proc getRefcount*[T](x: ref T): int {.importc: "getRefcount", noSideEffect.} proc getRefcount*(x: string): int {.importc: "getRefcount", noSideEffect.} diff --git a/lib/system/repr.nim b/lib/system/repr.nim index 2775b1b3e..172b4c08c 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -16,9 +16,9 @@ proc reprInt(x: int64): string {.compilerproc.} = return $x proc reprFloat(x: float): string {.compilerproc.} = return $x proc reprPointer(x: pointer): string {.compilerproc.} = - result = newString(60) - let newLen = c_sprintf(result[0].addr, "%p", x) - result.setLen newLen + var buf: array[60, char] + discard c_sprintf(result[0].addr, "%p", x) + result = $buf.cstring proc `$`(x: uint64): string = if x == 0: diff --git a/tests/async/tnewasyncudp.nim b/tests/async/tnewasyncudp.nim index bf54c0d06..da731f4b8 100644 --- a/tests/async/tnewasyncudp.nim +++ b/tests/async/tnewasyncudp.nim @@ -54,7 +54,7 @@ proc launchSwarm(name: ptr SockAddr) {.async.} = k = 0 while k < messagesToSend: zeroMem(addr(buffer[0]), 16384) - zeroMem(cast[pointer](addr(saddr)), sizeof(Sockaddr_in)) + zeroMem(cast[pointer](addr(saddr)), sizeof(Sockaddr_in)) var message = "Message " & $(i * messagesToSend + k) await sendTo(sock, addr message[0], len(message), name, sizeof(Sockaddr_in).SockLen) @@ -62,7 +62,7 @@ proc launchSwarm(name: ptr SockAddr) {.async.} = 16384, cast[ptr SockAddr](addr saddr), addr slen) size = 0 - var grammString = $buffer + var grammString = $buffer.cstring if grammString == message: saveSendingPort(sockport) inc(recvCount) @@ -84,7 +84,7 @@ proc readMessages(server: AsyncFD) {.async.} = 16384, cast[ptr SockAddr](addr(saddr)), addr(slen)) size = 0 - var grammString = $buffer + var grammString = $buffer.cstring if grammString.startswith("Message ") and saddr.sin_addr.s_addr == 0x100007F: await sendTo(server, addr grammString[0], len(grammString), diff --git a/tests/misc/treadx.nim b/tests/misc/treadx.nim index 49b6ad691..2e3904cd1 100644 --- a/tests/misc/treadx.nim +++ b/tests/misc/treadx.nim @@ -6,9 +6,8 @@ when not defined(windows): var buf: array[0..10, char] while true: var r = read(0, addr(buf), sizeof(buf)-1) - add inp, $buf + add inp, $buf.cstring if r != sizeof(buf)-1: break echo inp #dafkladskölklödsaf ölksdakölfölksfklwe4iojr389wr 89uweokf sdlkf jweklr jweflksdj fioewjfsdlfsd - diff --git a/tests/system/toString.nim b/tests/system/toString.nim index f9697ec75..cd9a49272 100644 --- a/tests/system/toString.nim +++ b/tests/system/toString.nim @@ -13,9 +13,6 @@ inf nan nil nil -(a: 0, b: nil) -nil -ptr (a: 0, b: nil)''' """ echo($(@[23, 45])) @@ -49,12 +46,8 @@ type b: string var foo1: Foo -var foo2: ref Foo -var foo3: ptr Foo = foo1.addr -echo foo1 -echo foo2 -echo foo3 +doAssert $foo1 == "(a: 0, b: nil)" const data = @['a','b', '\0', 'c','d'] @@ -67,5 +60,6 @@ import strutils # array test let arr = ['H','e','l','l','o',' ','W','o','r','l','d','!','\0'] +# not sure if this is really a good idea doAssert startsWith($arr, "[H, e, l, l, o, , W, o, r, l, d, !,") -doAssert newString(arr) == "Hello World!" +doAssert $arr.cstring == "Hello World!" -- cgit 1.4.1-2-gfad0 From c9a2acefc1f34801df4e57d8a2462bff4a0666d6 Mon Sep 17 00:00:00 2001 From: Arne Döring Date: Tue, 6 Jun 2017 22:33:52 +0200 Subject: fix --- lib/system/repr.nim | 2 +- tests/gc/gctest.nim | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) (limited to 'lib/system') diff --git a/lib/system/repr.nim b/lib/system/repr.nim index 172b4c08c..58c86b0db 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -17,7 +17,7 @@ proc reprFloat(x: float): string {.compilerproc.} = return $x proc reprPointer(x: pointer): string {.compilerproc.} = var buf: array[60, char] - discard c_sprintf(result[0].addr, "%p", x) + discard c_sprintf(buf.cstring, "%p", x) result = $buf.cstring proc `$`(x: uint64): string = diff --git a/tests/gc/gctest.nim b/tests/gc/gctest.nim index b3b9af608..f5c81f033 100644 --- a/tests/gc/gctest.nim +++ b/tests/gc/gctest.nim @@ -31,7 +31,7 @@ type of nkList: sons: seq[PCaseNode] else: unused: seq[string] - TIdObj* = object of TObject + TIdObj* = object of RootObj id*: int # unique id; use this for comparisons and not the pointers PIdObj* = ref TIdObj -- cgit 1.4.1-2-gfad0 From d55e02ddf12662781cf89e2fd91473dbf7552e5a Mon Sep 17 00:00:00 2001 From: Charlie Barto Date: Mon, 9 Oct 2017 11:26:53 -0400 Subject: fixes to allow the usage of clang on windows with the msvc abi and ms headers (#6442) --- lib/pure/times.nim | 15 +++++---------- lib/system.nim | 2 +- lib/system/ansi_c.nim | 8 ++++++-- lib/system/sysio.nim | 9 ++++++--- lib/windows/winlean.nim | 4 ++-- 5 files changed, 20 insertions(+), 18 deletions(-) (limited to 'lib/system') diff --git a/lib/pure/times.nim b/lib/pure/times.nim index 553e3fe01..96668c4f8 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -83,16 +83,11 @@ when defined(posix) and not defined(JS): elif defined(windows): import winlean - when defined(vcc) or defined(bcc) or defined(icl): - # newest version of Visual C++ defines time_t to be of 64 bits - type TimeImpl {.importc: "time_t", header: "".} = int64 - # visual c's c runtime exposes these under a different name - var - timezone {.importc: "_timezone", header: "".}: int - else: - type TimeImpl {.importc: "time_t", header: "".} = int - var - timezone {.importc, header: "".}: int + # newest version of Visual C++ defines time_t to be of 64 bits + type TimeImpl {.importc: "time_t", header: "".} = int64 + # visual c's c runtime exposes these under a different name + var + timezone {.importc: "_timezone", header: "".}: int type Time* = distinct TimeImpl diff --git a/lib/system.nim b/lib/system.nim index 42d5794f5..207d616d2 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -2872,7 +2872,7 @@ when not defined(JS): #and not defined(nimscript): importc: when defined(bcc): "setmode" else: "_setmode", header: "".} var - O_BINARY {.importc: "O_BINARY", nodecl.}: cint + O_BINARY {.importc: "_O_BINARY", header:"".}: cint # we use binary mode on Windows: c_setmode(c_fileno(stdin), O_BINARY) diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index b2f6d314f..0bac979e7 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -103,8 +103,12 @@ proc c_sprintf(buf, frmt: cstring): cint {. importc: "sprintf", header: "", varargs, noSideEffect.} # we use it only in a way that cannot lead to security issues -proc c_fileno(f: File): cint {. - importc: "fileno", header: "".} +when defined(windows): + proc c_fileno(f: File): cint {. + importc: "_fileno", header: "".} +else: + proc c_fileno(f: File): cint {. + importc: "fileno", header: "".} proc c_malloc(size: csize): pointer {. importc: "malloc", header: "".} diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 7b6d93fe0..4f266e0ae 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -15,9 +15,12 @@ {.push debugger:off .} # the user does not want to trace a part # of the standard library! - -proc c_fdopen(filehandle: cint, mode: cstring): File {. - importc: "fdopen", header: "".} +when defined(windows): + proc c_fdopen(filehandle: cint, mode: cstring): File {. + importc: "_fdopen", header: "".} +else: + proc c_fdopen(filehandle: cint, mode: cstring): File {. + importc: "fdopen", header: "".} proc c_fputs(c: cstring, f: File): cint {. importc: "fputs", header: "", tags: [WriteIOEffect].} proc c_fgets(c: cstring, n: cint, f: File): cstring {. diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 7a221ceb1..c3229cc7b 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -14,8 +14,8 @@ import dynlib -when defined(vcc): - {.passC: "-DWIN32_LEAN_AND_MEAN".} + +{.passC: "-DWIN32_LEAN_AND_MEAN".} const useWinUnicode* = not defined(useWinAnsi) -- cgit 1.4.1-2-gfad0 From edefe4db21e64d751d503e55e502849ea2bbd6ed Mon Sep 17 00:00:00 2001 From: Eduardo Bart Date: Mon, 9 Oct 2017 17:55:12 -0300 Subject: Futher improve seq assingment speed by 2x factor (#6437) --- lib/system/assign.nim | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) (limited to 'lib/system') diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 115df61a7..f061c89cf 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -61,13 +61,17 @@ proc genericAssignAux(dest, src: pointer, mt: PNimType, shallow: bool) = unsureAsgnRef(x, s2) return sysAssert(dest != nil, "genericAssignAux 3") - unsureAsgnRef(x, newSeq(mt, seq.len)) - var dst = cast[ByteAddress](cast[PPointer](dest)[]) if ntfNoRefs in mt.base.flags: + var ss = nimNewSeqOfCap(mt, seq.len) + cast[PGenericSeq](ss).len = seq.len + unsureAsgnRef(x, ss) + var dst = cast[ByteAddress](cast[PPointer](dest)[]) copyMem(cast[pointer](dst +% GenericSeqSize), cast[pointer](cast[ByteAddress](s2) +% GenericSeqSize), seq.len * mt.base.size) else: + unsureAsgnRef(x, newSeq(mt, seq.len)) + var dst = cast[ByteAddress](cast[PPointer](dest)[]) for i in 0..seq.len-1: genericAssignAux( cast[pointer](dst +% i*% mt.base.size +% GenericSeqSize), -- cgit 1.4.1-2-gfad0 From 3308d265816b342a842e7cabef492a54ea722e74 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Tue, 10 Oct 2017 00:17:20 +0200 Subject: breaking change: arrays of char do not convert to cstring; ptr to array of char does --- changelog.md | 3 +++ compiler/condsyms.nim | 1 + compiler/rodutils.nim | 11 ++++++++--- compiler/sigmatch.nim | 13 +++++++------ compiler/types.nim | 8 -------- lib/pure/nativesockets.nim | 14 ++++++++------ lib/pure/os.nim | 5 ++++- lib/pure/strutils.nim | 10 ++++++++-- lib/system/dyncalls.nim | 5 ++++- lib/system/excpt.nim | 8 ++++++-- lib/system/repr.nim | 11 ++++++++--- lib/system/sysstr.nim | 20 ++++++++++++++++---- 12 files changed, 73 insertions(+), 36 deletions(-) (limited to 'lib/system') diff --git a/changelog.md b/changelog.md index 9f6a83a37..22d763f53 100644 --- a/changelog.md +++ b/changelog.md @@ -5,3 +5,6 @@ - Removed basic2d/basic3d out of the stdlib and into Nimble packages. These packages deprecated however, use the ``glm``, ``arraymancer``, ``neo`` or another package. +- Arrays of char cannot be converted to ``cstring`` anymore, pointers to + arrays of char can! This means ``$`` for arrays can finally exist + in ``system.nim`` and do the right thing. diff --git a/compiler/condsyms.nim b/compiler/condsyms.nim index 9863e90bb..02c31163a 100644 --- a/compiler/condsyms.nim +++ b/compiler/condsyms.nim @@ -108,3 +108,4 @@ proc initDefines*() = defineSymbol("nimHasCppDefine") defineSymbol("nimGenericInOutFlags") when false: defineSymbol("nimHasOpt") + defineSymbol("nimNoArrayToCstringConversion") diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 6e77e6b8f..0456e9349 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -21,9 +21,14 @@ proc toStrMaxPrecision*(f: BiggestFloat, literalPostfix = ""): string = if f > 0.0: result = "INF" else: result = "-INF" else: - var buf: array[0..80, char] - discard c_snprintf(buf.cstring, buf.len.uint, "%#.16e%s", f, literalPostfix.cstring) - result = $buf.cstring + when defined(nimNoArrayToCstringConversion): + result = newString(81) + let n = c_snprintf(result.cstring, result.len.uint, "%#.16e%s", f, literalPostfix.cstring) + setLen(result, n) + else: + var buf: array[0..80, char] + discard c_snprintf(buf.cstring, buf.len.uint, "%#.16e%s", f, literalPostfix.cstring) + result = $buf.cstring proc encodeStr*(s: string, result: var string) = for i in countup(0, len(s) - 1): diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index f2bc24399..50d4178b6 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -1288,12 +1288,13 @@ proc typeRelImpl(c: var TCandidate, f, aOrig: PType, of tyString: result = isConvertible of tyPtr: # ptr[Tag, char] is not convertible to 'cstring' for now: - if a.len == 1 and a.sons[0].kind == tyChar: result = isConvertible - of tyArray: - if (firstOrd(a.sons[0]) == 0) and - (skipTypes(a.sons[0], {tyRange}).kind in {tyInt..tyInt64}) and - (a.sons[1].kind == tyChar): - result = isConvertible + if a.len == 1: + let pointsTo = a.sons[0].skipTypes(abstractInst) + if pointsTo.kind == tyChar: result = isConvertible + elif pointsTo.kind == tyArray and firstOrd(pointsTo.sons[0]) == 0 and + skipTypes(pointsTo.sons[0], {tyRange}).kind in {tyInt..tyInt64} and + pointsTo.sons[1].kind == tyChar: + result = isConvertible else: discard of tyEmpty, tyVoid: diff --git a/compiler/types.nim b/compiler/types.nim index 3dbf6fd18..f32b0da18 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -667,14 +667,6 @@ proc lengthOrd*(t: PType): BiggestInt = else: result = lastOrd(t) - firstOrd(t) + 1 -proc isCompatibleToCString*(a: PType): bool = - if a.kind == tyArray: - if (firstOrd(a.sons[0]) == 0) and - (skipTypes(a.sons[0], {tyRange, tyGenericInst, tyAlias}).kind in - {tyInt..tyInt64, tyUInt..tyUInt64}) and - (a.sons[1].kind == tyChar): - result = true - # -------------- type equality ----------------------------------------------- type diff --git a/lib/pure/nativesockets.nim b/lib/pure/nativesockets.nim index c8fb041d8..6c8701843 100644 --- a/lib/pure/nativesockets.nim +++ b/lib/pure/nativesockets.nim @@ -496,11 +496,12 @@ proc getLocalAddr*(socket: SocketHandle, domain: Domain): (string, Port) = addr(namelen)) == -1'i32: raiseOSError(osLastError()) # Cannot use INET6_ADDRSTRLEN here, because it's a C define. - var buf: array[64, char] + result[0] = newString(64) if inet_ntop(name.sin6_family.cint, - addr name.sin6_addr, buf.cstring, sizeof(buf).int32).isNil: + addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil: raiseOSError(osLastError()) - result = ($buf.cstring, Port(nativesockets.ntohs(name.sin6_port))) + setLen(result[0], result[0].cstring.len) + result[1] = Port(nativesockets.ntohs(name.sin6_port)) else: raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr") @@ -532,11 +533,12 @@ proc getPeerAddr*(socket: SocketHandle, domain: Domain): (string, Port) = addr(namelen)) == -1'i32: raiseOSError(osLastError()) # Cannot use INET6_ADDRSTRLEN here, because it's a C define. - var buf: array[64, char] + result[0] = newString(64) if inet_ntop(name.sin6_family.cint, - addr name.sin6_addr, buf.cstring, sizeof(buf).int32).isNil: + addr name.sin6_addr, addr result[0][0], (result[0].len+1).int32).isNil: raiseOSError(osLastError()) - result = ($buf.cstring, Port(nativesockets.ntohs(name.sin6_port))) + setLen(result[0], result[0].cstring.len) + result[1] = Port(nativesockets.ntohs(name.sin6_port)) else: raiseOSError(OSErrorCode(-1), "invalid socket family in getLocalAddr") diff --git a/lib/pure/os.nim b/lib/pure/os.nim index e6ef96ba3..a1ae4e250 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -790,7 +790,10 @@ iterator walkDir*(dir: string; relative=false): tuple[kind: PathComponent, path: while true: var x = readdir(d) if x == nil: break - var y = $x.d_name.cstring + when defined(nimNoArrayToCstringConversion): + var y = $cstring(addr x.d_name) + else: + var y = $x.d_name.cstring if y != "." and y != "..": var s: Stat if not relative: diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 910d09afd..cc0f474f4 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -1890,11 +1890,17 @@ proc formatBiggestFloat*(f: BiggestFloat, format: FloatFormatMode = ffDefault, frmtstr[3] = '*' frmtstr[4] = floatFormatToChar[format] frmtstr[5] = '\0' - L = c_sprintf(buf, frmtstr, precision, f) + when defined(nimNoArrayToCstringConversion): + L = c_sprintf(addr buf, addr frmtstr, precision, f) + else: + L = c_sprintf(buf, frmtstr, precision, f) else: frmtstr[1] = floatFormatToChar[format] frmtstr[2] = '\0' - L = c_sprintf(buf, frmtstr, f) + when defined(nimNoArrayToCstringConversion): + L = c_sprintf(addr buf, addr frmtstr, f) + else: + L = c_sprintf(buf, frmtstr, f) result = newString(L) for i in 0 ..< L: # Depending on the locale either dot or comma is produced, diff --git a/lib/system/dyncalls.nim b/lib/system/dyncalls.nim index 2b86ddf25..c8e251d1e 100644 --- a/lib/system/dyncalls.nim +++ b/lib/system/dyncalls.nim @@ -142,7 +142,10 @@ elif defined(windows) or defined(dos): dec(m) k = k div 10 if k == 0: break - result = getProcAddress(cast[THINSTANCE](lib), decorated) + when defined(nimNoArrayToCstringConversion): + result = getProcAddress(cast[THINSTANCE](lib), addr decorated) + else: + result = getProcAddress(cast[THINSTANCE](lib), decorated) if result != nil: return procAddrError(name) diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index cee4e33a5..950981227 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -289,8 +289,12 @@ proc raiseExceptionAux(e: ref Exception) = add(buf, " [") xadd(buf, e.name, e.name.len) add(buf, "]\n") - unhandled(buf): - showErrorMessage(buf) + when defined(nimNoArrayToCstringConversion): + template tbuf(): untyped = addr buf + else: + template tbuf(): untyped = buf + unhandled(tbuf()): + showErrorMessage(tbuf()) quitOrDebug() proc raiseException(e: ref Exception, ename: cstring) {.compilerRtl.} = diff --git a/lib/system/repr.nim b/lib/system/repr.nim index 58c86b0db..19fa564fb 100644 --- a/lib/system/repr.nim +++ b/lib/system/repr.nim @@ -16,9 +16,14 @@ proc reprInt(x: int64): string {.compilerproc.} = return $x proc reprFloat(x: float): string {.compilerproc.} = return $x proc reprPointer(x: pointer): string {.compilerproc.} = - var buf: array[60, char] - discard c_sprintf(buf.cstring, "%p", x) - result = $buf.cstring + when defined(nimNoArrayToCstringConversion): + result = newString(60) + let n = c_sprintf(addr result[0], "%p", x) + setLen(result, n) + else: + var buf: array[0..59, char] + discard c_sprintf(buf, "%p", x) + return $buf proc `$`(x: uint64): string = if x == 0: diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index 90201202c..43b5a0292 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -24,7 +24,10 @@ proc cmpStrings(a, b: NimString): int {.inline, compilerProc.} = if a == b: return 0 if a == nil: return -1 if b == nil: return 1 - return c_strcmp(a.data, b.data) + when defined(nimNoArrayToCstringConversion): + return c_strcmp(addr a.data, addr b.data) + else: + return c_strcmp(a.data, b.data) proc eqStrings(a, b: NimString): bool {.inline, compilerProc.} = if a == b: return true @@ -320,7 +323,10 @@ proc nimIntToStr(x: int): string {.compilerRtl.} = proc add*(result: var string; x: float) = var buf: array[0..64, char] - var n: int = c_sprintf(buf, "%.16g", x) + when defined(nimNoArrayToCstringConversion): + var n: int = c_sprintf(addr buf, "%.16g", x) + else: + var n: int = c_sprintf(buf, "%.16g", x) var hasDot = false for i in 0..n-1: if buf[i] == ',': @@ -342,7 +348,10 @@ proc add*(result: var string; x: float) = else: result.add "inf" else: - result.add buf + var i = 0 + while buf[i] != '\0': + result.add buf[i] + inc i proc nimFloatToStr(f: float): string {.compilerproc.} = result = newStringOfCap(8) @@ -507,7 +516,10 @@ proc nimParseBiggestFloat(s: string, number: var BiggestFloat, t[ti-2] = ('0'.ord + abs_exponent mod 10).char; abs_exponent = abs_exponent div 10 t[ti-3] = ('0'.ord + abs_exponent mod 10).char - number = c_strtod(t, nil) + when defined(nimNoArrayToCstringConversion): + number = c_strtod(addr t, nil) + else: + number = c_strtod(t, nil) proc nimInt64ToStr(x: int64): string {.compilerRtl.} = result = newStringOfCap(sizeof(x)*4) -- cgit 1.4.1-2-gfad0 From 55cb959a68f00e4702bf1f80207d574dd1888f46 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Tue, 10 Oct 2017 09:18:31 +0200 Subject: make tests green again; closes #5861 --- lib/system/endb.nim | 30 +++++++++++++++--------------- tests/async/tnewasyncudp.nim | 4 ++-- tests/float/tfloat4.nim | 2 +- tests/system/toString.nim | 2 +- 4 files changed, 19 insertions(+), 19 deletions(-) (limited to 'lib/system') diff --git a/lib/system/endb.nim b/lib/system/endb.nim index d4d10a52c..35d8f25c4 100644 --- a/lib/system/endb.nim +++ b/lib/system/endb.nim @@ -76,10 +76,10 @@ proc `==`(a, b: StaticStr): bool = return true proc `==`(a: StaticStr, b: cstring): bool = - result = c_strcmp(a.data, b) == 0 + result = c_strcmp(unsafeAddr a.data, b) == 0 proc write(f: File, s: StaticStr) = - write(f, cstring(s.data)) + write(f, cstring(unsafeAddr s.data)) proc listBreakPoints() = write(stdout, EndbBeg) @@ -260,8 +260,8 @@ proc parseBreakpoint(s: cstring, start: int): Breakpoint = if result.high == 0: result.high = result.low i = scanFilename(s, dbgTemp, i) if dbgTemp.len != 0: - if not hasExt(dbgTemp.data): add(dbgTemp, ".nim") - result.filename = canonFilename(dbgTemp.data.cstring) + if not hasExt(addr dbgTemp.data): add(dbgTemp, ".nim") + result.filename = canonFilename(addr dbgTemp.data) if result.filename.isNil: debugOut("[Warning] no breakpoint could be set; unknown filename ") return @@ -292,12 +292,12 @@ proc dbgEvaluate(stream: File, s: cstring, start: int, f: PFrame) = i = scanAndAppendWord(s, dbgTemp, i) for i in 0 .. getGlobalLen()-1: let v = getGlobal(i) - if c_strcmp(v.name, dbgTemp.data) == 0: + if c_strcmp(v.name, addr dbgTemp.data) == 0: writeVariable(stream, v) else: for i in 0 .. f.len-1: let v = getLocal(f, i) - if c_strcmp(v.name, dbgTemp.data) == 0: + if c_strcmp(v.name, addr dbgTemp.data) == 0: writeVariable(stream, v) proc dbgOut(s: cstring, start: int, currFrame: PFrame) = @@ -306,7 +306,7 @@ proc dbgOut(s: cstring, start: int, currFrame: PFrame) = if dbgTemp.len == 0: invalidCommand() return - var stream = openAppend(dbgTemp.data) + var stream = openAppend(addr dbgTemp.data) if stream == nil: debugOut("[Warning] could not open or create file ") return @@ -320,7 +320,7 @@ proc dbgStackFrame(s: cstring, start: int, currFrame: PFrame) = # just write it to stdout: listFrame(stdout, currFrame) else: - var stream = openAppend(dbgTemp.data) + var stream = openAppend(addr dbgTemp.data) if stream == nil: debugOut("[Warning] could not open or create file ") return @@ -369,7 +369,7 @@ proc commandPrompt() = if not readLine(stdin, dbgUser): break if dbgUser.len == 0: dbgUser.len = oldLen # now look what we have to do: - var i = scanWord(dbgUser.data, dbgTemp, 0) + var i = scanWord(addr dbgUser.data, dbgTemp, 0) template `?`(x: expr): expr = dbgTemp == cstring(x) if ?"s" or ?"step": dbgState = dbStepInto @@ -400,13 +400,13 @@ proc commandPrompt() = prevState = dbgState prevSkipFrame = dbgSkipToFrame dbgState = dbSkipCurrent - dbgEvaluate(stdout, dbgUser.data, i, dbgFramePtr) + dbgEvaluate(stdout, addr dbgUser.data, i, dbgFramePtr) dbgState = prevState dbgSkipToFrame = prevSkipFrame elif ?"o" or ?"out": - dbgOut(dbgUser.data, i, dbgFramePtr) + dbgOut(addr dbgUser.data, i, dbgFramePtr) elif ?"stackframe": - dbgStackFrame(dbgUser.data, i, dbgFramePtr) + dbgStackFrame(addr dbgUser.data, i, dbgFramePtr) elif ?"w" or ?"where": dbgShowExecutionPoint() elif ?"l" or ?"locals": @@ -444,16 +444,16 @@ proc commandPrompt() = elif ?"bt" or ?"backtrace": dbgWriteStackTrace(framePtr) elif ?"b" or ?"break": - createBreakPoint(dbgUser.data, i) + createBreakPoint(addr dbgUser.data, i) elif ?"breakpoints": listBreakPoints() elif ?"toggle": - breakpointToggle(dbgUser.data, i) + breakpointToggle(addr dbgUser.data, i) elif ?"filenames": listFilenames() elif ?"maxdisplay": var parsed: int - i = scanNumber(dbgUser.data, parsed, i) + i = scanNumber(addr dbgUser.data, parsed, i) if dbgUser.data[i-1] in {'0'..'9'}: if parsed == 0: maxDisplayRecDepth = -1 else: maxDisplayRecDepth = parsed diff --git a/tests/async/tnewasyncudp.nim b/tests/async/tnewasyncudp.nim index da731f4b8..b56cdc71b 100644 --- a/tests/async/tnewasyncudp.nim +++ b/tests/async/tnewasyncudp.nim @@ -62,7 +62,7 @@ proc launchSwarm(name: ptr SockAddr) {.async.} = 16384, cast[ptr SockAddr](addr saddr), addr slen) size = 0 - var grammString = $buffer.cstring + var grammString = $cstring(addr buffer) if grammString == message: saveSendingPort(sockport) inc(recvCount) @@ -84,7 +84,7 @@ proc readMessages(server: AsyncFD) {.async.} = 16384, cast[ptr SockAddr](addr(saddr)), addr(slen)) size = 0 - var grammString = $buffer.cstring + var grammString = $cstring(addr buffer) if grammString.startswith("Message ") and saddr.sin_addr.s_addr == 0x100007F: await sendTo(server, addr grammString[0], len(grammString), diff --git a/tests/float/tfloat4.nim b/tests/float/tfloat4.nim index d7783ce26..559c8aaca 100644 --- a/tests/float/tfloat4.nim +++ b/tests/float/tfloat4.nim @@ -9,7 +9,7 @@ proc c_sprintf(buf, fmt: cstring) {.importc:"sprintf", header: "", vara proc floatToStr(f: float64): string = var buffer: array[128, char] - c_sprintf(buffer, "%.16e", f) + c_sprintf(addr buffer, "%.16e", f) result = "" for ch in buffer: if ch == '\0': diff --git a/tests/system/toString.nim b/tests/system/toString.nim index bc8720b55..1279897a7 100644 --- a/tests/system/toString.nim +++ b/tests/system/toString.nim @@ -50,4 +50,4 @@ import strutils let arr = ['H','e','l','l','o',' ','W','o','r','l','d','!','\0'] doAssert $arr == "[H, e, l, l, o, , W, o, r, l, d, !, \0]" -doAssert $arr.cstring == "Hello World!" +doAssert $cstring(unsafeAddr arr) == "Hello World!" -- cgit 1.4.1-2-gfad0 From 4a7266e1c1ba34318e1aabf5977fb9dc2f19e355 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 16 Oct 2017 12:29:40 +0200 Subject: fixes #3558 --- lib/system/alloc.nim | 15 ++++++++------- lib/system/gc.nim | 17 +++++++++-------- 2 files changed, 17 insertions(+), 15 deletions(-) (limited to 'lib/system') diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index 78db96e77..19d27e7d2 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -301,13 +301,14 @@ proc pageAddr(p: pointer): PChunk {.inline.} = result = cast[PChunk](cast[ByteAddress](p) and not PageMask) #sysAssert(Contains(allocator.chunkStarts, pageIndex(result))) -proc writeFreeList(a: MemRegion) = - var it = a.freeChunksList - c_fprintf(stdout, "freeChunksList: %p\n", it) - while it != nil: - c_fprintf(stdout, "it: %p, next: %p, prev: %p, size: %ld\n", - it, it.next, it.prev, it.size) - it = it.next +when false: + proc writeFreeList(a: MemRegion) = + var it = a.freeChunksList + c_fprintf(stdout, "freeChunksList: %p\n", it) + while it != nil: + c_fprintf(stdout, "it: %p, next: %p, prev: %p, size: %ld\n", + it, it.next, it.prev, it.size) + it = it.next const nimMaxHeap {.intdefine.} = 0 diff --git a/lib/system/gc.nim b/lib/system/gc.nim index a2ff72a30..21757cf78 100644 --- a/lib/system/gc.nim +++ b/lib/system/gc.nim @@ -155,14 +155,15 @@ template setColor(c, col) = else: c.refcount = c.refcount and not colorMask or col -proc writeCell(msg: cstring, c: PCell) = - var kind = -1 - var typName: cstring = "nil" - if c.typ != nil: - kind = ord(c.typ.kind) - when defined(nimTypeNames): - if not c.typ.name.isNil: - typName = c.typ.name +when defined(logGC): + proc writeCell(msg: cstring, c: PCell) = + var kind = -1 + var typName: cstring = "nil" + if c.typ != nil: + kind = ord(c.typ.kind) + when defined(nimTypeNames): + if not c.typ.name.isNil: + typName = c.typ.name when leakDetector: c_fprintf(stdout, "[GC] %s: %p %d %s rc=%ld from %s(%ld)\n", -- cgit 1.4.1-2-gfad0 From b219fc74ad057a02a7455f0b83fa4239dbfe5979 Mon Sep 17 00:00:00 2001 From: Araq Date: Mon, 16 Oct 2017 12:45:43 +0200 Subject: fixes #5143 --- lib/system/threads.nim | 2 +- tests/testament/categories.nim | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) (limited to 'lib/system') diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 96c045e6b..016bf5822 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -398,7 +398,7 @@ template afterThreadRuns() = threadDestructionHandlers[i]() when not defined(boehmgc) and not hasSharedHeap and not defined(gogc) and not defined(gcRegions): - proc deallocOsPages() + proc deallocOsPages() {.rtl.} when defined(boehmgc): type GCStackBaseProc = proc(sb: pointer, t: pointer) {.noconv.} diff --git a/tests/testament/categories.nim b/tests/testament/categories.nim index a93c79f5c..d620a4587 100644 --- a/tests/testament/categories.nim +++ b/tests/testament/categories.nim @@ -83,9 +83,9 @@ proc runBasicDLLTest(c, r: var TResults, cat: Category, options: string) = "" testSpec c, makeTest("lib/nimrtl.nim", - options & " --app:lib -d:createNimRtl", cat) + options & " --app:lib -d:createNimRtl --threads:on", cat) testSpec c, makeTest("tests/dll/server.nim", - options & " --app:lib -d:useNimRtl" & rpath, cat) + options & " --app:lib -d:useNimRtl --threads:on" & rpath, cat) when defined(Windows): @@ -101,7 +101,7 @@ proc runBasicDLLTest(c, r: var TResults, cat: Category, options: string) = var nimrtlDll = DynlibFormat % "nimrtl" safeCopyFile("lib" / nimrtlDll, "tests/dll" / nimrtlDll) - testSpec r, makeTest("tests/dll/client.nim", options & " -d:useNimRtl" & rpath, + testSpec r, makeTest("tests/dll/client.nim", options & " -d:useNimRtl --threads:on" & rpath, cat, actionRun) proc dllTests(r: var TResults, cat: Category, options: string) = -- cgit 1.4.1-2-gfad0 From 7eeef4aae7391f0e9e53c9009cf722545cee954c Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Mon, 16 Oct 2017 16:46:38 +0200 Subject: fixes #1137 --- compiler/ccgexprs.nim | 28 ++++++++++++++++------------ lib/system/sysio.nim | 12 ++++++++++++ 2 files changed, 28 insertions(+), 12 deletions(-) (limited to 'lib/system') diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 254248f9f..008599727 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -965,23 +965,27 @@ proc genEcho(p: BProc, n: PNode) = # this unusal way of implementing it ensures that e.g. ``echo("hallo", 45)`` # is threadsafe. internalAssert n.kind == nkBracket - var args: Rope = nil - var a: TLoc - for i in countup(0, n.len-1): - if n.sons[i].skipConv.kind == nkNilLit: - add(args, ", \"nil\"") - else: - initLocExpr(p, n.sons[i], a) - addf(args, ", $1? ($1)->data:\"nil\"", [rdLoc(a)]) if platform.targetOS == osGenode: # bypass libc and print directly to the Genode LOG session + var args: Rope = nil + var a: TLoc + for i in countup(0, n.len-1): + if n.sons[i].skipConv.kind == nkNilLit: + add(args, ", \"nil\"") + else: + initLocExpr(p, n.sons[i], a) + addf(args, ", $1? ($1)->data:\"nil\"", [rdLoc(a)]) p.module.includeHeader("") linefmt(p, cpsStmts, """Genode::log(""$1);$n""", args) else: - p.module.includeHeader("") - linefmt(p, cpsStmts, "printf($1$2);$n", - makeCString(repeat("%s", n.len) & tnl), args) - linefmt(p, cpsStmts, "fflush(stdout);$n") + var a: TLoc + initLocExpr(p, n, a) + linefmt(p, cpsStmts, "#echoBinSafe($1, $2);$n", a.rdLoc, n.len.rope) + when false: + p.module.includeHeader("") + linefmt(p, cpsStmts, "printf($1$2);$n", + makeCString(repeat("%s", n.len) & tnl), args) + linefmt(p, cpsStmts, "fflush(stdout);$n") proc gcUsage(n: PNode) = if gSelectedGC == gcNone: message(n.info, warnGcMem, n.renderTree) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 4f266e0ae..c0da983f1 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -404,4 +404,16 @@ proc setStdIoUnbuffered() = when declared(stdin): discard c_setvbuf(stdin, nil, IONBF, 0) +when declared(stdout): + proc echoBinSafe(args: openArray[string]) {.compilerProc.} = + proc flockfile(f: File) {.importc, noDecl.} + proc funlockfile(f: File) {.importc, noDecl.} + flockfile(stdout) + for s in args: + discard c_fwrite(s.cstring, s.len, 1, stdout) + const linefeed = "\n" # can be 1 or more chars + discard c_fwrite(linefeed.cstring, linefeed.len, 1, stdout) + discard c_fflush(stdout) + funlockfile(stdout) + {.pop.} -- cgit 1.4.1-2-gfad0 From 527e20fd3a0f2cc13afcfb0d402b77087c94c3ee Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Mon, 16 Oct 2017 19:52:22 +0200 Subject: fixes the Windows build --- lib/system/sysio.nim | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) (limited to 'lib/system') diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index c0da983f1..a40fcc67d 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -406,14 +406,16 @@ proc setStdIoUnbuffered() = when declared(stdout): proc echoBinSafe(args: openArray[string]) {.compilerProc.} = - proc flockfile(f: File) {.importc, noDecl.} - proc funlockfile(f: File) {.importc, noDecl.} - flockfile(stdout) + when not defined(windows): + proc flockfile(f: File) {.importc, noDecl.} + proc funlockfile(f: File) {.importc, noDecl.} + flockfile(stdout) for s in args: discard c_fwrite(s.cstring, s.len, 1, stdout) const linefeed = "\n" # can be 1 or more chars discard c_fwrite(linefeed.cstring, linefeed.len, 1, stdout) discard c_fflush(stdout) - funlockfile(stdout) + when not defined(windows): + funlockfile(stdout) {.pop.} -- cgit 1.4.1-2-gfad0 From 7ee825a6e5979a23cb0e0323f8d8069edc3285ba Mon Sep 17 00:00:00 2001 From: Araq Date: Tue, 17 Oct 2017 09:27:44 +0200 Subject: make the Windows build green again --- lib/system/sysstr.nim | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) (limited to 'lib/system') diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index 43b5a0292..50a8e6baa 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -338,9 +338,10 @@ proc add*(result: var string; x: float) = buf[n] = '.' buf[n+1] = '0' buf[n+2] = '\0' - # On Windows nice numbers like '1.#INF', '-1.#INF' or '1.#NAN' are produced. + # On Windows nice numbers like '1.#INF', '-1.#INF' or '1.#NAN' + # of '-1.#IND' are produced. # We want to get rid of these here: - if buf[n-1] in {'n', 'N'}: + if buf[n-1] in {'n', 'N', 'D', 'd'}: result.add "nan" elif buf[n-1] == 'F': if buf[0] == '-': -- cgit 1.4.1-2-gfad0 From dcfc2b0e5f94a3a6daf1e30dc337470702c662eb Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Sat, 28 Oct 2017 12:10:22 +0200 Subject: sysstr: code formatting --- lib/system/sysstr.nim | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) (limited to 'lib/system') diff --git a/lib/system/sysstr.nim b/lib/system/sysstr.nim index 50a8e6baa..5db16b233 100644 --- a/lib/system/sysstr.nim +++ b/lib/system/sysstr.nim @@ -363,9 +363,9 @@ proc c_strtod(buf: cstring, endptr: ptr cstring): float64 {. const IdentChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'} - powtens = [ 1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, - 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, - 1e20, 1e21, 1e22] + powtens = [1e0, 1e1, 1e2, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, + 1e10, 1e11, 1e12, 1e13, 1e14, 1e15, 1e16, 1e17, 1e18, 1e19, + 1e20, 1e21, 1e22] proc nimParseBiggestFloat(s: string, number: var BiggestFloat, start = 0): int {.compilerProc.} = -- cgit 1.4.1-2-gfad0 From 6a3288a60e78c9b17f2640fff20ab94969914974 Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Sun, 29 Oct 2017 08:55:30 +0100 Subject: more replacements for the deprecated '<' --- lib/core/macros.nim | 6 +++--- lib/deprecated/pure/actors.nim | 6 +++--- lib/pure/collections/critbits.nim | 2 +- lib/pure/collections/tableimpl.nim | 2 +- lib/pure/concurrency/threadpool.nim | 4 ++-- lib/pure/future.nim | 6 +++--- lib/pure/json.nim | 16 ++++++++-------- lib/pure/marshal.nim | 2 +- lib/pure/selectors.nim | 4 ++-- lib/pure/strutils.nim | 6 +++--- lib/pure/uri.nim | 2 +- lib/system/debugger.nim | 2 +- lib/system/gc.nim | 6 +++--- lib/system/gc2.nim | 6 +++--- lib/system/gc_ms.nim | 4 ++-- lib/system/repr.nim | 2 +- lib/system/reprjs.nim | 6 +++--- lib/system/sysstr.nim | 2 +- lib/wrappers/openssl.nim | 2 +- 19 files changed, 43 insertions(+), 43 deletions(-) (limited to 'lib/system') diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 22c479a4a..d3f541153 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -839,7 +839,7 @@ proc newNilLit*(): NimNode {.compileTime.} = ## New nil literal shortcut result = newNimNode(nnkNilLit) -proc last*(node: NimNode): NimNode {.compileTime.} = node[`*(p, b: untyped): untyped = if c[0].kind == nnkIdent and c[0].ident == !"->": var procTy = createProcType(c[1], c[2]) params[0] = procTy[0][0] - for i in 1 .. ) got (" & $c[0].ident & ").") @@ -96,7 +96,7 @@ macro `=>`*(p, b: untyped): untyped = if p[0].kind == nnkIdent and p[0].ident == !"->": var procTy = createProcType(p[1], p[2]) params[0] = procTy[0][0] - for i in 1 .. ) got (" & $p[0].ident & ").") diff --git a/lib/pure/json.nim b/lib/pure/json.nim index fd7a3af03..3d86cc9d7 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -823,13 +823,13 @@ proc toJson(x: NimNode): NimNode {.compiletime.} = of nnkBracket: # array if x.len == 0: return newCall(bindSym"newJArray") result = newNimNode(nnkBracket) - for i in 0 .. s.len: return -1 - + if sub.len == 1: return find(s, sub[0], start, last) - + var a {.noinit.}: SkipTable initSkipTable(a, sub) result = find(a, s, sub, start, last) diff --git a/lib/pure/uri.nim b/lib/pure/uri.nim index 4b2e4e052..c702b054c 100644 --- a/lib/pure/uri.nim +++ b/lib/pure/uri.nim @@ -250,7 +250,7 @@ proc combine*(base: Uri, reference: Uri): Uri = proc combine*(uris: varargs[Uri]): Uri = ## Combines multiple URIs together. result = uris[0] - for i in 1 .. 0 : add(result, ", ") # advance pointer and point to element at index @@ -192,7 +192,7 @@ proc reprRecordAux(result: var string, o: pointer, typ: PNimType, cl: var ReprCl reprAux(result, val, typ.node.typ, cl) else: # if the object has more than one field, sons is not nil and contains the fields. - for i in 0 .. Date: Sun, 29 Oct 2017 19:42:33 +0100 Subject: make some system modules compile again --- lib/system/debugger.nim | 2 +- lib/system/reprjs.nim | 36 ++++++++++++++++++------------------ 2 files changed, 19 insertions(+), 19 deletions(-) (limited to 'lib/system') diff --git a/lib/system/debugger.nim b/lib/system/debugger.nim index cbf977f19..d9075de16 100644 --- a/lib/system/debugger.nim +++ b/lib/system/debugger.nim @@ -127,7 +127,7 @@ proc fileMatches(c, bp: cstring): bool = proc canonFilename*(filename: cstring): cstring = ## returns 'nil' if the filename cannot be found. - for i in 0 ..< dbgFilenameLen: + for i in 0 .. dbgFilenameLen-1: result = dbgFilenames[i] if fileMatches(result, filename): return result result = nil diff --git a/lib/system/reprjs.nim b/lib/system/reprjs.nim index 12379042e..658220c11 100644 --- a/lib/system/reprjs.nim +++ b/lib/system/reprjs.nim @@ -9,13 +9,13 @@ # The generic ``repr`` procedure for the javascript backend. proc reprInt(x: int64): string {.compilerproc.} = return $x -proc reprFloat(x: float): string {.compilerproc.} = +proc reprFloat(x: float): string {.compilerproc.} = # Js toString doesn't differentiate between 1.0 and 1, # but we do. if $x == $(x.int): $x & ".0" else: $x -proc reprPointer(p: pointer): string {.compilerproc.} = +proc reprPointer(p: pointer): string {.compilerproc.} = # Do we need to generate the full 8bytes ? In js a pointer is an int anyway var tmp: int {. emit: """ @@ -38,7 +38,7 @@ proc reprEnum(e: int, typ: PNimType): string {.compilerRtl.} = result = $typ.node.sons[e].name else: result = $e & " (invalid data!)" - + proc reprChar(x: char): string {.compilerRtl.} = result = "\'" case x @@ -50,7 +50,7 @@ proc reprChar(x: char): string {.compilerRtl.} = proc reprStrAux(result: var string, s: cstring, len: int) = add(result, "\"") - for i in 0 ..< len: + for i in 0 .. len-1: let c = s[i] case c of '"': add(result, "\\\"") @@ -67,7 +67,7 @@ proc reprStr(s: string): string {.compilerRtl.} = if cast[pointer](s).isNil: # Handle nil strings here because they don't have a length field in js # TODO: check for null/undefined before generating call to length in js? - # Also: c backend repr of a nil string is "", but repr of an + # Also: c backend repr of a nil string is "", but repr of an # array of string that is not initialized is [nil, nil, ...] ?? add(result, "nil") else: @@ -86,7 +86,7 @@ proc addSetElem(result: var string, elem: int, typ: PNimType) = iterator setKeys(s: int): int {.inline.} = # The type of s is a lie, but it's expected to be a set. - # Iterate over the JS object representing a set + # Iterate over the JS object representing a set # and returns the keys as int. var len: int var yieldRes: int @@ -124,16 +124,16 @@ proc initReprClosure(cl: var ReprClosure) = cl.recDepth = -1 # default is to display everything! cl.indent = 0 -proc reprAux(result: var string, p: pointer, typ: PNimType, cl: var ReprClosure) +proc reprAux(result: var string, p: pointer, typ: PNimType, cl: var ReprClosure) -proc reprArray(a: pointer, typ: PNimType, +proc reprArray(a: pointer, typ: PNimType, cl: var ReprClosure): string {.compilerRtl.} = var isNilArrayOrSeq: bool # isnil is not enough here as it would try to deref `a` without knowing what's inside {. emit: """ - if (`a` == null) { + if (`a` == null) { `isNilArrayOrSeq` = true; - } else if (`a`[0] == null) { + } else if (`a`[0] == null) { `isNilArrayOrSeq` = true; } else { `isNilArrayOrSeq` = false; @@ -146,19 +146,19 @@ proc reprArray(a: pointer, typ: PNimType, result = if typ.kind == tySequence: "@[" else: "[" var len: int = 0 var i: int = 0 - + {. emit: "`len` = `a`.length;\n" .} var dereffed: pointer = a - for i in 0 ..< len: + for i in 0 .. len-1: if i > 0 : add(result, ", ") # advance pointer and point to element at index {. emit: """ - `dereffed`_Idx = `i`; + `dereffed`_Idx = `i`; `dereffed` = `a`[`dereffed`_Idx]; """ .} reprAux(result, dereffed, typ.base, cl) - + add(result, "]") proc isPointedToNil(p: pointer): bool {.inline.}= @@ -181,7 +181,7 @@ proc reprRef(result: var string, p: pointer, typ: PNimType, proc reprRecordAux(result: var string, o: pointer, typ: PNimType, cl: var ReprClosure) = add(result, "[") - + var first: bool = true var val: pointer = o if typ.node.len == 0: @@ -192,7 +192,7 @@ proc reprRecordAux(result: var string, o: pointer, typ: PNimType, cl: var ReprCl reprAux(result, val, typ.node.typ, cl) else: # if the object has more than one field, sons is not nil and contains the fields. - for i in 0 ..< typ.node.len: + for i in 0 .. typ.node.len-1: if first: first = false else: add(result, ",\n") @@ -214,11 +214,11 @@ proc reprJSONStringify(p: int): string {.compilerRtl.} = {. emit: "`tmp` = JSON.stringify(`p`);\n" .} result = $tmp -proc reprAux(result: var string, p: pointer, typ: PNimType, +proc reprAux(result: var string, p: pointer, typ: PNimType, cl: var ReprClosure) = if cl.recDepth == 0: add(result, "...") - return + return dec(cl.recDepth) case typ.kind of tyInt..tyInt64, tyUInt..tyUInt64: -- cgit 1.4.1-2-gfad0 From 08950649839c1df1504d495fccfea04bf11f55ed Mon Sep 17 00:00:00 2001 From: Andreas Rumpf Date: Mon, 30 Oct 2017 17:21:05 +0100 Subject: getEnv now supports a 'default' parameter; refs #6019 --- changelog.md | 2 ++ compiler/scriptconfig.nim | 2 +- compiler/vmops.nim | 7 ++++++- lib/pure/includes/osenv.nim | 4 ++-- lib/system/nimscript.nim | 2 +- 5 files changed, 12 insertions(+), 5 deletions(-) (limited to 'lib/system') diff --git a/changelog.md b/changelog.md index f8ad88842..7a3cbd5e7 100644 --- a/changelog.md +++ b/changelog.md @@ -37,3 +37,5 @@ This means its results are more precise and it can't run into an infinite loop anymore. - Added ``typetraits.$`` as an alias for ``typetraits.name``. +- ``os.getEnv`` now takes an optional ``default`` parameter that tells ``getEnv`` + what to return if the environment variable does not exist. diff --git a/compiler/scriptconfig.nim b/compiler/scriptconfig.nim index 0c31eadbe..22377a1e2 100644 --- a/compiler/scriptconfig.nim +++ b/compiler/scriptconfig.nim @@ -79,7 +79,7 @@ proc setupVM*(module: PSym; cache: IdentCache; scriptName: string; setResult(a, osproc.execCmd getString(a, 0)) cbconf getEnv: - setResult(a, os.getEnv(a.getString 0)) + setResult(a, os.getEnv(a.getString 0, a.getString 1)) cbconf existsEnv: setResult(a, os.existsEnv(a.getString 0)) cbconf dirExists: diff --git a/compiler/vmops.nim b/compiler/vmops.nim index 38135951d..2a00f207a 100644 --- a/compiler/vmops.nim +++ b/compiler/vmops.nim @@ -47,6 +47,11 @@ template wrap1s_ospaths(op) {.dirty.} = setResult(a, op(getString(a, 0))) ospathsop op +template wrap2s_ospaths(op) {.dirty.} = + proc `op Wrapper`(a: VmArgs) {.nimcall.} = + setResult(a, op(getString(a, 0), getString(a, 1))) + ospathsop op + template wrap1s_system(op) {.dirty.} = proc `op Wrapper`(a: VmArgs) {.nimcall.} = setResult(a, op(getString(a, 0))) @@ -96,7 +101,7 @@ proc registerAdditionalOps*(c: PCtx) = wrap1f_math(ceil) wrap2f_math(fmod) - wrap1s_ospaths(getEnv) + wrap2s_ospaths(getEnv) wrap1s_ospaths(existsEnv) wrap1s_os(dirExists) wrap1s_os(fileExists) diff --git a/lib/pure/includes/osenv.nim b/lib/pure/includes/osenv.nim index 8d2fc235a..ae62a5c4e 100644 --- a/lib/pure/includes/osenv.nim +++ b/lib/pure/includes/osenv.nim @@ -94,7 +94,7 @@ proc findEnvVar(key: string): int = if startsWith(environment[i], temp): return i return -1 -proc getEnv*(key: string): TaintedString {.tags: [ReadEnvEffect].} = +proc getEnv*(key: string, default = ""): TaintedString {.tags: [ReadEnvEffect].} = ## Returns the value of the `environment variable`:idx: named `key`. ## ## If the variable does not exist, "" is returned. To distinguish @@ -108,7 +108,7 @@ proc getEnv*(key: string): TaintedString {.tags: [ReadEnvEffect].} = return TaintedString(substr(environment[i], find(environment[i], '=')+1)) else: var env = c_getenv(key) - if env == nil: return TaintedString("") + if env == nil: return TaintedString(default) result = TaintedString($env) proc existsEnv*(key: string): bool {.tags: [ReadEnvEffect].} = diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index f5b9cf3ed..f91dae41e 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -106,7 +106,7 @@ proc cmpic*(a, b: string): int = ## Compares `a` and `b` ignoring case. cmpIgnoreCase(a, b) -proc getEnv*(key: string): string {.tags: [ReadIOEffect].} = +proc getEnv*(key: string; default = ""): string {.tags: [ReadIOEffect].} = ## Retrieves the environment variable of name `key`. builtin -- cgit 1.4.1-2-gfad0 From 7c03c882f55d7c03ce94943d0d8f622c6904a334 Mon Sep 17 00:00:00 2001 From: Fabian Keller Date: Tue, 31 Oct 2017 19:48:01 +0100 Subject: Remove more usages of unary lt (fixes #6634) (#6641) * fixes #6634 * remove more usages of unary < --- compiler/semdata.nim | 2 +- lib/pure/securehash.nim | 2 +- lib/system/debugger.nim | 4 ++-- lib/system/repr.nim | 2 +- lib/system/sysspawn.nim | 2 +- nimsuggest/sexp.nim | 2 +- 6 files changed, 7 insertions(+), 7 deletions(-) (limited to 'lib/system') diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 3e57d1104..5057260a4 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -339,7 +339,7 @@ proc makeNotType*(c: PContext, t1: PType): PType = proc nMinusOne*(n: PNode): PNode = result = newNode(nkCall, n.info, @[ - newSymNode(getSysMagic("<", mUnaryLt)), + newSymNode(getSysMagic("pred", mPred)), n]) # Remember to fix the procs below this one when you make changes! diff --git a/lib/pure/securehash.nim b/lib/pure/securehash.nim index c19146669..57c1f3631 100644 --- a/lib/pure/securehash.nim +++ b/lib/pure/securehash.nim @@ -181,7 +181,7 @@ proc `$`*(self: SecureHash): string = result.add(toHex(int(v), 2)) proc parseSecureHash*(hash: string): SecureHash = - for i in 0..