lisette-stdlib 0.13.2

Little language inspired by Rust that compiles to Go
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
// Lisette prelude type definitions
//
// This file declares the types available in every Lisette program 
// without an explicit import. The compiler embeds this file at build
// time for type checking.

// -----------------------
//    Primitive types
// -----------------------

/// Signed integer (platform-dependent size).
type int

/// 8-bit signed integer.
type int8

/// 16-bit signed integer.
type int16

/// 32-bit signed integer.
type int32

/// 64-bit signed integer.
type int64

/// Alias for `int32`, for a Unicode code point.
type rune = int32

/// Unsigned integer (platform-dependent size).
type uint

/// 8-bit unsigned integer.
type uint8

/// 16-bit unsigned integer.
type uint16

/// 32-bit unsigned integer.
type uint32

/// 64-bit unsigned integer.
type uint64

/// Unsigned integer large enough to hold a pointer.
type uintptr

/// Alias for `uint8`, for raw byte data.
type byte = uint8

/// 32-bit floating-point number.
type float32

/// 64-bit floating-point number.
type float64

/// Complex number with `float32` real and imaginary parts.
type complex64

/// Complex number with `float64` real and imaginary parts.
type complex128

/// A boolean value: `true` or `false`.
///
/// Example:
///   let ready = true
///   if ready && count > 0 {
///     process()
///   }
type bool

/// A UTF-8 encoded string.
type string

impl string {
  /// Returns the number of bytes in the string. To count runes, use `runes().length()`.
  ///
  /// Example:
  ///   // !callout-right `5`, since `é` is two bytes
  ///   let bytes = "café".length()
  fn length(self) -> int

  /// Returns `true` if the string has length zero.
  ///
  /// Example:
  ///   // !callout-right `true`
  ///   let blank = "".is_empty()
  fn is_empty(self) -> bool

  /// Returns `true` if the string contains the given substring.
  ///
  /// Example:
  ///   // !callout-right `true`
  ///   let found = "hello world".contains("world")
  fn contains(self, substr: string) -> bool

  /// Splits the string around each occurrence of `sep` and returns the substrings.
  ///
  /// Example:
  ///   // !callout-right `["alice", "30", "berlin"]`
  ///   let fields = "alice,30,berlin".split(",")
  fn split(self, sep: string) -> mut Slice<string>

  /// Returns `true` if the string starts with `prefix`.
  ///
  /// Example:
  ///   // !callout-right `true`
  ///   let is_go = "go:fmt".starts_with("go:")
  fn starts_with(self, prefix: string) -> bool

  /// Returns `true` if the string ends with `suffix`.
  ///
  /// Example:
  ///   // !callout-right `true`
  ///   let is_lisette = "main.lis".ends_with(".lis")
  fn ends_with(self, suffix: string) -> bool

  /// Returns the byte at byte index `i`.
  ///
  /// Example:
  ///   // !callout-right `104`, the byte value of `h`
  ///   let first = "hello".byte_at(0)
  fn byte_at(self, i: int) -> byte

  /// Returns the rune at rune index `i`. The index counts runes, not bytes, so the last
  /// valid index is `runes().length() - 1`, not `length() - 1`.
  ///
  /// Example:
  ///   // !callout-right `233`, the code point of `é`
  ///   let accented = "café".rune_at(3)
  fn rune_at(self, i: int) -> rune

  /// Returns the bytes of the string as a `Slice<byte>`.
  ///
  /// Example:
  ///   // !callout-right `[104, 105]`, one byte per char
  ///   let raw = "hi".bytes()
  fn bytes(self) -> mut Slice<byte>

  /// Returns the runes of the string as a `Slice<rune>`.
  ///
  /// Example:
  ///   // !callout-right `[99, 97, 102, 233]`, one code point per char
  ///   let points = "café".runes()
  ///   // !callout-right `4`, one fewer than `length()`
  ///   let count = points.length()
  fn runes(self) -> mut Slice<rune>

  /// Returns the substring at the given rune-indexed range.
  ///
  /// Example:
  ///   // !callout-right `"hello"`
  ///   let word = "hello world".substring(0..5)
  fn substring(self, r: Range<int>) -> string
}

// -----------------------
//     Composite types
// -----------------------

/// A value that may or may not be present. Equivalent to Go's `(T, bool)`.
enum Option<T> {
  Some(T),
  None,
}

impl<T> Option<T> {
  /// Returns `true` if `Option` wraps a value.
  ///
  /// Example:
  ///   // !callout[/is_some\(\)/] `true` if `id` was found
  ///   let found = users.get(id).is_some()
  fn is_some(self) -> bool

  /// Returns `true` if `Option` is `None`.
  ///
  /// Example:
  ///   // !callout[/is_none\(\)/] `false` if `id` was found
  ///   let missing = users.get(id).is_none()
  fn is_none(self) -> bool

  /// Returns the wrapped value, or `default` if `None`.
  ///
  /// Example:
  ///   // !callout[/unwrap_or/] `"alice"` if `id` was found, else `"stranger"`
  ///   let name = users.get(id).unwrap_or("stranger")
  fn unwrap_or(self, default: T) -> T

  /// Returns the wrapped value, or computes it from `f` if `None`.
  ///
  /// Example:
  ///   // !callout[/unwrap_or_else/] runs `f` only if `id` was absent
  ///   let name = users.get(id).unwrap_or_else(|| default_name())
  fn unwrap_or_else(self, f: fn() -> T) -> T

  /// Applies `f` to the wrapped value, or returns `None` if `None`.
  ///
  /// Example:
  ///   // !callout[/map/] `Some(5)` for `"alice"`
  ///   let length = users.get(id).map(|name| name.length())
  fn map<U>(self, f: fn(T) -> U) -> Option<U>

  /// Applies `f` to the wrapped value, or returns `default` if `None`.
  ///
  /// Example:
  ///   // !callout[/map_or/] `5` for `"alice"`, `0` when absent
  ///   let length = users.get(id).map_or(0, |name| name.length())
  fn map_or<U>(self, default: U, f: fn(T) -> U) -> U

  /// Applies `f` to the wrapped value, or computes a default from
  /// `default` if `None`.
  ///
  /// Example:
  ///   // !callout-above[/map_or_else/] runs `default` only if `id` was absent
  ///   let length = users.get(id).map_or_else(
  ///     || 0,
  ///     |name| name.length(),
  ///   )
  fn map_or_else<U>(self, default: fn() -> U, f: fn(T) -> U) -> U

  /// Calls `f` with the wrapped value and returns its own `Option`,
  /// or returns `None` if `None`.
  ///
  /// Example:
  ///   // !callout[/and_then/] `Some(30)`, chaining one lookup into the next
  ///   let age = users.get(id).and_then(|name| ages.get(name))
  fn and_then<U>(self, f: fn(T) -> Option<U>) -> Option<U>

  /// Returns `Option` if it is `Some`, otherwise calls `f`.
  ///
  /// Example:
  ///   // !callout[/or_else/] runs `f` only if `id` was absent
  ///   let name = users.get(id).or_else(|| Some("stranger"))
  fn or_else(self, f: fn() -> Option<T>) -> Option<T>

  /// Returns the `Option` if it is `Some` and `f` returns `true`, otherwise `None`.
  ///
  /// Example:
  ///   // !callout[/filter/] drops an empty name
  ///   let named = users.get(id).filter(|name| !name.is_empty())
  fn filter(self, f: fn(T) -> bool) -> Option<T>

  /// Takes the value out of `Option`, leaving `None` in its place.
  ///
  /// Example:
  ///   let mut slot = users.get(id)
  ///   // !callout[/take\(\)/] `Some("alice")`
  ///   let taken = slot.take()
  ///   // !callout[/is_none\(\)/] `true`, the slot is now `None`
  ///   let emptied = slot.is_none()
  fn take(self: mut Ref<Option<T>>) -> Option<T>

  /// Transforms `Option<T>` into `Result<T, E>`, mapping `Some(v)`
  /// to `Ok(v)` and `None` to `Err(err)`.
  ///
  /// Example:
  ///   // !callout[/ok_or/] `Ok("alice")` if `id` was found
  ///   let result = users.get(id).ok_or("no such user")
  fn ok_or<E>(self, err: E) -> Result<T, E>

  /// Transforms `Option<T>` into `Result<T, E>`, mapping `Some(v)`
  /// to `Ok(v)` and `None` to `Err(f())`.
  ///
  /// Example:
  ///   // !callout[/ok_or_else/] runs `f` only if `id` was absent
  ///   let result = users.get(id).ok_or_else(|| missing_user(id))
  fn ok_or_else<E>(self, f: fn() -> E) -> Result<T, E>

  /// Pairs two `Option` values into one `Option` of a tuple.
  /// Returns `Some((a, b))` if both are `Some`, otherwise `None`.
  ///
  /// Example:
  ///   // !callout[/zip/] `Some(("alice", 30))` when both were found
  ///   let pair = users.get(id).zip(age)
  fn zip<U>(self, other: Option<U>) -> Option<(T, U)>
}

impl<U> Option<Option<U>> {
  /// Converts `Option<Option<U>>` into `Option<U>`.
  ///
  /// Example:
  ///   let nested = users.get(id).map(|name| ages.get(name))
  ///   // !callout[/flatten/] `Some(30)`, one `Option` instead of two
  ///   let age = nested.flatten()
  fn flatten(self) -> Option<U>
}

/// A result that either succeeded or failed. Equivalent to Go's `(T, error)`, or to a
/// bare `error` when there is no value to carry.
enum Result<T, E> {
  Ok(T),
  Err(E),
}

impl<T, E> Result<T, E> {
  /// Returns `true` if `Result` is `Ok`.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/is_ok\(\)/] `true` if `raw` parsed
  ///   let succeeded = strconv.Atoi(raw).is_ok()
  fn is_ok(self) -> bool

  /// Returns `true` if `Result` is `Err`.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/is_err\(\)/] `false` if `raw` parsed
  ///   let failed = strconv.Atoi(raw).is_err()
  fn is_err(self) -> bool

  /// Converts to `Option<T>`, discarding the error if any.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/ok\(\)/] `Some(8080)` if `raw` parsed
  ///   let maybe_port = strconv.Atoi(raw).ok()
  fn ok(self) -> Option<T>

  /// Converts to `Option<E>`, discarding the success value if any.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/err\(\)/] `None` if `raw` parsed
  ///   let maybe_failure = strconv.Atoi(raw).err()
  fn err(self) -> Option<E>

  /// Returns the wrapped `Ok` value, or `default` if `Err`.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/unwrap_or/] `8080` if `raw` parsed, else `80`
  ///   let port = strconv.Atoi(raw).unwrap_or(80)
  fn unwrap_or(self, default: T) -> T

  /// Returns the wrapped `Ok` value, or computes it by calling `f` with the `Err` value.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout-above[/unwrap_or_else/] runs `f` only if `raw` failed to parse
  ///   let port = strconv.Atoi(raw).unwrap_or_else(|failure| {
  ///     fmt.Println(failure.Error())
  ///     80
  ///   })
  fn unwrap_or_else(self, f: fn(E) -> T) -> T

  /// Transforms the `Ok` value by applying `f`, leaving `Err` unchanged.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/map/] `Ok(16160)` if `raw` parsed
  ///   let doubled = strconv.Atoi(raw).map(|n| n * 2)
  fn map<U>(self, f: fn(T) -> U) -> Result<U, E>

  /// Transforms the `Err` value by applying `f`, leaving `Ok` unchanged.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/map_err/] leaves `Ok(8080)` untouched
  ///   let described = strconv.Atoi(raw).map_err(|failure| failure.Error())
  fn map_err<F>(self, f: fn(E) -> F) -> Result<T, F>

  /// Returns `default` if `Err`, otherwise applies `f` to the `Ok` value.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/map_or/] `16160` if `raw` parsed, else `0`
  ///   let doubled = strconv.Atoi(raw).map_or(0, |n| n * 2)
  fn map_or<U>(self, default: U, f: fn(T) -> U) -> U

  /// Applies `default` to the `Err` value, or `f` to the `Ok` value.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout-above[/map_or_else/] port, or parse error
  ///   let shown = strconv.Atoi(raw).map_or_else(
  ///     |failure| failure.Error(),
  ///     strconv.Itoa,
  ///   )
  fn map_or_else<U>(self, default: fn(E) -> U, f: fn(T) -> U) -> U

  /// Calls `f` with the `Ok` value and returns the result,
  /// leaving `Err` unchanged.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout-above[/and_then/] a second check, run only if `raw` parsed
  ///   let port = strconv.Atoi(raw).and_then(|n| {
  ///     if n <= 65535 { Ok(n) } else { Err(errors.New("port out of range")) }
  ///   })
  fn and_then<U>(self, f: fn(T) -> Result<U, E>) -> Result<U, E>

  /// Calls `f` with the `Err` value and returns the result,
  /// leaving `Ok` unchanged.
  ///
  /// Example:
  ///   let raw = "8080"
  ///   // !callout[/or_else/] runs `f` only if `raw` failed to parse
  ///   let port = strconv.Atoi(raw).or_else(|_| strconv.Atoi("80"))
  fn or_else<F>(self, f: fn(E) -> Result<T, F>) -> Result<T, F>
}

impl<T> Result<T, error> {
  /// Wraps the `Err` value with `msg` and the original error, leaving `Ok` unchanged.
  ///
  /// Example:
  ///   // !callout[/wrap_err/] `Err("read port: ...")`, keeping the original
  ///   let port = strconv.Atoi(raw).wrap_err("read port")
  fn wrap_err(self, msg: string) -> Result<T, error>
}

/// A result where _both_ a value and an error may be meaningful. Equivalent to Go's
/// `(T, error)`, where the two are not exclusive.
///
/// A common use case is `io.Reader.Read`, where `(n > 0, io.EOF)` means that
/// `n` bytes arrived and the stream ended.
///
/// `Err` arises only where the Go call can return no value at all, such as a nil
/// slice or a nil pointer. `io.Reader.Read` returns an `int`, which always carries
/// a value, so it yields `Ok` or `Both` and never `Err`.
enum Partial<T, E> {
  Ok(T),
  Err(E),
  Both(T, E),
}

impl<T, E> Partial<T, E> {
  /// Returns `true` if `Partial` is `Ok`.
  ///
  /// Example:
  ///   // !callout[/is_ok\(\)/] `true`, the read filled without ending
  ///   let complete = outcome.is_ok()
  fn is_ok(self) -> bool

  /// Returns `true` if `Partial` is `Err`.
  ///
  /// Example:
  ///   // !callout[/is_err\(\)/] `true` only when the call returned no value at all
  ///   let failed = outcome.is_err()
  fn is_err(self) -> bool

  /// Returns `true` if `Partial` is `Both`.
  ///
  /// Example:
  ///   // !callout[/is_both\(\)/] `true` when bytes arrived and the stream ended
  ///   let stopped_early = outcome.is_both()
  fn is_both(self) -> bool

  /// Returns `Some(value)` if `Ok` or `Both`, otherwise `None`.
  ///
  /// Example:
  ///   // !callout[/ok\(\)/] `Some(5)`, the byte count
  ///   let maybe_count = outcome.ok()
  fn ok(self) -> Option<T>

  /// Returns `Some(error)` if `Err` or `Both`, otherwise `None`.
  ///
  /// Example:
  ///   // !callout[/err\(\)/] `None` when the read carried no error
  ///   let maybe_reason = outcome.err()
  fn err(self) -> Option<E>

  /// Returns the wrapped value if `Ok` or `Both`, otherwise `default`.
  ///
  /// Example:
  ///   // !callout[/unwrap_or/] `5`, or `0` when the read failed outright
  ///   let count = outcome.unwrap_or(0)
  fn unwrap_or(self, default: T) -> T

  /// Returns the wrapped value if `Ok` or `Both`, or computes it by calling `f`
  /// with the error.
  ///
  /// Example:
  ///   // !callout[/unwrap_or_else/] runs `f` only when the read failed outright
  ///   let count = outcome.unwrap_or_else(|failure| failure.Error().length())
  fn unwrap_or_else(self, f: fn(E) -> T) -> T

  /// Applies `f` to the wrapped value of an `Ok` or a `Both`, leaving `Err`
  /// unchanged.
  ///
  /// Example:
  ///   // !callout[/map/] `Ok(40)`, the byte count in bits
  ///   let bits = outcome.map(|count| count * 8)
  fn map<U>(self, f: fn(T) -> U) -> Partial<U, E>

  /// Applies `f` to the error of an `Err` or a `Both`, leaving `Ok` unchanged.
  ///
  /// Example:
  ///   // !callout[/map_err/] leaves `Ok(5)` untouched
  ///   let described = outcome.map_err(|failure| failure.Error())
  fn map_err<F>(self, f: fn(E) -> F) -> Partial<T, F>
}

/// A fixed-size, indexable sequence of elements. Equivalent to Go's `[N]T`.
///
/// The size is part of the type, so `Array<byte, 2>` and `Array<byte, 4>` are distinct types.
///
/// A list literal is a `Slice` by default, so an `Array` needs the annotation.
///
/// Example:
///   // !callout-right `Array<int, 3>`
///   let rgb: Array<int, 3> = [255, 128, 0]
///   // !callout-right `Slice<int>`
///   let growable = [255, 128, 0]
type Array<T>

impl<T> Array<T> {
  /// Returns the size of the `Array`.
  ///
  /// Example:
  ///   let rgb: Array<int, 3> = [255, 128, 0]
  ///   // !callout-right `3`
  ///   let size = rgb.length()
  fn length(self) -> int

  /// Returns the element at `index`, or `None` if out of bounds.
  ///
  /// Example:
  ///   let rgb: Array<int, 3> = [255, 128, 0]
  ///   // !callout[/get/] `Some(128)`, or `None` when out of bounds
  ///   let green = rgb.get(1)
  fn get(self, index: int) -> Option<T>

  /// Copies the elements of the `Array` into a new `Slice`.
  ///
  /// Example:
  ///   let parts: Array<string, 3> = ["a", "b", "c"]
  ///   // !callout[/to_slice\(\)/] `strings.Join` takes a `Slice`, not an `Array`
  ///   let path = strings.Join(parts.to_slice(), "-")
  fn to_slice(self) -> mut Slice<T>
}

/// A growable, indexable sequence of elements. Equivalent to Go's `[]T`.
///
/// Example:
///   let scores = [90, 75, 88]
///   // !callout-right `90`
///   let first = scores[0]
///   // !callout-right `[75, 88]`
///   let rest = scores[1..3]
///   for score in scores {
///     // !callout-right `90`, then `75`, then `88`
///     fmt.Println(score)
///   }
type Slice<T>

impl<T> Slice<T> {
  /// Creates an empty `Slice`.
  ///
  /// Example:
  ///   // !callout-right `[]`
  ///   let scores = Slice.new<int>()
  fn new() -> mut Slice<T>

  /// Creates a `Slice` of `length` elements, each set to its zero value, if any.
  /// The `Slice` starts with no spare capacity.
  ///
  /// Example:
  ///   // !callout-right `[0, 0, 0]`
  ///   let scores = Slice.make<int>(3)
  fn make(length: int) -> mut Slice<T>

  /// Returns the number of elements in the `Slice`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `3`
  ///   let count = scores.length()
  fn length(self) -> int

  /// Returns `true` if the `Slice` holds no elements.
  ///
  /// Example:
  ///   let scores = Slice.new<int>()
  ///   // !callout-right `true`
  ///   let blank = scores.is_empty()
  fn is_empty(self) -> bool

  /// Returns the number of elements the `Slice` can hold before reallocating.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `3`
  ///   let room = scores.capacity()
  fn capacity(self) -> int

  /// Returns a `Slice` with capacity for at least `additional` more elements.
  ///
  /// Example:
  ///   let mut scores = [90, 75, 88]
  ///   // !callout[/reserve/] room for `100` more, length still `3`
  ///   scores = scores.reserve(100)
  fn reserve(self, additional: int) -> mut Slice<T>

  /// Returns the element at `index`, or `None` if out of bounds. Indexing out of
  /// range with `[]` panics, so use `get()` for a checked index.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout[/get/] `Some(75)`, or `None` when out of bounds
  ///   let second = scores.get(1)
  fn get(self, index: int) -> Option<T>

  /// Returns a new `Slice` with the given elements appended. Does not modify the
  /// original `Slice`, so reassign the output to grow in place.
  ///
  /// Example:
  ///   let digits = [1, 2]
  ///   // !callout-right `[1, 2, 3]`
  ///   let extended = digits.append(3)
  ///   let more = [4, 5]
  ///   // !callout-right `[1, 2, 3, 4, 5]`
  ///   let joined = extended.append(more...)
  fn append(self, elements: VarArgs<T>) -> mut Slice<T>

  /// Overwrites the elements of this `Slice` in place with elements from `src`,
  /// up to the shorter of the two lengths. Returns the number of elements copied.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   let mut head = Slice.make<int>(2)
  ///   // !callout[/copy_from/] `2`, the shorter length, leaving `[90, 75]`
  ///   let copied = head.copy_from(scores)
  fn copy_from(self: mut Slice<T>, src: Slice<T>) -> int

  /// Returns a new `Slice` containing only elements for which `f` returns `true`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `[90, 88]`
  ///   let passing = scores.filter(|score| score >= 80)
  fn filter(self, f: fn(T) -> bool) -> mut Slice<T>

  /// Returns a new `Slice` with `f` applied to each element.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `[95, 80, 93]`
  ///   let curved = scores.map(|score| score + 5)
  fn map<U>(self, f: fn(T) -> U) -> mut Slice<U>

  /// Returns `true` if the `Slice` contains `value`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `true`
  ///   let present = scores.contains(75)
  fn contains(self, value: T) -> bool

  /// Returns `true` if this `Slice` is equal to `other`, when comparing element
  /// by element.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `true`
  ///   let same = scores.equals([90, 75, 88])
  fn equals(self, other: Slice<T>) -> bool

  /// Reduces the `Slice` to a single value by applying `f` to each element
  /// with an accumulator, starting from `a`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `253`
  ///   let total = scores.fold(0, |sum, score| sum + score)
  fn fold<U>(self, a: U, f: fn(U, T) -> U) -> U

  /// Returns the first element for which `f` returns `true`, or `None`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `Some(75)`
  ///   let failing = scores.find(|score| score < 80)
  fn find(self, f: fn(T) -> bool) -> Option<T>

  /// Returns `true` if any element satisfies `f`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `true`
  ///   let has_failing = scores.any(|score| score < 80)
  fn any(self, f: fn(T) -> bool) -> bool

  /// Returns `true` if all elements satisfy `f`.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   // !callout-right `true`
  ///   let none_failing = scores.all(|score| score >= 60)
  fn all(self, f: fn(T) -> bool) -> bool

  /// Returns an `EnumeratedSlice` for indexed iteration.
  ///
  /// Example:
  ///   let scores = [90, 75, 88]
  ///   for (index, score) in scores.enumerate() {
  ///     fmt.Println(index, score)
  ///   }
  fn enumerate(self) -> EnumeratedSlice<T>

  /// Returns a copy of the `Slice`, including any nested slices, maps, and tuples.
  ///
  /// Example:
  ///   let rounds = [[90, 75], [88]]
  ///   let copy = rounds.clone()
  fn clone(self) -> mut Slice<T>
}

/// A slice paired with element indices, returned by `Slice.enumerate()`.
/// Supports `for (i, v) in` iteration and chaining methods like `filter`, `map`, `fold`, and `find`.
type EnumeratedSlice<T>

impl<T> EnumeratedSlice<T> {
  /// Returns the `(index, element)` pairs for which `f` returns `true`.
  ///
  /// Example:
  ///   let names = ["alice", "bob", "charles"]
  ///   let even_positions = names
  ///     .enumerate()
  ///     .filter(|(index, _)| index % 2 == 0)
  fn filter(self, f: fn((int, T)) -> bool) -> mut Slice<(int, T)>

  /// Returns a new slice with `f` applied to each `(index, element)` pair.
  ///
  /// Example:
  ///   let names = ["alice", "bob"]
  ///   let numbered = names
  ///     .enumerate()
  ///     .map(|(index, name)| fmt.Sprintf("%d: %s", index, name))
  fn map<U>(self, f: fn((int, T)) -> U) -> mut Slice<U>

  /// Reduces the `(index, element)` pairs to a single value by applying `f`
  /// to each pair with an accumulator, starting from `a`.
  ///
  /// Example:
  ///   let names = ["alice", "bob"]
  ///   let characters = names
  ///     .enumerate()
  ///     .fold(0, |sum, (_, name)| sum + name.length())
  fn fold<U>(self, a: U, f: fn(U, (int, T)) -> U) -> U

  /// Returns the first `(index, element)` pair for which `f` returns `true`,
  /// or `None`.
  ///
  /// Example:
  ///   let names = ["alice", "bob"]
  ///   let found = names.enumerate().find(|(_, name)| name == "bob")
  fn find(self, f: fn((int, T)) -> bool) -> Option<(int, T)>

  /// Returns a copy, including any nested slices, maps, and tuples.
  ///
  /// Example:
  ///   let pairs = [[1], [2]].enumerate()
  ///   let copy = pairs.clone()
  fn clone(self) -> mut EnumeratedSlice<T>
}

impl Slice<string> {
  /// Joins the elements with `sep` between each pair.
  ///
  /// Example:
  ///   let names = ["alice", "bob", "charles"]
  ///   // !callout-right `"alice, bob, charles"`
  ///   let line = names.join(", ")
  fn join(self, sep: string) -> string
}

/// An unordered collection of key-value pairs. Equivalent to Go's `map[K]V`.
/// Keys must be [comparable](/docs/prelude/constraints/#comparable).
///
/// Example:
///   let mut ages = Map.new<string, int>()
///
///   // !callout-right set value at key
///   ages["alice"] = 30
///   // !callout-right access value at key
///   let alice_age = ages["alice"]
///
///   // !callout[/in ages/] order changes between runs
///   for (name, age) in ages {
///     fmt.Println(name, age)
///   }
type Map<K: Comparable, V>

impl<K, V> Map<K, V> {
  /// Creates an empty `Map`.
  ///
  /// Example:
  ///   let mut ages = Map.new<string, int>()
  ///   ages["alice"] = 30
  fn new() -> mut Map<K, V>

  /// Creates a `Map` from a `Slice` of key-value pairs.
  ///
  /// Example:
  ///   let ages = Map.from([("alice", 30), ("bob", 25)])
  fn from(pairs: Slice<(K, V)>) -> mut Map<K, V>

  /// Returns the number of entries in the `Map`.
  ///
  /// Example:
  ///   let ages = Map.from([("alice", 30), ("bob", 25)])
  ///   // !callout-right `2`
  ///   let entries = ages.length()
  fn length(self) -> int

  /// Returns `true` if the `Map` holds no entries.
  ///
  /// Example:
  ///   let ages = Map.new<string, int>()
  ///   // !callout-right `true`
  ///   let blank = ages.is_empty()
  fn is_empty(self) -> bool

  /// Returns the value for `key`, or `None` if not present. Reading a missing key
  /// with `[]` gives the value type's zero value, so use `get()` to tell a miss
  /// from a stored zero.
  ///
  /// Example:
  ///   let ages = Map.from([("alice", 30)])
  ///   // !callout-right `Some(30)`
  ///   let age = ages.get("alice")
  ///   // !callout-right `None`, while `ages["bob"]` gives `0`
  ///   let missing = ages.get("bob")
  fn get(self, key: K) -> Option<V>

  /// Removes the entry for `key` from the `Map`.
  ///
  /// Example:
  ///   let mut ages = Map.from([("alice", 30), ("bob", 25)])
  ///   // !callout[/delete/] leaves `bob` as the only entry
  ///   ages.delete("alice")
  fn delete(self: mut Map<K, V>, key: K)

  /// Returns a copy of the `Map`, including any nested slices, maps, and tuples.
  ///
  /// Example:
  ///   let ages = Map.from([("alice", 30)])
  ///   let copy = ages.clone()
  fn clone(self) -> mut Map<K, V>

  /// Returns `true` if this `Map` has the same keys and values as `other`.
  ///
  /// Example:
  ///   let first = Map.from([("alice", 30)])
  ///   let second = Map.from([("alice", 30)])
  ///   // !callout-right `true`
  ///   first.equals(second)
  fn equals(self, other: Map<K, V>) -> bool
}

/// A reference to a value of type `T`, equivalent to Go's `*T` but never nil.
///
/// Example:
///   let mut count = 1
///   // !callout-right `mut Ref<int>`, since `count` allows writes
///   let mut count_ref = &count
///   // !callout-right `count` is now `2`
///   count_ref.* += 1
type Ref<T>

/// A channel for sending and receiving values between tasks. Equivalent to Go's `chan T`.
///
/// Example:
///   let jobs = Channel.new<int>()
///   task jobs.send(7)
///   // !callout-right `Some(7)`, once the `task` sends
///   let first = jobs.receive()
type Channel<T>

impl<T> Channel<T> {
  /// Creates an unbuffered `Channel`.
  ///
  /// Example:
  ///   // !callout-right capacity `0`, so every send waits for a receive
  ///   let jobs = Channel.new<int>()
  fn new() -> Channel<T>

  /// Creates a `Channel` with room for `capacity` values.
  ///
  /// Example:
  ///   // !callout-right room for `4` values before a send waits
  ///   let jobs = Channel.buffered<int>(4)
  fn buffered(capacity: int) -> Channel<T>

  /// Sends a value into the `Channel`. Returns `true` if the value was sent, `false`
  /// if the `Channel` was closed.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(1)
  ///   let sent = jobs.send(7)
  fn send(self, value: T) -> bool

  /// Receives a value from the `Channel`, or `None` once it is closed and drained.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(1)
  ///   jobs.send(7)
  ///   // !callout-right `Some(7)`
  ///   let job = jobs.receive()
  fn receive(self) -> Option<T>

  /// Splits the `Channel` into a `Sender` and a `Receiver`.
  ///
  /// Example:
  ///   let (sender, receiver) = Channel.buffered<int>(1).split()
  ///   sender.send(7)
  ///   // !callout-right `Some(7)`
  ///   let job = receiver.receive()
  fn split(self) -> (Sender<T>, Receiver<T>)

  /// Returns the number of values waiting in the `Channel` buffer.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(4)
  ///   jobs.send(7)
  ///   // !callout-right `1`
  ///   let queued = jobs.length()
  fn length(self) -> int

  /// Returns `true` if the `Channel` buffer holds no values.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(4)
  ///   // !callout-right `true`
  ///   let idle = jobs.is_empty()
  fn is_empty(self) -> bool

  /// Returns the number of values the `Channel` buffer can hold.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(4)
  ///   // !callout-right `4`
  ///   let room = jobs.capacity()
  fn capacity(self) -> int

  /// Closes the `Channel`. Safe to call more than once.
  ///
  /// Example:
  ///   let jobs = Channel.buffered<int>(1)
  ///   jobs.send(7)
  ///   jobs.close()
  fn close(self)
}

/// The sending half of a `Channel`. Equivalent to Go's `chan<- T`.
///
/// Example:
///   let (sender, _) = Channel.buffered<int>(1).split()
///   sender.send(7)
///   sender.close()
type Sender<T>

impl<T> Sender<T> {
  /// Sends a value into the `Channel`. Returns `true` if the value was sent, `false`
  /// if the `Channel` was closed.
  ///
  /// Example:
  ///   let (sender, _) = Channel.buffered<int>(1).split()
  ///   let sent = sender.send(7)
  fn send(self, value: T) -> bool

  /// Returns the number of values waiting in the `Channel` buffer.
  ///
  /// Example:
  ///   let (sender, _) = Channel.buffered<int>(4).split()
  ///   sender.send(7)
  ///   // !callout-right `1`
  ///   let queued = sender.length()
  fn length(self) -> int

  /// Returns `true` if the `Channel` buffer holds no values.
  ///
  /// Example:
  ///   let (sender, _) = Channel.buffered<int>(4).split()
  ///   // !callout-right `true`
  ///   let idle = sender.is_empty()
  fn is_empty(self) -> bool

  /// Returns the number of values the `Channel` buffer can hold.
  ///
  /// Example:
  ///   let (sender, _) = Channel.buffered<int>(4).split()
  ///   // !callout-right `4`
  ///   let room = sender.capacity()
  fn capacity(self) -> int

  /// Closes the `Channel`. Safe to call more than once.
  ///
  /// Example:
  ///   let (sender, _) = Channel.buffered<int>(1).split()
  ///   sender.send(7)
  ///   sender.close()
  fn close(self)
}

/// The receiving half of a `Channel`. Equivalent to Go's `<-chan T`.
///
/// Example:
///   let (sender, receiver) = Channel.new<int>().split()
///   task sender.send(7)
///   // !callout-right `Some(7)`, once the `task` sends
///   let job = receiver.receive()
type Receiver<T>

impl<T> Receiver<T> {
  /// Receives a value from the `Channel`, or `None` once it is closed and drained.
  ///
  /// Example:
  ///   let (sender, receiver) = Channel.buffered<int>(1).split()
  ///   sender.send(7)
  ///   // !callout-right `Some(7)`
  ///   let job = receiver.receive()
  fn receive(self) -> Option<T>

  /// Returns the number of values waiting in the `Channel` buffer.
  ///
  /// Example:
  ///   let (sender, receiver) = Channel.buffered<int>(4).split()
  ///   sender.send(7)
  ///   // !callout-right `1`
  ///   let queued = receiver.length()
  fn length(self) -> int

  /// Returns `true` if the `Channel` buffer holds no values.
  ///
  /// Example:
  ///   let (_, receiver) = Channel.buffered<int>(4).split()
  ///   // !callout-right `true`
  ///   let idle = receiver.is_empty()
  fn is_empty(self) -> bool

  /// Returns the number of values the `Channel` buffer can hold.
  ///
  /// Example:
  ///   let (_, receiver) = Channel.buffered<int>(4).split()
  ///   // !callout-right `4`
  ///   let room = receiver.capacity()
  fn capacity(self) -> int
}

/// A `Range` covers `start` to `end`, excluding `end`.
///
/// Example:
///   for i in 0..5 {
///     // !callout-right `0` through `4`, excluding `5`
///     fmt.Println(i)
///   }
pub struct Range<T> {
  pub start: T,
  pub end: T,
}

/// A `RangeInclusive` covers `start` to `end`, including `end`.
///
/// Example:
///   for i in 0..=5 {
///     // !callout-right `0` through `5`, including `5`
///     fmt.Println(i)
///   }
pub struct RangeInclusive<T> {
  pub start: T,
  pub end: T,
}

/// A `RangeFrom` starts at `start` and has no upper bound.
///
/// Example:
///   for i in 0.. {
///     // !callout-right no upper bound, so the loop sets one
///     if i >= 3 { break }
///     fmt.Println(i)
///   }
pub struct RangeFrom<T> {
  pub start: T,
}

/// A `RangeTo` covers up to `end`, excluding `end`.
///
/// Example:
///   let letters = ["a", "b", "c", "d"]
///   // !callout-right `["a", "b"]`
///   let first_two = letters[..2]
pub struct RangeTo<T> {
  pub end: T,
}

/// A `RangeToInclusive` covers up to `end`, including `end`.
///
/// Example:
///   let letters = ["a", "b", "c", "d"]
///   // !callout-right `["a", "b", "c"]`
///   let first_three = letters[..=2]
pub struct RangeToInclusive<T> {
  pub end: T,
}

// -----------------------
//     Special types
// -----------------------

/// Equivalent to Go's `any`.
///
/// Example:
///   let mut fields: Map<string, Unknown> = Map.new()
///   let _ = json.Unmarshal("{\"name\": \"alice\"}".bytes(), &fields)
///
///   match fields.get("name") {
///     Some(value) => {
///       // !callout[/name/] `Some("alice")`
///       let name = assert_type<string>(value)
///       fmt.Println(name)
///     },
///     None => fmt.Println("missing"),
///   }
type Unknown

/// The type returned when there is no meaningful value.
///
/// Example:
///   fn save(path: string) -> Result<(), error> {
///     os.WriteFile(path, "data".bytes(), 0o644)
///   }
///
///   match save("out.txt") {
///     // !callout[/\(\)/] `Unit`
///     Ok(()) => fmt.Println("saved"),
///     Err(err) => fmt.Println(err.Error()),
///   }
type Unit

/// Indicates a function never returns, e.g. functions that panic or loop forever.
///
/// Example:
///   fn fail(msg: string) -> Never {
///     panic(msg)
///   }
///
///   fn serve() -> Never {
///     loop {
///       handle(accept())
///     }
///   }
type Never

/// Equivalent to Go's `comparable`. Satisfied by every type that admits
/// `==` and `!=`.
///
/// Example:
///   fn unique<T: Comparable>(items: Slice<T>) -> Map<T, bool> {
///     let mut seen = Map.new<T, bool>()
///     for item in items {
///       seen[item] = true
///     }
///     seen
///   }
///
///   // !callout-right `3`
///   let numbers = unique([1, 2, 2, 3]).length()
///   // !callout-right `2`
///   let words = unique(["a", "b", "a"]).length()
type Comparable

/// Equivalent to Go's `cmp.Ordered`. Satisfied by every type that admits
/// `<`, `<=`, `>=` and `>`.
///
/// Example:
///   fn descending<T: Ordered>(a: T, b: T) -> (T, T) {
///     if a > b { (a, b) } else { (b, a) }
///   }
///
///   // !callout-right `(7, 3)`
///   let numbers = descending(3, 7)
///   // !callout-right `("pear", "apple")`
///   let words = descending("pear", "apple")
type Ordered

/// Satisfied by any type that has a [zero value](/docs/types/#types-with-zero-values).
///
/// Example:
///   fn parse_json<T: Zeroable>(data: Slice<byte>) -> Result<T, error> {
///     let mut parsed = zero<T>()
///     json.Unmarshal(data, &parsed)?
///     Ok(parsed)
///   }
type Zeroable

/// Equivalent to Go's `...T`.
///
/// Example:
///   fn sum(numbers: VarArgs<int>) -> int {
///     let mut total = 0
///     for n in numbers { total += n }
///     total
///   }
///
///   let total = sum(1, 2, 3)
type VarArgs<T>

/// A value captured from a `recover` block after a panic.
///
/// Example:
///   fn will_panic() -> int {
///     panic("boom")
///   }
///
///   // !callout[/result/] `Result<int, PanicValue>`
///   let result = recover { will_panic() }
///
///   match result {
///     Ok(value) => fmt.Println(value),
///     // !callout[/pv/] `PanicValue`
///     Err(pv) => fmt.Println("recovered from a panic"),
///   }
struct PanicValue {}

impl PanicValue {
  /// Returns the message string in the `PanicValue`.
  ///
  /// Example:
  ///   let digits = [1, 2, 3]
  ///   // !callout[/result/] `Result<int, PanicValue>`
  ///   let result = recover { digits[10] }
  ///
  ///   match result {
  ///     Ok(value) => fmt.Println(value),
  ///     // !callout[/message\(\)/] `"index out of range [10] with length 3"`
  ///     Err(pv) => fmt.Println(pv.message()),
  ///   }
  fn message(self) -> string

  /// Returns the `PanicValue` as an `error`, if it implements the `error` interface.
  ///
  /// Example:
  ///   let digits = [1, 2, 3]
  ///   // !callout[/result/] `Result<int, PanicValue>`
  ///   let result = recover { digits[10] }
  ///
  ///   match result {
  ///     Ok(value) => fmt.Println(value),
  ///     Err(pv) => match pv.as_error() {
  ///       // !callout[/Error\(\)/] `"index out of range [10] with length 3"`
  ///       Some(err) => fmt.Println(err.Error()),
  ///       None => fmt.Println(pv.message()),
  ///     },
  ///   }
  fn as_error(self) -> Option<error>

  /// Returns the stack trace at the point of the panic.
  ///
  /// Example:
  ///   let digits = [1, 2, 3]
  ///   // !callout[/result/] `Result<int, PanicValue>`
  ///   let result = recover { digits[10] }
  ///
  ///   match result {
  ///     Ok(value) => fmt.Println(value),
  ///     // !callout[/stack_trace\(\)/] `"goroutine 1 [running]:\nruntime/debug.Stack()\nprelude.RecoverBlock[...].func1.1()\n..."`
  ///     Err(pv) => fmt.Println(pv.stack_trace()),
  ///   }
  fn stack_trace(self) -> string
}

/// The interface every error type satisfies, by having an `Error()` method.
///
/// Example:
///   match os.ReadFile("missing.txt") {
///     Ok(bytes) => fmt.Println(bytes.length()),
///     // !callout[/Error\(\)/] `"open missing.txt: no such file or directory"`
///     Err(err) => fmt.Println(err.Error()),
///   }
interface error {
  fn Error() -> string
}

// -----------------------
//       Functions
// -----------------------

/// Checks at runtime whether an `Unknown` value is type `T`. Equivalent to Go's
/// `v, ok := x.(T)`.
///
/// Example:
///   let value: Unknown = get_unknown_value()
///   // !callout-right `Some(n)` if the expected type, else `None`
///   let n = assert_type<int>(value)
fn assert_type<T>(value: Unknown) -> Option<T>

/// Returns the [zero value](/docs/types/#types-with-zero-values) of `T` if
/// [`Zeroable`](/docs/prelude/constraints/#zeroable).
///
/// Example:
///   fn reset<T: Zeroable>(items: mut Slice<T>) {
///     for i in 0..items.length() {
///       items[i] = zero<T>()
///     }
///   }
fn zero<T: Zeroable>() -> T

/// Creates a complex number from real and imaginary parts.
///
/// Example:
///   // !callout-right `(3+4i)`
///   let z = complex(3.0, 4.0)
fn complex(r: float64, i: float64) -> complex128

/// Returns the real part of a complex number.
///
/// Example:
///   let z = complex(3.0, 4.0)
///   // !callout-right `3`
///   let real_part = real(z)
fn real(c: complex128) -> float64

/// Returns the imaginary part of a complex number.
///
/// Example:
///   let z = complex(3.0, 4.0)
///   // !callout-right `4`
///   let imaginary_part = imaginary(z)
#[go("imag")]
fn imaginary(c: complex128) -> float64

/// Panics with the given value. The program ends, unless a
/// [`recover`](/docs/failures/#panic-recovery) block catches the panic.
///
/// Example:
///   panic("something went wrong")
///   panic(err)
fn panic(msg: Unknown) -> Never

/// Returns the smallest of its arguments, which must share one
/// [`Ordered`](/docs/prelude/constraints/#ordered) type.
///
/// Example:
///   // !callout-right `1`
///   let smallest = min(3, 1, 2)
///   // !callout-right `"apple"`, compared alphabetically
///   let first_word = min("pear", "apple")
fn min<T: Ordered>(x: T, rest: VarArgs<T>) -> T

/// Returns the largest of its arguments, which must share one
/// [`Ordered`](/docs/prelude/constraints/#ordered) type.
///
/// Example:
///   // !callout-right `3`
///   let largest = max(3, 1, 2)
///   // !callout-right `"pear"`, compared alphabetically
///   let last_word = max("pear", "apple")
fn max<T: Ordered>(x: T, rest: VarArgs<T>) -> T