This commit is contained in:
Andreas Rumpf 2017-10-30 14:45:57 +01:00
commit b14cc1e3b2
8 changed files with 65 additions and 38 deletions

View file

@ -24,8 +24,9 @@
use the ``pred`` proc. use the ``pred`` proc.
- We changed how array accesses "from backwards" like ``a[^1]`` or ``a[0..^1]`` are - We changed how array accesses "from backwards" like ``a[^1]`` or ``a[0..^1]`` are
implemented. These are now implemented purely in ``system.nim`` without compiler implemented. These are now implemented purely in ``system.nim`` without compiler
support. ``system.Slice`` now takes 2 generic parameters so that it can support. There is a new "heterogenous" slice type ``system.HSlice`` that takes 2
take ``BackwardsIndex`` indices. ``BackwardsIndex`` is produced by ``system.^``. generic parameters which can be ``BackwardsIndex`` indices. ``BackwardsIndex`` is
produced by ``system.^``.
This means if you overload ``[]`` or ``[]=`` you need to ensure they also work This means if you overload ``[]`` or ``[]=`` you need to ensure they also work
with ``system.BackwardsIndex`` (if applicable for the accessors). with ``system.BackwardsIndex`` (if applicable for the accessors).
- ``mod`` and bitwise ``and`` do not produce ``range`` subtypes anymore. This - ``mod`` and bitwise ``and`` do not produce ``range`` subtypes anymore. This

View file

@ -155,7 +155,7 @@ type
## - ``"abc".match(re"(?<letter>\w)").captures["letter"] == "a"`` ## - ``"abc".match(re"(?<letter>\w)").captures["letter"] == "a"``
## - ``"abc".match(re"(\w)\w").captures[-1] == "ab"`` ## - ``"abc".match(re"(\w)\w").captures[-1] == "ab"``
## ##
## ``captureBounds[]: Option[Slice[int, int]]`` ## ``captureBounds[]: Option[HSlice[int, int]]``
## gets the bounds of the given capture according to the same rules as ## gets the bounds of the given capture according to the same rules as
## the above. If the capture is not filled, then ``None`` is returned. ## the above. If the capture is not filled, then ``None`` is returned.
## The bounds are both inclusive. ## The bounds are both inclusive.
@ -167,7 +167,7 @@ type
## ``match: string`` ## ``match: string``
## the full text of the match. ## the full text of the match.
## ##
## ``matchBounds: Slice[int, int]`` ## ``matchBounds: HSlice[int, int]``
## the bounds of the match, as in ``captureBounds[]`` ## the bounds of the match, as in ``captureBounds[]``
## ##
## ``(captureBounds|captures).toTable`` ## ``(captureBounds|captures).toTable``
@ -182,7 +182,7 @@ type
## Not nil. ## Not nil.
str*: string ## The string that was matched against. str*: string ## The string that was matched against.
## Not nil. ## Not nil.
pcreMatchBounds: seq[Slice[cint, cint]] ## First item is the bounds of the match pcreMatchBounds: seq[HSlice[cint, cint]] ## First item is the bounds of the match
## Other items are the captures ## Other items are the captures
## `a` is inclusive start, `b` is exclusive end ## `a` is inclusive start, `b` is exclusive end
@ -251,13 +251,13 @@ proc captureBounds*(pattern: RegexMatch): CaptureBounds = return CaptureBounds(p
proc captures*(pattern: RegexMatch): Captures = return Captures(pattern) proc captures*(pattern: RegexMatch): Captures = return Captures(pattern)
proc `[]`*(pattern: CaptureBounds, i: int): Option[Slice[int, int]] = proc `[]`*(pattern: CaptureBounds, i: int): Option[HSlice[int, int]] =
let pattern = RegexMatch(pattern) let pattern = RegexMatch(pattern)
if pattern.pcreMatchBounds[i + 1].a != -1: if pattern.pcreMatchBounds[i + 1].a != -1:
let bounds = pattern.pcreMatchBounds[i + 1] let bounds = pattern.pcreMatchBounds[i + 1]
return some(int(bounds.a) .. int(bounds.b-1)) return some(int(bounds.a) .. int(bounds.b-1))
else: else:
return none(Slice[int, int]) return none(HSlice[int, int])
proc `[]`*(pattern: Captures, i: int): string = proc `[]`*(pattern: Captures, i: int): string =
let pattern = RegexMatch(pattern) let pattern = RegexMatch(pattern)
@ -272,10 +272,10 @@ proc `[]`*(pattern: Captures, i: int): string =
proc match*(pattern: RegexMatch): string = proc match*(pattern: RegexMatch): string =
return pattern.captures[-1] return pattern.captures[-1]
proc matchBounds*(pattern: RegexMatch): Slice[int, int] = proc matchBounds*(pattern: RegexMatch): HSlice[int, int] =
return pattern.captureBounds[-1].get return pattern.captureBounds[-1].get
proc `[]`*(pattern: CaptureBounds, name: string): Option[Slice[int, int]] = proc `[]`*(pattern: CaptureBounds, name: string): Option[HSlice[int, int]] =
let pattern = RegexMatch(pattern) let pattern = RegexMatch(pattern)
return pattern.captureBounds[pattern.pattern.captureNameToId.fget(name)] return pattern.captureBounds[pattern.pattern.captureNameToId.fget(name)]
@ -295,9 +295,9 @@ proc toTable*(pattern: Captures, default: string = nil): Table[string, string] =
result = initTable[string, string]() result = initTable[string, string]()
toTableImpl(nextVal == nil) toTableImpl(nextVal == nil)
proc toTable*(pattern: CaptureBounds, default = none(Slice[int, int])): proc toTable*(pattern: CaptureBounds, default = none(HSlice[int, int])):
Table[string, Option[Slice[int, int]]] = Table[string, Option[HSlice[int, int]]] =
result = initTable[string, Option[Slice[int, int]]]() result = initTable[string, Option[HSlice[int, int]]]()
toTableImpl(nextVal.isNone) toTableImpl(nextVal.isNone)
template itemsImpl(cond: untyped) {.dirty.} = template itemsImpl(cond: untyped) {.dirty.} =
@ -309,13 +309,13 @@ template itemsImpl(cond: untyped) {.dirty.} =
yield nextYieldVal yield nextYieldVal
iterator items*(pattern: CaptureBounds, default = none(Slice[int, int])): Option[Slice[int, int]] = iterator items*(pattern: CaptureBounds, default = none(HSlice[int, int])): Option[HSlice[int, int]] =
itemsImpl(nextVal.isNone) itemsImpl(nextVal.isNone)
iterator items*(pattern: Captures, default: string = nil): string = iterator items*(pattern: Captures, default: string = nil): string =
itemsImpl(nextVal == nil) itemsImpl(nextVal == nil)
proc toSeq*(pattern: CaptureBounds, default = none(Slice[int, int])): seq[Option[Slice[int, int]]] = proc toSeq*(pattern: CaptureBounds, default = none(HSlice[int, int])): seq[Option[HSlice[int, int]]] =
accumulateResult(pattern.items(default)) accumulateResult(pattern.items(default))
proc toSeq*(pattern: Captures, default: string = nil): seq[string] = proc toSeq*(pattern: Captures, default: string = nil): seq[string] =
@ -462,7 +462,7 @@ proc matchImpl(str: string, pattern: Regex, start, endpos: int, flags: int): Opt
# 1x capture count as slack space for PCRE # 1x capture count as slack space for PCRE
let vecsize = (pattern.captureCount() + 1) * 3 let vecsize = (pattern.captureCount() + 1) * 3
# div 2 because each element is 2 cints long # div 2 because each element is 2 cints long
myResult.pcreMatchBounds = newSeq[Slice[cint, cint]](ceil(vecsize / 2).int) myResult.pcreMatchBounds = newSeq[HSlice[cint, cint]](ceil(vecsize / 2).int)
myResult.pcreMatchBounds.setLen(vecsize div 3) myResult.pcreMatchBounds.setLen(vecsize div 3)
let strlen = if endpos == int.high: str.len else: endpos+1 let strlen = if endpos == int.high: str.len else: endpos+1

View file

@ -425,7 +425,7 @@ proc rotatedInternal[T](arg: openarray[T]; first, middle, last: int): seq[T] =
for i in last ..< arg.len: for i in last ..< arg.len:
result[i] = arg[i] result[i] = arg[i]
proc rotateLeft*[T](arg: var openarray[T]; slice: Slice[int, int]; dist: int): int = proc rotateLeft*[T](arg: var openarray[T]; slice: HSlice[int, int]; dist: int): int =
## Performs a left rotation on a range of elements. If you want to rotate right, use a negative ``dist``. ## Performs a left rotation on a range of elements. If you want to rotate right, use a negative ``dist``.
## Specifically, ``rotateLeft`` rotates the elements at ``slice`` by ``dist`` positions. ## Specifically, ``rotateLeft`` rotates the elements at ``slice`` by ``dist`` positions.
## The element at index ``slice.a + dist`` will be at index ``slice.a``. ## The element at index ``slice.a + dist`` will be at index ``slice.a``.
@ -457,7 +457,7 @@ proc rotateLeft*[T](arg: var openarray[T]; dist: int): int =
let distLeft = ((dist mod arglen) + arglen) mod arglen let distLeft = ((dist mod arglen) + arglen) mod arglen
arg.rotateInternal(0, distLeft, arglen) arg.rotateInternal(0, distLeft, arglen)
proc rotatedLeft*[T](arg: openarray[T]; slice: Slice[int, int], dist: int): seq[T] = proc rotatedLeft*[T](arg: openarray[T]; slice: HSlice[int, int], dist: int): seq[T] =
## same as ``rotateLeft``, just with the difference that it does ## same as ``rotateLeft``, just with the difference that it does
## not modify the argument. It creates a new ``seq`` instead ## not modify the argument. It creates a new ``seq`` instead
let sliceLen = slice.b + 1 - slice.a let sliceLen = slice.b + 1 - slice.a

View file

@ -55,7 +55,7 @@ proc `[]=`*(s: var SharedString; i: Natural; value: char) =
if i < s.len: s.buffer.data[i+s.first] = value if i < s.len: s.buffer.data[i+s.first] = value
else: raise newException(IndexError, "index out of bounds") else: raise newException(IndexError, "index out of bounds")
proc `[]`*(s: SharedString; ab: Slice[int]): SharedString = proc `[]`*(s: SharedString; ab: HSlice[int, int]): SharedString =
#incRef(src.buffer) #incRef(src.buffer)
if ab.a < s.len: if ab.a < s.len:
result.buffer = s.buffer result.buffer = s.buffer

View file

@ -48,7 +48,7 @@ proc validEmailAddress*(s: string): bool {.noSideEffect,
"aero", "jobs", "museum": return true "aero", "jobs", "museum": return true
else: return false else: return false
proc parseInt*(s: string, value: var int, validRange: Slice[int, int]) {. proc parseInt*(s: string, value: var int, validRange: HSlice[int, int]) {.
noSideEffect, rtl, extern: "nmatchParseInt".} = noSideEffect, rtl, extern: "nmatchParseInt".} =
## parses `s` into an integer in the range `validRange`. If successful, ## parses `s` into an integer in the range `validRange`. If successful,
## `value` is modified to contain the result. Otherwise no exception is ## `value` is modified to contain the result. Otherwise no exception is

View file

@ -93,7 +93,7 @@ proc random*(max: float): float {.benign.} =
let u = (0x3FFu64 shl 52u64) or (x shr 12u64) let u = (0x3FFu64 shl 52u64) or (x shr 12u64)
result = (cast[float](u) - 1.0) * max result = (cast[float](u) - 1.0) * max
proc random*[T](x: Slice[T, T]): T = proc random*[T](x: HSlice[T, T]): T =
## For a slice `a .. b` returns a value in the range `a .. b-1`. ## For a slice `a .. b` returns a value in the range `a .. b-1`.
result = T(random(x.b - x.a)) + x.a result = T(random(x.b - x.a)) + x.a

View file

@ -308,14 +308,12 @@ when defined(nimArrIdx):
shallowCopy(x, y) shallowCopy(x, y)
type type
Slice*[T, U] = object ## builtin slice type HSlice*[T, U] = object ## "heterogenous" slice type
a*: T ## the lower bound (inclusive) a*: T ## the lower bound (inclusive)
b*: U ## the upper bound (inclusive) b*: U ## the upper bound (inclusive)
Slice*[T] = HSlice[T, T] ## an alias for ``HSlice[T, T]``
when defined(nimalias): proc `..`*[T, U](a: T, b: U): HSlice[T, U] {.noSideEffect, inline, magic: "DotDot".} =
{.deprecated: [TSlice: Slice].}
proc `..`*[T, U](a: T, b: U): Slice[T, U] {.noSideEffect, inline, magic: "DotDot".} =
## `slice`:idx: operator that constructs an interval ``[a, b]``, both `a` ## `slice`:idx: operator that constructs an interval ``[a, b]``, both `a`
## and `b` are inclusive. Slices can also be used in the set constructor ## and `b` are inclusive. Slices can also be used in the set constructor
## and in ordinal case statements, but then they are special-cased by the ## and in ordinal case statements, but then they are special-cased by the
@ -323,7 +321,7 @@ proc `..`*[T, U](a: T, b: U): Slice[T, U] {.noSideEffect, inline, magic: "DotDot
result.a = a result.a = a
result.b = b result.b = b
proc `..`*[T](b: T): Slice[int, T] {.noSideEffect, inline, magic: "DotDot".} = proc `..`*[T](b: T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot".} =
## `slice`:idx: operator that constructs an interval ``[default(T), b]`` ## `slice`:idx: operator that constructs an interval ``[default(T), b]``
result.b = b result.b = b
@ -1169,7 +1167,7 @@ proc contains*[T](x: set[T], y: T): bool {.magic: "InSet", noSideEffect.}
## is achieved by reversing the parameters for ``contains``; ``in`` then ## is achieved by reversing the parameters for ``contains``; ``in`` then
## passes its arguments in reverse order. ## passes its arguments in reverse order.
proc contains*[T](s: Slice[T, T], value: T): bool {.noSideEffect, inline.} = proc contains*[T](s: HSlice[T, T], value: T): bool {.noSideEffect, inline.} =
## Checks if `value` is within the range of `s`; returns true iff ## Checks if `value` is within the range of `s`; returns true iff
## `value >= s.a and value <= s.b` ## `value >= s.a and value <= s.b`
## ##
@ -2088,7 +2086,7 @@ proc clamp*[T](x, a, b: T): T =
if x > b: return b if x > b: return b
return x return x
proc len*[T: Ordinal](x: Slice[T, T]): int {.noSideEffect, inline.} = proc len*[T: Ordinal](x: HSlice[T, T]): int {.noSideEffect, inline.} =
## length of ordinal slice, when x.b < x.a returns zero length ## length of ordinal slice, when x.b < x.a returns zero length
## ##
## .. code-block:: Nim ## .. code-block:: Nim
@ -2156,7 +2154,7 @@ iterator items*(E: typedesc[enum]): E =
for v in low(E)..high(E): for v in low(E)..high(E):
yield v yield v
iterator items*[T](s: Slice[T, T]): T = iterator items*[T](s: HSlice[T, T]): T =
## iterates over the slice `s`, yielding each value between `s.a` and `s.b` ## iterates over the slice `s`, yielding each value between `s.a` and `s.b`
## (inclusively). ## (inclusively).
for x in s.a..s.b: for x in s.a..s.b:
@ -3457,7 +3455,7 @@ template `^^`(s, i: untyped): untyped =
(when i is BackwardsIndex: s.len - int(i) else: int(i)) (when i is BackwardsIndex: s.len - int(i) else: int(i))
when hasAlloc or defined(nimscript): when hasAlloc or defined(nimscript):
proc `[]`*[T, U](s: string, x: Slice[T, U]): string {.inline.} = proc `[]`*[T, U](s: string, x: HSlice[T, U]): string {.inline.} =
## slice operation for strings. ## slice operation for strings.
## returns the inclusive range [s[x.a], s[x.b]]: ## returns the inclusive range [s[x.a], s[x.b]]:
## ##
@ -3466,7 +3464,7 @@ when hasAlloc or defined(nimscript):
## assert s[1..3] == "bcd" ## assert s[1..3] == "bcd"
result = s.substr(s ^^ x.a, s ^^ x.b) result = s.substr(s ^^ x.a, s ^^ x.b)
proc `[]=`*[T, U](s: var string, x: Slice[T, U], b: string) = proc `[]=`*[T, U](s: var string, x: HSlice[T, U], b: string) =
## slice assignment for strings. If ## slice assignment for strings. If
## ``b.len`` is not exactly the number of elements that are referred to ## ``b.len`` is not exactly the number of elements that are referred to
## by `x`, a `splice`:idx: is performed: ## by `x`, a `splice`:idx: is performed:
@ -3482,7 +3480,7 @@ when hasAlloc or defined(nimscript):
else: else:
spliceImpl(s, a, L, b) spliceImpl(s, a, L, b)
proc `[]`*[Idx, T, U, V](a: array[Idx, T], x: Slice[U, V]): seq[T] = proc `[]`*[Idx, T, U, V](a: array[Idx, T], x: HSlice[U, V]): seq[T] =
## slice operation for arrays. ## slice operation for arrays.
## returns the inclusive range [a[x.a], a[x.b]]: ## returns the inclusive range [a[x.a], a[x.b]]:
## ##
@ -3494,7 +3492,7 @@ proc `[]`*[Idx, T, U, V](a: array[Idx, T], x: Slice[U, V]): seq[T] =
result = newSeq[T](L) result = newSeq[T](L)
for i in 0..<L: result[i] = a[Idx(i + xa + int low(a))] for i in 0..<L: result[i] = a[Idx(i + xa + int low(a))]
proc `[]=`*[Idx, T, U, V](a: var array[Idx, T], x: Slice[U, V], b: openArray[T]) = proc `[]=`*[Idx, T, U, V](a: var array[Idx, T], x: HSlice[U, V], b: openArray[T]) =
## slice assignment for arrays. ## slice assignment for arrays.
let xa = a ^^ x.a let xa = a ^^ x.a
let L = (a ^^ x.b) - xa + 1 let L = (a ^^ x.b) - xa + 1
@ -3503,7 +3501,7 @@ proc `[]=`*[Idx, T, U, V](a: var array[Idx, T], x: Slice[U, V], b: openArray[T])
else: else:
sysFatal(RangeError, "different lengths for slice assignment") sysFatal(RangeError, "different lengths for slice assignment")
proc `[]`*[T, U, V](s: seq[T], x: Slice[U, V]): seq[T] = proc `[]`*[T, U, V](s: openArray[T], x: HSlice[U, V]): seq[T] =
## slice operation for sequences. ## slice operation for sequences.
## returns the inclusive range [s[x.a], s[x.b]]: ## returns the inclusive range [s[x.a], s[x.b]]:
## ##
@ -3515,7 +3513,7 @@ proc `[]`*[T, U, V](s: seq[T], x: Slice[U, V]): seq[T] =
newSeq(result, L) newSeq(result, L)
for i in 0 ..< L: result[i] = s[i + a] for i in 0 ..< L: result[i] = s[i + a]
proc `[]=`*[T, U, V](s: var seq[T], x: Slice[U, V], b: openArray[T]) = proc `[]=`*[T, U, V](s: var seq[T], x: HSlice[U, V], b: openArray[T]) =
## slice assignment for sequences. If ## slice assignment for sequences. If
## ``b.len`` is not exactly the number of elements that are referred to ## ``b.len`` is not exactly the number of elements that are referred to
## by `x`, a `splice`:idx: is performed. ## by `x`, a `splice`:idx: is performed.
@ -3526,12 +3524,16 @@ proc `[]=`*[T, U, V](s: var seq[T], x: Slice[U, V], b: openArray[T]) =
else: else:
spliceImpl(s, a, L, b) spliceImpl(s, a, L, b)
proc `[]`*[T](s: seq[T]; i: BackwardsIndex): T = s[s.len - int(i)] proc `[]`*[T](s: openArray[T]; i: BackwardsIndex): T = s[s.len - int(i)]
proc `[]`*[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T = proc `[]`*[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T =
a[Idx(a.len - int(i) + int low(a))] a[Idx(a.len - int(i) + int low(a))]
proc `[]`*(s: string; i: BackwardsIndex): char = s[s.len - int(i)] proc `[]`*(s: string; i: BackwardsIndex): char = s[s.len - int(i)]
proc `[]=`*[T](s: var seq[T]; i: BackwardsIndex; x: T) = proc `[]`*[T](s: var openArray[T]; i: BackwardsIndex): var T = s[s.len - int(i)]
proc `[]`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T =
a[Idx(a.len - int(i) + int low(a))]
proc `[]=`*[T](s: var openArray[T]; i: BackwardsIndex; x: T) =
s[s.len - int(i)] = x s[s.len - int(i)] = x
proc `[]=`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) = proc `[]=`*[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T) =
a[Idx(a.len - int(i) + int low(a))] = x a[Idx(a.len - int(i) + int low(a))] = x

View file

@ -1,6 +1,10 @@
discard """ discard """
output: '''@[2, 3, 4]321 output: '''@[2, 3, 4]321
9.0 4.0''' 9.0 4.0
3
@[(Field0: 1, Field1: 2), (Field0: 3, Field1: 5)]
2
@[a, new one, c]'''
""" """
proc foo[T](x, y: T): T = x proc foo[T](x, y: T): T = x
@ -11,3 +15,23 @@ echo a[1.. ^1], a[^2], a[^3], a[^4]
echo b[^1][^1], " ", (b[^2]).foo(b[^1])[^1] echo b[^1][^1], " ", (b[^2]).foo(b[^1])[^1]
b[^1] = [8.8, 8.9] b[^1] = [8.8, 8.9]
var c: seq[(int, int)] = @[(1,2), (3,4)]
proc takeA(x: ptr int) = echo x[]
takeA(addr c[^1][0])
c[^1][1] = 5
echo c
proc useOpenarray(x: openArray[int]) =
echo x[^2]
proc mutOpenarray(x: var openArray[string]) =
x[^2] = "new one"
useOpenarray([1, 2, 3])
var z = @["a", "b", "c"]
mutOpenarray(z)
echo z