-
Notifications
You must be signed in to change notification settings - Fork 43
Expand file tree
/
Copy pathsystem.nim
More file actions
651 lines (541 loc) · 23.6 KB
/
Copy pathsystem.nim
File metadata and controls
651 lines (541 loc) · 23.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
## System module for Nimony
{.feature: "lenientnils".}
{.feature: "staticContracts".}
include "system/basic_types"
iterator unpack*(): untyped {.magic: Unpack.}
func unpackToCall(fn: untyped) {.magic: Unpack.}
const
isMainModule* {.magic: "IsMainModule".}: bool = false
Inf* {.magic: "Inf".}: float64 = 0.0
## Contains the IEEE floating point value of positive infinity.
NaN* {.magic: "NaN".}: float64 = 0.0
## Contains an IEEE floating point value of *Not A Number*.
##
## Note that you cannot compare a floating point value to this value
## and expect a reasonable result - use the `isNaN` or `classify` procedure
## in the `math module <math.html>`_ for checking for NaN.
func `[]`*[T: tuple](x: T, i: int): untyped {.magic: "TupAt".}
func `[]`*[I, T](x: array[I, T], i: I): var T {.magic: "ArrAt".}
func `[]`*(x: cstring, i: int): var char {.magic: "Pat".}
func `[]`*[T](x: ptr UncheckedArray[T], i: int): var T {.magic: "Pat".}
func `[]`*[T](x: UncheckedArray[T], i: int): var T {.magic: "Pat".}
template `[]=`*[T: tuple](x: T, i: int, elem: typed) =
(x[i]) = elem
template `[]=`*[I, T](x: array[I, T], i: I; elem: T) =
(x[i]) = elem
template `[]=`*(x: cstring, i: int; elem: char) =
(x[i]) = elem
template `[]=`*[T](x: ptr UncheckedArray[T], i: int; elem: T) =
(x[i]) = elem
template `[]=`*[T](x: UncheckedArray[T], i: int; elem: T) =
(x[i]) = elem
func `[]`*[T](x: ptr T): var T {.magic: "Deref", noSideEffect.}
func `[]`*[T](x: ref T): var T {.magic: "Deref", noSideEffect.}
template `[]=`*[T](x: ptr T, val: T) =
(x[]) = val
template `[]=`*[T](x: ref T, val: T) =
(x[]) = val
include "system/arithmetics"
include "system/comparisons"
func old*(x: int): int {.semantics: "old".} = x
## The value `x` had when the routine was *entered*. Meaningful only inside an
## `.ensures`, which is never evaluated at run time — it is how a routine that
## mutates a `var` parameter states what the mutation leaves alone:
## `ensures: s.len == old(s.len)`.
func defined*(x: untyped): bool {.magic: Defined.}
## Checks whether the symbol named by `x` is defined (typically via `-d:name` or `define`).
func declared*(x: untyped): bool {.magic: Declared.}
## Checks whether the symbol named by `x` is declared in the current scope.
func astToStr*[T](x: T): string {.magic: AstToStr.}
## Converts the AST of `x` into a string representation. This is very useful
## for debugging.
func compiles*(x: untyped): bool {.magic: Compiles.}
## Special compile-time procedure that checks whether `x` can be compiled
## without any semantic error.
## This can be used to check whether a type supports some operation:
## ```nim
## when compiles(3 + 4):
## echo "'+' for integers is available"
## ```
const
# Use string literals for one digit numbers to avoid the allocations as they are so common.
NegTen = [
"-0", "-1", "-2", "-3", "-4",
"-5", "-6", "-7", "-8", "-9"]
func `$`*(x: uint64): string =
result = ""
if x < 10:
result = NegTen[int x].substr(1, 1)
else:
var y = x
while true:
result.add char((y mod 10'u) + uint('0'))
y = y div 10'u
if y == 0'u: break
# Reverse in place. Two converging indices rather than `i` and `last-i`:
# `lo < hi <= len-1` is what proves both accesses, and `len div 2` is not a
# bound the contract prover can follow.
var lo = 0
var hi = result.len-1
while lo < hi:
let ch = result[lo]
result[lo] = result[hi]
result[hi] = ch
inc lo
dec hi
func `$`*(x: int64): string =
if x < 0:
if x > -10:
result = NegTen[int(-x)]
elif x == -9223372036854775808:
result = "-" & $cast[uint64](x)
else:
result = "-" & $(0-x)
elif x < 10:
result = ""
result.add char(x + int64('0'))
else:
result = $cast[uint64](x)
func `$`*(x: int32): string =
$(int64(x))
func addInt*(s: var string; x: int64) {.inline.} =
s.add $x
func addInt*(s: var string; x: uint64) {.inline.} =
s.add $x
func `$`*(b: bool): string =
if b: "true" else: "false"
func `$`*[T: enum](x: T): string {.magic: "EnumToStr", noSideEffect.}
## Converts an enum value to a string.
type Stringable* = concept
## A type that can be rendered as a `string` via the `$` operator. Generic
## code that stringifies an abstract type parameter `T` should constrain it
## with `[T: Stringable]`, since nimony binds generic bodies eagerly.
func `$`(x: Self): string
func addr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.}
## Returns the address of `x`.
func unsafeAddr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.}
func sizeof*[T](x: typedesc[T]): int {.magic: "SizeOf", noSideEffect.}
## Returns the size of type `T` in bytes.
template sizeof*[T](_: T): int =
## Returns the size in bytes of the type of the given value.
sizeof(T)
func `=destroy`*[T](x: T) {.magic: "Destroy", noSideEffect.}
func `=dup`*[T](x: T): T {.magic: "Dup", noSideEffect.}
func `=copy`*[T](dest: var T; src: T) {.magic: "Copy", noSideEffect.}
func `=wasMoved`*[T](x: var T) {.magic: "WasMoved", noSideEffect.}
func `=sink`*[T](dest: var T; src: T) {.magic: "SinkHook", noSideEffect.}
func `=trace`*[T](x: var T; env: pointer) {.magic: "Trace", noSideEffect.}
func ensureMove*[T](x: T): T {.magic: "EnsureMove", noSideEffect.}
## Hint for the compiler to treat `x` as a moved-from value where applicable.
func move*[T](x: var T): T {.nodestroy, inline, noSideEffect.} =
## Moves `x` out: returns its value and leaves `x` in a moved-from state.
result = x
`=wasMoved`(x)
template len*[I, T](x: typedesc[array[I, T]]): int =
## Returns the length of an array type.
## This is roughly the same as `high(T)-low(T)+1`.
high(array[I, T]).int - low(array[I, T]).int + 1
template len*[I, T](x: array[I, T]): int =
## Returns the length of an array.
## This is roughly the same as `high(T)-low(T)+1`.
len(array[I, T])
func swap*[T](x, y: var T) {.inline, nodestroy.} =
## Swaps two values bitwise without invoking `=sink`, `=copy`, or `=dup`.
let tmp = x
x = y
y = tmp
template `in`*(x, y: untyped): untyped =
contains(y, x)
template `notin`*(x, y: untyped): untyped =
not contains(y, x)
func `is`*[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
## True if `x` has exactly type `S` (compile-time check).
template `isnot`*(x, y: untyped): untyped =
not (x is y)
include "system/iterators"
include "system/defaults"
include "system/countbits_impl"
include "system/setops"
include "system/ctypes"
when defined(embedded):
# The console of a bare-metal image, and its `exit`. Included BEFORE `exits`,
# which uses it, and only on the target that has no OS to ask instead.
include "system/semihosting"
include "system/exits"
include "system/atomintrin"
include "system/memory"
template linear*() {.pragma.}
## Marks an indexed accessor (`[]=`, or a `var T`-returning `[]`) as *linear*:
## for distinct keys it yields distinct, non-aliasing, stable locations and
## never invalidates a previously obtained location. `std/parfor`'s `||` uses
## this to allow parallel `c[i] = …` writes. `seq`/array indexing is linear;
## `Table` indexing is not (it may rehash and relocate other slots).
include "system/seqimpl"
include "system/stringimpl"
include "system/openarrays"
# The memory management strategy, chosen by `--mm:NAME`: `$MM` expands to
# `system/<name>`, so a strategy is a file and needs no `when` chain here.
include "$MM"
include "system/refops"
func newConstr[T](t: typedesc[T]): T {.magic: "NewRef", nodecl.}
func new*[T: ref](x: out T) {.inline.} = x = newConstr(T)
template runnableExamples*(body: untyped) {.untyped.} =
discard "ignore runnable examples"
func overflowFlag*(): bool {.magic: "OverflowFlag".}
template ord*[T: Ordinal|enum](x: T): int =
## Returns the internal `int` value of `x`, including for enum with holes
## and distinct ordinal types.
int(x)
include "system/panics"
include "system/dyncalls"
func `of`*[T, S](x: T; y: typedesc[S]): bool {.magic: "Of", noSideEffect.}
## True if `x`'s runtime type is `S` or a subtype (runtime subtype check).
func procCall*[T](x: T): untyped {.magic: "ProcCall".}
type
Rtti* = object
dl: int
dy: ptr UncheckedArray[uint32]
mt: UncheckedArray[pointer]
func getRtti(dummy: pointer): ptr Rtti {.nodecl, noinit.} = discard "patched by vtables.nim"
type
ComparableAndNegatable = concept
func `<`(x, y: Self): bool
func `-`(x: Self): Self
func abs*[T: ComparableAndNegatable](x: T): T {.inline.} =
## Returns the absolute value of `x`.
if x < 0: -x else: x
template isNil*(s: cstring): bool = s == nil
func chr*(u: range[0..255]): char {.inline.} =
## Converts `u` to a `char`, same as `char(u)`.
char(u.int)
include "system/formatfloat"
include "errorcodes/errorcodes"
var localErr* {.threadvar.}: ErrorCode
type
ContinuationProc* = proc (coro: ptr CoroutineBase): Continuation {.nimcall.}
Continuation* = object
fn*: ContinuationProc
env*: ptr CoroutineBase
CoroutineBase* = object of RootObj
caller*: Continuation
callee*: ptr CoroutineBase
yielded*: bool
## Set by an iterator's `yield`, cleared by the `for` loop that takes the
## value (`iterYielded`). A step that lands in this frame is not by
## itself a yield: a passive proc the iterator called returns into it too.
method cancel*(coro: ptr CoroutineBase) =
discard "to override"
func delay*(): Continuation {.magic: "Delay".}
## Creates a continuation for the current coroutine's own continuation from the point
## of the call to `suspend` forward. Think of it as a reification of the "semicolon": To split up `a; b` use
## `a; let cont = delay(); suspend(); b`.
func delay*(x: typed): Continuation {.magic: "Delay".}
## Delays the execution of a `.passive` proc and returns a continuation representation
## this call. Think of it as a `toTask` builtin.
proc suspend*() {.magic: "Suspend".}
## Parks the current coroutine. In CPS, this inserts
## `return Continuation(fn: nil, env: this)`.
proc trivialTick(c: Continuation): Continuation =
result = c.fn(c.env)
type
Scheduler* = proc (c: Continuation): Continuation {.nimcall.}
## A scheduler is a function that takes a continuation and returns a new continuation.
var scheduler: Scheduler = trivialTick
proc setScheduler*(handler: Scheduler) {.inline.} =
# XXX needs atomic store here
scheduler = handler
proc advance*(c: Continuation): Continuation =
## Single steps through a list of continuations. Usually this does not need
## to be called directly. Used by the compiler to run a coroutine.
result = scheduler(c)
proc complete*(c: Continuation) =
## Used by the compiler to run a coroutine until it has no next step
## (`stopping`): it either finishes or parks (`delay(); suspend()`) to await
## an external scheduler. With the default trivial scheduler a park simply
## stops the loop; a real scheduler resumes parked continuations and drives
## them onward. Takes `c` by value so a coroutine may reassign the variable
## it was driven from (e.g. to reschedule via `delay(call)`). Bare
## `suspend()` transitions synchronously, so it does not stop the loop.
var c = c
while not stopping(c):
c = scheduler(c)
proc parked*(c: Continuation): bool {.inline.} =
## True when a coroutine has parked via `suspend()` and not yet been
## resumed. The `env` field identifies the coroutine frame.
c.fn == nil and c.env != nil
proc stopping*(c: Continuation): bool {.inline.} =
## True when a coroutine has no next step: either finished or parked.
c.fn == nil
proc iterYielded*(c: Continuation; myEnv: ptr CoroutineBase): bool {.inline.} =
## Used by the compiler: did the `for` loop's iterator just yield? Its own
## frame has to be the one that stopped, AND it has to have stopped at a
## `yield` — a passive proc it called returns into the same frame without
## producing a value, and the loop ran its body again for the previous one.
result = c.env != nil and c.env == myEnv and c.env.yielded
if result: c.env.yielded = false
proc iterStopped*(c: Continuation): bool {.inline.} =
## Used by the compiler: the `for` loop's exit test. A PARKED iterator has
## not ended — but this loop cannot wait for it, because the loop and the
## frame it would cancel are both driven from this stack — so it says so
## instead of ending quietly and cancelling a frame the I/O ring still owns.
if parked(c):
panic "a `.passive` iterator parked inside a `for` loop\n"
result = c.fn == nil
proc finished*(c: Continuation): bool {.inline.} =
## True once a coroutine has run to completion. Compatible with
## Nim's `finished` builtin: returns `true` when there are no more values
## to produce. Used by the closure-iterator trampoline that the compiler
## emits for `for x in closureIter(...)` loops.
##
## Parked continuations (`suspend`) are not finished: they have
## `fn == nil` but a non-nil `env`.
c.fn == nil and c.env == nil
proc finalizeCoroutine*(c: var Continuation) =
## Cancels and deallocates a coroutine frame that is still live (i.e.
## the loop exited via `break`/`return`/exception before the iterator
## completed, or the coroutine is parked). A no-op once the coroutine
## has run to completion since its terminating state already freed the
## frame. Called from the `finally` clause of the closure-iterator
## trampoline.
##
## For iter-VALUE-owned frames (the iter-value tuple's env slot owns
## the frame as a `ref CoroType`), we run `cancel` but skip
## `deallocFrame` — the ref's destructor frees the memory later when
## the iter-value goes out of scope. The ownership marker is
## `frame.caller.env`: nil ⇒ wrapper-allocated, non-nil ⇒ value-owned.
if c.env != nil:
cancel(c.env)
if c.env.caller.env == nil:
deallocFrame(c.env)
c.fn = nil
c.env = nil
func `==`*[T: tuple|object](x, y: T): bool =
## Return true only if each fields of `x` and `y` are equal.
for xf, yf in fields(x, y):
if xf != yf: return false
return true
func `==`*[T: Equatable](x, y: seq[T]): bool =
## Generic equals operator for sequences: relies on a equals operator for
## the element type `T`.
if y.rawData == x.rawData:
return true
if x.len != y.len:
return false
for i in 0..x.len-1:
if x[i] != y[i]:
return false
return true
const HexChars = "0123456789ABCDEF"
func addEscapedChar*(s: var string, c: char) {.noSideEffect, inline.} =
## Adds a char to string `s` and applies the following escaping:
##
## * replaces any ``\`` by `\\`
## * replaces any `'` by `\'`
## * replaces any `"` by `\"`
## * replaces any `\a` by `\\a`
## * replaces any `\b` by `\\b`
## * replaces any `\t` by `\\t`
## * replaces any `\n` by `\\n`
## * replaces any `\v` by `\\v`
## * replaces any `\f` by `\\f`
## * replaces any `\r` by `\\r`
## * replaces any `\e` by `\\e`
## * replaces any other character not in the set `{\21..\126}`
## by `\xHH` where `HH` is its hexadecimal value
##
## The procedure has been designed so that its output is usable for many
## different common syntaxes.
##
## .. warning:: This is **not correct** for producing ANSI C code!
##
case c
of '\a': s.add "\\a" # \x07
of '\b': s.add "\\b" # \x08
of '\t': s.add "\\t" # \x09
of '\n': s.add "\\n" # \x0A
of '\v': s.add "\\v" # \x0B
of '\f': s.add "\\f" # \x0C
of '\r': (when defined(nimLegacyAddEscapedCharx0D): s.add "\\c" else: s.add "\\r") # \x0D
of '\e': s.add "\\e" # \x1B
of '\\': s.add("\\\\")
of '\'': s.add("\\'")
of '\"': s.add("\\\"")
of {'\32'..'\126'} - {'\\', '\'', '\"'}: s.add(c)
else:
s.add("\\x")
let n = ord(c)
s.add(HexChars[int((n and 0xF0) shr 4)])
s.add(HexChars[int(n and 0xF)])
func addQuoted*[T](s: var string, x: T) =
## Appends `x` to string `s` in place, applying quoting and escaping
## if `x` is a string or char.
##
## See `addEscapedChar <#addEscapedChar,string,char>`_
## for the escaping scheme. When `x` is a string, characters in the
## range `{\128..\255}` are never escaped so that multibyte UTF-8
## characters are untouched (note that this behavior is different from
## `addEscapedChar`).
##
## The Nim standard library uses this function on the elements of
## collections when producing a string representation of a collection.
## It is recommended to use this function as well for user-side collections.
## Users may overload `addQuoted` for custom (string-like) types if
## they want to implement a customized element representation.
##
## ```nim
## var tmp = ""
## tmp.addQuoted(1)
## tmp.add(", ")
## tmp.addQuoted("string")
## tmp.add(", ")
## tmp.addQuoted('c')
## assert(tmp == """1, "string", 'c'""")
## ```
when T is string or T is cstring:
s.add("\"")
for c in x:
# Only ASCII chars are escaped to avoid butchering
# multibyte UTF-8 characters.
if c <= 127.char:
s.addEscapedChar(c)
else:
s.add c
s.add("\"")
elif T is char:
s.add("'")
s.addEscapedChar(x)
s.add("'")
# prevent temporary string allocation
elif T is SomeInteger:
s.addInt(x)
elif T is SomeFloat:
s.addFloat(x)
elif compiles(s.add(x)):
s.add(x)
else:
s.add($x)
type
Natural* = range[0 .. high(int)]
## is an `int` type ranging from zero to the maximum value
## of an `int`.
##
## It is a real `range` type, so a `Natural` parameter *states* `0 <= x` and
## the contract analysis reads it straight off the type
## (`contracts_fir.seedRangeFacts`). That is what lets an indexing routine
## discharge the lower half of `0 <= i and i < s.len` without a guard or a
## `.requires` at any call site. Binding a value to a `Natural` owes
## `0 <= value` in return, and that obligation is proven at compile time —
## no range check is ever emitted.
Positive* = range[1 .. high(int)]
## is an `int` type ranging from one to the maximum value
## of an `int`. Like `Natural`, it is a real `range` type.
HSlice*[T, U] = object ## "Heterogeneous" slice type.
a*: T ## The lower bound (inclusive).
b*: U ## The upper bound (inclusive).
Slice*[T] = HSlice[T, T] ## An alias for `HSlice[T, T]`.
func `..`*[T, U](a: sink T; b: sink U): HSlice[T, U] {.inline.} =
## Binary `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 in ordinal case
## statements, but then they are special-cased by the compiler.
## ```nim
## let a = [10, 20, 30, 40, 50]
## echo a[2 .. 3] # @[30, 40]
## ```
result = HSlice[T, U](a: a, b: b)
func `..<`*[T, U: Ordinal](a: sink T; b: sink U): HSlice[T, U] {.inline.} =
## Binary `..<` operator that constructs the half-open interval `[a, b)`,
## i.e. it is equivalent to `a .. pred(b)`.
##
## This is the *value* form used by slice indexing such as `s[a ..< b]`;
## the for-loop form `for i in a ..< b` resolves to the `..<` iterator.
result = HSlice[T, U](a: a, b: pred(b))
func contains*[T: Comparable](s: Slice[T]; x: T): bool {.inline.} =
## True when `x` lies within the inclusive interval `s`; enables `x in a .. b`.
not (x < s.a) and not (s.b < x)
type
BackwardsIndex* = distinct int ## Type constructed by `^` for reversed
## array/string/seq access.
template `^`*(x: int): BackwardsIndex = BackwardsIndex(x)
## Builtin `roof`:idx: operator. `a[^x]` is a shortcut for `a[a.len - x]`.
template `[]`*[T](s: seq[T]; i: BackwardsIndex): var T =
s[s.len - int(i)]
template `[]`*[T](s: openArray[T]; i: BackwardsIndex): var T =
s[s.len - int(i)]
template `[]`*(s: string; i: BackwardsIndex): var char =
s[s.len - int(i)]
template `..^`*(a, b: untyped): untyped =
## A shortcut for `a .. ^b`. Note that `a .. ^b` would be tokenized as
## `a` `..^` `b` anyway, so this operator must exist for that to parse.
a .. ^b
# ---- slice indexing ----
# These live here (rather than in `system/stringimpl` or `system/seqimpl`)
# because they read `HSlice`'s `a`/`b` fields, and `HSlice` is declared above
# in this file *after* those includes. A field read placed textually before
# the type's declaration binds to the wrong same-named field.
func `[]`*(s: string; x: HSlice[int, int]): string {.inline.} =
## Slice indexing: returns the substring for the inclusive range `x.a .. x.b`
## (a fresh copy). Works with `s[a .. b]` and `s[a ..< b]`.
result = substr(s, x.a, x.b)
func `[]`*(s: string; x: HSlice[int, BackwardsIndex]): string {.inline.} =
## Slice indexing with a backwards upper bound, e.g. `s[a .. ^1]`.
result = substr(s, x.a, s.len - int(x.b))
func `[]`*[T](s: seq[T]; x: HSlice[int, int]): seq[T] {.nodestroy.} =
## Slice indexing: returns a fresh `seq` with copies of the elements in the
## inclusive range `x.a .. x.b`. Works with `s[a .. b]` and `s[a ..< b]`.
let a = max(x.a, 0)
let b = min(x.b, s.len - 1)
let n = if b >= a: (b - a) + 1 else: 0
result = newSeqUninit[T](n)
var i = 0
while i < n:
(result.rawData[i]) = `=dup`(s.rawData[a+i])
inc i
func `[]`*[T](s: seq[T]; x: HSlice[int, BackwardsIndex]): seq[T] {.inline.} =
## Slice indexing with a backwards upper bound, e.g. `s[a .. ^1]`.
result = s[x.a .. (s.len - int(x.b))]
type
TypeOfMode* = enum ## Possible modes of `typeof`.
typeOfProc, ## Prefer the interpretation that means `x` is a proc call.
typeOfIter ## Prefer the interpretation that means `x` is an iterator call.
proc typeof*(x: untyped; mode = typeOfIter): typedesc {.magic: TypeOf.}
## Builtin `typeof` operation for accessing the type of an expression.
proc allocFrame*(size: int): ptr CoroutineBase =
## Allocates a new coroutine frame of the given size on the heap.
##
## ZEROED, and that is load-bearing rather than tidy. A frame holds the
## coroutine's locals, and the CPS lowering writes them with ordinary
## DESTRUCTIVE assignments — `=destroy` the old value, then store the new one —
## including the very first write, when there is no old value. On raw `alloc`
## memory that first `=destroy` reads whatever the allocator last left there:
## for a `string` it is `nimStrDestroy` branching on a garbage `slen`, and a
## garbage `slen > 14` would call `dealloc` on a garbage pointer.
##
## Zero is a valid — and destructible — initial value for every type that can
## live in a frame: a `string` reads `slen = 0` (the empty short string), a
## `seq` reads `data = nil`, a `ref` reads nil, and `=destroy` on each is a
## no-op. `deallocFrame` below also reads `frame.callee` before anything is
## guaranteed to have written it.
##
## The alternative — teaching the lowering to emit an initializing store for the
## first write to each frame field — is better code, and is not a prerequisite
## for this being correct: it would make the memset redundant, not necessary.
result = cast[ptr CoroutineBase](alloc0(size))
proc deallocFrame*(frame: ptr CoroutineBase) =
## Frees a coroutine frame previously allocated by `allocFrame`.
if frame.callee != nil:
dealloc(frame)
type
Exception* = object of RootObj
msg*: string
var exc* {.threadvar.}: ref Exception
proc newException*[T](exceptn: typedesc[T]; message: string): ref T {.inline, untyped.} =
## Creates a heap-based exception object of type `T` for Nim 2 interop:
## `raise newException(ValueError, "wrong value")`.
new(result)
result.msg = message
proc instantiationInfo*(): tuple[filename: string, line: int, column: int] {.magic: "InstantiationInfo".}
## The source position of the call. Inside a template body it is the
## position of the template's call site, so a template can report where it
## was invoked. `filename` is the file name without directories.