-
Notifications
You must be signed in to change notification settings - Fork 67
/
read.go
1531 lines (1425 loc) · 35.4 KB
/
read.go
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
package core
import (
"bytes"
"fmt"
"io"
"math"
"math/big"
"math/rand"
"regexp"
"strconv"
"unicode"
"unicode/utf8"
)
type (
ReadError struct {
line int
column int
filename *string
msg string
}
ReadFunc func(reader *Reader) Object
pos struct {
line int
column int
}
)
const EOF = -1
var (
LINTER_MODE bool = false
FORMAT_MODE bool = false
PROBLEM_COUNT = 0
DIALECT Dialect
LINTER_CONFIG *Var
SUPPRESS_READ bool = false
)
var (
ARGS map[int]Symbol
GENSYM int
)
var NIL = Nil{}
var posStack = make([]pos, 0, 8)
func pushPos(reader *Reader) {
posStack = append(posStack, pos{line: reader.line, column: reader.column})
}
func popPos() pos {
p := posStack[len(posStack)-1]
posStack = posStack[:len(posStack)-1]
return p
}
func escapeRune(r rune) string {
switch r {
case ' ':
return "\\space"
case '\n':
return "\\newline"
case '\t':
return "\\tab"
case '\r':
return "\\return"
case '\b':
return "\\backspace"
case '\f':
return "\\formfeed"
default:
return "\\" + string(r)
}
}
func escapeString(str string) string {
var b bytes.Buffer
b.WriteRune('"')
for _, r := range str {
switch r {
case '"':
b.WriteString("\\\"")
case '\\':
b.WriteString("\\\\")
case '\t':
b.WriteString("\\t")
case '\r':
b.WriteString("\\r")
case '\n':
b.WriteString("\\n")
case '\f':
b.WriteString("\\f")
case '\b':
b.WriteString("\\b")
default:
b.WriteRune(r)
}
}
b.WriteRune('"')
return b.String()
}
func MakeReadError(reader *Reader, msg string) ReadError {
return ReadError{
line: reader.line,
column: reader.column,
filename: reader.filename,
msg: msg,
}
}
func MakeReadObject(reader *Reader, obj Object) Object {
p := popPos()
return obj.WithInfo(&ObjectInfo{Position: Position{
startColumn: p.column,
startLine: p.line,
endLine: reader.line,
endColumn: reader.column,
filename: reader.filename,
}})
}
func DeriveReadObject(base Object, obj Object) Object {
baseInfo := base.GetInfo()
if baseInfo != nil {
bi := *baseInfo
return obj.WithInfo(&bi)
}
return obj
}
func (err ReadError) Message() Object {
return MakeString(err.msg)
}
func (err ReadError) Error() string {
return fmt.Sprintf("%s:%d:%d: Read error: %s", filename(err.filename), err.line, err.column, err.msg)
}
func isDelimiter(r rune) bool {
switch r {
case '(', ')', '[', ']', '{', '}', '"', ';', EOF, '\\':
return true
}
return isWhitespace(r)
}
func eatString(reader *Reader, str string) {
for _, sr := range str {
if r := reader.Get(); r != sr {
panic(MakeReadError(reader, fmt.Sprintf("Unexpected character %U", r)))
}
}
}
func peekExpectedDelimiter(reader *Reader) {
r := reader.Peek()
if !isDelimiter(r) {
panic(MakeReadError(reader, "Character not followed by delimiter"))
}
}
func readSpecialCharacter(reader *Reader, ending string, r rune) Object {
eatString(reader, ending)
peekExpectedDelimiter(reader)
return MakeReadObject(reader, Char{Ch: r})
}
func isJavaSpace(r rune) bool {
switch r {
case ' ', '\t', '\n', '\r': // Listed here purely for speed of common cases
return true
case 0xa0 /* */, 0x85 /*NEL*/, 0x2007 /* */, 0x202f /*narrow non-break space*/ :
return false
case 0x1c /*FS*/, 0x1d /*GS*/, 0x1e /*RS*/, 0x1f /*US*/ :
return true
default:
if r > unicode.MaxLatin1 && unicode.In(r, unicode.Zl, unicode.Zp, unicode.Zs) {
return true
}
}
return unicode.IsSpace(r)
}
func isWhitespace(r rune) bool {
return isJavaSpace(r) || r == ','
}
func readComment(reader *Reader) Object {
var b bytes.Buffer
r := reader.Peek()
for r != '\n' && r != EOF {
b.WriteRune(r)
reader.Get()
r = reader.Peek()
}
return MakeReadObject(reader, Comment{C: b.String()})
}
func eatWhitespace(reader *Reader) {
r := reader.Get()
for r != EOF {
if FORMAT_MODE && r == ',' {
reader.Unget()
break
}
if isWhitespace(r) {
r = reader.Get()
continue
}
if (r == ';' || (r == '#' && reader.Peek() == '!')) && !FORMAT_MODE {
for r != '\n' && r != EOF {
r = reader.Get()
}
r = reader.Get()
continue
}
if r == '#' && reader.Peek() == '_' && !FORMAT_MODE {
reader.Get()
Read(reader)
r = reader.Get()
continue
}
reader.Unget()
break
}
}
func readUnicodeCharacter(reader *Reader, length, base int) Object {
var b bytes.Buffer
for n := reader.Get(); !isDelimiter(n); n = reader.Get() {
b.WriteRune(n)
}
reader.Unget()
str := b.String()
if len(str) != length {
panic(MakeReadError(reader, "Invalid unicode character: \\o"+str))
}
i, err := strconv.ParseInt(str, base, 32)
if err != nil {
panic(MakeReadError(reader, "Invalid unicode character: \\o"+str))
}
peekExpectedDelimiter(reader)
return MakeReadObject(reader, Char{Ch: rune(i)})
}
func readCharacter(reader *Reader) Object {
r := reader.Get()
if r == EOF {
panic(MakeReadError(reader, "Incomplete character literal"))
}
switch r {
case 's':
if reader.Peek() == 'p' {
return readSpecialCharacter(reader, "pace", ' ')
}
case 'n':
if reader.Peek() == 'e' {
return readSpecialCharacter(reader, "ewline", '\n')
}
case 't':
if reader.Peek() == 'a' {
return readSpecialCharacter(reader, "ab", '\t')
}
case 'f':
if reader.Peek() == 'o' {
return readSpecialCharacter(reader, "ormfeed", '\f')
}
case 'b':
if reader.Peek() == 'a' {
return readSpecialCharacter(reader, "ackspace", '\b')
}
case 'r':
if reader.Peek() == 'e' {
return readSpecialCharacter(reader, "eturn", '\r')
}
case 'u':
if !isDelimiter(reader.Peek()) {
return readUnicodeCharacter(reader, 4, 16)
}
case 'o':
if !isDelimiter(reader.Peek()) {
return readUnicodeCharacter(reader, 3, 8)
}
}
peekExpectedDelimiter(reader)
return MakeReadObject(reader, Char{Ch: r})
}
func invalidNumberError(reader *Reader, str string) error {
return MakeReadError(reader, fmt.Sprintf("Invalid number: %s", str))
}
func scanBigInt(orig, str string, base int, reader *Reader) Object {
var bi = &big.Int{}
if _, ok := bi.SetString(str, base); !ok {
panic(invalidNumberError(reader, str))
}
res := BigInt{b: bi, Original: orig}
return MakeReadObject(reader, &res)
}
func scanRatio(str string, reader *Reader) Object {
var rat = &big.Rat{}
if _, ok := rat.SetString(str); !ok {
panic(invalidNumberError(reader, str))
}
return MakeReadObject(reader, ratioOrIntWithOriginal(str, rat))
}
func scanBigFloat(orig, str string, reader *Reader) Object {
if f, ok := MakeBigFloatWithOrig(str, orig); ok {
return MakeReadObject(reader, f)
}
panic(invalidNumberError(reader, str))
}
func scanInt(orig, str string, base int, reader *Reader) Object {
i, e := strconv.ParseInt(str, base, 0)
if e != nil {
return scanBigInt(orig, str, base, reader)
}
// TODO: 32-bit issue
return MakeReadObject(reader, Int{I: int(i), Original: orig})
}
func scanFloat(str string, reader *Reader) Object {
dbl, e := strconv.ParseFloat(str, 64)
if e != nil {
panic(invalidNumberError(reader, str))
}
return MakeReadObject(reader, Double{D: dbl, Original: str})
}
func readNumber(reader *Reader) Object {
var b bytes.Buffer
isDouble, isHex, isExp, isRatio, baseLen, nonDigits := false, false, false, false, 0, 0
d := reader.Get()
last := d
for !isDelimiter(d) {
switch d {
case '.':
isDouble = true
case '/':
isRatio = true
case 'x', 'X':
isHex = true
case 'e', 'E':
isExp = true
case 'r', 'R':
if baseLen == 0 {
baseLen = b.Len()
}
}
if !unicode.IsDigit(d) {
nonDigits++
}
b.WriteRune(d)
last = d
d = reader.Get()
}
reader.Unget()
str := b.String()
if baseLen != 0 {
baseInt, err := strconv.ParseInt(str[0:baseLen], 0, 0)
if err != nil {
panic(invalidNumberError(reader, str))
}
negative := false
if baseInt < 0 {
baseInt = -baseInt
negative = true
}
if baseInt < 2 || baseInt > 36 {
panic(invalidNumberError(reader, str))
}
var number string
if negative {
number = "-" + str[baseLen+1:]
} else {
number = str[baseLen+1:] // Avoid an expensive catenation in positive/zero case
}
return scanInt(str, number, int(baseInt), reader)
}
if isRatio {
if nonDigits > 2 || nonDigits > 1 && str[0] != '-' && str[0] != '+' {
panic(invalidNumberError(reader, str))
}
return scanRatio(str, reader)
}
if last == 'N' {
return scanBigInt(str, str[:b.Len()-1], 0, reader)
}
if last == 'M' {
return scanBigFloat(str, str[:b.Len()-1], reader)
}
if isDouble || (!isHex && isExp) {
return scanFloat(str, reader)
}
return scanInt(str, str, 0, reader)
}
/*
Returns whether the rune may be a non-initial character in a symbol
/* or keyword name.
*/
func isIdentRune(r rune) bool {
switch r {
case '"', ';', '@', '^', '`', '~', '(', ')', '[', ']', '{', '}', '\\', ',', ' ', '\t', '\n', '\r', EOF:
// Whitespace listed above (' ', '\t', '\n', '\r') purely for speed of common cases
return false
}
return !isJavaSpace(r)
}
/* Reads (lexes) a token and returns either a Symbol or Keyword. */
func readIdent(reader *Reader, first rune) Object {
var b bytes.Buffer
if first != ':' {
b.WriteRune(first)
}
var lastAdded rune
r := reader.Get()
for isIdentRune(r) {
if r == ':' {
if lastAdded == ':' {
panic(MakeReadError(reader, "Invalid use of ':' in symbol name"))
}
}
b.WriteRune(r)
lastAdded = r
r = reader.Get()
}
if lastAdded == ':' || lastAdded == '/' {
panic(MakeReadError(reader, fmt.Sprintf("Invalid use of %c in symbol name", lastAdded)))
}
reader.Unget()
str := b.String()
switch {
case str == "":
panic(MakeReadError(reader, "Invalid keyword: :"))
case first == ':':
if str[0] == '/' {
panic(MakeReadError(reader, "Blank namespaces are not allowed"))
}
if str[0] == ':' {
if FORMAT_MODE {
return MakeReadObject(reader, MakeKeyword(str))
}
sym := MakeSymbol(str[1:])
ns := GLOBAL_ENV.NamespaceFor(GLOBAL_ENV.CurrentNamespace(), sym)
if ns == nil {
msg := fmt.Sprintf("Unable to resolve namespace %s in keyword %s", *sym.ns, ":"+str)
if LINTER_MODE {
printReadWarning(reader, msg)
return MakeReadObject(reader, MakeKeyword(*sym.name))
}
panic(MakeReadError(reader, msg))
}
ns.isUsed = true
ns.isGloballyUsed = true
return MakeReadObject(reader, MakeKeyword(*ns.Name.name+"/"+*sym.name))
}
return MakeReadObject(reader, MakeKeyword(str))
case str == "nil":
return MakeReadObject(reader, NIL)
case str == "true":
return MakeReadObject(reader, Boolean{B: true})
case str == "false":
return MakeReadObject(reader, Boolean{B: false})
default:
return MakeReadObject(reader, MakeSymbol(str))
}
}
/* When validating symbol/keyword names, which is done only in
LINTER_MODE given the appropriate :rules in place, use function
variables for a) simplicity of functions, b) ease of adding new
ones (if new rules are desired), and c) hope for reasonably good
performance. */
/*
Returns whether a rune is a character that is inherently allowed in
/* identifiers (symbols, keywords) by dint of the fact that
/* clojure.core and other core packages define identifiers with these
/* characters. While not important for parsing (Clojure is extremely
/* permissive regarding which characters can be lexed into an
/* identifier), linting can helpfully find and warn about characters
/* outside of this set (as extended via configuration).
*/
func isCoreIdentRune(r rune) bool {
switch r {
case '*', '+', '!', '-', '?', '=', '<', '>', '&', '_', '.', '\'', '#', '$', ':', '%': // Used in clojure.core, joker.core, etc.
return true
}
return ('a' <= r && r <= 'z') || ('A' <= r && r <= 'Z') || ('0' <= r && r <= '9')
}
const isValidCoreReason = "not a Letter nor (Decimal) Digit (category L nor Nd)"
func isValidCore(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r)
}
const isValidSymbolReason = "not a Letter, (Decimal) Digit, nor Symbol (category L, Nd, nor S)"
func isValidSymbol(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSymbol(r)
}
const isValidVisibleReason = "not a Letter, (Decimal) Digit, Symbol, Punctuation, nor Mark (category L, Nd, S, P, nor M)"
func isValidVisible(r rune) bool {
return unicode.IsLetter(r) || unicode.IsDigit(r) || unicode.IsSymbol(r) || unicode.IsPunct(r) || unicode.IsMark(r)
}
const isValidUnicodeReason = "not a Unicode character"
func isValidUnicode(r rune) bool {
return r <= unicode.MaxRune
}
const isValidASCIIReason = "not a (7-bit) ASCII character"
func isValidASCII(r rune) bool {
return r <= unicode.MaxASCII
}
const isValidAnyReason = "not anything!?"
func isValidAny(r rune) bool {
return true
}
var identValidationSetFn = isValidCore
var identValidationSetWhy = isValidCoreReason
var identValidationRangeFn = isValidASCII
var identValidationRangeWhy = isValidASCIIReason
func warnInvalidIdent(reader *Reader, s *string) {
if s == nil {
return
}
k := 0
for _, r := range *s {
if !isCoreIdentRune(r) && (!identValidationSetFn(r) || !identValidationRangeFn(r)) {
var explain string
if identValidationSetFn(r) {
explain = identValidationRangeWhy
} else if identValidationRangeFn(r) {
explain = identValidationSetWhy
} else {
explain = identValidationSetWhy + "; " + identValidationRangeWhy
}
msg := fmt.Sprintf("Impermissible character %q at %d in %q (%s)", r, k, *s, explain)
printReadWarning(reader, msg)
}
k++
}
}
func readValidatedIdent(reader *Reader, first rune) Object {
obj := readIdent(reader, first)
switch o := obj.(type) {
case Keyword:
warnInvalidIdent(reader, o.ns)
warnInvalidIdent(reader, o.name)
case Symbol:
warnInvalidIdent(reader, o.ns)
warnInvalidIdent(reader, o.name)
}
return obj
}
var readIdentFn = readIdent
func EnableIdentValidation() {
readIdentFn = readValidatedIdent
}
func SetIdentSetCore() {
identValidationSetFn = isValidCore
identValidationSetWhy = isValidCoreReason
}
func SetIdentSetSymbol() {
identValidationSetFn = isValidSymbol
identValidationSetWhy = isValidSymbolReason
}
func SetIdentSetVisible() {
identValidationSetFn = isValidVisible
identValidationSetWhy = isValidVisibleReason
}
func SetIdentSetAny() {
identValidationSetFn = isValidAny
identValidationSetWhy = isValidAnyReason
}
func SetIdentRangeUnicode() {
identValidationRangeFn = isValidUnicode
identValidationRangeWhy = isValidUnicodeReason
}
func SetIdentRangeASCII() {
identValidationRangeFn = isValidASCII
identValidationRangeWhy = isValidASCIIReason
}
func SetIdentRangeAny() {
identValidationRangeFn = isValidAny
identValidationRangeWhy = isValidAnyReason
}
func readRegex(reader *Reader) Object {
var b bytes.Buffer
r := reader.Get()
for r != '"' {
if r == EOF {
panic(MakeReadError(reader, "Non-terminated regex literal"))
}
b.WriteRune(r)
if r == '\\' {
r = reader.Get()
if r == EOF {
panic(MakeReadError(reader, "Non-terminated regex literal"))
}
b.WriteRune(r)
}
r = reader.Get()
}
s := b.String()
regex, err := regexp.Compile(s)
if err != nil {
if LINTER_MODE {
return MakeReadObject(reader, &Regex{})
}
if FORMAT_MODE {
res := MakeReadObject(reader, MakeString(s))
addPrefix(res, "#")
return res
}
panic(MakeReadError(reader, "Invalid regex: "+err.Error()))
}
return MakeReadObject(reader, &Regex{R: regex})
}
func readUnicodeCharacterInString(reader *Reader, initial rune, length, base int, exactLength bool) rune {
n := initial
var b bytes.Buffer
for i := 0; i < length && n != '"'; i++ {
b.WriteRune(n)
n = reader.Get()
}
reader.Unget()
str := b.String()
if exactLength && len(str) != length {
panic(MakeReadError(reader, fmt.Sprintf("Invalid character length: %d, should be: %d", len(str), length)))
}
i, err := strconv.ParseInt(str, base, 32)
if err != nil {
panic(MakeReadError(reader, "Invalid unicode code: "+str))
}
return rune(i)
}
func readString(reader *Reader) Object {
var b bytes.Buffer
r := reader.Get()
for r != '"' {
if r == '\\' {
r = reader.Get()
if FORMAT_MODE {
b.WriteRune('\\')
} else {
switch r {
case '\\':
r = '\\'
case '"':
r = '"'
case 'n':
r = '\n'
case 't':
r = '\t'
case 'r':
r = '\r'
case 'b':
r = '\b'
case 'f':
r = '\f'
case 'u':
n := reader.Get()
r = readUnicodeCharacterInString(reader, n, 4, 16, true)
default:
if unicode.IsDigit(r) {
r = readUnicodeCharacterInString(reader, r, 3, 8, false)
} else {
panic(MakeReadError(reader, "Unsupported escape character: \\"+string(r)))
}
}
}
}
if r == EOF {
panic(MakeReadError(reader, "Non-terminated string literal"))
}
b.WriteRune(r)
r = reader.Get()
}
return MakeReadObject(reader, String{S: b.String()})
}
func readMulti(reader *Reader, previouslyRead []Object) (Object, []Object) {
if len(previouslyRead) == 0 {
obj, multi := Read(reader)
if multi {
v := obj.(Vec)
for i := 0; i < v.Count(); i++ {
previouslyRead = append(previouslyRead, v.At(i))
}
} else {
return obj, previouslyRead
}
}
obj := previouslyRead[len(previouslyRead)-1]
previouslyRead = previouslyRead[0 : len(previouslyRead)-1]
return obj, previouslyRead
}
func readError(reader *Reader, msg string) {
if LINTER_MODE {
printReadError(reader, msg)
} else {
panic(MakeReadError(reader, msg))
}
}
func readCondList(reader *Reader) Object {
previousSuppressRead := SUPPRESS_READ
defer func() {
SUPPRESS_READ = previousSuppressRead
}()
var forms []Object
eatWhitespace(reader)
r := reader.Peek()
var res Object = nil
for r != ')' || len(forms) != 0 {
if res == nil {
feature, forms := readMulti(reader, forms)
if feature.Equals(KEYWORDS.none) || feature.Equals(KEYWORDS.else_) {
panic(MakeReadError(reader, "Feature name "+feature.ToString(false)+" is reserved"))
}
if !IsKeyword(feature) {
panic(MakeReadError(reader, "Feature should be a keyword"))
}
eatWhitespace(reader)
if len(forms) == 0 && reader.Peek() == ')' {
reader.Get()
readError(reader, "Reader conditional requires an even number of forms")
return feature
}
if ok, _ := GLOBAL_ENV.Features.Get(feature); ok {
res, forms = readMulti(reader, forms)
} else {
SUPPRESS_READ = true
_, forms = readMulti(reader, forms)
SUPPRESS_READ = false
}
} else {
SUPPRESS_READ = true
_, forms = readMulti(reader, forms)
SUPPRESS_READ = false
}
eatWhitespace(reader)
r = reader.Peek()
}
reader.Get()
return res
}
func readList(reader *Reader) Object {
s := make([]Object, 0, 10)
eatWhitespace(reader)
r := reader.Peek()
for r != ')' {
obj, multi := Read(reader)
if multi {
v := obj.(Vec)
for i := 0; i < v.Count(); i++ {
s = append(s, v.At(i))
}
} else {
s = append(s, obj)
}
eatWhitespace(reader)
r = reader.Peek()
}
reader.Get()
list := EmptyList
for i := len(s) - 1; i >= 0; i-- {
list = list.conj(s[i])
}
res := MakeReadObject(reader, list)
return res
}
func readVector(reader *Reader) Object {
res := EmptyArrayVector()
eatWhitespace(reader)
r := reader.Peek()
for r != ']' {
obj, multi := Read(reader)
if multi {
v := obj.(Vec)
for i := 0; i < v.Count(); i++ {
res.Append(v.At(i))
}
} else {
res.Append(obj)
}
eatWhitespace(reader)
r = reader.Peek()
}
reader.Get()
return MakeReadObject(reader, res)
}
func resolveKey(key Object, nsname string) Object {
if nsname == "" {
return key
}
switch key := key.(type) {
case Keyword:
if key.ns == nil {
return DeriveReadObject(key, MakeKeyword(nsname+"/"+key.Name()))
}
if key.Namespace() == "_" {
return DeriveReadObject(key, MakeKeyword(key.Name()))
}
case Symbol:
if key.ns == nil {
return DeriveReadObject(key, MakeSymbol(nsname+"/"+key.Name()))
}
if key.Namespace() == "_" {
return DeriveReadObject(key, MakeSymbol(key.Name()))
}
}
return key
}
func readMap(reader *Reader) Object {
return readMapWithNamespace(reader, "")
}
func appendMapElement(objs []Object, obj Object) []Object {
objs = append(objs, obj)
if FORMAT_MODE {
if isComment(obj) {
// Add surrogate object to always have even number of elements in the map.
// Use rand to avoid duplicate keys.
objs = append(objs, MakeDouble(rand.Float64()))
}
}
return objs
}
func readMapWithNamespace(reader *Reader, nsname string) Object {
eatWhitespace(reader)
r := reader.Peek()
objs := []Object{}
for r != '}' {
obj, multi := Read(reader)
if !multi {
objs = appendMapElement(objs, obj)
} else {
v := obj.(Vec)
for i := 0; i < v.Count(); i++ {
objs = appendMapElement(objs, v.At(i))
}
}
eatWhitespace(reader)
r = reader.Peek()
}
reader.Get()
if len(objs)%2 != 0 {
panic(MakeReadError(reader, "Map literal must contain an even number of forms"))
}
if int64(len(objs)) >= HASHMAP_THRESHOLD {
hashMap := NewHashMap()
for i := 0; i < len(objs); i += 2 {
key := resolveKey(objs[i], nsname)
if hashMap.containsKey(key) {
panic(MakeReadError(reader, "Duplicate key "+key.ToString(false)))
}
hashMap = hashMap.Assoc(key, objs[i+1]).(*HashMap)
}
return MakeReadObject(reader, hashMap)
}
m := EmptyArrayMap()
for i := 0; i < len(objs); i += 2 {
key := resolveKey(objs[i], nsname)
if !m.Add(key, objs[i+1]) {
panic(MakeReadError(reader, "Duplicate key "+key.ToString(false)))
}
}
return MakeReadObject(reader, m)
}
func readSet(reader *Reader) Object {
set := EmptySet()
eatWhitespace(reader)
r := reader.Peek()
for r != '}' {
obj, multi := Read(reader)
if !multi {
if !set.Add(obj) {
panic(MakeReadError(reader, "Duplicate set element "+obj.ToString(false)))
}
} else {
v := obj.(Vec)
for i := 0; i < v.Count(); i++ {
if !set.Add(v.At(i)) {
panic(MakeReadError(reader, "Duplicate set element "+v.At(i).ToString(false)))
}
}
}
eatWhitespace(reader)
r = reader.Peek()
}
reader.Get()
return MakeReadObject(reader, set)
}
func makeQuote(obj Object, quote Symbol) Object {
res := NewListFrom(quote, obj)
return DeriveReadObject(obj, res)
}
func readMeta(reader *Reader) *ArrayMap {
obj := readFirst(reader)
switch v := obj.(type) {
case *ArrayMap:
return v
case String, Symbol:
return &ArrayMap{arr: []Object{DeriveReadObject(obj, KEYWORDS.tag), obj}}
case Keyword:
return &ArrayMap{arr: []Object{obj, DeriveReadObject(obj, Boolean{B: true})}}
default:
panic(MakeReadError(reader, "Metadata must be Symbol, Keyword, String or Map"))
}
}
func fillInMissingArgs(args map[int]Symbol) {
max := 0
for k := range args {
if k > max {
max = k
}
}
for i := 1; i < max; i++ {
if _, ok := args[i]; !ok {
args[i] = generateSymbol("p__")
}
}
}
func makeFnForm(args map[int]Symbol, body Object) Object {
fillInMissingArgs(args)
a := make([]Symbol, len(args))
for key, value := range args {
if key != -1 {
a[key-1] = value
}
}
if v, ok := args[-1]; ok {
a[len(args)-1] = SYMBOLS.amp
a = append(a, v)
}
argVector := EmptyVector()
for _, v := range a {
argVector = argVector.Conjoin(v)
}
if LINTER_MODE {
if meta, ok := body.(Meta); ok {
m := EmptyArrayMap().Plus(MakeKeyword("skip-redundant-do"), Boolean{B: true})
body = meta.WithMeta(m)
}
}
return DeriveReadObject(body, NewListFrom(MakeSymbol("joker.core/fn"), argVector, body))
}
func isTerminatingMacro(r rune) bool {
switch r {
case '"', ';', '@', '^', '`', '~', '(', ')', '[', ']', '{', '}', '\\':