From 0f14ce0f3b293f0f9e9a0f916377e06e21773053 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Sun, 31 Jul 2022 12:42:51 -0700 Subject: [PATCH 01/16] internals: leaf nodes do not have sons - pulls nkEmpty and nkNone into a branch without sons - various small fixes to get bootstrap working - no tests failed, so that's a good{?} sign --- compiler/ast/ast.nim | 7 +++++-- compiler/ast/ast_types.nim | 21 +++++++++++++++------ compiler/ast/trees.nim | 3 +-- compiler/sem/evaltempl.nim | 2 +- compiler/sem/pragmas.nim | 3 +-- compiler/sem/sem.nim | 7 ++++--- compiler/sem/semexprs.nim | 5 +++-- compiler/sem/semtempl.nim | 10 +++++++--- compiler/sem/sigmatch.nim | 2 +- compiler/vm/vm.nim | 2 +- 10 files changed, 39 insertions(+), 23 deletions(-) diff --git a/compiler/ast/ast.nim b/compiler/ast/ast.nim index ebe61c51d3e..f0ea3c31018 100644 --- a/compiler/ast/ast.nim +++ b/compiler/ast/ast.nim @@ -430,8 +430,10 @@ proc addSonNilAllowed*(father, son: PNode) = father.sons.add(son) proc delSon*(father: PNode, idx: int) = - if father.len == 0: return - for i in idx.. Date: Sun, 31 Jul 2022 13:52:08 -0700 Subject: [PATCH 02/16] stdlib: remove deprecated modules deprecated stdlib module removal: - removed events, LockFreeHash, parseopt2, and securehash - associated clean-up in testament - lib/deprecate/pure now only contains ospaths, an include for os - remove events related tests --- lib/deprecated/pure/LockFreeHash.nim | 611 -------------------------- lib/deprecated/pure/events.nim | 104 ----- lib/deprecated/pure/parseopt2.nim | 155 ------- lib/deprecated/pure/securehash.nim | 5 - testament/categories.nim | 4 +- testament/testament.nim | 1 - tests/misc/tevents.nim | 48 -- tests/types/tillegaltyperecursion.nim | 66 --- 8 files changed, 2 insertions(+), 992 deletions(-) delete mode 100644 lib/deprecated/pure/LockFreeHash.nim delete mode 100644 lib/deprecated/pure/events.nim delete mode 100644 lib/deprecated/pure/parseopt2.nim delete mode 100644 lib/deprecated/pure/securehash.nim delete mode 100644 tests/misc/tevents.nim delete mode 100644 tests/types/tillegaltyperecursion.nim diff --git a/lib/deprecated/pure/LockFreeHash.nim b/lib/deprecated/pure/LockFreeHash.nim deleted file mode 100644 index 69e12226fe0..00000000000 --- a/lib/deprecated/pure/LockFreeHash.nim +++ /dev/null @@ -1,611 +0,0 @@ -#nim c -t:-march=i686 --cpu:amd64 --threads:on -d:release lockfreehash.nim - -#------------------------------------------------------------------------------ -## Memory Utility Functions - -{.deprecated.} - -import math, hashes - -proc newHeap*[T](): ptr T = - result = cast[ptr T](alloc0(sizeof(T))) - -proc copyNew*[T](x: var T): ptr T = - var - size = sizeof(T) - mem = alloc(size) - copyMem(mem, x.addr, size) - return cast[ptr T](mem) - -proc copyTo*[T](val: var T, dest: int) = - copyMem(pointer(dest), val.addr, sizeof(T)) - -proc allocType*[T](): pointer = alloc(sizeof(T)) - -proc newShared*[T](): ptr T = - result = cast[ptr T](allocShared0(sizeof(T))) - -proc copyShared*[T](x: var T): ptr T = - var - size = sizeof(T) - mem = allocShared(size) - copyMem(mem, x.addr, size) - return cast[ptr T](mem) - -#------------------------------------------------------------------------------ -## Pointer arithmetic - -proc `+`*(p: pointer, i: int): pointer {.inline.} = - cast[pointer](cast[int](p) + i) - -const - minTableSize = 8 - reProbeLimit = 12 - minCopyWork = 4096 - intSize = sizeof(int) - - - -when sizeof(int) == 4: # 32bit - type - Raw = range[0..1073741823] - ## The range of uint values that can be stored directly in a value slot - ## when on a 32 bit platform -elif sizeof(int) == 8: # 64bit - type - Raw = range[0'i64..4611686018427387903'i64] - ## The range of uint values that can be stored directly in a value slot - ## when on a 64 bit platform -else: - {.error: "unsupported platform".} - -type - Entry = tuple - key: int - value: int - - EntryArr = ptr array[0..10_000_000, Entry] - - PConcTable[K, V] = ptr object {.pure.} - len: int - used: int - active: int - copyIdx: int - copyDone: int - next: PConcTable[K, V] - data: EntryArr - -proc setVal[K, V](table: var PConcTable[K, V], key: int, val: int, - expVal: int, match: bool): int - -#------------------------------------------------------------------------------ - -# Create a new table -proc newLFTable*[K, V](size: int = minTableSize): PConcTable[K, V] = - let - dataLen = max(nextPowerOfTwo(size), minTableSize) - dataSize = dataLen*sizeof(Entry) - dataMem = allocShared0(dataSize) - tableSize = 7 * intSize - tableMem = allocShared0(tableSize) - table = cast[PConcTable[K, V]](tableMem) - table.len = dataLen - table.used = 0 - table.active = 0 - table.copyIdx = 0 - table.copyDone = 0 - table.next = nil - table.data = cast[EntryArr](dataMem) - result = table - -#------------------------------------------------------------------------------ - -# Delete a table -proc deleteConcTable[K, V](tbl: PConcTable[K, V]) = - deallocShared(tbl.data) - deallocShared(tbl) - -#------------------------------------------------------------------------------ - -proc `[]`[K, V](table: var PConcTable[K, V], i: int): var Entry {.inline.} = - table.data[i] - -#------------------------------------------------------------------------------ -# State flags stored in ptr - - -proc pack[T](x: T): int {.inline.} = - result = (cast[int](x) shl 2) - #echo("packKey ",cast[int](x) , " -> ", result) - -# Pop the flags off returning a 4 byte aligned ptr to our Key or Val -proc pop(x: int): int {.inline.} = - result = x and 0xFFFFFFFC'i32 - -# Pop the raw value off of our Key or Val -proc popRaw(x: int): int {.inline.} = - result = x shr 2 - -# Pop the flags off returning a 4 byte aligned ptr to our Key or Val -proc popPtr[V](x: int): ptr V {.inline.} = - result = cast[ptr V](pop(x)) - #echo("popPtr " & $x & " -> " & $cast[int](result)) - -# Ghost (sentinel) -# K or V is no longer valid use new table -const Ghost = 0xFFFFFFFC -proc isGhost(x: int): bool {.inline.} = - result = x == 0xFFFFFFFC - -# Tombstone -# applied to V = K is dead -proc isTomb(x: int): bool {.inline.} = - result = (x and 0x00000002) != 0 - -proc setTomb(x: int): int {.inline.} = - result = x or 0x00000002 - -# Prime -# K or V is in new table copied from old -proc isPrime(x: int): bool {.inline.} = - result = (x and 0x00000001) != 0 - -proc setPrime(x: int): int {.inline.} = - result = x or 0x00000001 - -#------------------------------------------------------------------------------ - -##This is for i32 only need to override for i64 -proc hashInt(x: int): int {.inline.} = - var h = uint32(x) #shr 2'u32 - h = h xor (h shr 16'u32) - h *= 0x85ebca6b'u32 - h = h xor (h shr 13'u32) - h *= 0xc2b2ae35'u32 - h = h xor (h shr 16'u32) - result = int(h) - -#------------------------------------------------------------------------------ - -proc resize[K, V](self: PConcTable[K, V]): PConcTable[K, V] = - var next = atomic_load_n(self.next.addr, ATOMIC_RELAXED) - #echo("next = " & $cast[int](next)) - if next != nil: - #echo("A new table already exists, copy in progress") - return next - var - oldLen = atomic_load_n(self.len.addr, ATOMIC_RELAXED) - newTable = newLFTable[K, V](oldLen*2) - success = atomic_compare_exchange_n(self.next.addr, next.addr, newTable, - false, ATOMIC_RELAXED, ATOMIC_RELAXED) - if not success: - echo("someone beat us to it! delete table we just created and return his " & - $cast[int](next)) - deleteConcTable(newTable) - return next - else: - echo("Created New Table! " & $cast[int](newTable) & " Size = " & $newTable.len) - return newTable - - -#------------------------------------------------------------------------------ -#proc keyEQ[K](key1: ptr K, key2: ptr K): bool {.inline.} = -proc keyEQ[K](key1: int, key2: int): bool {.inline.} = - result = false - when K is Raw: - if key1 == key2: - result = true - else: - var - p1 = popPtr[K](key1) - p2 = popPtr[K](key2) - if p1 != nil and p2 != nil: - if cast[int](p1) == cast[int](p2): - return true - if p1[] == p2[]: - return true - -#------------------------------------------------------------------------------ - -#proc tableFull(self: var PConcTable[K,V]) : bool {.inline.} = - - -#------------------------------------------------------------------------------ - -proc copySlot[K, V](idx: int, oldTbl: var PConcTable[K, V], - newTbl: var PConcTable[K, V]): bool = - #echo("Copy idx " & $idx) - var - oldVal = 0 - oldkey = 0 - ok = false - result = false - #Block the key so no other threads waste time here - while not ok: - ok = atomic_compare_exchange_n(oldTbl[idx].key.addr, oldKey.addr, - setTomb(oldKey), false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("oldKey was = " & $oldKey & " set it to tomb " & $setTomb(oldKey)) - #Prevent new values from appearing in the old table by priming - oldVal = atomic_load_n(oldTbl[idx].value.addr, ATOMIC_RELAXED) - while not isPrime(oldVal): - var box = if oldVal == 0 or isTomb(oldVal): oldVal.setTomb.setPrime - else: oldVal.setPrime - if atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, - box, false, ATOMIC_RELAXED, ATOMIC_RELAXED): - if isPrime(box) and isTomb(box): - return true - oldVal = box - break - #echo("oldVal was = ", oldVal, " set it to prime ", box) - if isPrime(oldVal) and isTomb(oldVal): - #when not (K is Raw): - # deallocShared(popPtr[K](oldKey)) - return false - if isTomb(oldVal): - echo("oldVal is Tomb!!!, should not happen") - if pop(oldVal) != 0: - result = setVal(newTbl, pop(oldKey), pop(oldVal), 0, true) == 0 - #if result: - #echo("Copied a Slot! idx= " & $idx & " key= " & $oldKey & " val= " & $oldVal) - #else: - #echo("copy slot failed") - # Our copy is done so we disable the old slot - while not ok: - ok = atomic_compare_exchange_n(oldTbl[idx].value.addr, oldVal.addr, - oldVal.setTomb.setPrime, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("disabled old slot") - #echo"---------------------" - -#------------------------------------------------------------------------------ - -proc promote[K, V](table: var PConcTable[K, V]) = - var - newData = atomic_load_n(table.next.data.addr, ATOMIC_RELAXED) - newLen = atomic_load_n(table.next.len.addr, ATOMIC_RELAXED) - newUsed = atomic_load_n(table.next.used.addr, ATOMIC_RELAXED) - - deallocShared(table.data) - atomic_store_n(table.data.addr, newData, ATOMIC_RELAXED) - atomic_store_n(table.len.addr, newLen, ATOMIC_RELAXED) - atomic_store_n(table.used.addr, newUsed, ATOMIC_RELAXED) - atomic_store_n(table.copyIdx.addr, 0, ATOMIC_RELAXED) - atomic_store_n(table.copyDone.addr, 0, ATOMIC_RELAXED) - deallocShared(table.next) - atomic_store_n(table.next.addr, nil, ATOMIC_RELAXED) - echo("new table swapped!") - -#------------------------------------------------------------------------------ - -proc checkAndPromote[K, V](table: var PConcTable[K, V], workDone: int): bool = - var - oldLen = atomic_load_n(table.len.addr, ATOMIC_RELAXED) - copyDone = atomic_load_n(table.copyDone.addr, ATOMIC_RELAXED) - ok: bool - result = false - if workDone > 0: - #echo("len to copy =" & $oldLen) - #echo("copyDone + workDone = " & $copyDone & " + " & $workDone) - while not ok: - ok = atomic_compare_exchange_n(table.copyDone.addr, copyDone.addr, - copyDone + workDone, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #if ok: echo("set copyDone") - # If the copy is done we can promote this table - if copyDone + workDone >= oldLen: - # Swap new data - #echo("work is done!") - table.promote - result = true - -#------------------------------------------------------------------------------ - -proc copySlotAndCheck[K, V](table: var PConcTable[K, V], idx: int): - PConcTable[K, V] = - var - newTable = cast[PConcTable[K, V]](atomic_load_n(table.next.addr, - ATOMIC_RELAXED)) - result = newTable - if newTable != nil and copySlot(idx, table, newTable): - #echo("copied a single slot, idx = " & $idx) - if checkAndPromote(table, 1): return table - - -#------------------------------------------------------------------------------ - -proc helpCopy[K, V](table: var PConcTable[K, V]): PConcTable[K, V] = - var - newTable = cast[PConcTable[K, V]](atomic_load_n(table.next.addr, - ATOMIC_RELAXED)) - result = newTable - if newTable != nil: - var - oldLen = atomic_load_n(table.len.addr, ATOMIC_RELAXED) - copyDone = atomic_load_n(table.copyDone.addr, ATOMIC_RELAXED) - copyIdx = 0 - work = min(oldLen, minCopyWork) - #panicStart = -1 - workDone = 0 - if copyDone < oldLen: - var ok: bool - while not ok: - ok = atomic_compare_exchange_n(table.copyIdx.addr, copyIdx.addr, - copyIdx + work, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - #echo("copy idx = ", copyIdx) - for i in 0..work-1: - var idx = (copyIdx + i) and (oldLen - 1) - if copySlot(idx, table, newTable): - workDone += 1 - if workDone > 0: - #echo("did work ", workDone, " on thread ", cast[int](myThreadID[pointer]())) - if checkAndPromote(table, workDone): return table - # In case a thread finished all the work then got stalled before promotion - if checkAndPromote(table, 0): return table - - - -#------------------------------------------------------------------------------ - -proc setVal[K, V](table: var PConcTable[K, V], key: int, val: int, - expVal: int, match: bool): int = - #echo("-try set- in table ", " key = ", (popPtr[K](key)[]), " val = ", val) - when K is Raw: - var idx = hashInt(key) - else: - var idx = popPtr[K](key)[].hash - var - nextTable: PConcTable[K, V] - probes = 1 - # spin until we find a key slot or build and jump to next table - while true: - idx = idx and (table.len - 1) - #echo("try set idx = " & $idx & "for" & $key) - var - probedKey = 0 - openKey = atomic_compare_exchange_n(table[idx].key.addr, probedKey.addr, - key, false, ATOMIC_RELAXED, ATOMIC_RELAXED) - if openKey: - if val.isTomb: - #echo("val was tomb, bail, no reason to set an open slot to tomb") - return val - #increment used slots - #echo("found an open slot, total used = " & - #$atomic_add_fetch(table.used.addr, 1, ATOMIC_RELAXED)) - discard atomic_add_fetch(table.used.addr, 1, ATOMIC_RELAXED) - break # We found an open slot - #echo("set idx ", idx, " key = ", key, " probed = ", probedKey) - if keyEQ[K](probedKey, key): - #echo("we found the matching slot") - break # We found a matching slot - if (not(expVal != 0 and match)) and (probes >= reProbeLimit or key.isTomb): - if key.isTomb: echo("Key is Tombstone") - #if probes >= reProbeLimit: echo("Too much probing " & $probes) - #echo("try to resize") - #create next bigger table - nextTable = resize(table) - #help do some copying - #echo("help copy old table to new") - nextTable = helpCopy(table) - #now setVal in the new table instead - #echo("jumping to next table to set val") - return setVal(nextTable, key, val, expVal, match) - else: - idx += 1 - probes += 1 - # Done spinning for a new slot - var oldVal = atomic_load_n(table[idx].value.addr, ATOMIC_RELAXED) - if val == oldVal: - #echo("this val is already in the slot") - return oldVal - nextTable = atomic_load_n(table.next.addr, ATOMIC_SEQ_CST) - if nextTable == nil and - ((oldVal == 0 and - (probes >= reProbeLimit or table.used / table.len > 0.8)) or - (isPrime(oldVal))): - if table.used / table.len > 0.8: echo("resize because usage ratio = " & - $(table.used / table.len)) - if isPrime(oldVal): echo("old val isPrime, should be a rare mem ordering event") - nextTable = resize(table) - if nextTable != nil: - #echo("tomb old slot then set in new table") - nextTable = copySlotAndCheck(table, idx) - return setVal(nextTable, key, val, expVal, match) - # Finally ready to add new val to table - while true: - if match and oldVal != expVal: - #echo("set failed, no match oldVal= " & $oldVal & " expVal= " & $expVal) - return oldVal - if atomic_compare_exchange_n(table[idx].value.addr, oldVal.addr, - val, false, ATOMIC_RELEASE, ATOMIC_RELAXED): - #echo("val set at table " & $cast[int](table)) - if expVal != 0: - if (oldVal == 0 or isTomb(oldVal)) and not isTomb(val): - discard atomic_add_fetch(table.active.addr, 1, ATOMIC_RELAXED) - elif not (oldVal == 0 or isTomb(oldVal)) and isTomb(val): - discard atomic_add_fetch(table.active.addr, -1, ATOMIC_RELAXED) - if oldVal == 0 and expVal != 0: - return setTomb(oldVal) - else: return oldVal - if isPrime(oldVal): - nextTable = copySlotAndCheck(table, idx) - return setVal(nextTable, key, val, expVal, match) - -#------------------------------------------------------------------------------ - -proc getVal[K, V](table: var PConcTable[K, V], key: int): int = - #echo("-try get- key = " & $key) - when K is Raw: - var idx = hashInt(key) - else: - var idx = popPtr[K](key)[].hash - #echo("get idx ", idx) - var - probes = 0 - val: int - while true: - idx = idx and (table.len - 1) - var - newTable: PConcTable[K, V] # = atomic_load_n(table.next.addr, ATOMIC_ACQUIRE) - probedKey = atomic_load_n(table[idx].key.addr, ATOMIC_SEQ_CST) - if keyEQ[K](probedKey, key): - #echo("found key after ", probes+1) - val = atomic_load_n(table[idx].value.addr, ATOMIC_ACQUIRE) - if not isPrime(val): - if isTomb(val): - #echo("val was tomb but not prime") - return 0 - else: - #echo("-GotIt- idx = ", idx, " key = ", key, " val ", val ) - return val - else: - newTable = copySlotAndCheck(table, idx) - return getVal(newTable, key) - else: - #echo("probe ", probes, " idx = ", idx, " key = ", key, " found ", probedKey ) - if probes >= reProbeLimit*4 or key.isTomb: - if newTable == nil: - #echo("too many probes and no new table ", key, " ", idx ) - return 0 - else: - newTable = helpCopy(table) - return getVal(newTable, key) - idx += 1 - probes += 1 - -#------------------------------------------------------------------------------ - -#proc set*(table: var PConcTable[Raw,Raw], key: Raw, val: Raw) = -# discard setVal(table, pack(key), pack(key), 0, false) - -#proc set*[V](table: var PConcTable[Raw,V], key: Raw, val: ptr V) = -# discard setVal(table, pack(key), cast[int](val), 0, false) - -proc set*[K, V](table: var PConcTable[K, V], key: var K, val: var V) = - when not (K is Raw): - var newKey = cast[int](copyShared(key)) - else: - var newKey = pack(key) - when not (V is Raw): - var newVal = cast[int](copyShared(val)) - else: - var newVal = pack(val) - var oldPtr = pop(setVal(table, newKey, newVal, 0, false)) - #echo("oldPtr = ", cast[int](oldPtr), " newPtr = ", cast[int](newPtr)) - when not (V is Raw): - if newVal != oldPtr and oldPtr != 0: - deallocShared(cast[ptr V](oldPtr)) - - - -proc get*[K, V](table: var PConcTable[K, V], key: var K): V = - when not (V is Raw): - when not (K is Raw): - return popPtr[V](getVal(table, cast[int](key.addr)))[] - else: - return popPtr[V](getVal(table, pack(key)))[] - else: - when not (K is Raw): - return popRaw(getVal(table, cast[int](key.addr))) - else: - return popRaw(getVal(table, pack(key))) - - - - - - - - - - - -#proc `[]`[K,V](table: var PConcTable[K,V], key: K): PEntry[K,V] {.inline.} = -# getVal(table, key) - -#proc `[]=`[K,V](table: var PConcTable[K,V], key: K, val: V): PEntry[K,V] {.inline.} = -# setVal(table, key, val) - - - - - - -#Tests ---------------------------- -when not defined(testing) and isMainModule: - import locks, times, mersenne - - const - numTests = 100000 - numThreads = 10 - - - - type - TestObj = tuple - thr: int - f0: int - f1: int - - Data = tuple[k: string, v: TestObj] - PDataArr = array[0..numTests-1, Data] - Dict = PConcTable[string, TestObj] - - var - thr: array[0..numThreads-1, Thread[Dict]] - - table = newLFTable[string, TestObj](8) - rand = newMersenneTwister(2525) - - proc createSampleData(len: int): PDataArr = - #result = cast[PDataArr](allocShared0(sizeof(Data)*numTests)) - for i in 0..len-1: - result[i].k = "mark" & $(i+1) - #echo("mark" & $(i+1), " ", hash("mark" & $(i+1))) - result[i].v.thr = 0 - result[i].v.f0 = i+1 - result[i].v.f1 = 0 - #echo("key = " & $(i+1) & " Val ptr = " & $cast[int](result[i].v.addr)) - - - - proc threadProc(tp: Dict) {.thread.} = - var t = cpuTime(); - for i in 1..numTests: - var key = "mark" & $(i) - var got = table.get(key) - got.thr = cast[int](myThreadID[pointer]()) - got.f1 = got.f1 + 1 - table.set(key, got) - t = cpuTime() - t - echo t - - - var testData = createSampleData(numTests) - - for i in 0..numTests-1: - table.set(testData[i].k, testData[i].v) - - var i = 0 - while i < numThreads: - createThread(thr[i], threadProc, table) - i += 1 - - joinThreads(thr) - - - - - - var fails = 0 - - for i in 0..numTests-1: - var got = table.get(testData[i].k) - if got.f0 != i+1 or got.f1 != numThreads: - fails += 1 - echo(got) - - echo("Failed read or write = ", fails) - - - #for i in 1..numTests: - # echo(i, " = ", hashInt(i) and 8191) - - deleteConcTable(table) diff --git a/lib/deprecated/pure/events.nim b/lib/deprecated/pure/events.nim deleted file mode 100644 index 85fc349c244..00000000000 --- a/lib/deprecated/pure/events.nim +++ /dev/null @@ -1,104 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2011 Alexander Mitchell-Robinson -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## :Author: Alexander Mitchell-Robinson -## -## Unstable API. -## -## This module implements an event system that is not dependent on external -## graphical toolkits. It was originally called `NimEE` because -## it was inspired by Python's PyEE module. There are two ways you can use -## events: one is a python-inspired way; the other is more of a C-style way. -## -## .. code-block:: Nim -## var ee = initEventEmitter() -## var genericargs: EventArgs -## proc handleevent(e: EventArgs) = -## echo("Handled!") -## -## # Python way -## ee.on("EventName", handleevent) -## ee.emit("EventName", genericargs) -## -## # C/Java way -## # Declare a type -## type -## SomeObject = object of RootObj -## SomeEvent: EventHandler -## var myobj: SomeObject -## myobj.SomeEvent = initEventHandler("SomeEvent") -## myobj.SomeEvent.addHandler(handleevent) -## ee.emit(myobj.SomeEvent, genericargs) - -{.deprecated.} - -type - EventArgs* = object of RootObj ## Base object for event arguments that are passed to callback functions. - EventHandler* = tuple[name: string, handlers: seq[proc(e: EventArgs) {.closure.}]] ## An eventhandler for an event. - -type - EventEmitter* = object ## An object that fires events and holds event handlers for an object. - s: seq[EventHandler] - EventError* = object of ValueError - -proc initEventHandler*(name: string): EventHandler = - ## Initializes an EventHandler with the specified name and returns it. - result.handlers = @[] - result.name = name - -proc addHandler*(handler: var EventHandler, fn: proc(e: EventArgs) {.closure.}) = - ## Adds the callback to the specified event handler. - handler.handlers.add(fn) - -proc removeHandler*(handler: var EventHandler, fn: proc(e: EventArgs) {.closure.}) = - ## Removes the callback from the specified event handler. - for i in countup(0, len(handler.handlers)-1): - if fn == handler.handlers[i]: - handler.handlers.del(i) - break - -proc containsHandler*(handler: var EventHandler, fn: proc(e: EventArgs) {.closure.}): bool = - ## Checks if a callback is registered to this event handler. - return handler.handlers.contains(fn) - - -proc clearHandlers*(handler: var EventHandler) = - ## Clears all of the callbacks from the event handler. - setLen(handler.handlers, 0) - -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 EventEmitter, event: string, fn: 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) - if i < 0: - var eh = initEventHandler(event) - addHandler(eh, fn) - emitter.s.add(eh) - else: - addHandler(emitter.s[i], fn) - -proc emit*(emitter: var EventEmitter, eventhandler: var EventHandler, - args: EventArgs) = - ## Fires an event handler with specified event arguments. - for fn in items(eventhandler.handlers): fn(args) - -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*(): EventEmitter = - ## Creates and returns a new EventEmitter. - result.s = @[] diff --git a/lib/deprecated/pure/parseopt2.nim b/lib/deprecated/pure/parseopt2.nim deleted file mode 100644 index a6d5de06df2..00000000000 --- a/lib/deprecated/pure/parseopt2.nim +++ /dev/null @@ -1,155 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2015 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module provides the standard Nim command line parser. -## It supports one convenience iterator over all command line options and some -## lower-level features. -## -## Supported syntax: -## -## 1. short options - `-abcd`, where a, b, c, d are names -## 2. long option - `--foo:bar`, `--foo=bar` or `--foo` -## 3. argument - everything else - -{.deprecated: "Use the 'parseopt' module instead".} -{.push debugger: off.} - -include "system/inclrtl" - -import - os, strutils - -type - 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 - OptParser* = - object of RootObj ## this object implements the command line parser - cmd: seq[string] - pos: int - remainingShortOptions: string - kind*: CmdLineKind ## the detected command line token - key*, val*: string ## 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]): OptParser {.rtl.} = - ## Initializes option parses with cmdline. cmdline should not contain - ## argument 0 - program name. - ## If cmdline.len == 0 default to current command line arguments. - result.remainingShortOptions = "" - when not defined(createNimRtl): - if cmdline.len == 0: - result.cmd = commandLineParams() - return - else: - assert cmdline != nil, "Cannot determine command line arguments." - - result.cmd = @cmdline - -when not defined(createNimRtl): - proc initOptParser*(): OptParser = - ## Initializes option parser from current command line arguments. - return initOptParser(commandLineParams()) - -proc next*(p: var OptParser) {.rtl, extern: "npo2$1".} - -proc nextOption(p: var OptParser, token: string, allowEmpty: bool) = - for splitchar in [':', '=']: - if splitchar in token: - let pos = token.find(splitchar) - p.key = token[0..pos-1] - p.val = token[pos+1..token.len-1] - return - - p.key = token - if allowEmpty: - p.val = "" - else: - p.remainingShortOptions = token[0..token.len-1] - p.next() - -proc next(p: var OptParser) = - if p.remainingShortOptions.len != 0: - p.kind = cmdShortOption - p.key = p.remainingShortOptions[0..0] - p.val = "" - p.remainingShortOptions = p.remainingShortOptions[1..p.remainingShortOptions.len-1] - return - - if p.pos >= p.cmd.len: - p.kind = cmdEnd - return - - let token = p.cmd[p.pos] - p.pos += 1 - - if token.startsWith("--"): - p.kind = cmdLongOption - nextOption(p, token[2..token.len-1], allowEmpty=true) - elif token.startsWith("-"): - p.kind = cmdShortOption - nextOption(p, token[1..token.len-1], allowEmpty=true) - else: - p.kind = cmdArgument - p.key = token - p.val = "" - -proc cmdLineRest*(p: OptParser): string {.rtl, extern: "npo2$1".} = - ## Returns the part of command line string that has not been parsed yet, - ## properly quoted. - return p.cmd[p.pos..p.cmd.len-1].quoteShellCommand - -type - GetoptResult* = tuple[kind: CmdLineKind, key, val: string] - -iterator getopt*(p: var OptParser): GetoptResult = - ## This is an convenience iterator for iterating over the given OptParser object. - ## Example: - ## - ## .. code-block:: nim - ## var p = initOptParser("--left --debug:3 -l=4 -r:2") - ## for kind, key, val in p.getopt(): - ## case kind - ## of cmdArgument: - ## filename = key - ## of cmdLongOption, cmdShortOption: - ## case key - ## of "help", "h": writeHelp() - ## of "version", "v": writeVersion() - ## of cmdEnd: assert(false) # cannot happen - ## if filename == "": - ## # no filename has been given, so we show the help: - ## writeHelp() - p.pos = 0 - while true: - next(p) - if p.kind == cmdEnd: break - yield (p.kind, p.key, p.val) - -when declared(paramCount): - iterator getopt*(): GetoptResult = - ## This is an convenience iterator for iterating over the command line arguments. - ## This create a new OptParser object. - ## See above for a more detailed example - ## - ## .. code-block:: nim - ## for kind, key, val in getopt(): - ## # this will iterate over all arguments passed to the cmdline. - ## continue - ## - var p = initOptParser() - while true: - next(p) - if p.kind == cmdEnd: break - yield (p.kind, p.key, p.val) - -{.pop.} diff --git a/lib/deprecated/pure/securehash.nim b/lib/deprecated/pure/securehash.nim deleted file mode 100644 index ea7930f8112..00000000000 --- a/lib/deprecated/pure/securehash.nim +++ /dev/null @@ -1,5 +0,0 @@ -## This module is a deprecated alias for the `sha1` module. - -{.deprecated: "use `std/sha1` instead".} - -include "../std/sha1" diff --git a/testament/categories.nim b/testament/categories.nim index d3214af4f41..4028cd52bf0 100644 --- a/testament/categories.nim +++ b/testament/categories.nim @@ -254,8 +254,8 @@ proc testStdlib(r: var TResults, pattern, options: string, cat: Category) = let name = extractFilename(file) if name.splitFile.ext != ".nim": return false for namei in disabledFiles: - # because of `LockFreeHash.nim` which has case - if namei.cmpPaths(name) == 0: return false + if namei.cmpPaths(name) == 0: + return false return true for testFile in os.walkDirRec(pattern): diff --git a/testament/testament.nim b/testament/testament.nim index f3a7d463ef8..3c3883d81bf 100644 --- a/testament/testament.nim +++ b/testament/testament.nim @@ -1139,7 +1139,6 @@ proc makeTestWithDummySpec(test, options: string, cat: Category): TTest = # TODO: fix these files const disabledFilesDefault = @[ - "LockFreeHash.nim", "tableimpl.nim", "setimpl.nim", "hashcommon.nim", diff --git a/tests/misc/tevents.nim b/tests/misc/tevents.nim deleted file mode 100644 index 045c9fc5b09..00000000000 --- a/tests/misc/tevents.nim +++ /dev/null @@ -1,48 +0,0 @@ -discard """ -output: ''' -HandlePrintEvent: Output -> Handled print event -HandlePrintEvent2: Output -> printing for ME -HandlePrintEvent2: Output -> printing for ME -''' -""" - -import events - -type - PrintEventArgs = object of EventArgs - user*: string - -proc handleprintevent*(e: EventArgs) = - write(stdout, "HandlePrintEvent: Output -> Handled print event\n") - -proc handleprintevent2*(e: EventArgs) = - var args: PrintEventArgs = PrintEventArgs(e) - write(stdout, "HandlePrintEvent2: Output -> printing for " & args.user) - -var ee = initEventEmitter() - -var eventargs: PrintEventArgs -eventargs.user = "ME\n" - -##method one test - -ee.on("print", handleprintevent) -ee.on("print", handleprintevent2) - -ee.emit("print", eventargs) - -##method two test - -type - SomeObject = object of RootObj - printEvent: EventHandler - -var obj: SomeObject -obj.printEvent = initEventHandler("print") -obj.printEvent.addHandler(handleprintevent2) - -ee.emit(obj.printEvent, eventargs) - -obj.printEvent.removeHandler(handleprintevent2) - -ee.emit(obj.printEvent, eventargs) diff --git a/tests/types/tillegaltyperecursion.nim b/tests/types/tillegaltyperecursion.nim deleted file mode 100644 index 4c53a8b0ee6..00000000000 --- a/tests/types/tillegaltyperecursion.nim +++ /dev/null @@ -1,66 +0,0 @@ -discard """ - cmd: "nim $target --threads:on $options $file" - errormsg: "illegal recursion in type 'TIRC'" - line: 16 -""" - -import events -import net -import strutils -import os - -type - TMessageReceivedEventArgs = object of EventArgs - Nick*: string - Message*: string - TIRC = object - EventEmitter: EventEmitter - MessageReceivedHandler*: EventHandler - Socket: Socket - Thread: Thread[TIRC] - -proc initIRC*(): TIRC = - result.Socket = socket() - result.EventEmitter = initEventEmitter() - result.MessageReceivedHandler = initEventHandler("MessageReceived") - -proc IsConnected*(irc: var TIRC): bool = - return running(irc.Thread) - - -proc sendRaw*(irc: var TIRC, message: string) = - irc.Socket.send(message & "\r\L") -proc handleData(irc: TIRC) {.thread.} = - var connected = False - while connected: - var tup = @[irc.Socket] - var o = select(tup, 200) - echo($o) - echo($len(tup)) - if len(tup) == 1: - #Connected - connected = True - - #Parse data here - - else: - #Disconnected - connected = False - return - -proc Connect*(irc: var TIRC, nick: string, host: string, port: int = 6667) = - connect(irc.Socket, host, TPort(port), TDomain.AF_INET) - send(irc.Socket,"USER " & nick & " " & nick & " " & nick & " " & nick & "\r\L") - send(irc.Socket,"NICK " & nick & "\r\L") - var thread: Thread[TIRC] - createThread(thread, handleData, irc) - irc.Thread = thread - - - - -when true: - var irc = initIRC() - irc.Connect("AmryBot[Nim]","irc.freenode.net",6667) - irc.sendRaw("JOIN #nim") - os.Sleep(4000) From 2b4101ec0e46fafa780165de36c317e1119c9012 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Sun, 31 Jul 2022 13:55:03 -0700 Subject: [PATCH 03/16] lang: remove deprecated c/C octal prefix - can no longer use 0c1 - this has long since been deprecated and not referenced in the manual --- compiler/ast/lexer.nim | 17 +++-------------- tests/lexer/tintegerliterals.nim | 3 --- 2 files changed, 3 insertions(+), 17 deletions(-) diff --git a/compiler/ast/lexer.nim b/compiler/ast/lexer.nim index 33cf797262f..54bcd6f6ee5 100644 --- a/compiler/ast/lexer.nim +++ b/compiler/ast/lexer.nim @@ -358,8 +358,7 @@ proc getNumber(L: var Lexer, result: var Token) = isBase10 = true numDigits = 0 const - # 'c', 'C' is deprecated - baseCodeChars = {'X', 'x', 'o', 'b', 'B', 'c', 'C'} + baseCodeChars = {'X', 'x', 'o', 'b', 'B'} literalishChars = baseCodeChars + {'A'..'F', 'a'..'f', '0'..'9', '_', '\''} floatTypes = {tkFloatLit, tkFloat32Lit, tkFloat64Lit, tkFloat128Lit} result.tokType = tkIntLit # int literal until we know better @@ -378,19 +377,10 @@ proc getNumber(L: var Lexer, result: var Token) = field = (if isPositive: value else: -value) # First stage: find out base, make verifications, build token literal string - # {'c', 'C'} is added for deprecation reasons to provide a clear error message - if L.buf[L.bufpos] == '0' and L.buf[L.bufpos + 1] in baseCodeChars + {'c', 'C', 'O'}: + if L.buf[L.bufpos] == '0' and L.buf[L.bufpos + 1] in baseCodeChars + {'O'}: isBase10 = false eatChar(L, result, '0') case L.buf[L.bufpos] - of 'c', 'C': - lexMessageLitNum(L, - "$1 will soon be invalid for oct literals; Use '0o' " & - "for octals. 'c', 'C' prefix", - startpos, - rlexDeprecatedOctalPrefix) - eatChar(L, result, 'c') - numDigits = matchUnderscoreChars(L, result, {'0'..'7'}) of 'O': lexMessageLitNum(L, "$1 is an invalid int literal; For octal literals " & "use the '0o' prefix.", startpos, rlexInvalidIntegerPrefix) @@ -484,8 +474,7 @@ proc getNumber(L: var Lexer, result: var Token) = if L.buf[pos] != '_': xi = `shl`(xi, 1) or (ord(L.buf[pos]) - ord('0')) inc(pos) - # 'c', 'C' is deprecated (a warning is issued elsewhere) - of 'o', 'c', 'C': + of 'o': result.base = base8 while pos < endpos: if L.buf[pos] != '_': diff --git a/tests/lexer/tintegerliterals.nim b/tests/lexer/tintegerliterals.nim index fd401b71b04..dda4f4a85b4 100644 --- a/tests/lexer/tintegerliterals.nim +++ b/tests/lexer/tintegerliterals.nim @@ -4,6 +4,3 @@ doAssert 0B10 == 2 doAssert 0x10 == 16 doAssert 0X10 == 16 doAssert 0o10 == 8 -# the following is deprecated: -doAssert 0c10 == 8 -doAssert 0C10 == 8 From c6d28331930491de892018d196d584c2026e4ca4 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Sun, 31 Jul 2022 14:00:42 -0700 Subject: [PATCH 04/16] macros: remove deprecated TNimSym/TypeKinds not used in the code based, removing --- lib/core/macros.nim | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/core/macros.nim b/lib/core/macros.nim index 8ddbdb74407..b2a8a077233 100644 --- a/lib/core/macros.nim +++ b/lib/core/macros.nim @@ -128,7 +128,6 @@ type # compiler that still has ntyConcept (e.g. in bootstrapping) ord(ntyFromExpr) + 2 - TNimTypeKinds* {.deprecated.} = set[NimTypeKind] NimSymKind* = enum nskUnknown, nskConditional, nskDynLib, nskParam, nskGenericParam, nskTemp, nskModule, nskType, nskVar, nskLet, @@ -138,8 +137,6 @@ type nskEnumField, nskForVar, nskLabel, nskStub - TNimSymKinds* {.deprecated.} = set[NimSymKind] - const nnkLiterals* = {nnkCharLit..nnkNilLit} nnkCallKinds* = {nnkCall, nnkInfix, nnkPrefix, nnkPostfix, nnkCommand, From 66144e5e696d2c8c6ee8dfd75cf2a0741fb866e1 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Sun, 31 Jul 2022 19:14:00 -0700 Subject: [PATCH 05/16] dialect: remove old case object define note reset magic is still present --- config/nim.cfg | 6 ------ lib/system/assign.nim | 11 ++--------- 2 files changed, 2 insertions(+), 15 deletions(-) diff --git a/config/nim.cfg b/config/nim.cfg index aa652c1ee0f..144c644bd81 100644 --- a/config/nim.cfg +++ b/config/nim.cfg @@ -311,12 +311,6 @@ tcc.options.always = "-w" --define:nimEmulateOverflowChecks @end -@if nimv019: - --multimethods:on - --define:nimOldCaseObjects - --define:nimOldShiftRight -@end - @if lto or lto_incremental: @if lto_incremental: vcc.options.always%= "${vcc.options.always} /GL /Gw /Gy" diff --git a/lib/system/assign.nim b/lib/system/assign.nim index a49d9c9e9bb..7baf4e1a0f7 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -293,12 +293,5 @@ proc FieldDiscriminantCheck(oldDiscVal, newDiscVal: int, L: int) {.compilerproc.} = let oldBranch = selectBranch(oldDiscVal, L, a) let newBranch = selectBranch(newDiscVal, L, a) - when defined(nimOldCaseObjects): - if newBranch != oldBranch and oldDiscVal != 0: - sysFatal(FieldDefect, "assignment to discriminant changes object branch") - else: - if newBranch != oldBranch: - if oldDiscVal != 0: - sysFatal(FieldDefect, "assignment to discriminant changes object branch") - else: - sysFatal(FieldDefect, "assignment to discriminant changes object branch; compile with -d:nimOldCaseObjects for a transition period") + if newBranch != oldBranch: + sysFatal(FieldDefect, "assignment to discriminant changes object branch") From 184139bb9be656ff0513eb80d90d9a89b8e1f96a Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Mon, 1 Aug 2022 12:55:06 -0700 Subject: [PATCH 06/16] stdlib: httpcore ==(string, HttpCode):bool removed dropped proc from stdlib, it been deprecatd forever --- lib/pure/httpcore.nim | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/lib/pure/httpcore.nim b/lib/pure/httpcore.nim index fdd5926f72e..7e995ac46b3 100644 --- a/lib/pure/httpcore.nim +++ b/lib/pure/httpcore.nim @@ -347,16 +347,6 @@ func `$`*(code: HttpCode): string = func `==`*(a, b: HttpCode): bool {.borrow.} -proc `==`*(rawCode: string, code: HttpCode): bool - {.deprecated: "Deprecated since v1.2; use rawCode == $code instead".} = - ## Compare the string form of the status code with a HttpCode - ## - ## **Note**: According to HTTP/1.1 specification, the reason phrase is - ## optional and should be ignored by the client, making this - ## proc only suitable for comparing the `HttpCode` against the - ## string form of itself. - return cmpIgnoreCase(rawCode, $code) == 0 - func is1xx*(code: HttpCode): bool {.inline, since: (1, 5).} = ## Determines whether `code` is a 1xx HTTP status code. runnableExamples: From 368609a0f16a89ec367fdd91b63b60d7d5b2a08e Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Mon, 1 Aug 2022 12:58:14 -0700 Subject: [PATCH 07/16] stdlib: removed deprecated module oswalkdir functionality has long since been moved to `std/os` --- lib/pure/oswalkdir.nim | 13 ------------- 1 file changed, 13 deletions(-) delete mode 100644 lib/pure/oswalkdir.nim diff --git a/lib/pure/oswalkdir.nim b/lib/pure/oswalkdir.nim deleted file mode 100644 index 866f9ed7026..00000000000 --- a/lib/pure/oswalkdir.nim +++ /dev/null @@ -1,13 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2015 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module is deprecated, `import os` instead. -{.deprecated: "import os.nim instead".} -import os -export PathComponent, walkDir, walkDirRec From 6cfb322f732314d13ccb7c7f67dda9e8c003083f Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Mon, 1 Aug 2022 16:01:21 -0700 Subject: [PATCH 08/16] stdlib: times, remove deprecated procs Removed deprecated constructors and setters for `times.DateTime` Updated associated broken tests. --- lib/pure/times.nim | 58 ------------- tests/metatype/tstaticparams.nim | 2 +- tests/stdlib/tstrformat.nim | 2 +- tests/stdlib/ttimes.nim | 135 +++++++++++++++++-------------- 4 files changed, 78 insertions(+), 119 deletions(-) diff --git a/lib/pure/times.nim b/lib/pure/times.nim index dcff960733e..dd06b8c48d8 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -1353,23 +1353,6 @@ proc dateTime*(year: int, month: Month, monthday: MonthdayRange, ) result = initDateTime(zone.zonedTimeFromAdjTime(dt.toAdjTime), zone) -proc initDateTime*(monthday: MonthdayRange, month: Month, year: int, - hour: HourRange, minute: MinuteRange, second: SecondRange, - nanosecond: NanosecondRange, - zone: Timezone = local()): DateTime {.deprecated: "use `dateTime`".} = - ## Create a new `DateTime <#DateTime>`_ in the specified timezone. - runnableExamples("--warning:deprecated:off"): - assert $initDateTime(30, mMar, 2017, 00, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z" - dateTime(year, month, monthday, hour, minute, second, nanosecond, zone) - -proc initDateTime*(monthday: MonthdayRange, month: Month, year: int, - hour: HourRange, minute: MinuteRange, second: SecondRange, - zone: Timezone = local()): DateTime {.deprecated: "use `dateTime`".} = - ## Create a new `DateTime <#DateTime>`_ in the specified timezone. - runnableExamples("--warning:deprecated:off"): - assert $initDateTime(30, mMar, 2017, 00, 00, 00, utc()) == "2017-03-30T00:00:00Z" - dateTime(year, month, monthday, hour, minute, second, 0, zone) - proc `+`*(dt: DateTime, dur: Duration): DateTime = runnableExamples: let dt = dateTime(2017, mMar, 30, 00, 00, 00, 00, utc()) @@ -2650,44 +2633,3 @@ when not defined(js): toFloat(ts.tv_nsec.int) / 1_000_000_000 else: result = toFloat(int(getClock())) / toFloat(clocksPerSec) - - -# -# Deprecations -# - -proc `nanosecond=`*(dt: var DateTime, value: NanosecondRange) {.deprecated: "Deprecated since v1.3.1".} = - dt.nanosecond = value - -proc `second=`*(dt: var DateTime, value: SecondRange) {.deprecated: "Deprecated since v1.3.1".} = - dt.second = value - -proc `minute=`*(dt: var DateTime, value: MinuteRange) {.deprecated: "Deprecated since v1.3.1".} = - dt.minute = value - -proc `hour=`*(dt: var DateTime, value: HourRange) {.deprecated: "Deprecated since v1.3.1".} = - dt.hour = value - -proc `monthdayZero=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} = - dt.monthdayZero = value - -proc `monthZero=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} = - dt.monthZero = value - -proc `year=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} = - dt.year = value - -proc `weekday=`*(dt: var DateTime, value: WeekDay) {.deprecated: "Deprecated since v1.3.1".} = - dt.weekday = value - -proc `yearday=`*(dt: var DateTime, value: YeardayRange) {.deprecated: "Deprecated since v1.3.1".} = - dt.yearday = value - -proc `isDst=`*(dt: var DateTime, value: bool) {.deprecated: "Deprecated since v1.3.1".} = - dt.isDst = value - -proc `timezone=`*(dt: var DateTime, value: Timezone) {.deprecated: "Deprecated since v1.3.1".} = - dt.timezone = value - -proc `utcOffset=`*(dt: var DateTime, value: int) {.deprecated: "Deprecated since v1.3.1".} = - dt.utcOffset = value diff --git a/tests/metatype/tstaticparams.nim b/tests/metatype/tstaticparams.nim index de80d46ae89..11350d1a5fd 100644 --- a/tests/metatype/tstaticparams.nim +++ b/tests/metatype/tstaticparams.nim @@ -194,4 +194,4 @@ block: # #12864 when true: #12864 original snippet import times - discard times.format(initDateTime(30, mMar, 2017, 0, 0, 0, 0, utc()), TimeFormat()) + discard times.format(dateTime(2017, mMar, 30, 0, 0, 0, 0, utc()), TimeFormat()) diff --git a/tests/stdlib/tstrformat.nim b/tests/stdlib/tstrformat.nim index 1863d313881..b9c9f204e9d 100644 --- a/tests/stdlib/tstrformat.nim +++ b/tests/stdlib/tstrformat.nim @@ -473,7 +473,7 @@ proc main() = # Note: times.format adheres to the format protocol. Test that this # works: - var dt = initDateTime(01, mJan, 2000, 00, 00, 00) + var dt = dateTime(2000, mJan, 01, 00, 00, 00) check &"{dt:yyyy-MM-dd}", "2000-01-01" var tm = fromUnix(0) diff --git a/tests/stdlib/ttimes.nim b/tests/stdlib/ttimes.nim index 66157b91c28..9f042011a80 100644 --- a/tests/stdlib/ttimes.nim +++ b/tests/stdlib/ttimes.nim @@ -151,30 +151,46 @@ block: # ttimes usingTimezone("Europe/Stockholm"): # In case of an impossible time, the time is moved to after the # impossible time period - check initDateTime(26, mMar, 2017, 02, 30, 00).format(f) == + check dateTime(2017, mMar, 26, 02, 30, 00).format(f) == "2017-03-26 03:30 +02:00" # In case of an ambiguous time, the earlier time is chosen - check initDateTime(29, mOct, 2017, 02, 00, 00).format(f) == + check dateTime(2017, mOct, 29, 02, 00, 00).format(f) == "2017-10-29 02:00 +02:00" # These are just dates on either side of the dst switch - check initDateTime(29, mOct, 2017, 01, 00, 00).format(f) == + check dateTime(2017, mOct, 29, 01, 00, 00).format(f) == "2017-10-29 01:00 +02:00" - check initDateTime(29, mOct, 2017, 01, 00, 00).isDst - check initDateTime(29, mOct, 2017, 03, 01, 00).format(f) == + check dateTime(2017, mOct, 29, 01, 00, 00).isDst + check dateTime(2017, mOct, 29, 03, 01, 00).format(f) == "2017-10-29 03:01 +01:00" - check (not initDateTime(29, mOct, 2017, 03, 01, 00).isDst) + check (not dateTime(2017, mOct, 29, 03, 01, 00).isDst) - check initDateTime(21, mOct, 2017, 01, 00, 00).format(f) == + check dateTime(2017, mOct, 21, 01, 00, 00).format(f) == "2017-10-21 01:00 +02:00" block: # issue #6520 usingTimezone("Europe/Stockholm"): - var local = fromUnix(1469275200).local - var utc = fromUnix(1469275200).utc - - let claimedOffset = initDuration(seconds = local.utcOffset) - local.utcOffset = 0 - check claimedOffset == utc.toTime - local.toTime + let + local = fromUnix(1469275200).local + ## local DateTime from a unix time, on c backends this respects + ## historic time zone changes, hence the TZ and unix time choices + utc = fromUnix(1469275200).utc + ## utc DateTime for the same unix time + claimedOffset = initDuration(seconds = local.utcOffset) + ## the offset between the local and utc DateTime + localShifted = dateTime(local.year, local.month, local.monthday, + local.hour, local.minute, local.second, + local.nanosecond, utc()).local + ## local DateTime data except we pretend it's UTC and then convert it + ## back to local + + # if the conversions are correctly done, historic time zone data should + # not cause claimedOffset to disagree with the original utc less the + # locally shifted time + + # this catches issues where conversions use current UTC offset where it + # should have used the historic UTC offset (stored in the DateTime object + + check claimedOffset == utc.toTime - localShifted.toTime block: # issue #5704 usingTimezone("Asia/Seoul"): @@ -190,10 +206,10 @@ block: # ttimes block: # adding/subtracting time across dst usingTimezone("Europe/Stockholm"): - let dt1 = initDateTime(26, mMar, 2017, 03, 00, 00) + let dt1 = dateTime(2017, mMar, 26, 03, 00, 00) check $(dt1 - 1.seconds) == "2017-03-26T01:59:59+01:00" - var dt2 = initDateTime(29, mOct, 2017, 02, 59, 59) + var dt2 = dateTime(2017, mOct, 29, 02, 59, 59) check $(dt2 + 1.seconds) == "2017-10-29T02:00:00+01:00" block: # datetime before epoch @@ -266,7 +282,7 @@ block: # ttimes block: # dynamic timezone let tz = staticTz(seconds = -9000) - let dt = initDateTime(1, mJan, 2000, 12, 00, 00, tz) + let dt = dateTime(2000, mJan, 1, 12, 00, 00, zone = tz) check dt.utcOffset == -9000 check dt.isDst == false check $dt == "2000-01-01T12:00:00+02:30" @@ -292,18 +308,19 @@ block: # ttimes check (t - 1.hours).toTime.toUnix == t.toTime.toUnix - 60 * 60 block: # TimeInterval - months - var dt = initDateTime(1, mFeb, 2017, 00, 00, 00, utc()) + var dt = dateTime(2017, mFeb, 1, 00, 00, 00, zone = utc()) check $(dt - initTimeInterval(months = 1)) == "2017-01-01T00:00:00Z" - dt = initDateTime(15, mMar, 2017, 00, 00, 00, utc()) + dt = dateTime(2017, mMar, 15, 00, 00, 00, zone = utc()) check $(dt - initTimeInterval(months = 1)) == "2017-02-15T00:00:00Z" - dt = initDateTime(31, mMar, 2017, 00, 00, 00, utc()) + dt = dateTime(2017, mMar, 31, 00, 00, 00, zone = utc()) # This happens due to monthday overflow. It's consistent with Phobos. check $(dt - initTimeInterval(months = 1)) == "2017-03-03T00:00:00Z" block: # duration let d = initDuration check d(hours = 48) + d(days = 5) == d(weeks = 1) - let dt = initDateTime(01, mFeb, 2000, 00, 00, 00, 0, utc()) + d(milliseconds = 1) + let dt = dateTime(2000, mFeb, 01, 00, 00, 00, 0, zone = utc()) + + d(milliseconds = 1) check dt.nanosecond == convert(Milliseconds, Nanoseconds, 1) check d(seconds = 1, milliseconds = 500) * 2 == d(seconds = 3) check d(seconds = 3) div 2 == d(seconds = 1, milliseconds = 500) @@ -321,12 +338,12 @@ block: # ttimes initDuration(seconds = 1, nanoseconds = 1)).not block: # large/small dates - discard initDateTime(1, mJan, -35_000, 12, 00, 00, utc()) + discard dateTime(-35_000, mJan, 1, 12, 00, 00, zone = utc()) # with local tz - discard initDateTime(1, mJan, -35_000, 12, 00, 00) - discard initDateTime(1, mJan, 35_000, 12, 00, 00) + discard dateTime(-35_000, mJan, 1, 12, 00, 00) + discard dateTime( 35_000, mJan, 1, 12, 00, 00) # with duration/timeinterval - let dt = initDateTime(1, mJan, -35_000, 12, 00, 00, utc()) + + let dt = dateTime(-35_000, mJan, 1, 12, 00, 00, zone = utc()) + initDuration(seconds = 1) check dt.second == 1 let dt2 = dt + 35_001.years @@ -386,7 +403,7 @@ block: # ttimes check t7620_pm.format(layout) == "4/15/2017 12:01:02 PM Z" block: # format - var dt = initDateTime(1, mJan, -0001, + var dt = dateTime(-0001, mJan, 1, 17, 01, 02, 123_456_789, staticTz(hours = 1, minutes = 2, seconds = 3)) check dt.format("d") == "1" @@ -421,15 +438,15 @@ block: # ttimes check dt.format("fff") == "123" check dt.format("ffffff") == "123456" check dt.format("fffffffff") == "123456789" - dt.nanosecond = 1 + dt -= initDuration(nanoseconds = dt.nanosecond - 1) check dt.format("fff") == "000" check dt.format("ffffff") == "000000" check dt.format("fffffffff") == "000000001" - dt.year = 12345 + dt += initTimeInterval(years = 12345 - dt.year) check dt.format("yyyy") == "+12345" check dt.format("uuuu") == "+12345" - dt.year = -12345 + dt += initTimeInterval(years = -12345 - dt.year) check dt.format("yyyy") == "+12346" check dt.format("uuuu") == "-12345" @@ -449,7 +466,7 @@ block: # ttimes (staticTz(seconds = -1800), "+0", "+00", "+00:30"), # half an hour (staticTz(seconds = 7200), "-2", "-02", "-02:00"), # positive (staticTz(seconds = 38700), "-10", "-10", "-10:45")]: # positive with three quaters hour - let dt = initDateTime(1, mJan, 2000, 00, 00, 00, tz[0]) + let dt = dateTime(2000, mJan, 1, 00, 00, 00, zone = tz[0]) doAssert dt.format("z") == tz[1] doAssert dt.format("zz") == tz[2] doAssert dt.format("zzz") == tz[3] @@ -461,7 +478,7 @@ block: # ttimes ddd: ["Red", "Ora.", "Yel.", "Gre.", "Blu.", "Vio.", "Whi."], dddd: ["Red", "Orange", "Yellow", "Green", "Blue", "Violet", "White"], ) - var dt = initDateTime(5, mJan, 2010, 17, 01, 02, utc()) + var dt = dateTime(2010, mJan, 5, 17, 01, 02, zone = utc()) check dt.format("d", loc) == "5" check dt.format("dd", loc) == "05" check dt.format("ddd", loc) == "Ora." @@ -520,14 +537,14 @@ block: # ttimes check getDayOfWeek(01, mJan, 2021) == dFri block: # between - simple - let x = initDateTime(10, mJan, 2018, 13, 00, 00) - let y = initDateTime(11, mJan, 2018, 12, 00, 00) + let x = dateTime(2018, mJan, 10, 13, 00, 00) + let y = dateTime(2018, mJan, 11, 12, 00, 00) doAssert x + between(x, y) == y block: # between - dst start usingTimezone("Europe/Stockholm"): - let x = initDateTime(25, mMar, 2018, 00, 00, 00) - let y = initDateTime(25, mMar, 2018, 04, 00, 00) + let x = dateTime(2018, mMar, 25, 00, 00, 00) + let y = dateTime(2018, mMar, 25, 04, 00, 00) doAssert x + between(x, y) == y block: # between - empty interval @@ -537,15 +554,15 @@ block: # ttimes block: # between - dst end usingTimezone("Europe/Stockholm"): - let x = initDateTime(27, mOct, 2018, 02, 00, 00) - let y = initDateTime(28, mOct, 2018, 01, 00, 00) + let x = dateTime(2018, mOct, 27, 02, 00, 00) + let y = dateTime(2018, mOct, 28, 01, 00, 00) doAssert x + between(x, y) == y block: # between - long day usingTimezone("Europe/Stockholm"): # This day is 25 hours long in Europe/Stockholm - let x = initDateTime(28, mOct, 2018, 00, 30, 00) - let y = initDateTime(29, mOct, 2018, 00, 00, 00) + let x = dateTime(2018, mOct, 28, 00, 30, 00) + let y = dateTime(2018, mOct, 29, 00, 00, 00) doAssert between(x, y) == 24.hours + 30.minutes doAssert x + between(x, y) == y @@ -553,62 +570,62 @@ block: # ttimes # This test case is important because in this case # `x + between(x.utc, y.utc) == y` is not true, which is very rare. usingTimezone("America/Belem"): - let x = initDateTime(24, mOct, 1987, 00, 00, 00) - let y = initDateTime(26, mOct, 1987, 23, 00, 00) + let x = dateTime(1987, mOct, 24, 00, 00, 00) + let y = dateTime(1987, mOct, 26, 23, 00, 00) doAssert x + between(x, y) == y doAssert y + between(y, x) == x block: # between - all units - let x = initDateTime(1, mJan, 2000, 00, 00, 00, utc()) + let x = dateTime(2000, mJan, 1, 00, 00, 00, zone = utc()) let ti = initTimeInterval(1, 1, 1, 1, 1, 1, 1, 1, 1, 1) let y = x + ti doAssert between(x, y) == ti doAssert between(y, x) == -ti block: # between - monthday overflow - let x = initDateTime(31, mJan, 2001, 00, 00, 00, utc()) - let y = initDateTime(1, mMar, 2001, 00, 00, 00, utc()) + let x = dateTime(2001, mJan, 31, 00, 00, 00, zone = utc()) + let y = dateTime(2001, mMar, 1, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y block: # between - misc block: - let x = initDateTime(31, mDec, 2000, 12, 00, 00, utc()) - let y = initDateTime(01, mJan, 2001, 00, 00, 00, utc()) + let x = dateTime(2000, mDec, 31, 12, 00, 00, zone = utc()) + let y = dateTime(2001, mJan, 01, 00, 00, 00, zone = utc()) doAssert between(x, y) == 12.hours block: - let x = initDateTime(31, mDec, 2000, 12, 00, 00, utc()) - let y = initDateTime(02, mJan, 2001, 00, 00, 00, utc()) + let x = dateTime(2000, mDec, 31, 12, 00, 00, zone = utc()) + let y = dateTime(2001, mJan, 02, 00, 00, 00, zone = utc()) doAssert between(x, y) == 1.days + 12.hours block: - let x = initDateTime(31, mDec, 1995, 00, 00, 00, utc()) - let y = initDateTime(01, mFeb, 2000, 00, 00, 00, utc()) + let x = dateTime(1995, mDec, 31, 00, 00, 00, zone = utc()) + let y = dateTime(2000, mFeb, 01, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y block: - let x = initDateTime(01, mDec, 1995, 00, 00, 00, utc()) - let y = initDateTime(31, mJan, 2000, 00, 00, 00, utc()) + let x = dateTime(1995, mDec, 01, 00, 00, 00, zone = utc()) + let y = dateTime(2000, mJan, 31, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y block: - let x = initDateTime(31, mJan, 2000, 00, 00, 00, utc()) - let y = initDateTime(01, mFeb, 2000, 00, 00, 00, utc()) + let x = dateTime(2000, mJan, 31, 00, 00, 00, zone = utc()) + let y = dateTime(2000, mFeb, 01, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y block: - let x = initDateTime(01, mJan, 1995, 12, 00, 00, utc()) - let y = initDateTime(01, mFeb, 1995, 00, 00, 00, utc()) + let x = dateTime(1995, mJan, 01, 12, 00, 00, zone = utc()) + let y = dateTime(1995, mFeb, 01, 00, 00, 00, zone = utc()) doAssert between(x, y) == 4.weeks + 2.days + 12.hours block: - let x = initDateTime(31, mJan, 1995, 00, 00, 00, utc()) - let y = initDateTime(10, mFeb, 1995, 00, 00, 00, utc()) + let x = dateTime(1995, mJan, 31, 00, 00, 00, zone = utc()) + let y = dateTime(1995, mFeb, 10, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y block: - let x = initDateTime(31, mJan, 1995, 00, 00, 00, utc()) - let y = initDateTime(10, mMar, 1995, 00, 00, 00, utc()) + let x = dateTime(1995, mJan, 31, 00, 00, 00, zone = utc()) + let y = dateTime(1995, mMar, 10, 00, 00, 00, zone = utc()) doAssert x + between(x, y) == y doAssert between(x, y) == 1.months + 1.weeks From f69624f229819c3b315a84e2ce2321dbd7ba2ff3 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Mon, 1 Aug 2022 17:06:01 -0700 Subject: [PATCH 09/16] stdlib: remove deprecated os.existsFile/Dir fileExists/dirExists are already present --- lib/pure/os.nim | 9 --------- lib/system/nimscript.nim | 8 -------- 2 files changed, 17 deletions(-) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 61bf2b02f9c..76a5631d49b 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -3522,12 +3522,3 @@ func isValidFilename*(filename: string, maxLen = 259.Positive): bool {.since: (1 find(f.name, invalidFilenameChars) != -1): return false for invalid in invalidFilenames: if cmpIgnoreCase(f.name, invalid) == 0: return false - -# deprecated declarations -when not defined(nimscript): - when not defined(js): # `noNimJs` doesn't work with templates, this should improve. - template existsFile*(args: varargs[untyped]): untyped {.deprecated: "use fileExists".} = - fileExists(args) - template existsDir*(args: varargs[untyped]): untyped {.deprecated: "use dirExists".} = - dirExists(args) - # {.deprecated: [existsFile: fileExists].} # pending bug #14819; this would avoid above mentioned issue diff --git a/lib/system/nimscript.nim b/lib/system/nimscript.nim index b4554d77810..0ef5fc584f3 100644 --- a/lib/system/nimscript.nim +++ b/lib/system/nimscript.nim @@ -136,14 +136,6 @@ proc dirExists*(dir: string): bool {. ## Checks if the directory `dir` exists. builtin -template existsFile*(args: varargs[untyped]): untyped {.deprecated: "use fileExists".} = - # xxx: warning won't be shown for nimsscript because of current logic handling - # `foreignPackageNotes` - fileExists(args) - -template existsDir*(args: varargs[untyped]): untyped {.deprecated: "use dirExists".} = - dirExists(args) - proc selfExe*(): string = ## Returns the currently running nim or nimble executable. # TODO: consider making this as deprecated alias of `getCurrentCompilerExe` From fa299661fde7732681c352e600cb2d59f8dec1e9 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Mon, 1 Aug 2022 17:09:13 -0700 Subject: [PATCH 10/16] pragma: remove the deprecated unroll pragma supposedly it was ignored by the compiler, the fewer pragmas the better. --- compiler/ast/wordrecg.nim | 2 +- compiler/sem/pragmas.nim | 18 +----------------- 2 files changed, 2 insertions(+), 18 deletions(-) diff --git a/compiler/ast/wordrecg.nim b/compiler/ast/wordrecg.nim index 9b825a7d76b..59fcb5441ac 100644 --- a/compiler/ast/wordrecg.nim +++ b/compiler/ast/wordrecg.nim @@ -77,7 +77,7 @@ type wCompileTime = "compileTime", wNoInit = "noinit", wPassc = "passc", wPassl = "passl", wLocalPassc = "localPassC", wBorrow = "borrow", wDiscardable = "discardable", wFieldChecks = "fieldChecks", wSubsChar = "subschar", wAcyclic = "acyclic", - wShallow = "shallow", wUnroll = "unroll", wLinearScanEnd = "linearScanEnd", + wShallow = "shallow", wLinearScanEnd = "linearScanEnd", wComputedGoto = "computedGoto", wExperimental = "experimental", wWrite = "write", wGensym = "gensym", wInject = "inject", wDirty = "dirty", wInheritable = "inheritable", wThreadVar = "threadvar", wEmit = "emit", diff --git a/compiler/sem/pragmas.nim b/compiler/sem/pragmas.nim index 412b5bea16c..b9f7b17885f 100644 --- a/compiler/sem/pragmas.nim +++ b/compiler/sem/pragmas.nim @@ -88,7 +88,7 @@ const wPassl, wPassc, wLocalPassc, wDeadCodeElimUnused, # deprecated, always on wDeprecated, - wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wUnroll, + wFloatChecks, wInfChecks, wNanChecks, wPragma, wEmit, wLinearScanEnd, wPatterns, wTrMacros, wEffects, wComputedGoto, wExperimental, wThis, wUsed, wAssert} lambdaPragmas* = {FirstCallConv..LastCallConv, @@ -826,20 +826,6 @@ proc noVal(c: PContext; n: PNode): PNode = else: n -proc pragmaUnroll(c: PContext, n: PNode): PNode = - result = n - if c.p.nestedLoopCounter <= 0: - result = invalidPragma(c, n) - elif n.kind in nkPragmaCallKinds and n.len == 2: - var (unrollFactor, err) = intLitToIntOrErr(c, n) - if err.isNil: - if unrollFactor <% 32: - n[1] = newIntNode(nkIntLit, unrollFactor) - else: - result = invalidPragma(c, n) - else: - result = err - proc pragmaLine(c: PContext, n: PNode): PNode = result = n if n.kind in nkPragmaCallKinds and n.len == 2: @@ -1650,8 +1636,6 @@ proc prepareSinglePragma( sym.typ.flags.incl tfExplicitCallConv of wEmit: result = pragmaEmit(c, it) - of wUnroll: - result = pragmaUnroll(c, it) of wLinearScanEnd, wComputedGoto: result = noVal(c, it) of wEffects: From b852b1dcb9a609235a18a4d5b77086fe163169a6 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Fri, 5 Aug 2022 18:29:19 -0700 Subject: [PATCH 11/16] strutils: remove deprecated delete proc - remove deprecated `delete(var string, int, int)` - removed associated tests - updated usage of removed proc in rstgen --- lib/packages/docutils/rstgen.nim | 2 +- lib/pure/strutils.nim | 23 ----------------------- tests/stdlib/tstrutils.nim | 11 ----------- 3 files changed, 1 insertion(+), 35 deletions(-) diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index 2e45bda4ce4..a2d51b9c96a 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -757,7 +757,7 @@ proc stripTocHtml(s: string): string = if last < 0: # Abort, since we didn't found a closing angled bracket. return - result.delete(first, last) + result.delete(first..last) first = result.find('<', first) proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index 1e894080f70..17f3cd26eec 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -1507,29 +1507,6 @@ func delete*(s: var string, slice: Slice[int]) = inc(j) setLen(s, newLen) -func delete*(s: var string, first, last: int) {.rtl, extern: "nsuDelete", deprecated: "use `delete(s, first..last)`".} = - ## Deletes in `s` the characters at positions `first .. last` (both ends included). - runnableExamples("--warning:deprecated:off"): - var a = "abracadabra" - - a.delete(4, 5) - doAssert a == "abradabra" - - a.delete(1, 6) - doAssert a == "ara" - - a.delete(2, 999) - doAssert a == "ar" - - var i = first - var j = min(len(s), last+1) - var newLen = len(s)-j+i - while i < newLen: - s[i] = s[j] - inc(i) - inc(j) - setLen(s, newLen) - func startsWith*(s: string, prefix: char): bool {.inline.} = ## Returns true if `s` starts with character `prefix`. ## diff --git a/tests/stdlib/tstrutils.nim b/tests/stdlib/tstrutils.nim index d8b6d848e69..608af5cd3fd 100644 --- a/tests/stdlib/tstrutils.nim +++ b/tests/stdlib/tstrutils.nim @@ -223,17 +223,6 @@ template main() = delete(s, 0..0) doAssert s == "b" - block: # delete(first, last) - {.push warning[deprecated]:off.} - var s = "0123456789ABCDEFGH" - delete(s, 4, 5) - doAssert s == "01236789ABCDEFGH" - delete(s, s.len-1, s.len-1) - doAssert s == "01236789ABCDEFG" - delete(s, 0, 0) - doAssert s == "1236789ABCDEFG" - {.pop.} - block: # find doAssert "0123456789ABCDEFGH".find('A') == 10 doAssert "0123456789ABCDEFGH".find('A', 5) == 10 From c27dfe22a50a24bc164afdbeff9a62d6ea6fd348 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Fri, 5 Aug 2022 18:35:49 -0700 Subject: [PATCH 12/16] sequtils: remove deprecated delete proc remove deprecated `delete[T](var T, int, int)` and its tests --- lib/pure/collections/sequtils.nim | 24 ------------------------ tests/stdlib/tsequtils.nim | 5 +---- 2 files changed, 1 insertion(+), 28 deletions(-) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index e92efcbdfaf..1616b45e9b4 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -563,30 +563,6 @@ func delete*[T](s: var seq[T]; slice: Slice[int]) = else: defaultImpl() -func delete*[T](s: var seq[T]; first, last: Natural) {.deprecated: "use `delete(s, first..last)`".} = - ## Deletes the items of a sequence `s` at positions `first..last` - ## (including both ends of the range). - ## This modifies `s` itself, it does not return a copy. - runnableExamples("--warning:deprecated:off"): - let outcome = @[1, 1, 1, 1, 1, 1, 1, 1] - var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] - dest.delete(3, 8) - assert outcome == dest - doAssert first <= last - if first >= s.len: - return - var i = first - var j = min(len(s), last + 1) - var newLen = len(s) - j + i - while i < newLen: - when defined(gcDestructors): - s[i] = move(s[j]) - else: - s[i].shallowCopy(s[j]) - inc(i) - inc(j) - setLen(s, newLen) - func insert*[T](dest: var seq[T], src: openArray[T], pos = 0) = ## Inserts items from `src` into `dest` at position `pos`. This modifies ## `dest` itself, it does not return a copy. diff --git a/tests/stdlib/tsequtils.nim b/tests/stdlib/tsequtils.nim index 179f619f0c2..b9d4a26eee3 100644 --- a/tests/stdlib/tsequtils.nim +++ b/tests/stdlib/tsequtils.nim @@ -487,13 +487,10 @@ template main = block: # delete tests let outcome = @[1, 1, 1, 1, 1, 1, 1, 1] var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1] - dest.delete(3, 8) + dest.delete(3..8) doAssert outcome == dest, """\ Deleting range 3-9 from [1,1,1,2,2,2,2,2,2,1,1,1,1,1] is [1,1,1,1,1,1,1,1]""" - var x = @[1, 2, 3] - x.delete(100, 100) - doAssert x == @[1, 2, 3] block: # delete tests var a = @[10, 11, 12, 13, 14] From e3c640bace3044e7107d94326cf79f993416461b Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Fri, 5 Aug 2022 18:37:00 -0700 Subject: [PATCH 13/16] algorithm: remove deprecated reversed proc - remove deprecated `reversed[T](var openArray[T], int, int): seq[T]` - removed associated tests --- lib/pure/algorithm.nim | 4 ---- tests/stdlib/talgorithm.nim | 4 ++-- 2 files changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 1ddcc9843bf..aa110e76053 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -143,10 +143,6 @@ proc reversed*[T](a: openArray[T]): seq[T] {.inline.} = result.setLen(n) for i in 0.. Date: Fri, 5 Aug 2022 18:37:33 -0700 Subject: [PATCH 14/16] math: renamed internal c_frexp2 to c_frexp --- lib/pure/math.nim | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/lib/pure/math.nim b/lib/pure/math.nim index 1c47258bc6f..9bd4f5ba3d4 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -69,10 +69,9 @@ when defined(c) or defined(cpp): proc c_signbit(x: SomeFloat): cint {.importc: "signbit", header: "".} - # don't export `c_frexp` in the future and remove `c_frexp2`. - func c_frexp2(x: cfloat, exponent: var cint): cfloat {. + func c_frexp(x: cfloat, exponent: var cint): cfloat {. importc: "frexpf", header: "".} - func c_frexp2(x: cdouble, exponent: var cint): cdouble {. + func c_frexp(x: cdouble, exponent: var cint): cdouble {. importc: "frexp", header: "".} func binom*(n, k: int): int = @@ -1005,7 +1004,7 @@ func frexp*[T: float32|float64](x: T): tuple[frac: T, exp: int] {.inline.} = when not defined(js): var exp: cint - result.frac = c_frexp2(x, exp) + result.frac = c_frexp(x, exp) result.exp = exp else: if x == 0.0: From bd037e910d5d3d3d81a7a6f53fcaccc8c5ffe484 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Fri, 5 Aug 2022 18:39:03 -0700 Subject: [PATCH 15/16] options: remove deprecated UnpackError - removed UnpackError, now uses UnpackDefect - Defects in general are a bad idea, but less code --- lib/pure/options.nim | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/pure/options.nim b/lib/pure/options.nim index 850bfa555d4..545f84721b0 100644 --- a/lib/pure/options.nim +++ b/lib/pure/options.nim @@ -90,7 +90,6 @@ type has: bool UnpackDefect* = object of Defect - UnpackError* {.deprecated: "See corresponding Defect".} = UnpackDefect proc option*[T](val: sink T): Option[T] {.inline.} = ## Can be used to convert a pointer type (`ptr`, `pointer`, `ref` or `proc`) to an option type. From 847484b7042fe3eca73c6d6851d897b3d5c60cf0 Mon Sep 17 00:00:00 2001 From: Saem Ghani Date: Fri, 5 Aug 2022 20:31:26 -0700 Subject: [PATCH 16/16] lang: remove for loop and case statement macros There are better ways to do these sorts of things. --- compiler/front/in_options.nim | 3 - compiler/sem/semstmts.nim | 78 ------------- doc/lib.rst | 3 - doc/manual.rst | 141 ------------------------ lib/pure/collections/lists.nim | 30 +++-- lib/pure/options.nim | 23 ---- lib/std/enumerate.nim | 70 ------------ lib/system.nim | 5 - tests/effects/tstrict_funcs_imports.nim | 1 - tests/js/tstdlib_imports.nim | 2 +- tests/macros/tcasestmtmacro.nim | 33 ------ tests/macros/tforloop_macro1.nim | 44 -------- tests/pragmas/mpushexperimental.nim | 30 ----- tests/pragmas/tpushexperimental.nim | 13 --- tests/stdlib/tenumerate.nim | 19 ---- tests/stylecheck/tstyle_imports.nim | 1 - tests/test_nimscript.nims | 2 +- 17 files changed, 25 insertions(+), 473 deletions(-) delete mode 100644 lib/std/enumerate.nim delete mode 100644 tests/macros/tcasestmtmacro.nim delete mode 100644 tests/macros/tforloop_macro1.nim delete mode 100644 tests/pragmas/mpushexperimental.nim delete mode 100644 tests/pragmas/tpushexperimental.nim delete mode 100644 tests/stdlib/tenumerate.nim diff --git a/compiler/front/in_options.nim b/compiler/front/in_options.nim index 06977a03c4c..74333a5c46e 100644 --- a/compiler/front/in_options.nim +++ b/compiler/front/in_options.nim @@ -190,9 +190,6 @@ type destructor, notnil, dynamicBindSym, - forLoopMacros, ## not experimental anymore; remains here for backwards - ## compatibility - caseStmtMacros,## ditto vmopsDanger, strictFuncs, views, diff --git a/compiler/sem/semstmts.nim b/compiler/sem/semstmts.nim index 8b8b9c6727d..9a1031669dd 100644 --- a/compiler/sem/semstmts.nim +++ b/compiler/sem/semstmts.nim @@ -1614,83 +1614,8 @@ proc isTrivalStmtExpr(n: PNode): bool = return false result = true -proc handleStmtMacro(c: PContext; n, selector: PNode; magicType: string; - flags: TExprFlags): PNode = - if selector.kind in nkCallKinds: - # we transform - # n := for a, b, c in m(x, y, z): Y - # to - # m(n) - let maType = magicsys.getCompilerProc(c.graph, magicType) - if maType == nil: return - - let headSymbol = selector[0] - var o: TOverloadIter - var match: PSym = nil - var symx = initOverloadIter(o, c, headSymbol) - while symx != nil: - if symx.kind in {skTemplate, skMacro}: - if symx.typ.len == 2 and symx.typ[1] == maType.typ: - if match == nil: - match = symx - else: - localReport( - c.config, n.info, - reportSymbols(rsemAmbiguous, @[match, symx]).withIt do: - it.ast = selector - ) - elif symx.isError: - localReport(c.config, symx.ast) - - symx = nextOverloadIter(o, c, headSymbol) - - if match == nil: return - var callExpr = newNodeI(nkCall, n.info) - callExpr.add newSymNode(match) - callExpr.add n - case match.kind - of skMacro: result = semMacroExpr(c, callExpr, match, flags) - of skTemplate: result = semTemplateExpr(c, callExpr, match, flags) - else: result = nil - -proc handleForLoopMacro(c: PContext; n: PNode; flags: TExprFlags): PNode = - result = handleStmtMacro(c, n, n[^2], "ForLoopStmt", flags) - -proc handleCaseStmtMacro(c: PContext; n: PNode; flags: TExprFlags): PNode = - # n[0] has been sem'checked and has a type. We use this to resolve - # '`case`(n[0])' but then we pass 'n' to the `case` macro. This seems to - # be the best solution. - var toResolve = newNodeI(nkCall, n.info) - toResolve.add newIdentNode(getIdent(c.cache, "case"), n.info) - toResolve.add n[0] - - var errors: seq[SemCallMismatch] - var r = resolveOverloads(c, toResolve, {skTemplate, skMacro}, {}, errors) - if r.state == csMatch: - var match = r.calleeSym - markUsed(c, n[0].info, match) - onUse(n[0].info, match) - - # but pass 'n' to the `case` macro, not 'n[0]': - r.call[1] = n - let toExpand = semResolvedCall(c, r, r.call, {}) - case match.kind - of skMacro: result = semMacroExpr(c, toExpand, match, flags) - of skTemplate: result = semTemplateExpr(c, toExpand, match, flags) - else: result = nil - else: - assert r.call.kind == nkError - result = r.call # xxx: hope this is nkError - # this would be the perfectly consistent solution with 'for loop macros', - # but it kinda sucks for pattern matching as the matcher is not attached to - # a type then: - when false: - result = handleStmtMacro(c, n, n[0], "CaseStmt") - proc semFor(c: PContext, n: PNode; flags: TExprFlags): PNode = checkMinSonsLen(n, 3, c.config) - result = handleForLoopMacro(c, n, flags) - if result != nil: return result openScope(c) result = n n[^2] = semExprNoDeref(c, n[^2], {efWantIterator}) @@ -1748,9 +1673,6 @@ proc semCase(c: PContext, n: PNode; flags: TExprFlags): PNode = else: popCaseContext(c) closeScope(c) - result = handleCaseStmtMacro(c, n, flags) - if result != nil: - return result result[0] = c.config.newError(n[0], reportSem rsemSelectorMustBeOfCertainTypes) return for i in 1..`_ This module implements color handling for Nim. -* `enumerate `_ - This module implements `enumerate` syntactic sugar based on Nim's macro system. - * `logging `_ This module implements a simple logger. diff --git a/doc/manual.rst b/doc/manual.rst index 6c68016e3a0..87c07d48ee3 100644 --- a/doc/manual.rst +++ b/doc/manual.rst @@ -4429,43 +4429,6 @@ parameters of an outer factory proc: for f in foo(): echo f -The call can be made more like an inline iterator with a for loop macro: - -.. code-block:: nim - import std/macros - macro toItr(x: ForLoopStmt): untyped = - let expr = x[0] - let call = x[1][1] # Get foo out of toItr(foo) - let body = x[2] - result = quote do: - block: - let itr = `call` - for `expr` in itr(): - `body` - - for f in toItr(mycount(1, 4)): # using early `proc mycount` - echo f - -Because of full backend function call aparatus involvment, closure iterator -invocation is typically higher cost than inline iterators. Adornment by -a macro wrapper at the call site like this is a possibly useful reminder. - -The factory `proc`, as an ordinary procedure, can be recursive. The -above macro allows such recursion to look much like a recursive iterator -would. For example: - -.. code-block:: nim - proc recCountDown(n: int): iterator(): int = - result = iterator(): int = - if n > 0: - yield n - for e in toItr(recCountDown(n - 1)): - yield e - - for i in toItr(recCountDown(6)): # Emits: 6 5 4 3 2 1 - echo i - - See also see `iterable <#overloading-resolution-iterable>`_ for passing iterators to templates and macros. Converters @@ -6018,110 +5981,6 @@ as arguments if called in statement form. echo num -For loop macro --------------- - -A macro that takes as its only input parameter an expression of the special -type `system.ForLoopStmt` can rewrite the entirety of a `for` loop: - -.. code-block:: nim - :test: "nim c $1" - - import std/macros - - macro example(loop: ForLoopStmt) = - result = newTree(nnkForStmt) # Create a new For loop. - result.add loop[^3] # This is "item". - result.add loop[^2][^1] # This is "[1, 2, 3]". - result.add newCall(bindSym"echo", loop[0]) - - for item in example([1, 2, 3]): discard - -Expands to: - -.. code-block:: nim - for item in items([1, 2, 3]): - echo item - -Another example: - -.. code-block:: nim - :test: "nim c $1" - - import std/macros - - macro enumerate(x: ForLoopStmt): untyped = - expectKind x, nnkForStmt - # check if the starting count is specified: - var countStart = if x[^2].len == 2: newLit(0) else: x[^2][1] - result = newStmtList() - # we strip off the first for loop variable and use it as an integer counter: - result.add newVarStmt(x[0], countStart) - var body = x[^1] - if body.kind != nnkStmtList: - body = newTree(nnkStmtList, body) - body.add newCall(bindSym"inc", x[0]) - var newFor = newTree(nnkForStmt) - for i in 1..x.len-3: - newFor.add x[i] - # transform enumerate(X) to 'X' - newFor.add x[^2][^1] - newFor.add body - result.add newFor - # now wrap the whole macro in a block to create a new scope - result = quote do: - block: `result` - - for a, b in enumerate(items([1, 2, 3])): - echo a, " ", b - - # without wrapping the macro in a block, we'd need to choose different - # names for `a` and `b` here to avoid redefinition errors - for a, b in enumerate(10, [1, 2, 3, 5]): - echo a, " ", b - - -Case statement macros ---------------------- - -Macros named `` `case` `` can provide implementations of `case` statements -for certain types. The following is an example of such an implementation -for tuples, leveraging the existing equality operator for tuples -(as provided in `system.==`): - -.. code-block:: nim - :test: "nim c $1" - import std/macros - - macro `case`(n: tuple): untyped = - result = newTree(nnkIfStmt) - let selector = n[0] - for i in 1 ..< n.len: - let it = n[i] - case it.kind - of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr: - result.add it - of nnkOfBranch: - for j in 0..it.len-2: - let cond = newCall("==", selector, it[j]) - result.add newTree(nnkElifBranch, cond, it[^1]) - else: - error "custom 'case' for tuple cannot handle this node", it - - case ("foo", 78) - of ("foo", 78): echo "yes" - of ("bar", 88): echo "no" - else: discard - -`case` macros are subject to overload resolution. The type of the -`case` statement's selector expression is matched against the type -of the first argument of the `case` macro. Then the complete `case` -statement is passed in place of the argument and the macro is evaluated. - -In other words, the macro needs to transform the full `case` statement -but only the statement's selector expression is used to determine which -macro to call. - Special Types ============= diff --git a/lib/pure/collections/lists.nim b/lib/pure/collections/lists.nim index d1de0ea6725..6f8aa397785 100644 --- a/lib/pure/collections/lists.nim +++ b/lib/pure/collections/lists.nim @@ -268,7 +268,7 @@ iterator mitems*[T](L: var SomeLinkedRing[T]): var T = itemsRingImpl() iterator nodes*[T](L: SomeLinkedList[T]): SomeLinkedNode[T] = - ## Iterates over every node of `x`. Removing the current node from the + ## Iterates over every node of `L`. Removing the current node from the ## list during traversal is supported. ## ## **See also:** @@ -293,7 +293,7 @@ iterator nodes*[T](L: SomeLinkedList[T]): SomeLinkedNode[T] = it = nxt iterator nodes*[T](L: SomeLinkedRing[T]): SomeLinkedNode[T] = - ## Iterates over every node of `x`. Removing the current node from the + ## Iterates over every node of `L`. Removing the current node from the ## list during traversal is supported. ## ## **See also:** @@ -319,6 +319,22 @@ iterator nodes*[T](L: SomeLinkedRing[T]): SomeLinkedNode[T] = it = nxt if it == L.head: break +iterator enumerate*[T](L: SomeLinkedList[T]): (int, T) = + ## Iterates over every node of `L`, yielding `(count, value)` tuples with + ## count starting at `0`. + var i = 0 + for n in L.items: + yield (i, n) + inc i + +iterator enumerate*[T](L: SomeLinkedRing[T]): (int, T) = + ## Iterates over every node of `L`, yielding `(count, value)` tuples with + ## count starting at `0`. + var i = 0 + for n in L.items: + yield (i, n) + inc i + proc `$`*[T](L: SomeLinkedCollection[T]): string = ## Turns a list into its string representation for logging and printing. runnableExamples: @@ -390,7 +406,7 @@ proc prependMoved*[T: SomeLinkedList](a, b: var T) {.since: (1, 5, 1).} = ## * `prepend proc <#prepend,T,T>`_ ## for prepending a copy of a list runnableExamples: - import std/[sequtils, enumerate, sugar] + import std/[sequtils, sugar] var a = [4, 5].toSinglyLinkedList b = [1, 2, 3].toSinglyLinkedList @@ -515,7 +531,7 @@ proc addMoved*[T](a, b: var SinglyLinkedList[T]) {.since: (1, 5, 1).} = ## **See also:** ## * `add proc <#add,T,T>`_ for adding a copy of a list runnableExamples: - import std/[sequtils, enumerate, sugar] + import std/[sequtils, sugar] var a = [1, 2, 3].toSinglyLinkedList b = [4, 5].toSinglyLinkedList @@ -659,7 +675,7 @@ proc addMoved*[T](a, b: var DoublyLinkedList[T]) {.since: (1, 5, 1).} = ## * `add proc <#add,T,T>`_ ## for adding a copy of a list runnableExamples: - import std/[sequtils, enumerate, sugar] + import std/[sequtils, sugar] var a = [1, 2, 3].toDoublyLinkedList b = [4, 5].toDoublyLinkedList @@ -712,7 +728,7 @@ proc remove*[T](L: var SinglyLinkedList[T], n: SinglyLinkedNode[T]): bool {.disc ## Attempting to remove an element not contained in the list is a no-op. ## When the list is cyclic, the cycle is preserved after removal. runnableExamples: - import std/[sequtils, enumerate, sugar] + import std/[sequtils, sugar] var a = [0, 1, 2].toSinglyLinkedList let n = a.head.next assert n.value == 1 @@ -749,7 +765,7 @@ proc remove*[T](L: var DoublyLinkedList[T], n: DoublyLinkedNode[T]) = ## otherwise the effects are undefined. ## When the list is cyclic, the cycle is preserved after removal. runnableExamples: - import std/[sequtils, enumerate, sugar] + import std/[sequtils, sugar] var a = [0, 1, 2].toSinglyLinkedList let n = a.head.next assert n.value == 1 diff --git a/lib/pure/options.nim b/lib/pure/options.nim index 850bfa555d4..2ba6709b2d5 100644 --- a/lib/pure/options.nim +++ b/lib/pure/options.nim @@ -42,29 +42,6 @@ raises `UnpackDefect` if there is no value. Note that `UnpackDefect` inherits from `system.Defect` and should therefore never be caught. Instead, rely on checking if the option contains a value with the `isSome <#isSome,Option[T]>`_ and `isNone <#isNone,Option[T]>`_ procs. - - -Pattern matching -================ - -.. note:: This requires the [fusion](https://github.com/nim-lang/fusion) package. - -[fusion/matching](https://nim-lang.github.io/fusion/src/fusion/matching.html) -supports pattern matching on `Option`s, with the `Some()` and -`None()` patterns. - -.. code-block:: nim - {.experimental: "caseStmtMacros".} - - import fusion/matching - - case some(42) - of Some(@a): - assert a == 42 - of None(): - assert false - - assertMatch(some(some(none(int))), Some(Some(None()))) ]## # xxx pending https://github.com/timotheecour/Nim/issues/376 use `runnableExamples` and `whichModule` diff --git a/lib/std/enumerate.nim b/lib/std/enumerate.nim deleted file mode 100644 index a8f0e1ba7f8..00000000000 --- a/lib/std/enumerate.nim +++ /dev/null @@ -1,70 +0,0 @@ -# -# -# Nim's Runtime Library -# (c) Copyright 2020 Nim contributors -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -## This module implements `enumerate` syntactic sugar based on Nim's -## macro system. - -import std/private/since -import macros - - -macro enumerate*(x: ForLoopStmt): untyped {.since: (1, 3).} = - ## Enumerating iterator for collections. - ## - ## It yields `(count, value)` tuples (which must be immediately unpacked). - ## The default starting count `0` can be manually overridden if needed. - runnableExamples: - let a = [10, 20, 30] - var b: seq[(int, int)] - for i, x in enumerate(a): - b.add((i, x)) - assert b == @[(0, 10), (1, 20), (2, 30)] - - let c = "abcd" - var d: seq[(int, char)] - for (i, x) in enumerate(97, c): - d.add((i, x)) - assert d == @[(97, 'a'), (98, 'b'), (99, 'c'), (100, 'd')] - - template genCounter(x): untyped = - # We strip off the first for loop variable and use it as an integer counter. - # We must immediately decrement it by one, because it gets incremented before - # the loop body - to be able to use the final expression in other macros. - newVarStmt(x, infix(countStart, "-", newLit(1))) - - template genInc(x): untyped = - newCall(bindSym"inc", x) - - expectKind x, nnkForStmt - # check if the starting count is specified: - var countStart = if x[^2].len == 2: newLit(0) else: x[^2][1] - result = newStmtList() - var body = x[^1] - if body.kind != nnkStmtList: - body = newTree(nnkStmtList, body) - var newFor = newTree(nnkForStmt) - if x.len == 3: # single iteration variable - if x[0].kind == nnkVarTuple: # for (x, y, ...) in iter - result.add genCounter(x[0][0]) - body.insert(0, genInc(x[0][0])) - for i in 1 .. x[0].len-2: - newFor.add x[0][i] - else: - error("Missing second for loop variable") # for x in iter - else: # for x, y, ... in iter - result.add genCounter(x[0]) - body.insert(0, genInc(x[0])) - for i in 1 .. x.len-3: - newFor.add x[i] - # transform enumerate(X) to 'X' - newFor.add x[^2][^1] - newFor.add body - result.add newFor - # now wrap the whole macro in a block to create a new scope - result = newBlockStmt(result) diff --git a/lib/system.nim b/lib/system.nim index fd9ada76617..cc8e67c9ea0 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -3102,11 +3102,6 @@ proc toOpenArrayByte*(x: openArray[char]; first, last: int): openArray[byte] {. proc toOpenArrayByte*(x: seq[char]; first, last: int): openArray[byte] {. magic: "Slice".} -type - ForLoopStmt* {.compilerproc.} = object ## \ - ## A special type that marks a macro as a `for-loop macro`:idx:. - ## See `"For Loop Macro" `_. - when defined(genode): var componentConstructHook*: proc (env: GenodeEnv) {.nimcall.} ## Hook into the Genode component bootstrap process. diff --git a/tests/effects/tstrict_funcs_imports.nim b/tests/effects/tstrict_funcs_imports.nim index 7e42733fedf..5a44a1a1b77 100644 --- a/tests/effects/tstrict_funcs_imports.nim +++ b/tests/effects/tstrict_funcs_imports.nim @@ -134,7 +134,6 @@ import std/[ compilesettings, editdistance, effecttraits, - enumerate, enumutils, exitprocs, isolation, diff --git a/tests/js/tstdlib_imports.nim b/tests/js/tstdlib_imports.nim index 8633c48789b..f2f3ca6bd56 100644 --- a/tests/js/tstdlib_imports.nim +++ b/tests/js/tstdlib_imports.nim @@ -63,7 +63,7 @@ import std/[ # fails due to copyMem/endians import: sha1 # Miscellaneous: - colors, logging, sugar, unittest, varints, enumerate, with, + colors, logging, sugar, unittest, varints, with, # fails due to FFI: browsers # works but uses FFI: segfaults diff --git a/tests/macros/tcasestmtmacro.nim b/tests/macros/tcasestmtmacro.nim deleted file mode 100644 index 32019a92a6c..00000000000 --- a/tests/macros/tcasestmtmacro.nim +++ /dev/null @@ -1,33 +0,0 @@ -discard """ - output: ''' -yes -''' -""" - -import macros - -macro `case`(n: tuple): untyped = - result = newTree(nnkIfStmt) - let selector = n[0] - for i in 1 ..< n.len: - let it = n[i] - case it.kind - of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr: - result.add it - of nnkOfBranch: - for j in 0..it.len-2: - let cond = newCall("==", selector, it[j]) - result.add newTree(nnkElifBranch, cond, it[^1]) - else: - error "custom 'case' for tuple cannot handle this node", it - -var correct = false - -case ("foo", 78) -of ("foo", 78): - correct = true - echo "yes" -of ("bar", 88): echo "no" -else: discard - -doAssert correct diff --git a/tests/macros/tforloop_macro1.nim b/tests/macros/tforloop_macro1.nim deleted file mode 100644 index a8f45c7ac44..00000000000 --- a/tests/macros/tforloop_macro1.nim +++ /dev/null @@ -1,44 +0,0 @@ -discard """ - output: '''0 1 -1 2 -2 3 -0 1 -1 2 -2 3 -0 1 -1 2 -2 3 -3 5''' -""" - -import macros - -macro mymacro(): untyped = - result = newLit([1, 2, 3]) - -for a, b in mymacro(): - echo a, " ", b - -macro enumerate(x: ForLoopStmt): untyped = - expectKind x, nnkForStmt - # we strip off the first for loop variable and use - # it as an integer counter: - result = newStmtList() - result.add newVarStmt(x[0], newLit(0)) - var body = x[^1] - if body.kind != nnkStmtList: - body = newTree(nnkStmtList, body) - body.add newCall(bindSym"inc", x[0]) - var newFor = newTree(nnkForStmt) - for i in 1..x.len-3: - newFor.add x[i] - # transform enumerate(X) to 'X' - newFor.add x[^2][1] - newFor.add body - result.add newFor - -for a, b in enumerate(items([1, 2, 3])): - echo a, " ", b - -for a2, b2 in enumerate([1, 2, 3, 5]): - echo a2, " ", b2 diff --git a/tests/pragmas/mpushexperimental.nim b/tests/pragmas/mpushexperimental.nim deleted file mode 100644 index 569861c1d9c..00000000000 --- a/tests/pragmas/mpushexperimental.nim +++ /dev/null @@ -1,30 +0,0 @@ - -import macros - -macro enumerate(x: ForLoopStmt): untyped = - expectKind x, nnkForStmt - # we strip off the first for loop variable and use - # it as an integer counter: - result = newStmtList() - result.add newVarStmt(x[0], newLit(0)) - var body = x[^1] - if body.kind != nnkStmtList: - body = newTree(nnkStmtList, body) - body.add newCall(bindSym"inc", x[0]) - var newFor = newTree(nnkForStmt) - for i in 1..x.len-3: - newFor.add x[i] - # transform enumerate(X) to 'X' - newFor.add x[^2][1] - newFor.add body - result.add newFor - -proc main*[T](x: T) = - {.push experimental: "forLoopMacros".} - - for a, b in enumerate(items([1, 2, 3])): - echo a, " ", b - - for a2, b2 in enumerate([1, 2, 3, 5]): - echo a2, " ", b2 - {.pop.} diff --git a/tests/pragmas/tpushexperimental.nim b/tests/pragmas/tpushexperimental.nim deleted file mode 100644 index 301419f607d..00000000000 --- a/tests/pragmas/tpushexperimental.nim +++ /dev/null @@ -1,13 +0,0 @@ -discard """ - output: '''0 1 -1 2 -2 3 -0 1 -1 2 -2 3 -3 5''' -""" - -import mpushexperimental - -main(12) diff --git a/tests/stdlib/tenumerate.nim b/tests/stdlib/tenumerate.nim deleted file mode 100644 index 7a1c2d10a1c..00000000000 --- a/tests/stdlib/tenumerate.nim +++ /dev/null @@ -1,19 +0,0 @@ -import std/enumerate - -let a = @[1, 3, 5, 7] - -block: - var res: seq[(int, int)] - for i, x in enumerate(a): - res.add (i, x) - doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)] -block: - var res: seq[(int, int)] - for (i, x) in enumerate(a.items): - res.add (i, x) - doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)] -block: - var res: seq[(int, int)] - for i, x in enumerate(3, a): - res.add (i, x) - doAssert res == @[(3, 1), (4, 3), (5, 5), (6, 7)] diff --git a/tests/stylecheck/tstyle_imports.nim b/tests/stylecheck/tstyle_imports.nim index b0242a159b9..17fe9a9fd71 100644 --- a/tests/stylecheck/tstyle_imports.nim +++ b/tests/stylecheck/tstyle_imports.nim @@ -140,7 +140,6 @@ import std/[ compilesettings, editdistance, effecttraits, - enumerate, enumutils, exitprocs, isolation, diff --git a/tests/test_nimscript.nims b/tests/test_nimscript.nims index ffb35e074ad..072606da57d 100644 --- a/tests/test_nimscript.nims +++ b/tests/test_nimscript.nims @@ -65,7 +65,7 @@ import std/[ # fails due to copyMem/endians import: sha1 # Miscellaneous: - colors, sugar, varints, enumerate, with, + colors, sugar, varints, with, # fails due to FFI: browsers, segfaults # fails due to times import/methods: logging # fails due to methods: unittest