forked from nim-lang/Nim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
system.nim
4563 lines (4021 loc) · 164 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
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*[T] {.magic: Ordinal.} ## 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`*[T] {.magic: Pointer.} ## Built-in generic untraced pointer type.
`ref`*[T] {.magic: Pointer.} ## 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.
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
when defined(nimHasRunnableExamples):
proc runnableExamples*(body: untyped) {.magic: "RunnableExamples".}
## A section you should use to mark `runnable example`:idx: code with.
##
## - In normal debug and release builds code within
## a ``runnableExamples`` section is ignored.
## - The documentation generator is aware of these examples and considers them
## part of the ``##`` doc comment. As the last step of documentation
## generation each runnableExample is put in its own file ``$file_examples$i.nim``,
## compiled and tested. The collected examples are
## put into their own module to ensure the examples do not refer to
## non-exported symbols.
##
## Usage:
##
## .. code-block:: Nim
## proc double*(x: int): int =
## ## This proc doubles a number.
## runnableExamples:
## ## at module scope
## assert double(5) == 10
## block: ## at block scope
## defer: echo "done"
##
## result = 2 * x
else:
template runnableExamples*(body: untyped) =
discard
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.
##
## See also:
## * `declaredInScope <#declaredInScope,untyped>`_
##
## 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.
##
## See also:
## * `unsafeAddr <#unsafeAddr,T>`_
##
## .. code-block:: 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.} =
## 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 <#addr,T>`_.
##
## **Note**: 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`*[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``.
else:
proc `type`*(x: untyped): typedesc {.magic: "TypeOf", noSideEffect, compileTime.} =
## Builtin `type` operator for accessing the type of an expression.
## Cannot be overloaded.
discard
when defined(nimHasTypeof):
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.
discard
proc `not`*(x: bool): bool {.magic: "Not", noSideEffect.}
## Boolean not; returns true if ``x == false``.
proc `and`*(x, y: bool): bool {.magic: "And", noSideEffect.}
## Boolean ``and``; returns true if ``x == y == true`` (if both arguments
## are 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 if ``not (not x and not y)`` (if any of
## the arguments is true).
##
## 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 if ``x != y`` (if either argument
## is true while the other is false).
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!
when defined(nimV2):
proc reset*[T](obj: var T) {.magic: "Destroy", noSideEffect.}
## Old runtime target: Resets an object `obj` to its initial (binary zero) value.
##
## New runtime target: An alias for `=destroy`.
else:
proc reset*[T](obj: var T) {.magic: "Reset", noSideEffect.}
## Old runtime target: Resets an object `obj` to its initial (binary zero) value.
##
## New runtime target: An alias for `=destroy`.
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*[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.
when defined(nimUncheckedArrayTyp):
type
UncheckedArray*[T]{.magic: "UncheckedArray".}
## Array with no bounds checking.
else:
type
UncheckedArray*[T]{.unchecked.} = array[0,T]
## 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.}
## Returns the highest possible value of an ordinal value `x`.
##
## As a special semantic rule, `x` may also be a type identifier.
##
## See also:
## * `low(T) <#low,T>`_
##
## .. code-block:: 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:.
##
## See also:
## * `low(typedesc) <#low,typedesc[T]>`_
##
## .. code-block:: Nim
## high(int) # => 9223372036854775807
proc high*[T](x: openArray[T]): int {.magic: "High", noSideEffect.}
## Returns the highest possible index of a sequence `x`.
##
## See also:
## * `low(openArray) <#low,openArray[T]>`_
##
## .. code-block:: Nim
## var s = @[1, 2, 3, 4, 5, 6, 7]
## high(s) # => 6
## for i in low(s)..high(s):
## echo s[i]
proc high*[I, T](x: array[I, T]): I {.magic: "High", noSideEffect.}
## Returns the highest possible index of an array `x`.
##
## See also:
## * `low(array) <#low,array[I,T]>`_
##
## .. code-block:: Nim
## var arr = [1, 2, 3, 4, 5, 6, 7]
## high(arr) # => 6
## for i in low(arr)..high(arr):
## echo arr[i]
proc high*[I, T](x: typedesc[array[I, T]]): I {.magic: "High", noSideEffect.}
## Returns the highest possible index of an array type.
##
## See also:
## * `low(typedesc[array]) <#low,typedesc[array[I,T]]>`_
##
## .. code-block:: Nim
## high(array[7, int]) # => 6
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`.
##
## See also:
## * `low(string) <#low,string>`_
##
## .. code-block:: Nim
## var str = "Hello world!"
## high(str) # => 11
proc low*[T: Ordinal|enum|range](x: T): T {.magic: "Low", noSideEffect.}
## Returns the lowest possible value of an ordinal value `x`. As a special
## semantic rule, `x` may also be a type identifier.
##
## See also:
## * `high(T) <#high,T>`_
##
## .. code-block:: 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:.
##
## See also:
## * `high(typedesc) <#high,typedesc[T]>`_
##
## .. code-block:: Nim
## low(int) # => -9223372036854775808
proc low*[T](x: openArray[T]): int {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of a sequence `x`.
##
## See also:
## * `high(openArray) <#high,openArray[T]>`_
##
## .. code-block:: Nim
## var s = @[1, 2, 3, 4, 5, 6, 7]
## low(s) # => 0
## for i in low(s)..high(s):
## echo s[i]
proc low*[I, T](x: array[I, T]): I {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of an array `x`.
##
## See also:
## * `high(array) <#high,array[I,T]>`_
##
## .. code-block:: Nim
## var arr = [1, 2, 3, 4, 5, 6, 7]
## low(arr) # => 0
## for i in low(arr)..high(arr):
## echo arr[i]
proc low*[I, T](x: typedesc[array[I, T]]): I {.magic: "Low", noSideEffect.}
## Returns the lowest possible index of an array type.
##
## See also:
## * `high(typedesc[array]) <#high,typedesc[array[I,T]]>`_
##
## .. code-block:: Nim
## low(array[7, int]) # => 0
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`.
##
## See also:
## * `high(string) <#high,string>`_
##
## .. code-block:: Nim
## var str = "Hello world!"
## low(str) # => 0
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".}
proc `=destroy`*[T](x: var T) {.inline, magic: "Destroy".} =
## 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.
##
## .. code-block:: 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: T): HSlice[int, T] {.noSideEffect, inline, magic: "DotDot".} =
## Unary `slice`:idx: operator that constructs an interval ``[default(int), b]``.
##
## .. code-block:: Nim
## let a = [10, 20, 30, 40, 50]
## echo a[.. 2] # @[10, 20, 30]
result = HSlice[int, T](a: 0, b: b)
when not defined(niminheritable):
{.pragma: inheritable.}
when not defined(nimunion):
{.pragma: unchecked.}
when not defined(nimHasHotCodeReloading):
{.pragma: nonReloadable.}
when defined(hotCodeReloading):
{.pragma: hcrInline, inline.}
else:
{.pragma: hcrInline.}
# 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.}
## Compares two strings and returns true if `x` is lexicographically
## before `y` (uppercase letters come before lowercase letters).
##
## .. code-block:: Nim
## let
## a = "abc"
## b = "abd"
## c = "ZZZ"
## assert a <= b
## assert a <= a
## assert (a <= c) == false
proc `<=`*(x, y: char): bool {.magic: "LeCh", noSideEffect.}
## Compares two chars and returns true if `x` is lexicographically
## before `y` (uppercase letters come before lowercase letters).
##
## .. code-block:: Nim
## let
## a = 'a'
## b = 'b'
## c = 'Z'
## assert a <= b
## assert a <= a
## assert (a <= c) == false
proc `<=`*[T](x, y: set[T]): bool {.magic: "LeSet", noSideEffect.}
## Returns true if `x` is a subset of `y`.
##
## A subset `x` has all of its members in `y` and `y` doesn't necessarily
## have more members than `x`. That is, `x` can be equal to `y`.
##
## .. code-block:: Nim
## let
## a = {3, 5}
## b = {1, 3, 5, 7}
## c = {2}
## assert a <= b
## assert a <= a
## assert (a <= c) == false
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.}
## Compares two strings and returns true if `x` is lexicographically
## before `y` (uppercase letters come before lowercase letters).
##
## .. code-block:: Nim
## let
## a = "abc"
## b = "abd"
## c = "ZZZ"
## assert a < b
## assert (a < a) == false
## assert (a < c) == false
proc `<`*(x, y: char): bool {.magic: "LtCh", noSideEffect.}
## Compares two chars and returns true if `x` is lexicographically
## before `y` (uppercase letters come before lowercase letters).
##
## .. code-block:: Nim
## let
## a = 'a'
## b = 'b'
## c = 'Z'
## assert a < b
## assert (a < a) == false
## assert (a < c) == false
proc `<`*[T](x, y: set[T]): bool {.magic: "LtSet", noSideEffect.}
## Returns true if `x` is a strict or proper subset of `y`.
##
## A strict or proper subset `x` has all of its members in `y` but `y` has
## more elements than `y`.
##
## .. code-block:: Nim
## let
## a = {3, 5}
## b = {1, 3, 5, 7}
## c = {2}
## assert a < b
## assert (a < a) == false
## assert (a < c) == false
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)
when not defined(nimV2):
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.
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`.
RootEffect* {.compilerproc.} = object of RootObj ## \
## Base effect class.
##
## Each effect should inherit from `RootEffect` unless you know what
## you're 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]
when defined(nimBoostrapCsources0_19_0):
# see #10315, bootstrap with `nim cpp` from csources gave error:
# error: no member named 'raise_id' in 'Exception'
raise_id: uint # set when exception is raised
else:
raiseId: 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 CatchableError ## \
## 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 module <segfaults.html>`_ was imported!
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.
##
## .. code-block:: Nim
## sizeof('A') # => 1
## sizeof(2) # => 8
when defined(nimHasalignOf):
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.}
when defined(nimtypedescfixed):
proc sizeof*(x: typedesc): int {.magic: "SizeOf", noSideEffect.}
proc `<`*[T](x: Ordinal[T]): T {.magic: "UnaryLt", noSideEffect, deprecated.}
## **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)``.
##
## Unary ``<`` that can be used for excluding ranges.
## Semantically this is the same as `pred <#pred,T,int>`_.
##
## .. code-block:: Nim
## for i in 0 .. <10: echo i # => 0 1 2 3 4 5 6 7 8 9
##
proc succ*[T: Ordinal](x: T, y = 1): T {.magic: "Succ", noSideEffect.}
## Returns the ``y``-th successor (default: 1) of the value ``x``.
## ``T`` has to be an `ordinal type <#Ordinal>`_.
##
## If such a value does not exist, ``OverflowError`` is raised
## or a compile time error occurs.
##
## .. code-block:: Nim
## let x = 5
## echo succ(5) # => 6
## echo succ(5, 3) # => 8
proc pred*[T: Ordinal](x: T, y = 1): T {.magic: "Pred", noSideEffect.}
## Returns the ``y``-th predecessor (default: 1) of the value ``x``.
## ``T`` has to be an `ordinal type <#Ordinal>`_.
##
## If such a value does not exist, ``OverflowError`` is raised
## or a compile time error occurs.
##
## .. code-block:: Nim
## let x = 5
## echo pred(5) # => 4
## echo pred(5, 3) # => 2
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, ``OverflowError`` 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) # i <- 3
## inc(i, 3) # i <- 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, ``OverflowError`` 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) # i <- 1
## dec(i, 3) # i <- -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.
## 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)
## 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.
##
## See also:
## * `newSeqOfCap <#newSeqOfCap,Natural>`_
## * `newSeqUninitialized <#newSeqUninitialized,Natural>`_
##
## .. code-block:: 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"
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