-
Notifications
You must be signed in to change notification settings - Fork 67
/
parse.go
1879 lines (1747 loc) · 44.1 KB
/
parse.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"
"regexp"
"sort"
"strings"
"unsafe"
)
type (
Expr interface {
Eval(env *LocalEnv) Object
InferType() *Type
Pos() Position
Dump(includePosition bool) Map
Pack(p []byte, env *PackEnv) []byte
}
LiteralExpr struct {
Position
obj Object
isSurrogate bool
}
VectorExpr struct {
Position
v []Expr
}
MapExpr struct {
Position
keys []Expr
values []Expr
}
SetExpr struct {
Position
elements []Expr
}
IfExpr struct {
Position
cond Expr
positive Expr
negative Expr
}
DefExpr struct {
Position
vr *Var
name Symbol
value Expr
meta Expr
isCreatedByMacro bool
}
CallExpr struct {
Position
callable Expr
args []Expr
}
MacroCallExpr struct {
Position
macro Callable
args []Object
name string
}
RecurExpr struct {
Position
args []Expr
}
VarRefExpr struct {
Position
vr *Var
}
BindingExpr struct {
Position
binding *Binding
}
MetaExpr struct {
Position
meta *MapExpr
expr Expr
}
DoExpr struct {
Position
body []Expr
isCreatedByMacro bool
}
FnArityExpr struct {
Position
args []Symbol
body []Expr
taggedType *Type
}
FnExpr struct {
Position
arities []FnArityExpr
variadic *FnArityExpr
self Symbol
}
LetExpr struct {
Position
names []Symbol
values []Expr
body []Expr
}
LoopExpr LetExpr
ThrowExpr struct {
Position
e Expr
}
CatchExpr struct {
Position
excType *Type
excSymbol Symbol
body []Expr
}
TryExpr struct {
Position
body []Expr
catches []*CatchExpr
finallyExpr []Expr
}
SetMacroExpr struct {
Position
vr *Var
}
ParseError struct {
obj Object
msg string
}
Callable interface {
Call(args []Object) Object
}
Binding struct {
name Symbol
index int
frame int
isUsed bool
}
Bindings struct {
bindings map[*string]*Binding
parent *Bindings
frame int
}
LocalEnv struct {
bindings []Object
parent *LocalEnv
frame int
}
ParseContext struct {
GlobalEnv *Env
localBindings *Bindings
loopBindings [][]Symbol
linterBindings *Bindings
recur bool
noRecurAllowed bool
isUnknownCallableScope bool
}
Warnings struct {
ifWithoutElse bool
unusedFnParameters bool
fnWithEmptyBody bool
ignoredUnusedNamespaces Set
IgnoredFileRegexes []*regexp.Regexp
entryPoints Set
}
Keywords struct {
tag Keyword
skipUnused Keyword
private Keyword
line Keyword
column Keyword
file Keyword
ns Keyword
macro Keyword
message Keyword
form Keyword
data Keyword
cause Keyword
arglist Keyword
doc Keyword
added Keyword
meta Keyword
knownMacros Keyword
rules Keyword
ifWithoutElse Keyword
unusedFnParameters Keyword
fnWithEmptyBody Keyword
_prefix Keyword
pos Keyword
startLine Keyword
endLine Keyword
startColumn Keyword
endColumn Keyword
filename Keyword
object Keyword
type_ Keyword
var_ Keyword
value Keyword
vector Keyword
name Keyword
dynamic Keyword
require Keyword
_import Keyword
else_ Keyword
none Keyword
validIdent Keyword
characterSet Keyword
encodingRange Keyword
core Keyword
symbol Keyword
visible Keyword
ascii Keyword
unicode Keyword
any Keyword
}
Symbols struct {
joker_core Symbol
underscore Symbol
catch Symbol
finally Symbol
amp Symbol
_if Symbol
quote Symbol
fn_ Symbol
fn Symbol
let_ Symbol
let Symbol
letfn_ Symbol
letfn Symbol
loop_ Symbol
loop Symbol
recur Symbol
setMacro_ Symbol
def Symbol
defLinter Symbol
_var Symbol
do Symbol
throw Symbol
try Symbol
unquoteSplicing Symbol
list Symbol
concat Symbol
seq Symbol
apply Symbol
emptySymbol Symbol
unquote Symbol
vector Symbol
hashMap Symbol
hashSet Symbol
defaultDataReaders Symbol
backslash Symbol
deref Symbol
ns Symbol
defrecord Symbol
defprotocol Symbol
extendProtocol Symbol
extendType Symbol
reify Symbol
}
Str struct {
_if *string
quote *string
fn_ *string
let_ *string
letfn_ *string
loop_ *string
recur *string
setMacro_ *string
def *string
defLinter *string
_var *string
do *string
throw *string
try *string
coreFilename *string
}
)
var (
LOCAL_BINDINGS *Bindings = nil
KNOWN_MACROS *Var
REQUIRE_VAR *Var
ALIAS_VAR *Var
REFER_VAR *Var
CREATE_NS_VAR *Var
IN_NS_VAR *Var
WARNINGS = Warnings{
fnWithEmptyBody: true,
entryPoints: EmptySet(),
}
)
func (b *Bindings) ToMap() Map {
var res Map = EmptyArrayMap()
for b != nil {
for _, v := range b.bindings {
res = res.Assoc(v.name, NIL).(Map)
}
b = b.parent
}
return res
}
func (localEnv *LocalEnv) addEmptyFrame(capacity int) *LocalEnv {
res := LocalEnv{
bindings: make([]Object, 0, capacity),
parent: localEnv,
}
if localEnv != nil {
res.frame = localEnv.frame + 1
}
return &res
}
func (localEnv *LocalEnv) addBinding(obj Object) {
localEnv.bindings = append(localEnv.bindings, obj)
}
func (localEnv *LocalEnv) addFrame(values []Object) *LocalEnv {
res := LocalEnv{
bindings: values,
parent: localEnv,
}
if localEnv != nil {
res.frame = localEnv.frame + 1
}
return &res
}
func (localEnv *LocalEnv) replaceFrame(values []Object) *LocalEnv {
res := LocalEnv{
bindings: values,
parent: localEnv.parent,
frame: localEnv.frame,
}
return &res
}
func (ctx *ParseContext) PushLoopBindings(bindings []Symbol) {
ctx.loopBindings = append(ctx.loopBindings, bindings)
}
func (ctx *ParseContext) PopLoopBindings() {
ctx.loopBindings = ctx.loopBindings[:len(ctx.loopBindings)-1]
}
func (ctx *ParseContext) GetLoopBindings() []Symbol {
n := len(ctx.loopBindings)
if n == 0 {
return nil
}
return ctx.loopBindings[n-1]
}
func (b *Bindings) PushFrame() *Bindings {
frame := 0
if b != nil {
frame = b.frame + 1
}
return &Bindings{
bindings: make(map[*string]*Binding),
parent: b,
frame: frame,
}
}
func (b *Bindings) PopFrame() *Bindings {
return b.parent
}
func (b *Bindings) AddBinding(sym Symbol, index int, skipUnused bool) {
if LINTER_MODE && !skipUnused {
old := b.bindings[sym.name]
if old != nil && needsUnusedWarning(old) {
printParseWarning(GetPosition(old.name), "Unused binding: "+old.name.ToString(false))
}
}
b.bindings[sym.name] = &Binding{
name: sym,
frame: b.frame,
index: index,
}
}
func (ctx *ParseContext) PushEmptyLocalFrame() {
ctx.localBindings = ctx.localBindings.PushFrame()
}
func (ctx *ParseContext) PushLocalFrame(names []Symbol) {
ctx.PushEmptyLocalFrame()
for i, sym := range names {
ctx.localBindings.AddBinding(sym, i, true)
}
}
func (ctx *ParseContext) PopLocalFrame() {
ctx.localBindings = ctx.localBindings.PopFrame()
}
func (b *Bindings) GetBinding(sym Symbol) *Binding {
env := b
for env != nil {
if b, ok := env.bindings[sym.name]; ok {
return b
}
env = env.parent
}
return nil
}
func (ctx *ParseContext) GetLocalBinding(sym Symbol) *Binding {
if sym.ns != nil {
return nil
}
return ctx.localBindings.GetBinding(sym)
}
func (pos Position) Pos() Position {
return pos
}
func printError(pos Position, msg string) {
PROBLEM_COUNT++
fmt.Fprintf(Stderr, "%s:%d:%d: %s\n", pos.Filename(), pos.startLine, pos.startColumn, msg)
}
func printParseWarning(pos Position, msg string) {
printError(pos, "Parse warning: "+msg)
}
func printParseError(pos Position, msg string) {
printError(pos, "Parse error: "+msg)
}
func printReadWarning(reader *Reader, msg string) {
pos := Position{
filename: reader.filename,
startColumn: reader.column,
startLine: reader.line,
}
printError(pos, "Read warning: "+msg)
}
func printReadError(reader *Reader, msg string) {
pos := Position{
filename: reader.filename,
startColumn: reader.column,
startLine: reader.line,
}
printError(pos, "Read error: "+msg)
}
func isIgnoredUnusedNamespace(ns *Namespace) bool {
if WARNINGS.ignoredUnusedNamespaces == nil {
return false
}
ok, _ := WARNINGS.ignoredUnusedNamespaces.Get(ns.Name)
return ok
}
func ResetUsage() {
for _, ns := range GLOBAL_ENV.Namespaces {
if ns == GLOBAL_ENV.CoreNamespace {
continue
}
ns.isUsed = true
for _, vr := range ns.mappings {
vr.isUsed = true
}
}
}
func isEntryPointNs(ns *Namespace) bool {
ok, _ := WARNINGS.entryPoints.Get(ns.Name)
return ok
}
func WarnOnGloballyUnusedNamespaces() {
var names []string
positions := make(map[string]Position)
for _, ns := range GLOBAL_ENV.Namespaces {
if !ns.isGloballyUsed && !isIgnoredUnusedNamespace(ns) && !isEntryPointNs(ns) {
pos := ns.Name.GetInfo()
if pos != nil && pos.Filename() != "<joker.core>" && pos.Filename() != "<user>" {
name := ns.Name.ToString(false)
names = append(names, name)
positions[name] = pos.Position
}
}
}
sort.Strings(names)
for _, name := range names {
printParseWarning(positions[name], "globally unused namespace "+name)
}
}
func WarnOnUnusedNamespaces() {
var names []string
positions := make(map[string]Position)
for _, ns := range GLOBAL_ENV.Namespaces {
if ns != GLOBAL_ENV.CurrentNamespace() && !ns.isUsed && !isIgnoredUnusedNamespace(ns) {
pos := ns.Name.GetInfo()
if pos != nil && pos.Filename() != "<joker.core>" && pos.Filename() != "<user>" {
name := ns.Name.ToString(false)
names = append(names, name)
positions[name] = pos.Position
}
}
}
sort.Strings(names)
for _, name := range names {
printParseWarning(positions[name], "unused namespace "+name)
}
}
func isEntryPointVar(vr *Var) bool {
if isEntryPointNs(vr.ns) {
return true
}
sym := Symbol{
ns: vr.ns.Name.name,
name: vr.name.name,
}
ok, _ := WARNINGS.entryPoints.Get(sym)
return ok
}
func WarnOnGloballyUnusedVars() {
var names []string
positions := make(map[string]Position)
for _, ns := range GLOBAL_ENV.Namespaces {
if ns == GLOBAL_ENV.CoreNamespace {
continue
}
for _, vr := range ns.mappings {
if vr.ns == ns && !vr.isGloballyUsed && !vr.isPrivate && !isRecordConstructor(vr.name) && !isEntryPointVar(vr) {
pos := vr.GetInfo()
if pos != nil {
varName := vr.Name()
names = append(names, varName)
positions[varName] = pos.Position
}
}
}
}
sort.Strings(names)
for _, name := range names {
printParseWarning(positions[name], "globally unused var "+name)
}
}
func WarnOnUnusedVars() {
var names []string
positions := make(map[string]Position)
for _, ns := range GLOBAL_ENV.Namespaces {
if ns == GLOBAL_ENV.CoreNamespace {
continue
}
for _, vr := range ns.mappings {
if vr.ns == ns && !vr.isUsed && vr.isPrivate {
pos := vr.GetInfo()
if pos != nil {
names = append(names, *vr.name.name)
positions[*vr.name.name] = pos.Position
}
}
}
}
sort.Strings(names)
for _, name := range names {
printParseWarning(positions[name], "unused var "+name)
}
}
func NewLiteralExpr(obj Object) *LiteralExpr {
res := LiteralExpr{obj: obj}
info := obj.GetInfo()
if info != nil {
res.Position = info.Position
}
return &res
}
func NewSurrogateExpr(obj Object) *LiteralExpr {
res := NewLiteralExpr(obj)
res.isSurrogate = true
return res
}
func (err *ParseError) ToString(escape bool) string {
return err.Error()
}
func (err *ParseError) Equals(other interface{}) bool {
return err == other
}
func (err *ParseError) GetInfo() *ObjectInfo {
return nil
}
func (err *ParseError) GetType() *Type {
return TYPE.ParseError
}
func (err *ParseError) Hash() uint32 {
return HashPtr(uintptr(unsafe.Pointer(err)))
}
func (err *ParseError) WithInfo(info *ObjectInfo) Object {
return err
}
func (err *ParseError) Message() Object {
return MakeString(err.msg)
}
func (err ParseError) Error() string {
line, column, filename := 0, 0, "<file>"
info := err.obj.GetInfo()
if info != nil {
line, column, filename = info.startLine, info.startColumn, info.Filename()
}
return fmt.Sprintf("%s:%d:%d: Parse error: %s", filename, line, column, err.msg)
}
func parseSeq(seq Seq, ctx *ParseContext) []Expr {
res := make([]Expr, 0)
for !seq.IsEmpty() {
res = append(res, Parse(seq.First(), ctx))
seq = seq.Rest()
}
return res
}
func parseVector(v *Vector, pos Position, ctx *ParseContext) Expr {
r := make([]Expr, v.count)
for i := 0; i < v.count; i++ {
r[i] = Parse(v.at(i), ctx)
}
return &VectorExpr{
v: r,
Position: pos,
}
}
func parseMap(m Map, pos Position, ctx *ParseContext) *MapExpr {
res := &MapExpr{
keys: make([]Expr, m.Count()),
values: make([]Expr, m.Count()),
Position: pos,
}
for iter, i := m.Iter(), 0; iter.HasNext(); i++ {
p := iter.Next()
res.keys[i] = Parse(p.Key, ctx)
res.values[i] = Parse(p.Value, ctx)
}
return res
}
func parseSet(s *MapSet, pos Position, ctx *ParseContext) Expr {
res := &SetExpr{
elements: make([]Expr, s.m.Count()),
Position: pos,
}
for iter, i := iter(s.Seq()), 0; iter.HasNext(); i++ {
res.elements[i] = Parse(iter.Next(), ctx)
}
return res
}
func checkForm(obj Object, min int, max int) int {
seq := obj.(Seq)
c := SeqCount(seq)
if c < min {
panic(&ParseError{obj: obj, msg: "Too few arguments to " + seq.First().ToString(false)})
}
if c > max {
panic(&ParseError{obj: obj, msg: "Too many arguments to " + seq.First().ToString(false)})
}
return c
}
func GetPosition(obj Object) Position {
info := obj.GetInfo()
if info != nil {
return info.Position
}
return Position{}
}
func updateVar(vr *Var, info *ObjectInfo, valueExpr Expr, sym Symbol) {
vr.WithInfo(info)
vr.expr = valueExpr
meta := sym.GetMeta()
if meta != nil {
if ok, p := meta.Get(KEYWORDS.private); ok {
vr.isPrivate = ToBool(p)
}
if ok, p := meta.Get(KEYWORDS.dynamic); ok {
vr.isDynamic = ToBool(p)
}
vr.taggedType = getTaggedType(sym)
}
}
func isCreatedByMacro(formSeq Seq) bool {
return formSeq.First().GetInfo().Pos().filename == STR.coreFilename
}
func parseDef(obj Object, ctx *ParseContext, isForLinter bool) *DefExpr {
count := checkForm(obj, 2, 4)
seq := obj.(Seq)
s := Second(seq)
var meta Map
switch sym := s.(type) {
case Symbol:
if sym.ns != nil && (Symbol{name: sym.ns} != ctx.GlobalEnv.CurrentNamespace().Name) {
panic(&ParseError{
msg: "Can't create defs outside of current ns",
obj: obj,
})
}
symWithoutNs := sym
symWithoutNs.ns = nil
vr := ctx.GlobalEnv.CurrentNamespace().Intern(symWithoutNs)
if isForLinter {
vr.isGloballyUsed = true
}
res := &DefExpr{
vr: vr,
name: sym,
value: nil,
Position: GetPosition(obj),
isCreatedByMacro: isCreatedByMacro(seq),
}
meta = sym.GetMeta()
if count == 3 {
res.value = Parse(Third(seq), ctx)
} else if count == 4 {
res.value = Parse(Fourth(seq), ctx)
docstring := Third(seq)
switch docstring.(type) {
case String:
if meta != nil {
meta = meta.Assoc(KEYWORDS.doc, docstring).(Map)
} else {
meta = EmptyArrayMap().Assoc(KEYWORDS.doc, docstring).(Map)
}
default:
panic(&ParseError{obj: docstring, msg: "Docstring must be a string"})
}
}
updateVar(vr, obj.GetInfo(), res.value, sym)
if meta != nil {
res.meta = Parse(DeriveReadObject(obj, meta), ctx)
}
return res
default:
panic(&ParseError{obj: s, msg: "First argument to def must be a Symbol"})
}
}
func skipRedundantDo(obj Object) bool {
if meta, ok := obj.(Meta); ok {
if m := meta.GetMeta(); m != nil {
if ok, res := m.Get(MakeKeyword("skip-redundant-do")); ok {
return res.Equals(Boolean{B: true})
}
}
}
return false
}
func parseBody(seq Seq, ctx *ParseContext) []Expr {
recur := ctx.recur
ctx.recur = false
defer func() { ctx.recur = recur }()
res := make([]Expr, 0)
for !seq.IsEmpty() {
ro := seq.First()
expr := Parse(ro, ctx)
seq = seq.Rest()
if ctx.recur && !seq.IsEmpty() && !LINTER_MODE {
panic(&ParseError{obj: ro, msg: "Can only recur from tail position"})
}
res = append(res, expr)
if LINTER_MODE {
if defExpr, ok := expr.(*DefExpr); ok && !defExpr.isCreatedByMacro {
printParseWarning(defExpr.Pos(), "inline def")
} else if doExpr, ok := expr.(*DoExpr); ok && !doExpr.isCreatedByMacro && !skipRedundantDo(ro) {
printParseWarning(doExpr.Pos(), "redundant do form")
}
}
}
return res
}
func parseParams(params Object) (bindings []Symbol, isVariadic bool) {
res := make([]Symbol, 0)
v := params.(*Vector)
for i := 0; i < v.count; i++ {
ro := v.at(i)
sym := ro
if !IsSymbol(sym) {
if LINTER_MODE {
sym = generateSymbol("linter")
} else {
panic(&ParseError{obj: ro, msg: "Unsupported binding form: " + sym.ToString(false)})
}
}
if SYMBOLS.amp.Equals(sym) {
if v.count > i+2 {
ro := v.at(i + 2)
panic(&ParseError{obj: ro, msg: "Unexpected parameter: " + ro.ToString(false)})
}
if v.count == i+2 {
variadic := v.at(i + 1)
if !IsSymbol(variadic) {
if LINTER_MODE {
variadic = generateSymbol("linter")
} else {
panic(&ParseError{obj: variadic, msg: "Unsupported binding form: " + variadic.ToString(false)})
}
}
res = append(res, variadic.(Symbol))
return res, true
} else {
return res, false
}
}
res = append(res, sym.(Symbol))
}
return res, false
}
func needsUnusedWarning(b *Binding) bool {
return !b.isUsed &&
!strings.HasPrefix(*b.name.name, "_") &&
!strings.HasPrefix(*b.name.name, "&form") &&
!strings.HasPrefix(*b.name.name, "&env") &&
!isSkipUnused(b.name)
}
func addArity(fn *FnExpr, sig Seq, ctx *ParseContext) {
params := sig.First()
body := sig.Rest()
args, isVariadic := parseParams(params)
ctx.PushLocalFrame(args)
defer ctx.PopLocalFrame()
ctx.PushLoopBindings(args)
defer ctx.PopLoopBindings()
noRecurAllowed := ctx.noRecurAllowed
ctx.noRecurAllowed = false
defer func() { ctx.noRecurAllowed = noRecurAllowed }()
arity := FnArityExpr{
Position: GetPosition(sig),
args: args,
body: parseBody(body, ctx),
taggedType: getTaggedType(params.(Meta)),
}
if isVariadic {
if fn.variadic != nil {
panic(&ParseError{obj: params, msg: "Can't have more than 1 variadic overload"})
}
for _, arity := range fn.arities {
if len(arity.args) >= len(args) {
panic(&ParseError{obj: params, msg: "Can't have fixed arity function with more params than variadic function"})
}
}
fn.variadic = &arity
} else {
for _, arity := range fn.arities {
if len(arity.args) == len(args) {
panic(&ParseError{obj: params, msg: "Can't have 2 overloads with same arity"})
}
}
if fn.variadic != nil && len(args) >= len(fn.variadic.args) {
panic(&ParseError{obj: params, msg: "Can't have fixed arity function with more params than variadic function"})
}
fn.arities = append(fn.arities, arity)
}
if LINTER_MODE {
if WARNINGS.fnWithEmptyBody {
if len(arity.body) == 0 {
printParseWarning(arity.Position, "fn form with empty body")
}
}
if WARNINGS.unusedFnParameters {
var unused []Symbol
for _, b := range ctx.localBindings.bindings {
if needsUnusedWarning(b) {
unused = append(unused, b.name)
}
}
sort.Sort(BySymbolName(unused))
for _, u := range unused {
printParseWarning(GetPosition(u), "unused parameter: "+u.ToString(false))
}
}
}
}
func wrapWithMeta(fnExpr *FnExpr, obj Object, ctx *ParseContext) Expr {
meta := obj.(Meta).GetMeta()
if meta != nil {
return &MetaExpr{
meta: parseMap(meta, fnExpr.Pos(), ctx),
expr: fnExpr,
Position: fnExpr.Pos(),
}
}
return fnExpr
}
// Examples:
// (fn f [] 1 2)
// (fn f ([] 1 2)
// ([a] a 3)
// ([a & b] a b))
func parseFn(obj Object, ctx *ParseContext) Expr {
res := &FnExpr{Position: GetPosition(obj)}
bodies := obj.(Seq).Rest()
p := bodies.First()
if IsSymbol(p) { // self reference
res.self = p.(Symbol)
bodies = bodies.Rest()
p = bodies.First()
ctx.PushLocalFrame([]Symbol{res.self})
defer ctx.PopLocalFrame()
}
if IsVector(p) { // single arity
addArity(res, bodies, ctx)
return wrapWithMeta(res, obj, ctx)
}
// multiple arities
if bodies.IsEmpty() {
panic(&ParseError{obj: p, msg: "Parameter declaration missing"})
}
for !bodies.IsEmpty() {
body := bodies.First()
switch s := body.(type) {
case Seq:
params := s.First()
if !IsVector(params) {
panic(&ParseError{obj: params, msg: "Parameter declaration must be a vector. Got: " + params.ToString(false)})
}
addArity(res, s, ctx)
default:
panic(&ParseError{obj: body, msg: "Function body must be a list. Got: " + s.ToString(false)})
}
bodies = bodies.Rest()
}
return wrapWithMeta(res, obj, ctx)
}
func isCatch(obj Object) bool {
return IsSeq(obj) && obj.(Seq).First().Equals(SYMBOLS.catch)
}
func isFinally(obj Object) bool {
return IsSeq(obj) && obj.(Seq).First().Equals(SYMBOLS.finally)
}
func resolveType(obj Object, ctx *ParseContext) *Type {
excType := Parse(obj, ctx)
switch excType := excType.(type) {
case *LiteralExpr:
switch t := excType.obj.(type) {
case *Type:
return t
}
}
if LINTER_MODE {
return TYPE.Error
}
panic(&ParseError{obj: obj, msg: "Unable to resolve type: " + obj.ToString(false)})
}
func parseCatch(obj Object, ctx *ParseContext) *CatchExpr {
seq := obj.(Seq).Rest()
if seq.IsEmpty() || seq.Rest().IsEmpty() {
panic(&ParseError{obj: obj, msg: "catch requires at least two arguments: type symbol and binding symbol"})
}
excSymbol := Second(seq)
excType := resolveType(seq.First(), ctx)
if !IsSymbol(excSymbol) {
panic(&ParseError{obj: excSymbol, msg: "Bad binding form, expected symbol, got: " + excSymbol.ToString(false)})
}
ctx.PushLocalFrame([]Symbol{excSymbol.(Symbol)})