-
-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
system.nim
4283 lines (3729 loc) · 163 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``.
##
## Module system
## =============
##
# That lonesome header above is to prevent :idx: entries from being mentioned
# in the global index as part of the previous header (Exception hierarchy).
type
int* {.magic: Int.} ## default integer type; bitwidth depends on
## architecture, but is always the same as a pointer
int8* {.magic: Int8.} ## signed 8 bit integer type
int16* {.magic: Int16.} ## signed 16 bit integer type
int32* {.magic: Int32.} ## signed 32 bit integer type
int64* {.magic: Int64.} ## signed 64 bit integer type
uint* {.magic: UInt.} ## unsigned default integer type
uint8* {.magic: UInt8.} ## unsigned 8 bit integer type
uint16* {.magic: UInt16.} ## unsigned 16 bit integer type
uint32* {.magic: UInt32.} ## unsigned 32 bit integer type
uint64* {.magic: UInt64.} ## unsigned 64 bit integer type
float* {.magic: Float.} ## default floating point type
float32* {.magic: Float32.} ## 32 bit floating point type
float64* {.magic: Float.} ## 64 bit floating point type
# 'float64' is now an alias to 'float'; this solves many problems
type # we need to start a new type section here, so that ``0`` can have a type
bool* {.magic: Bool.} = enum ## built-in boolean type
false = 0, true = 1
type
char* {.magic: Char.} ## built-in 8 bit character type (unsigned)
string* {.magic: String.} ## built-in string type
cstring* {.magic: Cstring.} ## built-in cstring (*compatible string*) type
pointer* {.magic: Pointer.} ## built-in pointer type, use the ``addr``
## operator to get a pointer to a variable
typedesc* {.magic: TypeDesc.} ## meta type to denote a type description
const
on* = true ## alias for ``true``
off* = false ## alias for ``false``
{.push warning[GcMem]: off, warning[Uninit]: off.}
{.push hints: off.}
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
type
Ordinal* {.magic: Ordinal.}[T] ## Generic ordinal type. Includes integer,
## bool, character, and enumeration types
## as well as their subtypes. Note `uint`
## and `uint64` are not ordinal types for
## implementation reasons
`ptr`* {.magic: Pointer.}[T] ## built-in generic untraced pointer type
`ref`* {.magic: Pointer.}[T] ## built-in generic traced pointer type
`nil` {.magic: "Nil".}
void* {.magic: "VoidType".} ## meta type to denote the absence of any type
auto* {.magic: Expr.} ## meta type for automatic type determination
any* = distinct auto ## meta type for any supported type
untyped* {.magic: Expr.} ## meta type to denote an expression that
## is not resolved (for templates)
typed* {.magic: Stmt.} ## meta type to denote an expression that
## is resolved (for templates)
SomeSignedInt* = int|int8|int16|int32|int64
## type class matching all signed integer types
SomeUnsignedInt* = uint|uint8|uint16|uint32|uint64
## type class matching all unsigned integer types
SomeInteger* = SomeSignedInt|SomeUnsignedInt
## type class matching all integer types
SomeOrdinal* = int|int8|int16|int32|int64|bool|enum|uint8|uint16|uint32
## type class matching all ordinal types; however this includes enums with
## holes.
SomeFloat* = float|float32|float64
## type class matching all floating point number types
SomeNumber* = SomeInteger|SomeFloat
## type class matching all number types
{.deprecated: [SomeReal: SomeFloat].}
proc defined*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
## Special compile-time procedure that checks whether `x` is
## defined.
## `x` is an external symbol introduced through the compiler's
## `-d:x switch <nimc.html#compile-time-symbols>`_ to enable build time
## conditionals:
##
## .. code-block:: Nim
## when not defined(release):
## # Do here programmer friendly expensive sanity checks.
## # Put here the normal code
proc declared*(x: untyped): bool {.magic: "Defined", noSideEffect, compileTime.}
## Special compile-time procedure that checks whether `x` is
## declared. `x` has to be an identifier or a qualified identifier.
## This can be used to check whether a library provides a certain
## feature or not:
##
## .. code-block:: Nim
## when not declared(strutils.toUpper):
## # provide our own toUpper proc here, because strutils is
## # missing it.
when defined(useNimRtl):
{.deadCodeElim: on.} # dce option deprecated
proc declaredInScope*(x: untyped): bool {.
magic: "DefinedInScope", noSideEffect, compileTime.}
## Special compile-time procedure that checks whether `x` is
## declared in the current scope. `x` has to be an identifier.
proc `addr`*[T](x: var T): ptr T {.magic: "Addr", noSideEffect.} =
## Builtin 'addr' operator for taking the address of a memory location.
## Cannot be overloaded.
##
## .. code-block:: nim
## var
## buf: seq[char] = @['a','b','c']
## p: pointer = buf[1].addr
## echo cast[ptr char](p)[] # b
discard
proc unsafeAddr*[T](x: T): ptr T {.magic: "Addr", noSideEffect.} =
## Builtin 'addr' operator for taking the address of a memory
## location. This works even for ``let`` variables or parameters
## for better interop with C and so it is considered even more
## unsafe than the ordinary ``addr``. When you use it to write a
## wrapper for a C library, 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.
discard
when defined(nimNewTypedesc):
type
`static`* {.magic: "Static".}[T]
## 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`* {.magic: "Type".}[T]
## 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``.
else:
proc `type`*(x: untyped): typeDesc {.magic: "TypeOf", noSideEffect, compileTime.} =
## Builtin 'type' operator for accessing the type of an expression.
## Cannot be overloaded.
discard
proc `not`*(x: bool): bool {.magic: "Not", noSideEffect.}
## Boolean not; returns true iff ``x == false``.
proc `and`*(x, y: bool): bool {.magic: "And", noSideEffect.}
## Boolean ``and``; returns true iff ``x == y == true``.
## Evaluation is lazy: if ``x`` is false,
## ``y`` will not even be evaluated.
proc `or`*(x, y: bool): bool {.magic: "Or", noSideEffect.}
## Boolean ``or``; returns true iff ``not (not x and not y)``.
## Evaluation is lazy: if ``x`` is true,
## ``y`` will not even be evaluated.
proc `xor`*(x, y: bool): bool {.magic: "Xor", noSideEffect.}
## Boolean `exclusive or`; returns true iff ``x != y``.
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
const ThisIsSystem = true
proc internalNew*[T](a: var ref T) {.magic: "New", noSideEffect.}
## leaked implementation detail. Do not use.
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 reset*[T](obj: var T) {.magic: "Reset", noSideEffect.}
## resets an object `obj` to its initial (binary zero) value. This needs to
## be called before any possible `object branch transition`:idx:.
when defined(nimNewRuntime):
proc wasMoved*[T](obj: var T) {.magic: "WasMoved", 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.
discard
proc move*[T](x: var T): T {.magic: "Move", noSideEffect.} =
result = x
wasMoved(x)
type
range*{.magic: "Range".}[T] ## Generic type to construct range types.
array*{.magic: "Array".}[I, T] ## Generic type to construct
## fixed-length arrays.
openArray*{.magic: "OpenArray".}[T] ## Generic type to construct open arrays.
## Open arrays are implemented as a
## pointer to the array data and a
## length field.
varargs*{.magic: "Varargs".}[T] ## Generic type to construct a varargs type.
seq*{.magic: "Seq".}[T] ## Generic type to construct sequences.
set*{.magic: "Set".}[T] ## Generic type to construct bit sets.
UncheckedArray* {.unchecked.}[T] = array[0, T]
## Array with no bounds checking
when defined(nimHasOpt):
type opt*{.magic: "Opt".}[T]
when defined(nimNewRuntime):
type sink*{.magic: "BuiltinType".}[T]
type lent*{.magic: "BuiltinType".}[T]
proc high*[T: Ordinal](x: T): T {.magic: "High", noSideEffect.}
## returns the highest possible index of an array, a sequence, a string or
## the highest possible value of an ordinal value `x`. As a special
## semantic rule, `x` may also be a type identifier.
## ``high(int)`` is Nim's way of writing `INT_MAX`:idx: or `MAX_INT`:idx:.
##
## .. code-block:: nim
## var arr = [1,2,3,4,5,6,7]
## high(arr) #=> 6
## high(2) #=> 9223372036854775807
## high(int) #=> 9223372036854775807
proc high*[T: Ordinal|enum](x: typeDesc[T]): T {.magic: "High", noSideEffect.}
proc high*[T](x: openArray[T]): int {.magic: "High", noSideEffect.}
proc high*[I, T](x: array[I, T]): I {.magic: "High", noSideEffect.}
proc high*[I, T](x: typeDesc[array[I, T]]): I {.magic: "High", noSideEffect.}
proc high*(x: cstring): int {.magic: "High", noSideEffect.}
proc high*(x: string): int {.magic: "High", noSideEffect.}
proc low*[T: Ordinal|enum](x: typeDesc[T]): T {.magic: "Low", noSideEffect.}
proc low*[T](x: openArray[T]): int {.magic: "Low", noSideEffect.}
proc low*[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect.}
proc low*[T](x: T): T {.magic: "Low", noSideEffect.}
proc low*[I, T](x: typeDesc[array[I, T]]): I {.magic: "Low", noSideEffect.}
proc low*(x: cstring): int {.magic: "Low", noSideEffect.}
proc low*(x: string): int {.magic: "Low", noSideEffect.}
## returns the lowest possible index of an array, a sequence, a string or
## the lowest possible value of an ordinal value `x`. As a special
## semantic rule, `x` may also be a type identifier.
##
## .. code-block:: nim
## var arr = [1,2,3,4,5,6,7]
## low(arr) #=> 0
## low(2) #=> -9223372036854775808
## low(int) #=> -9223372036854775808
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.
when defined(nimArrIdx):
# :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: S) {.noSideEffect, magic: "ArrPut".}
proc `=`*[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(nimNewRuntime):
proc `=destroy`*[T](x: var T) {.inline, magic: "Asgn".} =
## generic `destructor`:idx: implementation that can be overriden.
discard
proc `=sink`*[T](x: var T; y: T) {.inline, magic: "Asgn".} =
## generic `sink`:idx: implementation that can be overriden.
shallowCopy(x, y)
type
HSlice*[T, U] = object ## "heterogenous" 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: T, b: 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.
result.a = a
result.b = b
proc `..`*[T](b: T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot".} =
## unary `slice`:idx: operator that constructs an interval ``[default(int), b]``
result.b = b
when not defined(niminheritable):
{.pragma: inheritable.}
when not defined(nimunion):
{.pragma: unchecked.}
# comparison operators:
proc `==`*[Enum: enum](x, y: Enum): bool {.magic: "EqEnum", noSideEffect.}
## Checks whether values within the *same enum* have the same underlying value
##
## .. code-block:: nim
## type
## Enum1 = enum
## Field1 = 3, Field2
## Enum2 = enum
## Place1, Place2 = 3
## var
## e1 = Field1
## e2 = Enum1(Place2)
## echo (e1 == e2) # true
## echo (e1 == Place2) # raises error
proc `==`*(x, y: pointer): bool {.magic: "EqRef", noSideEffect.}
## .. code-block:: nim
## var # this is a wildly dangerous example
## a = cast[pointer](0)
## b = cast[pointer](nil)
## echo (a == b) # true due to the special meaning of `nil`/0 as a pointer
proc `==`*(x, y: string): bool {.magic: "EqStr", noSideEffect.}
## Checks for equality between two `string` variables
proc `==`*(x, y: char): bool {.magic: "EqCh", noSideEffect.}
## Checks for equality between two `char` variables
proc `==`*(x, y: bool): bool {.magic: "EqB", noSideEffect.}
## Checks for equality between two `bool` variables
proc `==`*[T](x, y: set[T]): bool {.magic: "EqSet", noSideEffect.}
## Checks for equality between two variables of type `set`
##
## .. code-block:: nim
## var a = {1, 2, 2, 3} # duplication in sets is ignored
## var b = {1, 2, 3}
## echo (a == b) # true
proc `==`*[T](x, y: ref T): bool {.magic: "EqRef", noSideEffect.}
## Checks that two `ref` variables refer to the same item
proc `==`*[T](x, y: ptr T): bool {.magic: "EqRef", noSideEffect.}
## Checks that two `ptr` variables refer to the same item
proc `==`*[T: proc](x, y: T): bool {.magic: "EqProc", noSideEffect.}
## Checks that two `proc` variables refer to the same procedure
proc `<=`*[Enum: enum](x, y: Enum): bool {.magic: "LeEnum", noSideEffect.}
proc `<=`*(x, y: string): bool {.magic: "LeStr", noSideEffect.}
proc `<=`*(x, y: char): bool {.magic: "LeCh", noSideEffect.}
proc `<=`*[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect.}
proc `<=`*(x, y: bool): bool {.magic: "LeB", noSideEffect.}
proc `<=`*[T](x, y: ref T): bool {.magic: "LePtr", noSideEffect.}
proc `<=`*(x, y: pointer): bool {.magic: "LePtr", noSideEffect.}
proc `<`*[Enum: enum](x, y: Enum): bool {.magic: "LtEnum", noSideEffect.}
proc `<`*(x, y: string): bool {.magic: "LtStr", noSideEffect.}
proc `<`*(x, y: char): bool {.magic: "LtCh", noSideEffect.}
proc `<`*[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect.}
proc `<`*(x, y: bool): bool {.magic: "LtB", noSideEffect.}
proc `<`*[T](x, y: ref T): bool {.magic: "LtPtr", noSideEffect.}
proc `<`*[T](x, y: ptr T): bool {.magic: "LtPtr", noSideEffect.}
proc `<`*(x, y: pointer): bool {.magic: "LtPtr", noSideEffect.}
template `!=`*(x, y: untyped): untyped =
## unequals operator. This is a shorthand for ``not (x == y)``.
not (x == y)
template `>=`*(x, y: untyped): untyped =
## "is greater or equals" operator. This is the same as ``y <= x``.
y <= x
template `>`*(x, y: untyped): untyped =
## "is greater" operator. This is the same as ``y < x``.
y < x
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'.
when not defined(JS) and not defined(gcDestructors):
type
TGenericSeq {.compilerproc, pure, inheritable.} = object
len, reserved: int
when defined(gogc):
elemSize: 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 not defined(JS) and not defined(nimscript):
when not defined(gcDestructors):
template space(s: PGenericSeq): int {.dirty.} =
s.reserved and not (seqShallowFlag or strlitFlag)
include "system/hti"
type
byte* = uint8 ## this is an alias for ``uint8``, that is an unsigned
## int 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.
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 allowed.
RootRef* = ref RootObj ## reference to RootObj
RootEffect* {.compilerproc.} = object of RootObj ## \
## base effect class; each effect should
## inherit from `RootEffect` unless you know what
## you doing.
TimeEffect* = object of RootEffect ## Time effect.
IOEffect* = object of RootEffect ## IO effect.
ReadIOEffect* = object of IOEffect ## Effect describing a read IO operation.
WriteIOEffect* = object of IOEffect ## Effect describing a write IO operation.
ExecIOEffect* = object of IOEffect ## Effect describing an executing IO operation.
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
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]
raise_id: uint # set when exception is raised
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.
IOError* = object of CatchableError ## \
## Raised if an IO error occurred.
EOFError* = object of IOError ## \
## Raised if an IO "end of file" error occurred.
OSError* = object of CatchableError ## \
## Raised if an operating system service failed.
errorCode*: int32 ## OS-defined error code describing this error.
LibraryError* = object of OSError ## \
## Raised if a dynamic library could not be loaded.
ResourceExhaustedError* = object of CatchableError ## \
## Raised if a resource request could not be fulfilled.
ArithmeticError* = object of Defect ## \
## Raised if any kind of arithmetic error occurred.
DivByZeroError* = object of ArithmeticError ## \
## Raised for runtime integer divide-by-zero errors.
OverflowError* = object of ArithmeticError ## \
## Raised for runtime integer overflows.
##
## This happens for calculations whose results are too large to fit in the
## provided bits.
AccessViolationError* = object of Defect ## \
## Raised for invalid memory access errors
AssertionError* = object of Defect ## \
## Raised when assertion is proved wrong.
##
## Usually the result of using the `assert() template <#assert>`_.
ValueError* = object of Defect ## \
## Raised for string and object conversion errors.
KeyError* = object of ValueError ## \
## Raised if a key cannot be found in a table.
##
## Mostly used by the `tables <tables.html>`_ module, it can also be raised
## by other collection modules like `sets <sets.html>`_ or `strtabs
## <strtabs.html>`_.
OutOfMemError* = object of Defect ## \
## Raised for unsuccessful attempts to allocate memory.
IndexError* = object of Defect ## \
## Raised if an array index is out of bounds.
FieldError* = object of Defect ## \
## Raised if a record field is not accessible because its dicriminant's
## value does not fit.
RangeError* = object of Defect ## \
## Raised if a range check error occurred.
StackOverflowError* = object of Defect ## \
## Raised if the hardware stack used for subroutine calls overflowed.
ReraiseError* = object of Defect ## \
## Raised if there is no exception to reraise.
ObjectAssignmentError* = object of Defect ## \
## Raised if an object gets assigned to its parent's object.
ObjectConversionError* = object of Defect ## \
## Raised if an object is converted to an incompatible object type.
## You can use ``of`` operator to check if conversion will succeed.
FloatingPointError* = object of Defect ## \
## Base class for floating point exceptions.
FloatInvalidOpError* = object of FloatingPointError ## \
## Raised by invalid operations according to IEEE.
##
## Raised by ``0.0/0.0``, for example.
FloatDivByZeroError* = object of FloatingPointError ## \
## Raised by division by zero.
##
## Divisor is zero and dividend is a finite nonzero number.
FloatOverflowError* = object of FloatingPointError ## \
## Raised for overflows.
##
## The operation produced a result that exceeds the range of the exponent.
FloatUnderflowError* = object of FloatingPointError ## \
## Raised for underflows.
##
## The operation produced a result that is too small to be represented as a
## normal number.
FloatInexactError* = object of FloatingPointError ## \
## Raised for inexact results.
##
## The operation produced a result that cannot be represented with infinite
## precision -- for example: ``2.0 / 3.0, log(1.1)``
##
## **NOTE**: Nim currently does not detect these!
DeadThreadError* = object of Defect ## \
## Raised if it is attempted to send a message to a dead thread.
NilAccessError* = object of Defect ## \
## Raised on dereferences of ``nil`` pointers.
##
## This is only raised if the ``segfaults.nim`` module was imported!
when defined(nimNewRuntime):
type
MoveError* = object of Defect ## \
## Raised on attempts to re-sink an already consumed ``sink`` parameter.
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!
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`` 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 within nim VM context ``sizeof`` will only work
## for simple types.
##
## .. code-block:: nim
## sizeof('A') #=> 1
## sizeof(2) #=> 8
when defined(nimtypedescfixed):
proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}
proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect, deprecated.}
## unary ``<`` that can be used for nice looking excluding ranges:
##
## .. code-block:: nim
## for i in 0 .. <10: echo i #=> 0 1 2 3 4 5 6 7 8 9
##
## Semantically this is the same as ``pred``.
##
## **Deprecated since version 0.18.0**. For the common excluding range
## write ``0 ..< 10`` instead of ``0 .. < 10`` (look at the spacing).
## For ``<x`` write ``pred(x)``.
proc succ*[T: Ordinal](x: T, y = 1): T {.magic: "Succ", noSideEffect.}
## returns the ``y``-th successor of the value ``x``. ``T`` has to be
## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised
## or a compile time error occurs.
proc pred*[T: Ordinal](x: T, y = 1): T {.magic: "Pred", noSideEffect.}
## returns the ``y``-th predecessor of the value ``x``. ``T`` has to be
## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised
## or a compile time error occurs.
proc inc*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Inc", noSideEffect.}
## increments the ordinal ``x`` by ``y``. If such a value does not
## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a
## short notation for: ``x = succ(x, y)``.
##
## .. code-block:: nim
## var i = 2
## inc(i) #=> 3
## inc(i, 3) #=> 6
proc dec*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Dec", noSideEffect.}
## decrements the ordinal ``x`` by ``y``. If such a value does not
## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a
## short notation for: ``x = pred(x, y)``.
##
## .. code-block:: nim
## var i = 2
## dec(i) #=> 1
## dec(i, 3) #=> -2
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, which can be a
## problem for sequences containing strings since their value will be
## ``nil``. After the creation of the sequence you should assign entries to
## the sequence instead of adding them. Example:
##
## .. code-block:: nim
## var inputStrings : seq[string]
## newSeq(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, which can be a
## problem for sequences containing strings since their value will be
## ``nil``. After the creation of the sequence you should assign entries to
## the sequence instead of adding them. Example:
##
## .. code-block:: nim
## var inputStrings = newSeq[string](3)
## inputStrings[0] = "The fourth"
## inputStrings[1] = "assignment"
## inputStrings[2] = "would crash"
## #inputStrings[3] = "out of bounds"
newSeq(result, len)
proc newSeqOfCap*[T](cap: Natural): seq[T] {.
magic: "NewSeqOfCap", noSideEffect.} =
## creates a new sequence of type ``seq[T]`` with length 0 and capacity
## ``cap``.
discard
when not defined(JS) and not defined(gcDestructors):
# XXX enable this for --gc:destructors
proc newSeqUninitialized*[T: SomeNumber](len: Natural): seq[T] =
## creates a new sequence of type ``seq[T]`` with length ``len``.
##
## Only available for numbers types. Note that the sequence will be
## uninitialized. After the creation of the sequence you should assign
## entries to the sequence instead of adding them.
result = newSeqOfCap[T](len)
var s = cast[PGenericSeq](result)
s.len = len
proc len*[TOpenArray: openArray|varargs](x: TOpenArray): int {.
magic: "LengthOpenArray", noSideEffect.}
proc len*(x: string): int {.magic: "LengthStr", noSideEffect.}
proc len*(x: cstring): int {.magic: "LengthStr", noSideEffect.}
proc len*(x: (type array)|array): int {.magic: "LengthArray", noSideEffect.}
proc len*[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}
## returns the length of an array, an openarray, a sequence or a string.
## This is roughly the same as ``high(T)-low(T)+1``, but its resulting type is
## always an int.
##
## .. code-block:: nim
## var arr = [1,1,1,1,1]
## len(arr) #=> 5
## for i in 0..<arr.len:
## echo arr[i] #=> 1,1,1,1,1
# set routines:
proc incl*[T](x: var set[T], y: T) {.magic: "Incl", noSideEffect.}
## includes element ``y`` to the set ``x``. This is the same as
## ``x = x + {y}``, but it might be more efficient.
##
## .. code-block:: nim
## var a = initSet[int](4)
## a.incl(2) #=> {2}
## a.incl(3) #=> {2, 3}
template incl*[T](s: var set[T], flags: set[T]) =
## includes the set of flags to the set ``x``.
s = s + flags
proc excl*[T](x: var set[T], y: T) {.magic: "Excl", noSideEffect.}
## excludes element ``y`` to the set ``x``. This is the same as
## ``x = x - {y}``, but it might be more efficient.
##
## .. code-block:: nim
## var b = {2,3,5,6,12,545}
## b.excl(5) #=> {2,3,6,12,545}
template excl*[T](s: var set[T], flags: set[T]) =
## excludes the set of flags to ``x``.
s = s - flags
proc card*[T](x: set[T]): int {.magic: "Card", noSideEffect.}
## returns the cardinality of the set ``x``, i.e. the number of elements
## in the set.
##
## .. code-block:: nim
## var i = {1,2,3,4}
## card(i) #=> 4
proc ord*[T: Ordinal|enum](x: T): int {.magic: "Ord", noSideEffect.}
## returns the internal int value of an ordinal value ``x``.
##
## .. code-block:: nim
## ord('A') #=> 65
proc chr*(u: range[0..255]): char {.magic: "Chr", noSideEffect.}
## converts an int in the range 0..255 to a character.
##
## .. code-block:: nim
## chr(65) #=> A
# --------------------------------------------------------------------------
# built-in operators
when not defined(JS):
proc ze*(x: int8): int {.magic: "Ze8ToI", noSideEffect.}
## zero extends a smaller integer type to ``int``. This treats `x` as
## unsigned.
proc ze*(x: int16): int {.magic: "Ze16ToI", noSideEffect.}
## zero extends a smaller integer type to ``int``. This treats `x` as
## unsigned.
proc ze64*(x: int8): int64 {.magic: "Ze8ToI64", noSideEffect.}
## zero extends a smaller integer type to ``int64``. This treats `x` as
## unsigned.
proc ze64*(x: int16): int64 {.magic: "Ze16ToI64", noSideEffect.}
## zero extends a smaller integer type to ``int64``. This treats `x` as
## unsigned.
proc ze64*(x: int32): int64 {.magic: "Ze32ToI64", noSideEffect.}
## zero extends a smaller integer type to ``int64``. This treats `x` as
## unsigned.
proc ze64*(x: int): int64 {.magic: "ZeIToI64", noSideEffect.}
## zero extends a smaller integer type to ``int64``. This treats `x` as
## unsigned. Does nothing if the size of an ``int`` is the same as ``int64``.
## (This is the case on 64 bit processors.)
proc toU8*(x: int): int8 {.magic: "ToU8", noSideEffect.}
## treats `x` as unsigned and converts it to a byte by taking the last 8 bits
## from `x`.
proc toU16*(x: int): int16 {.magic: "ToU16", noSideEffect.}
## treats `x` as unsigned and converts it to an ``int16`` by taking the last
## 16 bits from `x`.
proc toU32*(x: int64): int32 {.magic: "ToU32", noSideEffect.}
## treats `x` as unsigned and converts it to an ``int32`` by taking the
## last 32 bits from `x`.
# integer calculations:
proc `+`*(x: int): int {.magic: "UnaryPlusI", noSideEffect.}
proc `+`*(x: int8): int8 {.magic: "UnaryPlusI", noSideEffect.}
proc `+`*(x: int16): int16 {.magic: "UnaryPlusI", noSideEffect.}
proc `+`*(x: int32): int32 {.magic: "UnaryPlusI", noSideEffect.}
proc `+`*(x: int64): int64 {.magic: "UnaryPlusI", noSideEffect.}
## Unary `+` operator for an integer. Has no effect.
proc `-`*(x: int): int {.magic: "UnaryMinusI", noSideEffect.}
proc `-`*(x: int8): int8 {.magic: "UnaryMinusI", noSideEffect.}
proc `-`*(x: int16): int16 {.magic: "UnaryMinusI", noSideEffect.}
proc `-`*(x: int32): int32 {.magic: "UnaryMinusI", noSideEffect.}
proc `-`*(x: int64): int64 {.magic: "UnaryMinusI64", noSideEffect.}
## Unary `-` operator for an integer. Negates `x`.
proc `not`*(x: int): int {.magic: "BitnotI", noSideEffect.}
proc `not`*(x: int8): int8 {.magic: "BitnotI", noSideEffect.}
proc `not`*(x: int16): int16 {.magic: "BitnotI", noSideEffect.}
proc `not`*(x: int32): int32 {.magic: "BitnotI", noSideEffect.}
## computes the `bitwise complement` of the integer `x`.
when defined(nimnomagic64):
proc `not`*(x: int64): int64 {.magic: "BitnotI", noSideEffect.}
else:
proc `not`*(x: int64): int64 {.magic: "BitnotI64", noSideEffect.}
proc `+`*(x, y: int): int {.magic: "AddI", noSideEffect.}
proc `+`*(x, y: int8): int8 {.magic: "AddI", noSideEffect.}
proc `+`*(x, y: int16): int16 {.magic: "AddI", noSideEffect.}
proc `+`*(x, y: int32): int32 {.magic: "AddI", noSideEffect.}
## Binary `+` operator for an integer.
when defined(nimnomagic64):
proc `+`*(x, y: int64): int64 {.magic: "AddI", noSideEffect.}
else:
proc `+`*(x, y: int64): int64 {.magic: "AddI64", noSideEffect.}
proc `-`*(x, y: int): int {.magic: "SubI", noSideEffect.}
proc `-`*(x, y: int8): int8 {.magic: "SubI", noSideEffect.}
proc `-`*(x, y: int16): int16 {.magic: "SubI", noSideEffect.}
proc `-`*(x, y: int32): int32 {.magic: "SubI", noSideEffect.}
## Binary `-` operator for an integer.
when defined(nimnomagic64):
proc `-`*(x, y: int64): int64 {.magic: "SubI", noSideEffect.}
else:
proc `-`*(x, y: int64): int64 {.magic: "SubI64", noSideEffect.}
proc `*`*(x, y: int): int {.magic: "MulI", noSideEffect.}
proc `*`*(x, y: int8): int8 {.magic: "MulI", noSideEffect.}
proc `*`*(x, y: int16): int16 {.magic: "MulI", noSideEffect.}
proc `*`*(x, y: int32): int32 {.magic: "MulI", noSideEffect.}
## Binary `*` operator for an integer.
when defined(nimnomagic64):
proc `*`*(x, y: int64): int64 {.magic: "MulI", noSideEffect.}
else:
proc `*`*(x, y: int64): int64 {.magic: "MulI64", noSideEffect.}
proc `div`*(x, y: int): int {.magic: "DivI", noSideEffect.}
proc `div`*(x, y: int8): int8 {.magic: "DivI", noSideEffect.}
proc `div`*(x, y: int16): int16 {.magic: "DivI", noSideEffect.}
proc `div`*(x, y: int32): int32 {.magic: "DivI", noSideEffect.}
## computes the integer division. This is roughly the same as
## ``trunc(x/y)``.
##
## .. code-block:: Nim
## 1 div 2 == 0
## 2 div 2 == 1
## 3 div 2 == 1
## 7 div 5 == 1
when defined(nimnomagic64):
proc `div`*(x, y: int64): int64 {.magic: "DivI", noSideEffect.}
else:
proc `div`*(x, y: int64): int64 {.magic: "DivI64", noSideEffect.}
proc `mod`*(x, y: int): int {.magic: "ModI", noSideEffect.}
proc `mod`*(x, y: int8): int8 {.magic: "ModI", noSideEffect.}
proc `mod`*(x, y: int16): int16 {.magic: "ModI", noSideEffect.}
proc `mod`*(x, y: int32): int32 {.magic: "ModI", noSideEffect.}
## computes the integer modulo operation (remainder).
## This is the same as
## ``x - (x div y) * y``.
##
## .. code-block:: Nim
## (7 mod 5) == 2
when defined(nimnomagic64):
proc `mod`*(x, y: int64): int64 {.magic: "ModI", noSideEffect.}
else:
proc `mod`*(x, y: int64): int64 {.magic: "ModI64", noSideEffect.}
when defined(nimNewShiftOps):
proc `shr`*(x: int, y: SomeInteger): int {.magic: "ShrI", noSideEffect.}
proc `shr`*(x: int8, y: SomeInteger): int8 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x: int16, y: SomeInteger): int16 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x: int32, y: SomeInteger): int32 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x: int64, y: SomeInteger): int64 {.magic: "ShrI", noSideEffect.}
## computes the `shift right` operation of `x` and `y`, filling
## vacant bit positions with zeros.
##
## .. code-block:: Nim
## 0b0001_0000'i8 shr 2 == 0b0000_0100'i8
## 0b1000_0000'i8 shr 8 == 0b0000_0000'i8
## 0b0000_0001'i8 shr 1 == 0b0000_0000'i8
proc `shl`*(x: int, y: SomeInteger): int {.magic: "ShlI", noSideEffect.}
proc `shl`*(x: int8, y: SomeInteger): int8 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x: int16, y: SomeInteger): int16 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x: int32, y: SomeInteger): int32 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x: int64, y: SomeInteger): int64 {.magic: "ShlI", noSideEffect.}
## computes the `shift left` operation of `x` and `y`.
##
## .. code-block:: Nim
## 1'i32 shl 4 == 0x0000_0010
## 1'i64 shl 4 == 0x0000_0000_0000_0010
else:
proc `shr`*(x, y: int): int {.magic: "ShrI", noSideEffect.}
proc `shr`*(x, y: int8): int8 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x, y: int16): int16 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x, y: int32): int32 {.magic: "ShrI", noSideEffect.}
proc `shr`*(x, y: int64): int64 {.magic: "ShrI", noSideEffect.}
proc `shl`*(x, y: int): int {.magic: "ShlI", noSideEffect.}
proc `shl`*(x, y: int8): int8 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x, y: int16): int16 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x, y: int32): int32 {.magic: "ShlI", noSideEffect.}
proc `shl`*(x, y: int64): int64 {.magic: "ShlI", noSideEffect.}
when defined(nimAshr):
proc ashr*(x: int, y: SomeInteger): int {.magic: "AshrI", noSideEffect.}
proc ashr*(x: int8, y: SomeInteger): int8 {.magic: "AshrI", noSideEffect.}
proc ashr*(x: int16, y: SomeInteger): int16 {.magic: "AshrI", noSideEffect.}
proc ashr*(x: int32, y: SomeInteger): int32 {.magic: "AshrI", noSideEffect.}
proc ashr*(x: int64, y: SomeInteger): int64 {.magic: "AshrI", noSideEffect.}
## Shifts right by pushing copies of the leftmost bit in from the left,
## and let the rightmost bits fall off.
##
## .. code-block:: Nim
## 0b0001_0000'i8 shr 2 == 0b0000_0100'i8
## 0b1000_0000'i8 shr 8 == 0b1111_1111'i8
## 0b1000_0000'i8 shr 1 == 0b1100_0000'i8
else:
# used for bootstrapping the compiler
proc ashr*[T](x: T, y: SomeInteger): T = discard
proc `and`*(x, y: int): int {.magic: "BitandI", noSideEffect.}
proc `and`*(x, y: int8): int8 {.magic: "BitandI", noSideEffect.}
proc `and`*(x, y: int16): int16 {.magic: "BitandI", noSideEffect.}
proc `and`*(x, y: int32): int32 {.magic: "BitandI", noSideEffect.}
proc `and`*(x, y: int64): int64 {.magic: "BitandI", noSideEffect.}
## computes the `bitwise and` of numbers `x` and `y`.
##
## .. code-block:: Nim
## (0xffff'i16 and 0x0010'i16) == 0x0010
proc `or`*(x, y: int): int {.magic: "BitorI", noSideEffect.}
proc `or`*(x, y: int8): int8 {.magic: "BitorI", noSideEffect.}
proc `or`*(x, y: int16): int16 {.magic: "BitorI", noSideEffect.}
proc `or`*(x, y: int32): int32 {.magic: "BitorI", noSideEffect.}
proc `or`*(x, y: int64): int64 {.magic: "BitorI", noSideEffect.}
## computes the `bitwise or` of numbers `x` and `y`.
##
## .. code-block:: Nim
## (0x0005'i16 or 0x0010'i16) == 0x0015
proc `xor`*(x, y: int): int {.magic: "BitxorI", noSideEffect.}
proc `xor`*(x, y: int8): int8 {.magic: "BitxorI", noSideEffect.}
proc `xor`*(x, y: int16): int16 {.magic: "BitxorI", noSideEffect.}
proc `xor`*(x, y: int32): int32 {.magic: "BitxorI", noSideEffect.}
proc `xor`*(x, y: int64): int64 {.magic: "BitxorI", noSideEffect.}
## computes the `bitwise xor` of numbers `x` and `y`.
##
## .. code-block:: Nim