-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathsystem.nim
2980 lines (2608 loc) · 99.2 KB
/
system.nim
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
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#
#
# Nim's Runtime Library
# (c) Copyright 2015 Andreas Rumpf
#
# See the file "copying.txt", included in this
# distribution, for details about the copyright.
#
## The compiler depends on the System module to work properly and the System
## module depends on the compiler. Most of the routines listed here use
## special compiler magic.
##
## Each module implicitly imports the System module; it must not be listed
## explicitly. Because of this there cannot be a user-defined module named
## `system`.
##
## System module
## =============
##
## .. include:: ./system_overview.rst
include "system/basic_types"
func zeroDefault*[T](_: typedesc[T]): T {.magic: "ZeroDefault".} =
## Returns the binary zeros representation of the type `T`. It ignores
## default fields of an object.
##
## See also:
## * `default <#default,typedesc[T]>`_
include "system/compilation"
{.push warning[GcMem]: off, warning[Uninit]: off.}
# {.push hints: off.}
type
`static`*[T] {.magic: "Static".}
## Meta type representing all values that can be evaluated at compile-time.
##
## The type coercion `static(x)` can be used to force the compile-time
## evaluation of the given expression `x`.
`type`*[T] {.magic: "Type".}
## Meta type representing the type of all type values.
##
## The coercion `type(x)` can be used to obtain the type of the given
## expression `x`.
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", noSideEffect, compileTime.} =
## Builtin `typeof` operation for accessing the type of an expression.
## Since version 0.20.0.
runnableExamples:
proc myFoo(): float = 0.0
iterator myFoo(): string = yield "abc"
iterator myFoo2(): string = yield "abc"
iterator myFoo3(): string {.closure.} = yield "abc"
doAssert type(myFoo()) is string
doAssert typeof(myFoo()) is string
doAssert typeof(myFoo(), typeOfIter) is string
doAssert typeof(myFoo3) is iterator
doAssert typeof(myFoo(), typeOfProc) is float
doAssert typeof(0.0, typeOfProc) is float
doAssert typeof(myFoo3, typeOfProc) is iterator
doAssert not compiles(typeof(myFoo2(), typeOfProc))
# this would give: Error: attempting to call routine: 'myFoo2'
# since `typeOfProc` expects a typed expression and `myFoo2()` can
# only be used in a `for` context.
proc `or`*(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
## Constructs an `or` meta class.
proc `and`*(a, b: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
## Constructs an `and` meta class.
proc `not`*(a: typedesc): typedesc {.magic: "TypeTrait", noSideEffect.}
## Constructs an `not` meta class.
when defined(nimHasIterable):
type
iterable*[T] {.magic: IterableType.} ## Represents an expression that yields `T`
type
Ordinal*[T] {.magic: Ordinal.} ## Generic ordinal type. Includes integer,
## bool, character, and enumeration types
## as well as their subtypes. See also
## `SomeOrdinal`.
proc `addr`*[T](x: T): ptr T {.magic: "Addr", noSideEffect.} =
## Builtin `addr` operator for taking the address of a memory location.
##
## .. note:: This works for `let` variables or parameters
## for better interop with C. When you use it to write a wrapper
## for a C library and take the address of `let` variables or parameters,
## you should always check that the original library
## does never write to data behind the pointer that is returned from
## this procedure.
##
## Cannot be overloaded.
##
## ```nim
## var
## buf: seq[char] = @['a','b','c']
## p = buf[1].addr
## echo p.repr # ref 0x7faa35c40059 --> 'b'
## echo p[] # b
## ```
discard
proc unsafeAddr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.} =
## .. warning:: `unsafeAddr` is a deprecated alias for `addr`,
## use `addr` instead.
discard
const ThisIsSystem = true
const arcLikeMem = defined(gcArc) or defined(gcAtomicArc) or defined(gcOrc)
when defined(nimAllowNonVarDestructor) and arcLikeMem:
proc new*[T](a: var ref T, finalizer: proc (x: T) {.nimcall.}) {.
magic: "NewFinalize", noSideEffect.}
## Creates a new object of type `T` and returns a safe (traced)
## reference to it in `a`.
##
## When the garbage collector frees the object, `finalizer` is called.
## The `finalizer` may not keep a reference to the
## object pointed to by `x`. The `finalizer` cannot prevent the GC from
## freeing the object.
##
## **Note**: The `finalizer` refers to the type `T`, not to the object!
## This means that for each object of type `T` the finalizer will be called!
proc new*[T](a: var ref T, finalizer: proc (x: ref T) {.nimcall.}) {.
magic: "NewFinalize", noSideEffect, deprecated: "pass a finalizer of the 'proc (x: T) {.nimcall.}' type".}
else:
proc new*[T](a: var ref T, finalizer: proc (x: ref T) {.nimcall.}) {.
magic: "NewFinalize", noSideEffect.}
## Creates a new object of type `T` and returns a safe (traced)
## reference to it in `a`.
##
## When the garbage collector frees the object, `finalizer` is called.
## The `finalizer` may not keep a reference to the
## object pointed to by `x`. The `finalizer` cannot prevent the GC from
## freeing the object.
##
## **Note**: The `finalizer` refers to the type `T`, not to the object!
## This means that for each object of type `T` the finalizer will be called!
proc `=wasMoved`*[T](obj: var T) {.magic: "WasMoved", noSideEffect.} =
## Generic `wasMoved`:idx: implementation that can be overridden.
proc wasMoved*[T](obj: var T) {.inline, noSideEffect.} =
## Resets an object `obj` to its initial (binary zero) value to signify
## it was "moved" and to signify its destructor should do nothing and
## ideally be optimized away.
{.cast(raises: []), cast(tags: []).}:
`=wasMoved`(obj)
proc move*[T](x: var T): T {.magic: "Move", noSideEffect.} =
result = x
{.cast(raises: []), cast(tags: []).}:
`=wasMoved`(x)
when defined(nimHasEnsureMove):
proc ensureMove*[T](x: T): T {.magic: "EnsureMove", noSideEffect.} =
## Ensures that `x` is moved to the new location, otherwise it gives
## an error at the compile time.
runnableExamples:
proc foo =
var x = "Hello"
let y = ensureMove(x)
doAssert y == "Hello"
foo()
discard "implemented in injectdestructors"
type
range*[T]{.magic: "Range".} ## Generic type to construct range types.
array*[I, T]{.magic: "Array".} ## Generic type to construct
## fixed-length arrays.
openArray*[T]{.magic: "OpenArray".} ## Generic type to construct open arrays.
## Open arrays are implemented as a
## pointer to the array data and a
## length field.
varargs*[T]{.magic: "Varargs".} ## Generic type to construct a varargs type.
seq*[T]{.magic: "Seq".} ## Generic type to construct sequences.
set*[T]{.magic: "Set".} ## Generic type to construct bit sets.
type
UncheckedArray*[T]{.magic: "UncheckedArray".}
## Array with no bounds checking.
type sink*[T]{.magic: "BuiltinType".}
type lent*[T]{.magic: "BuiltinType".}
proc high*[T: Ordinal|enum|range](x: T): T {.magic: "High", noSideEffect,
deprecated: "Deprecated since v1.4; there should not be `high(value)`. Use `high(type)`.".}
## Returns the highest possible value of an ordinal value `x`.
##
## As a special semantic rule, `x` may also be a type identifier.
##
## **This proc is deprecated**, use this one instead:
## * `high(typedesc) <#high,typedesc[T]>`_
##
## ```nim
## high(2) # => 9223372036854775807
## ```
proc high*[T: Ordinal|enum|range](x: typedesc[T]): T {.magic: "High", noSideEffect.}
## Returns the highest possible value of an ordinal or enum type.
##
## `high(int)` is Nim's way of writing `INT_MAX`:idx: or `MAX_INT`:idx:.
## ```nim
## high(int) # => 9223372036854775807
## ```
##
## See also:
## * `low(typedesc) <#low,typedesc[T]>`_
proc high*[T](x: openArray[T]): int {.magic: "High", noSideEffect.}
## Returns the highest possible index of a sequence `x`.
## ```nim
## var s = @[1, 2, 3, 4, 5, 6, 7]
## high(s) # => 6
## for i in low(s)..high(s):
## echo s[i]
## ```
##
## See also:
## * `low(openArray) <#low,openArray[T]>`_
proc high*[I, T](x: array[I, T]): I {.magic: "High", noSideEffect.}
## Returns the highest possible index of an array `x`.
##
## For empty arrays, the return type is `int`.
## ```nim
## var arr = [1, 2, 3, 4, 5, 6, 7]
## high(arr) # => 6
## for i in low(arr)..high(arr):
## echo arr[i]
## ```
##
## See also:
## * `low(array) <#low,array[I,T]>`_
proc high*[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect.}
## Returns the highest possible index of an array type.
##
## For empty arrays, the return type is `int`.
## ```nim
## high(array[7, int]) # => 6
## ```
##
## See also:
## * `low(typedesc[array]) <#low,typedesc[array[I,T]]>`_
proc high*(x: cstring): int {.magic: "High", noSideEffect.}
## Returns the highest possible index of a compatible string `x`.
## This is sometimes an O(n) operation.
##
## See also:
## * `low(cstring) <#low,cstring>`_
proc high*(x: string): int {.magic: "High", noSideEffect.}
## Returns the highest possible index of a string `x`.
## ```nim
## var str = "Hello world!"
## high(str) # => 11
## ```
##
## See also:
## * `low(string) <#low,string>`_
proc low*[T: Ordinal|enum|range](x: T): T {.magic: "Low", noSideEffect,
deprecated: "Deprecated since v1.4; there should not be `low(value)`. Use `low(type)`.".}
## Returns the lowest possible value of an ordinal value `x`. As a special
## semantic rule, `x` may also be a type identifier.
##
## **This proc is deprecated**, use this one instead:
## * `low(typedesc) <#low,typedesc[T]>`_
##
## ```nim
## low(2) # => -9223372036854775808
## ```
proc low*[T: Ordinal|enum|range](x: typedesc[T]): T {.magic: "Low", noSideEffect.}
## Returns the lowest possible value of an ordinal or enum type.
##
## `low(int)` is Nim's way of writing `INT_MIN`:idx: or `MIN_INT`:idx:.
## ```nim
## low(int) # => -9223372036854775808
## ```
##
## See also:
## * `high(typedesc) <#high,typedesc[T]>`_
proc low*[T](x: openArray[T]): int {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of a sequence `x`.
## ```nim
## var s = @[1, 2, 3, 4, 5, 6, 7]
## low(s) # => 0
## for i in low(s)..high(s):
## echo s[i]
## ```
##
## See also:
## * `high(openArray) <#high,openArray[T]>`_
proc low*[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of an array `x`.
##
## For empty arrays, the return type is `int`.
## ```nim
## var arr = [1, 2, 3, 4, 5, 6, 7]
## low(arr) # => 0
## for i in low(arr)..high(arr):
## echo arr[i]
## ```
##
## See also:
## * `high(array) <#high,array[I,T]>`_
proc low*[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of an array type.
##
## For empty arrays, the return type is `int`.
## ```nim
## low(array[7, int]) # => 0
## ```
##
## See also:
## * `high(typedesc[array]) <#high,typedesc[array[I,T]]>`_
proc low*(x: cstring): int {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of a compatible string `x`.
##
## See also:
## * `high(cstring) <#high,cstring>`_
proc low*(x: string): int {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of a string `x`.
## ```nim
## var str = "Hello world!"
## low(str) # => 0
## ```
##
## See also:
## * `high(string) <#high,string>`_
when not defined(gcArc) and not defined(gcOrc) and not defined(gcAtomicArc):
proc shallowCopy*[T](x: var T, y: T) {.noSideEffect, magic: "ShallowCopy".}
## Use this instead of `=` for a `shallow copy`:idx:.
##
## The shallow copy only changes the semantics for sequences and strings
## (and types which contain those).
##
## Be careful with the changed semantics though!
## There is a reason why the default assignment does a deep copy of sequences
## and strings.
# :array|openArray|string|seq|cstring|tuple
proc `[]`*[I: Ordinal;T](a: T; i: I): T {.
noSideEffect, magic: "ArrGet".}
proc `[]=`*[I: Ordinal;T,S](a: T; i: I;
x: sink S) {.noSideEffect, magic: "ArrPut".}
proc `=`*[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn".}
proc `=copy`*[T](dest: var T; src: T) {.noSideEffect, magic: "Asgn".}
proc arrGet[I: Ordinal;T](a: T; i: I): T {.
noSideEffect, magic: "ArrGet".}
proc arrPut[I: Ordinal;T,S](a: T; i: I;
x: S) {.noSideEffect, magic: "ArrPut".}
when defined(nimAllowNonVarDestructor) and arcLikeMem and defined(nimPreviewNonVarDestructor):
proc `=destroy`*[T](x: T) {.inline, magic: "Destroy".} =
## Generic `destructor`:idx: implementation that can be overridden.
discard
else:
proc `=destroy`*[T](x: var T) {.inline, magic: "Destroy".} =
## Generic `destructor`:idx: implementation that can be overridden.
discard
when defined(nimAllowNonVarDestructor) and arcLikeMem:
proc `=destroy`*(x: string) {.inline, magic: "Destroy", enforceNoRaises.} =
discard
proc `=destroy`*[T](x: seq[T]) {.inline, magic: "Destroy".} =
discard
proc `=destroy`*[T](x: ref T) {.inline, magic: "Destroy".} =
discard
when defined(nimHasDup):
proc `=dup`*[T](x: T): T {.inline, magic: "Dup".} =
## Generic `dup`:idx: implementation that can be overridden.
discard
proc `=sink`*[T](x: var T; y: T) {.inline, nodestroy, magic: "Asgn".} =
## Generic `sink`:idx: implementation that can be overridden.
when defined(gcArc) or defined(gcOrc) or defined(gcAtomicArc):
x = y
else:
shallowCopy(x, y)
when defined(nimHasTrace):
proc `=trace`*[T](x: var T; env: pointer) {.inline, magic: "Trace".} =
## Generic `trace`:idx: implementation that can be overridden.
discard
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]`.
proc `..`*[T, U](a: sink T, b: sink U): HSlice[T, U] {.noSideEffect, inline, magic: "DotDot".} =
## 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)
proc `..`*[T](b: sink T): HSlice[int, T]
{.noSideEffect, inline, magic: "DotDot", deprecated: "replace `..b` with `0..b`".} =
## Unary `slice`:idx: operator that constructs an interval `[default(int), b]`.
## ```nim
## let a = [10, 20, 30, 40, 50]
## echo a[.. 2] # @[10, 20, 30]
## ```
result = HSlice[int, T](a: 0, b: b)
when defined(hotCodeReloading):
{.pragma: hcrInline, inline.}
else:
{.pragma: hcrInline.}
include "system/arithmetics"
include "system/comparisons"
const
appType* {.magic: "AppType".}: string = ""
## A string that describes the application type. Possible values:
## `"console"`, `"gui"`, `"lib"`.
include "system/inclrtl"
const NoFakeVars = defined(nimscript) ## `true` if the backend doesn't support \
## "fake variables" like `var EBADF {.importc.}: cint`.
const notJSnotNims = not defined(js) and not defined(nimscript)
when not defined(js) and not defined(nimSeqsV2):
type
TGenericSeq {.compilerproc, pure, inheritable.} = object
len, reserved: int
when defined(gogc):
elemSize: int
elemAlign: int
PGenericSeq {.exportc.} = ptr TGenericSeq
# len and space without counting the terminating zero:
NimStringDesc {.compilerproc, final.} = object of TGenericSeq
data: UncheckedArray[char]
NimString = ptr NimStringDesc
when notJSnotNims:
include "system/hti"
type
byte* = uint8 ## This is an alias for `uint8`, that is an unsigned
## integer, 8 bits wide.
Natural* = range[0..high(int)]
## is an `int` type ranging from zero to the maximum value
## of an `int`. This type is often useful for documentation and debugging.
Positive* = range[1..high(int)]
## is an `int` type ranging from one to the maximum value
## of an `int`. This type is often useful for documentation and debugging.
type
RootObj* {.compilerproc, inheritable.} =
object ## The root of Nim's object hierarchy.
##
## Objects should inherit from `RootObj` or one of its descendants.
## However, objects that have no ancestor are also allowed.
RootRef* = ref RootObj ## Reference to `RootObj`.
const NimStackTraceMsgs = compileOption("stacktraceMsgs")
type
RootEffect* {.compilerproc.} = object of RootObj ## \
## Base effect class.
##
## Each effect should inherit from `RootEffect` unless you know what
## you're doing.
type
StackTraceEntry* = object ## In debug mode exceptions store the stack trace that led
## to them. A `StackTraceEntry` is a single entry of the
## stack trace.
procname*: cstring ## Name of the proc that is currently executing.
line*: int ## Line number of the proc that is currently executing.
filename*: cstring ## Filename of the proc that is currently executing.
when NimStackTraceMsgs:
frameMsg*: string ## When a stacktrace is generated in a given frame and
## rendered at a later time, we should ensure the stacktrace
## data isn't invalidated; any pointer into PFrame is
## subject to being invalidated so shouldn't be stored.
when defined(nimStackTraceOverride):
programCounter*: uint ## Program counter - will be used to get the rest of the info,
## when `$` is called on this type. We can't use
## "cuintptr_t" in here.
procnameStr*, filenameStr*: string ## GC-ed alternatives to "procname" and "filename"
Exception* {.compilerproc, magic: "Exception".} = object of RootObj ## \
## Base exception class.
##
## Each exception has to inherit from `Exception`. See the full `exception
## hierarchy <manual.html#exception-handling-exception-hierarchy>`_.
parent*: ref Exception ## Parent exception (can be used as a stack).
name*: cstring ## The exception's name is its Nim identifier.
## This field is filled automatically in the
## `raise` statement.
msg* {.exportc: "message".}: string ## The exception's message. Not
## providing an exception message
## is bad style.
when defined(js):
trace*: string
else:
trace*: seq[StackTraceEntry]
up: ref Exception # used for stacking exceptions. Not exported!
Defect* = object of Exception ## \
## Abstract base class for all exceptions that Nim's runtime raises
## but that are strictly uncatchable as they can also be mapped to
## a `quit` / `trap` / `exit` operation.
CatchableError* = object of Exception ## \
## Abstract class for all exceptions that are catchable.
when defined(nimIcIntegrityChecks):
include "system/exceptions"
else:
import system/exceptions
export exceptions
when defined(js) or defined(nimdoc):
type
JsRoot* = ref object of RootObj
## Root type of the JavaScript object hierarchy
proc unsafeNew*[T](a: var ref T, size: Natural) {.magic: "New", noSideEffect.}
## Creates a new object of type `T` and returns a safe (traced)
## reference to it in `a`.
##
## This is **unsafe** as it allocates an object of the passed `size`.
## This should only be used for optimization purposes when you know
## what you're doing!
##
## See also:
## * `new <#new,ref.T,proc(ref.T)>`_
proc sizeof*[T](x: T): int {.magic: "SizeOf", noSideEffect.}
## Returns the size of `x` in bytes.
##
## Since this is a low-level proc,
## its usage is discouraged - using `new <#new,ref.T,proc(ref.T)>`_ for
## the most cases suffices that one never needs to know `x`'s size.
##
## As a special semantic rule, `x` may also be a type identifier
## (`sizeof(int)` is valid).
##
## Limitations: If used for types that are imported from C or C++,
## sizeof should fallback to the `sizeof` in the C compiler. The
## result isn't available for the Nim compiler and therefore can't
## be used inside of macros.
## ```nim
## sizeof('A') # => 1
## sizeof(2) # => 8
## ```
proc alignof*[T](x: T): int {.magic: "AlignOf", noSideEffect.}
proc alignof*(x: typedesc): int {.magic: "AlignOf", noSideEffect.}
proc offsetOfDotExpr(typeAccess: typed): int {.magic: "OffsetOf", noSideEffect, compileTime.}
template offsetOf*[T](t: typedesc[T]; member: untyped): int =
var tmp {.noinit.}: ptr T
offsetOfDotExpr(tmp[].member)
template offsetOf*[T](value: T; member: untyped): int =
offsetOfDotExpr(value.member)
#proc offsetOf*(memberaccess: typed): int {.magic: "OffsetOf", noSideEffect.}
proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}
proc newSeq*[T](s: var seq[T], len: Natural) {.magic: "NewSeq", noSideEffect.}
## Creates a new sequence of type `seq[T]` with length `len`.
##
## This is equivalent to `s = @[]; setlen(s, len)`, but more
## efficient since no reallocation is needed.
##
## Note that the sequence will be filled with zeroed entries.
## After the creation of the sequence you should assign entries to
## the sequence instead of adding them. Example:
## ```nim
## var inputStrings: seq[string]
## newSeq(inputStrings, 3)
## assert len(inputStrings) == 3
## inputStrings[0] = "The fourth"
## inputStrings[1] = "assignment"
## inputStrings[2] = "would crash"
## #inputStrings[3] = "out of bounds"
## ```
proc newSeq*[T](len = 0.Natural): seq[T] =
## Creates a new sequence of type `seq[T]` with length `len`.
##
## Note that the sequence will be filled with zeroed entries.
## After the creation of the sequence you should assign entries to
## the sequence instead of adding them.
## ```nim
## var inputStrings = newSeq[string](3)
## assert len(inputStrings) == 3
## inputStrings[0] = "The fourth"
## inputStrings[1] = "assignment"
## inputStrings[2] = "would crash"
## #inputStrings[3] = "out of bounds"
## ```
##
## See also:
## * `newSeqOfCap <#newSeqOfCap,Natural>`_
## * `newSeqUninit <#newSeqUninit,Natural>`_
newSeq(result, len)
proc newSeqOfCap*[T](cap: Natural): seq[T] {.
magic: "NewSeqOfCap", noSideEffect.} =
## Creates a new sequence of type `seq[T]` with length zero and capacity
## `cap`. Example:
## ```nim
## var x = newSeqOfCap[int](5)
## assert len(x) == 0
## x.add(10)
## assert len(x) == 1
## ```
discard
func len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.magic: "LengthOpenArray".} =
## Returns the length of an openArray.
runnableExamples:
proc bar[T](a: openArray[T]): int = len(a)
assert bar([1,2]) == 2
assert [1,2].len == 2
func len*(x: string): int {.magic: "LengthStr".} =
## Returns the length of a string.
runnableExamples:
assert "abc".len == 3
assert "".len == 0
assert string.default.len == 0
proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.} =
## Returns the length of a compatible string. This is an O(n) operation except
## in js at runtime.
##
## **Note:** On the JS backend this currently counts UTF-16 code points
## instead of bytes at runtime (not at compile time). For now, if you
## need the byte length of the UTF-8 encoding, convert to string with
## `$` first then call `len`.
runnableExamples:
doAssert len(cstring"abc") == 3
doAssert len(cstring r"ab\0c") == 5 # \0 is escaped
doAssert len(cstring"ab\0c") == 5 # ditto
var a: cstring = "ab\0c"
when defined(js): doAssert a.len == 4 # len ignores \0 for js
else: doAssert a.len == 2 # \0 is a null terminator
static:
var a2: cstring = "ab\0c"
doAssert a2.len == 2 # \0 is a null terminator, even in js vm
func len*(x: (type array)|array): int {.magic: "LengthArray".} =
## Returns the length of an array or an array type.
## This is roughly the same as `high(T)-low(T)+1`.
runnableExamples:
var a = [1, 1, 1]
assert a.len == 3
assert array[0, float].len == 0
static: assert array[-2..2, float].len == 5
func len*[T](x: seq[T]): int {.magic: "LengthSeq".} =
## Returns the length of `x`.
runnableExamples:
assert @[0, 1].len == 2
assert seq[int].default.len == 0
assert newSeq[int](3).len == 3
let s = newSeqOfCap[int](3)
assert s.len == 0
# xxx this gives cgen error: assert newSeqOfCap[int](3).len == 0
func ord*[T: Ordinal|enum](x: T): int {.magic: "Ord".} =
## Returns the internal `int` value of `x`, including for enum with holes
## and distinct ordinal types.
runnableExamples:
assert ord('A') == 65
type Foo = enum
f0 = 0, f1 = 3
assert f1.ord == 3
type Bar = distinct int
assert 3.Bar.ord == 3
func chr*(u: range[0..255]): char {.magic: "Chr".} =
## Converts `u` to a `char`, same as `char(u)`.
runnableExamples:
doAssert chr(65) == 'A'
doAssert chr(255) == '\255'
doAssert chr(255) == char(255)
doAssert not compiles chr(256)
doAssert not compiles char(256)
var x = 256
doAssertRaises(RangeDefect): discard chr(x)
doAssertRaises(RangeDefect): discard char(x)
include "system/setops"
proc contains*[U, V, W](s: HSlice[U, V], value: W): bool {.noSideEffect, inline.} =
## Checks if `value` is within the range of `s`; returns true if
## `value >= s.a and value <= s.b`.
## ```nim
## assert((1..3).contains(1) == true)
## assert((1..3).contains(2) == true)
## assert((1..3).contains(4) == false)
## ```
result = s.a <= value and value <= s.b
when not defined(nimHasCallsitePragma):
{.pragma: callsite.}
template `in`*(x, y: untyped): untyped {.dirty, callsite.} = contains(y, x)
## Sugar for `contains`.
## ```nim
## assert(1 in (1..3) == true)
## assert(5 in (1..3) == false)
## ```
template `notin`*(x, y: untyped): untyped {.dirty, callsite.} = not contains(y, x)
## Sugar for `not contains`.
## ```nim
## assert(1 notin (1..3) == false)
## assert(5 notin (1..3) == true)
## ```
proc `is`*[T, S](x: T, y: S): bool {.magic: "Is", noSideEffect.}
## Checks if `T` is of the same type as `S`.
##
## For a negated version, use `isnot <#isnot.t,untyped,untyped>`_.
##
## ```nim
## assert 42 is int
## assert @[1, 2] is seq
##
## proc test[T](a: T): int =
## when (T is int):
## return a
## else:
## return 0
##
## assert(test[int](3) == 3)
## assert(test[string]("xyz") == 0)
## ```
template `isnot`*(x, y: untyped): untyped {.callsite.} = not (x is y)
## Negated version of `is <#is,T,S>`_. Equivalent to `not(x is y)`.
## ```nim
## assert 42 isnot float
## assert @[1, 2] isnot enum
## ```
when (defined(nimOwnedEnabled) and not defined(nimscript)) or defined(nimFixedOwned):
type owned*[T]{.magic: "BuiltinType".} ## type constructor to mark a ref/ptr or a closure as `owned`.
else:
template owned*(t: typedesc): typedesc = t
when defined(nimOwnedEnabled) and not defined(nimscript):
proc new*[T](a: var owned(ref T)) {.magic: "New", noSideEffect.}
## Creates a new object of type `T` and returns a safe (traced)
## reference to it in `a`.
proc new*(t: typedesc): auto =
## Creates a new object of type `T` and returns a safe (traced)
## reference to it as result value.
##
## When `T` is a ref type then the resulting type will be `T`,
## otherwise it will be `ref T`.
when (t is ref):
var r: owned t
else:
var r: owned(ref t)
new(r)
return r
proc unown*[T](x: T): T {.magic: "Unown", noSideEffect.}
## Use the expression `x` ignoring its ownership attribute.
else:
template unown*(x: typed): untyped = x
proc new*[T](a: var ref T) {.magic: "New", noSideEffect.}
## Creates a new object of type `T` and returns a safe (traced)
## reference to it in `a`.
proc new*(t: typedesc): auto =
## Creates a new object of type `T` and returns a safe (traced)
## reference to it as result value.
##
## When `T` is a ref type then the resulting type will be `T`,
## otherwise it will be `ref T`.
when (t is ref):
var r: t
else:
var r: ref t
new(r)
return r
template disarm*(x: typed) =
## Useful for `disarming` dangling pointers explicitly for `--newruntime`.
## Regardless of whether `--newruntime` is used or not
## this sets the pointer or callback `x` to `nil`. This is an
## experimental API!
x = nil
proc `of`*[T, S](x: T, y: typedesc[S]): bool {.magic: "Of", noSideEffect.} =
## Checks if `x` is an instance of `y`.
runnableExamples:
type
Base = ref object of RootObj
Sub1 = ref object of Base
Sub2 = ref object of Base
Unrelated = ref object
var base: Base = Sub1() # downcast
doAssert base of Base # generates `CondTrue` (statically true)
doAssert base of Sub1
doAssert base isnot Sub1
doAssert not (base of Sub2)
base = Sub2() # re-assign
doAssert base of Sub2
doAssert Sub2(base) != nil # upcast
doAssertRaises(ObjectConversionDefect): discard Sub1(base)
var sub1 = Sub1()
doAssert sub1 of Base
doAssert sub1.Base of Sub1
doAssert not compiles(base of Unrelated)
proc cmp*[T](x, y: T): int =
## Generic compare proc.
##
## Returns:
## * a value less than zero, if `x < y`
## * a value greater than zero, if `x > y`
## * zero, if `x == y`
##
## This is useful for writing generic algorithms without performance loss.
## This generic implementation uses the `==` and `<` operators.
## ```nim
## import std/algorithm
## echo sorted(@[4, 2, 6, 5, 8, 7], cmp[int])
## ```
if x == y: return 0
if x < y: return -1
return 1
proc cmp*(x, y: string): int {.noSideEffect.}
## Compare proc for strings. More efficient than the generic version.
##
## **Note**: The precise result values depend on the used C runtime library and
## can differ between operating systems!
proc `@`* [IDX, T](a: sink array[IDX, T]): seq[T] {.magic: "ArrToSeq", noSideEffect.}
## Turns an array into a sequence.
##
## This most often useful for constructing
## sequences with the array constructor: `@[1, 2, 3]` has the type
## `seq[int]`, while `[1, 2, 3]` has the type `array[0..2, int]`.
##
## ```nim
## let
## a = [1, 3, 5]
## b = "foo"
##
## echo @a # => @[1, 3, 5]
## echo @b # => @['f', 'o', 'o']
## ```
proc default*[T](_: typedesc[T]): T {.magic: "Default", noSideEffect.} =
## Returns the default value of the type `T`. Contrary to `zeroDefault`, it takes default fields
## of an object into consideration.
##
## See also:
## * `zeroDefault <#zeroDefault,typedesc[T]>`_
##
runnableExamples("-d:nimPreviewRangeDefault"):
assert (int, float).default == (0, 0.0)
type Foo = object
a: range[2..6]
var x = Foo.default
assert x.a == 2
proc reset*[T](obj: var T) {.noSideEffect.} =
## Resets an object `obj` to its default value.
when nimvm:
obj = default(typeof(obj))
else:
when defined(gcDestructors):
{.cast(noSideEffect), cast(raises: []), cast(tags: []).}:
`=destroy`(obj)
`=wasMoved`(obj)
else:
obj = default(typeof(obj))
proc setLen*[T](s: var seq[T], newlen: Natural) {.
magic: "SetLengthSeq", noSideEffect, nodestroy.}
## Sets the length of seq `s` to `newlen`. `T` may be any sequence type.
##
## If the current length is greater than the new length,
## `s` will be truncated.
## ```nim
## var x = @[10, 20]
## x.setLen(5)
## x[4] = 50
## assert x == @[10, 20, 0, 0, 50]
## x.setLen(1)
## assert x == @[10]
## ```
proc setLen*(s: var string, newlen: Natural) {.
magic: "SetLengthStr", noSideEffect.}
## Sets the length of string `s` to `newlen`.
##
## If the current length is greater than the new length,
## `s` will be truncated.
## ```nim
## var myS = "Nim is great!!"
## myS.setLen(3) # myS <- "Nim"
## echo myS, " is fantastic!!"
## ```
proc newString*(len: Natural): string {.
magic: "NewString", importc: "mnewString", noSideEffect.}
## Returns a new string of length `len`.
## One needs to fill the string character after character
## with the index operator `s[i]`.
##
## This procedure exists only for optimization purposes;
## the same effect can be achieved with the `&` operator or with `add`.
proc newStringOfCap*(cap: Natural): string {.
magic: "NewStringOfCap", importc: "rawNewString", noSideEffect.}
## Returns a new string of length `0` but with capacity `cap`.
##
## This procedure exists only for optimization purposes; the same effect can
## be achieved with the `&` operator or with `add`.
proc `&`*(x: string, y: char): string {.
magic: "ConStrStr", noSideEffect.}
## Concatenates `x` with `y`.
## ```nim
## assert("ab" & 'c' == "abc")
## ```
proc `&`*(x, y: char): string {.
magic: "ConStrStr", noSideEffect.}
## Concatenates characters `x` and `y` into a string.
## ```nim
## assert('a' & 'b' == "ab")
## ```
proc `&`*(x, y: string): string {.