-
Notifications
You must be signed in to change notification settings - Fork 374
/
Parser.idr
2752 lines (2483 loc) · 109 KB
/
Parser.idr
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
module Idris.Parser
import Core.Options
import Core.Metadata
import Idris.Syntax
import Idris.Syntax.Traversals
import public Parser.Source
import TTImp.TTImp
import public Libraries.Text.Parser
import Data.Either
import Libraries.Data.IMaybe
import Data.List
import Data.List.Quantifiers
import Data.List1
import Data.Maybe
import Data.So
import Data.Nat
import Data.SnocList
import Data.String
import Libraries.Utils.String
import Libraries.Data.WithDefault
import Idris.Parser.Let
%default covering
decorate : OriginDesc -> Decoration -> Rule a -> Rule a
decorate fname decor rule = do
res <- bounds rule
actD (decorationFromBounded fname decor res)
pure res.val
boundedNameDecoration : OriginDesc -> Decoration -> WithBounds Name -> ASemanticDecoration
boundedNameDecoration fname decor bstr = ((fname, start bstr, end bstr)
, decor
, Just bstr.val)
decorateBoundedNames : OriginDesc -> Decoration -> List (WithBounds Name) -> EmptyRule ()
decorateBoundedNames fname decor bns
= act $ MkState (cast (map (boundedNameDecoration fname decor) bns)) []
decorateBoundedName : OriginDesc -> Decoration -> WithBounds Name -> EmptyRule ()
decorateBoundedName fname decor bn = actD (boundedNameDecoration fname decor bn)
decorateKeywords : OriginDesc -> List (WithBounds a) -> EmptyRule ()
decorateKeywords fname xs
= act $ MkState (cast (map (decorationFromBounded fname Keyword) xs)) []
dependentDecorate : OriginDesc -> Rule a -> (a -> Decoration) -> Rule a
dependentDecorate fname rule decor = do
res <- bounds rule
actD (decorationFromBounded fname (decor res.val) res)
pure res.val
decoratedKeyword : OriginDesc -> String -> Rule ()
decoratedKeyword fname kwd = decorate fname Keyword (keyword kwd)
decoratedPragma : OriginDesc -> String -> Rule ()
decoratedPragma fname prg = decorate fname Keyword (pragma prg)
decoratedSymbol : OriginDesc -> String -> Rule ()
decoratedSymbol fname smb = decorate fname Keyword (symbol smb)
decoratedNamespacedSymbol : OriginDesc -> String -> Rule (Maybe Namespace)
decoratedNamespacedSymbol fname smb =
decorate fname Keyword $ namespacedSymbol smb
parens : {b : _} -> OriginDesc -> BRule b a -> Rule a
parens fname p
= pure id <* decoratedSymbol fname "("
<*> p
<* decoratedSymbol fname ")"
decoratedDataTypeName : OriginDesc -> Rule Name
decoratedDataTypeName fname = decorate fname Typ dataTypeName
decoratedDataConstructorName : OriginDesc -> Rule Name
decoratedDataConstructorName fname = decorate fname Data dataConstructorName
decoratedSimpleBinderName : OriginDesc -> Rule String
decoratedSimpleBinderName fname = decorate fname Bound unqualifiedName
decoratedSimpleNamedArg : OriginDesc -> Rule String
decoratedSimpleNamedArg fname
= decorate fname Bound unqualifiedName
<|> parens fname (decorate fname Bound unqualifiedOperatorName)
-- Forward declare since they're used in the parser
topDecl : OriginDesc -> IndentInfo -> Rule (List PDecl)
collectDefs : List PDecl -> List PDecl
-- Some context for the parser
public export
record ParseOpts where
constructor MkParseOpts
eqOK : Bool -- = operator is parseable
withOK : Bool -- = with applications are parseable
peq : ParseOpts -> ParseOpts
peq = { eqOK := True }
pnoeq : ParseOpts -> ParseOpts
pnoeq = { eqOK := False }
export
pdef : ParseOpts
pdef = MkParseOpts {eqOK = True, withOK = True}
pnowith : ParseOpts
pnowith = MkParseOpts {eqOK = True, withOK = False}
export
plhs : ParseOpts
plhs = MkParseOpts {eqOK = False, withOK = False}
%hide Prelude.(>>)
%hide Prelude.(>>=)
%hide Core.Core.(>>)
%hide Core.Core.(>>=)
%hide Prelude.pure
%hide Core.Core.pure
%hide Prelude.(<*>)
%hide Core.Core.(<*>)
atom : OriginDesc -> Rule PTerm
atom fname
= do x <- bounds $ decorate fname Typ $ exactIdent "Type"
pure (PType (boundToFC fname x))
<|> do x <- bounds $ name
pure (PRef (boundToFC fname x) x.val)
<|> do x <- bounds $ dependentDecorate fname constant $ \c =>
if isPrimType c
then Typ
else Data
pure (PPrimVal (boundToFC fname x) x.val)
<|> do x <- bounds $ decoratedSymbol fname "_"
pure (PImplicit (boundToFC fname x))
<|> do x <- bounds $ symbol "?"
pure (PInfer (boundToFC fname x))
<|> do x <- bounds $ holeName
actH x.val -- record the hole name in the parser
pure (PHole (boundToFC fname x) False x.val)
<|> do x <- bounds $ decorate fname Data $ pragma "MkWorld"
pure (PPrimVal (boundToFC fname x) WorldVal)
<|> do x <- bounds $ decorate fname Typ $ pragma "World"
pure (PPrimVal (boundToFC fname x) $ PrT WorldType)
<|> do x <- bounds $ decoratedPragma fname "search"
pure (PSearch (boundToFC fname x) 50)
whereBlock : OriginDesc -> Int -> Rule (List PDecl)
whereBlock fname col
= do decoratedKeyword fname "where"
ds <- blockAfter col (topDecl fname)
pure (collectDefs (concat ds))
-- Expect a keyword, but if we get anything else it's a fatal error
commitKeyword : OriginDesc -> IndentInfo -> String -> Rule ()
commitKeyword fname indents req
= do mustContinue indents (Just req)
decoratedKeyword fname req
<|> the (Rule ()) (fatalError ("Expected '" ++ req ++ "'"))
mustContinue indents Nothing
commitSymbol : OriginDesc -> String -> Rule ()
commitSymbol fname req
= decoratedSymbol fname req
<|> fatalError ("Expected '" ++ req ++ "'")
continueWithDecorated : OriginDesc -> IndentInfo -> String -> Rule ()
continueWithDecorated fname indents req
= mustContinue indents (Just req) *> decoratedSymbol fname req
continueWith : IndentInfo -> String -> Rule ()
continueWith indents req
= mustContinue indents (Just req) *> symbol req
iOperator : Rule OpStr
iOperator
= OpSymbols <$> operator
<|> Backticked <$> (symbol "`" *> name <* symbol "`")
data ArgType
= UnnamedExpArg PTerm
| UnnamedAutoArg PTerm
| NamedArg Name PTerm
| WithArg PTerm
argTerm : ArgType -> PTerm
argTerm (UnnamedExpArg t) = t
argTerm (UnnamedAutoArg t) = t
argTerm (NamedArg _ t) = t
argTerm (WithArg t) = t
export
debugString : OriginDesc -> Rule PTerm
debugString fname = do
di <- bounds debugInfo
pure $ PPrimVal (boundToFC fname di) $ Str $ case di.val of
DebugLoc =>
let bnds = di.bounds in
joinBy ", "
[ "File \{show fname}"
, "line \{show (startLine bnds)}"
, "characters \{show (startCol bnds)}\{
ifThenElse (startLine bnds == endLine bnds)
("-\{show (endCol bnds)}")
""
}"
]
DebugFile => "\{show fname}"
DebugLine => "\{show (startLine di.bounds)}"
DebugCol => "\{show (startCol di.bounds)}"
totalityOpt : OriginDesc -> Rule TotalReq
totalityOpt fname
= (decoratedKeyword fname "partial" $> PartialOK)
<|> (decoratedKeyword fname "total" $> Total)
<|> (decoratedKeyword fname "covering" $> CoveringOnly)
fnOpt : OriginDesc -> Rule PFnOpt
fnOpt fname
= do x <- totalityOpt fname
pure $ IFnOpt (Totality x)
mutual
appExpr : ParseOpts -> OriginDesc -> IndentInfo -> Rule PTerm
appExpr q fname indents
= case_ fname indents
<|> doBlock fname indents
<|> lam fname indents
<|> lazy fname indents
<|> if_ fname indents
<|> with_ fname indents
<|> do b <- bounds (MkPair <$> simpleExpr fname indents <*> many (argExpr q fname indents))
(f, args) <- pure b.val
pure (applyExpImp (start b) (end b) f (concat args))
<|> do b <- bounds (MkPair <$> bounds iOperator <*> expr pdef fname indents)
(op, arg) <- pure b.val
pure (PPrefixOp (boundToFC fname b) (boundToFC fname op) op.val arg)
<|> fail "Expected 'case', 'if', 'do', application or operator expression"
where
applyExpImp : FilePos -> FilePos -> PTerm ->
List ArgType ->
PTerm
applyExpImp start end f [] = f
applyExpImp start end f (UnnamedExpArg exp :: args)
= applyExpImp start end (PApp (MkFC fname start end) f exp) args
applyExpImp start end f (UnnamedAutoArg imp :: args)
= applyExpImp start end (PAutoApp (MkFC fname start end) f imp) args
applyExpImp start end f (NamedArg n imp :: args)
= let fc = MkFC fname start end in
applyExpImp start end (PNamedApp fc f n imp) args
applyExpImp start end f (WithArg exp :: args)
= applyExpImp start end (PWithApp (MkFC fname start end) f exp) args
argExpr : ParseOpts -> OriginDesc -> IndentInfo -> Rule (List ArgType)
argExpr q fname indents
= do continue indents
arg <- simpleExpr fname indents
the (EmptyRule _) $ case arg of
PHole loc _ n => pure [UnnamedExpArg (PHole loc True n)]
t => pure [UnnamedExpArg t]
<|> do continue indents
braceArgs fname indents
<|> if withOK q
then do continue indents
decoratedSymbol fname "|"
arg <- expr ({withOK := False} q) fname indents
pure [WithArg arg]
else fail "| not allowed here"
where
underscore : FC -> ArgType
underscore fc = NamedArg (UN Underscore) (PImplicit fc)
braceArgs : OriginDesc -> IndentInfo -> Rule (List ArgType)
braceArgs fname indents
= do start <- bounds (decoratedSymbol fname "{")
mustWork $ do
list <- sepBy (decoratedSymbol fname ",")
$ do x <- bounds (UN . Basic <$> decoratedSimpleNamedArg fname)
let fc = boundToFC fname x
option (NamedArg x.val $ PRef fc x.val)
$ do tm <- decoratedSymbol fname "=" *> typeExpr pdef fname indents
pure (NamedArg x.val tm)
matchAny <- option [] (if isCons list then
do decoratedSymbol fname ","
x <- bounds (decoratedSymbol fname "_")
pure [underscore (boundToFC fname x)]
else fail "non-empty list required")
end <- bounds (decoratedSymbol fname "}")
matchAny <- do let fc = boundToFC fname (mergeBounds start end)
pure $ if isNil list
then [underscore fc]
else matchAny
pure $ matchAny ++ list
<|> do decoratedSymbol fname "@{"
commit
tm <- typeExpr pdef fname indents
decoratedSymbol fname "}"
pure [UnnamedAutoArg tm]
with_ : OriginDesc -> IndentInfo -> Rule PTerm
with_ fname indents
= do b <- bounds (do decoratedKeyword fname "with"
commit
ns <- singleName <|> nameList
end <- location
rhs <- expr pdef fname indents
pure (ns, rhs))
(ns, rhs) <- pure b.val
pure (PWithUnambigNames (boundToFC fname b) ns rhs)
where
singleName : Rule (List (FC, Name))
singleName = do
n <- bounds name
pure [(boundToFC fname n, n.val)]
nameList : Rule (List (FC, Name))
nameList = do
decoratedSymbol fname "["
commit
ns <- sepBy1 (decoratedSymbol fname ",") (bounds name)
decoratedSymbol fname "]"
pure (map (\ n => (boundToFC fname n, n.val)) $ forget ns)
-- The different kinds of operator bindings `x : ty` for typebind
-- x := e and x : ty := e for autobind
opBinderTypes : OriginDesc -> IndentInfo -> WithBounds PTerm -> Rule (OperatorLHSInfo PTerm)
opBinderTypes fname indents boundName =
do decoratedSymbol fname ":"
ty <- typeExpr pdef fname indents
decoratedSymbol fname ":="
exp <- expr pdef fname indents
pure (BindExplicitType boundName.val ty exp)
<|> do decoratedSymbol fname ":="
exp <- expr pdef fname indents
pure (BindExpr boundName.val exp)
<|> do decoratedSymbol fname ":"
ty <- typeExpr pdef fname indents
pure (BindType boundName.val ty)
opBinder : OriginDesc -> IndentInfo -> Rule (OperatorLHSInfo PTerm)
opBinder fname indents
= do boundName <- bounds (expr plhs fname indents)
opBinderTypes fname indents boundName
autobindOp : ParseOpts -> OriginDesc -> IndentInfo -> Rule PTerm
autobindOp q fname indents
= do binder <- bounds $ parens fname (opBinder fname indents)
continue indents
op <- bounds iOperator
commit
e <- bounds (expr q fname indents)
pure (POp (boundToFC fname $ mergeBounds binder e)
(boundToFC fname op)
binder.val
op.val
e.val)
opExprBase : ParseOpts -> OriginDesc -> IndentInfo -> Rule PTerm
opExprBase q fname indents
= do l <- bounds (appExpr q fname indents)
(if eqOK q
then do r <- bounds (continue indents
*> decoratedSymbol fname "="
*> opExprBase q fname indents)
pure $
let fc = boundToFC fname (mergeBounds l r)
opFC = virtualiseFC fc -- already been highlighted: we don't care
in POp fc opFC (NoBinder l.val) (OpSymbols $ UN $ Basic "=") r.val
else fail "= not allowed")
<|>
(do b <- bounds $ do
continue indents
op <- bounds iOperator
e <- case op.val of
OpSymbols (UN (Basic "$")) => typeExpr q fname indents
_ => expr q fname indents
pure (op, e)
(op, r) <- pure b.val
let fc = boundToFC fname (mergeBounds l b)
let opFC = boundToFC fname op
pure (POp fc opFC (NoBinder l.val) op.val r))
<|> pure l.val
opExpr : ParseOpts -> OriginDesc -> IndentInfo -> Rule PTerm
opExpr q fname indents = autobindOp q fname indents
<|> opExprBase q fname indents
dpairType : OriginDesc -> WithBounds t -> IndentInfo -> Rule PTerm
dpairType fname start indents
= do loc <- bounds (do x <- UN . Basic <$> decoratedSimpleBinderName fname
decoratedSymbol fname ":"
ty <- typeExpr pdef fname indents
pure (x, ty))
(x, ty) <- pure loc.val
op <- bounds (symbol "**")
rest <- bounds (nestedDpair fname loc indents <|> typeExpr pdef fname indents)
pure (PDPair (boundToFC fname (mergeBounds start rest))
(boundToFC fname op)
(PRef (boundToFC fname loc) x)
ty
rest.val)
nestedDpair : OriginDesc -> WithBounds t -> IndentInfo -> Rule PTerm
nestedDpair fname start indents
= dpairType fname start indents
<|> do l <- expr pdef fname indents
loc <- bounds (symbol "**")
rest <- bounds (nestedDpair fname loc indents <|> expr pdef fname indents)
pure (PDPair (boundToFC fname (mergeBounds start rest))
(boundToFC fname loc)
l
(PImplicit (boundToFC fname (mergeBounds start rest)))
rest.val)
bracketedExpr : OriginDesc -> WithBounds t -> IndentInfo -> Rule PTerm
bracketedExpr fname s indents
-- left section. This may also be a prefix operator, but we'll sort
-- that out when desugaring: if the operator is infix, treat it as a
-- section otherwise treat it as prefix
= do b <- bounds (do op <- bounds iOperator
e <- expr pdef fname indents
continueWithDecorated fname indents ")"
pure (op, e))
(op, e) <- pure b.val
actD (toNonEmptyFC $ boundToFC fname s, Keyword, Nothing)
let fc = boundToFC fname (mergeBounds s b)
let opFC = boundToFC fname op
pure (PSectionL fc opFC op.val e)
<|> do -- (.y.z) -- section of projection (chain)
b <- bounds $ forget <$> some (bounds postfixProj)
decoratedSymbol fname ")"
actD (toNonEmptyFC $ boundToFC fname s, Keyword, Nothing)
let projs = map (\ proj => (boundToFC fname proj, proj.val)) b.val
pure $ PPostfixAppPartial (boundToFC fname b) projs
-- unit type/value
<|> do b <- bounds (continueWith indents ")")
pure (PUnit (boundToFC fname (mergeBounds s b)))
-- dependent pairs with type annotation (so, the type form)
<|> do dpairType fname s indents <* (decorate fname Typ $ symbol ")")
<* actD (toNonEmptyFC $ boundToFC fname s, Typ, Nothing)
<|> do e <- bounds (typeExpr pdef fname indents)
-- dependent pairs with no type annotation
(do loc <- bounds (symbol "**")
rest <- bounds ((nestedDpair fname loc indents <|> expr pdef fname indents) <* symbol ")")
pure (PDPair (boundToFC fname (mergeBounds s rest))
(boundToFC fname loc)
e.val
(PImplicit (boundToFC fname (mergeBounds s rest)))
rest.val)) <|>
-- right sections
((do op <- bounds (bounds iOperator <* decoratedSymbol fname ")")
actD (toNonEmptyFC $ boundToFC fname s, Keyword, Nothing)
let fc = boundToFC fname (mergeBounds s op)
let opFC = boundToFC fname op.val
pure (PSectionR fc opFC e.val op.val.val)
<|>
-- all the other bracketed expressions
tuple fname s indents e.val))
<|> do here <- location
let fc = MkFC fname here here
let var = PRef fc (MN "__leftTupleSection" 0)
ts <- bounds (nonEmptyTuple fname s indents var)
pure (PLam fc top Explicit var (PInfer fc) ts.val)
getInitRange : List (WithBounds PTerm) -> EmptyRule (PTerm, Maybe PTerm)
getInitRange [x] = pure (x.val, Nothing)
getInitRange [x,y] = pure (x.val, Just y.val)
getInitRange _ = fatalError "Invalid list range syntax"
listRange : OriginDesc -> WithBounds t -> IndentInfo -> List (WithBounds PTerm) -> Rule PTerm
listRange fname s indents xs
= do b <- bounds (decoratedSymbol fname "]")
let fc = boundToFC fname (mergeBounds s b)
rstate <- getInitRange xs
decorateKeywords fname xs
pure (PRangeStream fc (fst rstate) (snd rstate))
<|> do y <- bounds (expr pdef fname indents <* decoratedSymbol fname "]")
let fc = boundToFC fname (mergeBounds s y)
rstate <- getInitRange xs
decorateKeywords fname xs
pure (PRange fc (fst rstate) (snd rstate) y.val)
listExpr : OriginDesc -> WithBounds () -> IndentInfo -> Rule PTerm
listExpr fname s indents
= do b <- bounds (do ret <- expr pnowith fname indents
decoratedSymbol fname "|"
conds <- sepBy1 (decoratedSymbol fname ",") (doAct fname indents)
decoratedSymbol fname "]"
pure (ret, conds))
(ret, conds) <- pure b.val
pure (PComprehension (boundToFC fname (mergeBounds s b)) ret (concat conds))
<|> do xs <- option [] $ do
hd <- expr pdef fname indents
tl <- many $ do b <- bounds (symbol ",")
x <- mustWork $ expr pdef fname indents
pure (x <$ b)
pure ((hd <$ s) :: tl)
(do decoratedSymbol fname ".."
listRange fname s indents xs)
<|> (do b <- bounds (symbol "]")
pure $
let fc = boundToFC fname (mergeBounds s b)
nilFC = if null xs then fc else boundToFC fname b
in PList fc nilFC (cast (map (\ t => (boundToFC fname t, t.val)) xs)))
snocListExpr : OriginDesc -> WithBounds () -> IndentInfo -> Rule PTerm
snocListExpr fname s indents
= {- TODO: comprehension -}
do mHeadTail <- optional $ do
hd <- many $ do x <- expr pdef fname indents
b <- bounds (symbol ",")
pure (x <$ b)
tl <- expr pdef fname indents
pure (hd, tl)
{- TODO: reverse ranges -}
b <- bounds (symbol "]")
pure $
let xs : SnocList (WithBounds PTerm)
= case mHeadTail of
Nothing => [<]
Just (hd,tl) => ([<] <>< hd) :< (tl <$ b)
fc = boundToFC fname (mergeBounds s b)
nilFC = ifThenElse (null xs) fc (boundToFC fname s)
in PSnocList fc nilFC (map (\ t => (boundToFC fname t, t.val)) xs) --)
nonEmptyTuple : OriginDesc -> WithBounds t -> IndentInfo -> PTerm -> Rule PTerm
nonEmptyTuple fname s indents e
= do vals <- some $ do b <- bounds (symbol ",")
exp <- optional (typeExpr pdef fname indents)
pure (boundToFC fname b, exp)
end <- continueWithDecorated fname indents ")"
actD (toNonEmptyFC (boundToFC fname s), Keyword, Nothing)
pure $ let (start ::: rest) = vals in
buildOutput (fst start) (mergePairs 0 start rest)
where
lams : List (FC, PTerm) -> PTerm -> PTerm
lams [] e = e
lams ((fc, var) :: vars) e
= let vfc = virtualiseFC fc in
PLam vfc top Explicit var (PInfer vfc) $ lams vars e
buildOutput : FC -> (List (FC, PTerm), PTerm) -> PTerm
buildOutput fc (vars, scope) = lams vars $ PPair fc e scope
optionalPair : Int ->
(FC, Maybe PTerm) -> (Int, (List (FC, PTerm), PTerm))
optionalPair i (fc, Just e) = (i, ([], e))
optionalPair i (fc, Nothing) =
let var = PRef fc (MN "__infixTupleSection" i) in
(i+1, ([(fc, var)], var))
mergePairs : Int -> (FC, Maybe PTerm) ->
List (FC, Maybe PTerm) -> (List (FC, PTerm), PTerm)
mergePairs i hd [] = snd (optionalPair i hd)
mergePairs i hd (exp :: rest)
= let (j, (var, t)) = optionalPair i hd in
let (vars, ts) = mergePairs j exp rest in
(var ++ vars, PPair (fst exp) t ts)
-- A pair, dependent pair, or just a single expression
tuple : OriginDesc -> WithBounds t -> IndentInfo -> PTerm -> Rule PTerm
tuple fname s indents e
= nonEmptyTuple fname s indents e
<|> do end <- bounds (continueWithDecorated fname indents ")")
actD (toNonEmptyFC $ boundToFC fname s, Keyword, Nothing)
pure (PBracketed (boundToFC fname (mergeBounds s end)) e)
simpleExpr : OriginDesc -> IndentInfo -> Rule PTerm
simpleExpr fname indents
= do -- x.y.z
b <- bounds (do root <- simplerExpr fname indents
projs <- many (bounds postfixProj)
pure (root, projs))
(root, projs) <- pure b.val
let projs = map (\ proj => (boundToFC fname proj, proj.val)) projs
pure $ case projs of
[] => root
_ => PPostfixApp (boundToFC fname b) root projs
<|> debugString fname
<|> do b <- bounds (forget <$> some (bounds postfixProj))
pure $ let projs = map (\ proj => (boundToFC fname proj, proj.val)) b.val in
PPostfixAppPartial (boundToFC fname b) projs
simplerExpr : OriginDesc -> IndentInfo -> Rule PTerm
simplerExpr fname indents
= do b <- bounds (do x <- bounds (UN . Basic <$> decoratedSimpleBinderName fname)
decoratedSymbol fname "@"
commit
expr <- simpleExpr fname indents
pure (x, expr))
(x, expr) <- pure b.val
pure (PAs (boundToFC fname b) (boundToFC fname x) x.val expr)
<|> do b <- bounds $ do
mns <- decoratedNamespacedSymbol fname "[|"
t <- expr pdef fname indents
decoratedSymbol fname "|]"
pure (t, mns)
pure (PIdiom (boundToFC fname b) (snd b.val) (fst b.val))
<|> atom fname
<|> record_ fname indents
<|> singlelineStr pdef fname indents
<|> multilineStr pdef fname indents
<|> do b <- bounds $ do
decoratedSymbol fname ".("
commit
t <- typeExpr pdef fname indents
decoratedSymbol fname ")"
pure t
pure (PDotted (boundToFC fname b) b.val)
<|> do b <- bounds $ do
decoratedSymbol fname "`("
t <- typeExpr pdef fname indents
decoratedSymbol fname ")"
pure t
pure (PQuote (boundToFC fname b) b.val)
<|> do b <- bounds $ do
decoratedSymbol fname "`{"
t <- name
decoratedSymbol fname "}"
pure t
pure (PQuoteName (boundToFC fname b) b.val)
<|> do b <- bounds $ do
decoratedSymbol fname "`["
ts <- nonEmptyBlock (topDecl fname)
decoratedSymbol fname "]"
pure ts
pure (PQuoteDecl (boundToFC fname b) (collectDefs (concat b.val)))
<|> do b <- bounds (decoratedSymbol fname "~" *> simplerExpr fname indents)
pure (PUnquote (boundToFC fname b) b.val)
<|> do start <- bounds (symbol "(")
bracketedExpr fname start indents
<|> do start <- bounds (symbol "[<")
snocListExpr fname start indents
<|> do start <- bounds (symbol "[>" <|> symbol "[")
listExpr fname start indents
<|> do b <- bounds (decoratedSymbol fname "!" *> simpleExpr fname indents)
pure (PBang (virtualiseFC $ boundToFC fname b) b.val)
<|> do b <- bounds $ do decoratedPragma fname "logging"
topic <- optional (split (('.') ==) <$> simpleStr)
lvl <- intLit
e <- expr pdef fname indents
pure (MkPair (mkLogLevel' topic (integerToNat lvl)) e)
(lvl, e) <- pure b.val
pure (PUnifyLog (boundToFC fname b) lvl e)
<|> withWarning "DEPRECATED: trailing lambda. Use a $ or parens"
(lam fname indents)
multiplicity : OriginDesc -> EmptyRule RigCount
multiplicity fname
= case !(optional $ decorate fname Keyword intLit) of
(Just 0) => pure erased
(Just 1) => pure linear
Nothing => pure top
_ => fail "Invalid multiplicity (must be 0 or 1)"
pibindAll : OriginDesc -> PiInfo PTerm ->
List (RigCount, WithBounds (Maybe Name), PTerm) ->
PTerm -> PTerm
pibindAll fname p [] scope = scope
pibindAll fname p ((rig, n, ty) :: rest) scope
= PPi (boundToFC fname n) rig p (n.val) ty (pibindAll fname p rest scope)
bindList : OriginDesc -> IndentInfo ->
Rule (List (RigCount, WithBounds PTerm, PTerm))
bindList fname indents
= forget <$> sepBy1 (decoratedSymbol fname ",")
(do rig <- multiplicity fname
pat <- bounds (simpleExpr fname indents)
ty <- option
(PInfer (boundToFC fname pat))
(decoratedSymbol fname ":" *> opExpr pdef fname indents)
pure (rig, pat, ty))
pibindListName : OriginDesc -> IndentInfo ->
Rule (List (RigCount, WithBounds Name, PTerm))
pibindListName fname indents
= do rig <- multiplicity fname
ns <- sepBy1 (decoratedSymbol fname ",")
(bounds $ UN <$> binderName)
let ns = forget ns
decorateBoundedNames fname Bound ns
decoratedSymbol fname ":"
ty <- typeExpr pdef fname indents
atEnd indents
pure (map (\n => (rig, n, ty)) ns)
where
-- _ gets treated specially here, it means "I don't care about the name"
binderName : Rule UserName
binderName = Basic <$> unqualifiedName
<|> symbol "_" $> Underscore
PiBindList : Type
PiBindList = List (RigCount, WithBounds (Maybe Name), PTerm)
pibindList : OriginDesc -> IndentInfo ->
Rule PiBindList
pibindList fname indents
= do params <- pibindListName fname indents
pure $ map (\(rig, n, ty) => (rig, map Just n, ty)) params
bindSymbol : OriginDesc -> Rule (PiInfo PTerm)
bindSymbol fname
= (decoratedSymbol fname "->" $> Explicit)
<|> (decoratedSymbol fname "=>" $> AutoImplicit)
explicitPi : OriginDesc -> IndentInfo -> Rule PTerm
explicitPi fname indents
= do b <- bounds $ parens fname $ pibindList fname indents
exp <- mustWorkBecause b.bounds "Cannot return a named argument"
$ bindSymbol fname
scope <- mustWork $ typeExpr pdef fname indents
pure (pibindAll fname exp b.val scope)
autoImplicitPi : OriginDesc -> IndentInfo -> Rule PTerm
autoImplicitPi fname indents
= do b <- bounds $ do
decoratedSymbol fname "{"
decoratedKeyword fname "auto"
commit
binders <- pibindList fname indents
decoratedSymbol fname "}"
pure binders
mustWorkBecause b.bounds "Cannot return an auto implicit argument"
$ decoratedSymbol fname "->"
scope <- mustWork $ typeExpr pdef fname indents
pure (pibindAll fname AutoImplicit b.val scope)
defaultImplicitPi : OriginDesc -> IndentInfo -> Rule PTerm
defaultImplicitPi fname indents
= do b <- bounds $ do
decoratedSymbol fname "{"
decoratedKeyword fname "default"
commit
t <- simpleExpr fname indents
binders <- pibindList fname indents
decoratedSymbol fname "}"
pure (t, binders)
mustWorkBecause b.bounds "Cannot return a default implicit argument"
$ decoratedSymbol fname "->"
scope <- mustWork $ typeExpr pdef fname indents
pure $ let (t, binders) = b.val in
pibindAll fname (DefImplicit t) binders scope
forall_ : OriginDesc -> IndentInfo -> Rule PTerm
forall_ fname indents
= do b <- bounds $ do
decoratedKeyword fname "forall"
commit
ns <- sepBy1 (decoratedSymbol fname ",")
(bounds (decoratedSimpleBinderName fname))
pure $ map (\n => ( erased {a=RigCount}
, map (Just . UN . Basic) n
, PImplicit (boundToFC fname n))
) (forget ns)
b' <- bounds peek
mustWorkBecause b'.bounds "Expected ',' or '.'"
$ decoratedSymbol fname "."
scope <- mustWork $ typeExpr pdef fname indents
pure (pibindAll fname Implicit b.val scope)
implicitPi : OriginDesc -> IndentInfo -> Rule PTerm
implicitPi fname indents
= do b <- bounds $ do
decoratedSymbol fname "{"
binders <- pibindList fname indents
decoratedSymbol fname "}"
pure binders
mustWorkBecause b.bounds "Cannot return an implicit argument"
$ decoratedSymbol fname "->"
scope <- mustWork $ typeExpr pdef fname indents
pure (pibindAll fname Implicit b.val scope)
lam : OriginDesc -> IndentInfo -> Rule PTerm
lam fname indents
= do decoratedSymbol fname "\\"
commit
switch <- optional (bounds $ decoratedKeyword fname "case")
case switch of
Nothing => continueLamImpossible <|> continueLam
Just r => continueLamCase r
where
continueLamImpossible : Rule PTerm
continueLamImpossible = do
lhs <- bounds (opExpr plhs fname indents)
end <- bounds (decoratedKeyword fname "impossible")
pure (
let fc = boundToFC fname (mergeBounds lhs end)
alt = (MkImpossible fc lhs.val)
fcCase = boundToFC fname lhs
n = MN "lcase" 0 in
(PLam fcCase top Explicit (PRef fcCase n) (PInfer fcCase) $
PCase (virtualiseFC fc) [] (PRef fcCase n) [alt]))
bindAll : List (RigCount, WithBounds PTerm, PTerm) -> PTerm -> PTerm
bindAll [] scope = scope
bindAll ((rig, pat, ty) :: rest) scope
= PLam (boundToFC fname pat) rig Explicit pat.val ty
(bindAll rest scope)
continueLam : Rule PTerm
continueLam = do
binders <- bindList fname indents
commitSymbol fname "=>"
mustContinue indents Nothing
scope <- typeExpr pdef fname indents
pure (bindAll binders scope)
continueLamCase : WithBounds () -> Rule PTerm
continueLamCase endCase = do
b <- bounds (forget <$> nonEmptyBlock (caseAlt fname))
pure
(let fc = boundToFC fname b
fcCase = virtualiseFC $ boundToFC fname endCase
n = MN "lcase" 0 in
PLam fcCase top Explicit (PRef fcCase n) (PInfer fcCase) $
PCase (virtualiseFC fc) [] (PRef fcCase n) b.val)
letBlock : OriginDesc -> IndentInfo -> Rule (WithBounds (Either LetBinder LetDecl))
letBlock fname indents = bounds (letBinder <||> letDecl) where
letBinder : Rule LetBinder
letBinder = do s <- bounds (MkPair <$> multiplicity fname <*> expr plhs fname indents)
(rig, pat) <- pure s.val
ty <- option (PImplicit (virtualiseFC $ boundToFC fname s))
(decoratedSymbol fname ":" *> typeExpr (pnoeq pdef) fname indents)
(decoratedSymbol fname "=" <|> decoratedSymbol fname ":=")
val <- typeExpr pnowith fname indents
alts <- block (patAlt fname)
pure (MkLetBinder rig pat ty val alts)
letDecl : Rule LetDecl
letDecl = collectDefs . concat <$> nonEmptyBlock (try . topDecl fname)
let_ : OriginDesc -> IndentInfo -> Rule PTerm
let_ fname indents
= do decoratedKeyword fname "let"
commit
res <- nonEmptyBlock (letBlock fname)
commitKeyword fname indents "in"
scope <- typeExpr pdef fname indents
pure (mkLets fname res scope)
case_ : OriginDesc -> IndentInfo -> Rule PTerm
case_ fname indents
= do opts <- many (fnDirectOpt fname)
b <- bounds (do decoratedKeyword fname "case"
scr <- expr pdef fname indents
mustWork (commitKeyword fname indents "of")
alts <- block (caseAlt fname)
pure (scr, alts))
(scr, alts) <- pure b.val
pure (PCase (virtualiseFC $ boundToFC fname b) opts scr alts)
caseAlt : OriginDesc -> IndentInfo -> Rule PClause
caseAlt fname indents
= do lhs <- bounds (opExpr plhs fname indents)
caseRHS fname lhs indents lhs.val
caseRHS : OriginDesc -> WithBounds t -> IndentInfo -> PTerm -> Rule PClause
caseRHS fname start indents lhs
= do rhs <- bounds $ do
decoratedSymbol fname "=>"
mustContinue indents Nothing
typeExpr pdef fname indents
atEnd indents
let fc = boundToFC fname (mergeBounds start rhs)
pure (MkPatClause fc lhs rhs.val [])
<|> do end <- bounds (decoratedKeyword fname "impossible")
atEnd indents
pure (MkImpossible (boundToFC fname (mergeBounds start end)) lhs)
<|> fatalError ("Expected '=>' or 'impossible'")
if_ : OriginDesc -> IndentInfo -> Rule PTerm
if_ fname indents
= do b <- bounds (do decoratedKeyword fname "if"
commit
x <- expr pdef fname indents
commitKeyword fname indents "then"
t <- typeExpr pdef fname indents
commitKeyword fname indents "else"
e <- typeExpr pdef fname indents
pure (x, t, e))
mustWork $ atEnd indents
(x, t, e) <- pure b.val
pure (PIfThenElse (boundToFC fname b) x t e)
record_ : OriginDesc -> IndentInfo -> Rule PTerm
record_ fname indents
= do
b <- (
withWarning oldSyntaxWarning (
bounds (do
decoratedKeyword fname "record"
commit
body True
))
<|>
bounds (body False))
pure (PUpdate (boundToFC fname b) b.val)
where
oldSyntaxWarning : String
oldSyntaxWarning = unlines
[ "DEPRECATED: old record update syntax."
, #" Use "{ f := v } p" instead of "record { f = v } p""#
, #" and "{ f $= v } p" instead of "record { f $= v } p""#
]
body : Bool -> Rule (List PFieldUpdate)
body kw = do
decoratedSymbol fname "{"
commit
fs <- sepBy1 (decoratedSymbol fname ",") (field kw fname indents)
decoratedSymbol fname "}"
pure $ forget fs
field : Bool -> OriginDesc -> IndentInfo -> Rule PFieldUpdate
field kw fname indents
= do path <- map fieldName <$> [| decorate fname Function name :: many recFieldCompat |]
upd <- (ifThenElse kw (decoratedSymbol fname "=") (decoratedSymbol fname ":=") $> PSetField)
<|>
(decoratedSymbol fname "$=" $> PSetFieldApp)
val <- typeExpr plhs fname indents
pure (upd path val)
where
fieldName : Name -> String
fieldName (UN (Basic s)) = s
fieldName (UN (Field s)) = s
fieldName _ = "_impossible"
-- this allows the dotted syntax .field
-- but also the arrowed syntax ->field for compatibility with Idris 1
recFieldCompat : Rule Name
recFieldCompat = decorate fname Function postfixProj
<|> (decoratedSymbol fname "->"
*> decorate fname Function name)
rewrite_ : OriginDesc -> IndentInfo -> Rule PTerm
rewrite_ fname indents
= do b <- bounds (do decoratedKeyword fname "rewrite"
rule <- expr pdef fname indents
commitKeyword fname indents "in"
tm <- typeExpr pdef fname indents
pure (rule, tm))
(rule, tm) <- pure b.val
pure (PRewrite (boundToFC fname b) rule tm)
doBlock : OriginDesc -> IndentInfo -> Rule PTerm
doBlock fname indents
= do b <- bounds $ decoratedKeyword fname "do" *> block (doAct fname)
commit
pure (PDoBlock (virtualiseFC $ boundToFC fname b) Nothing (concat b.val))
<|> do nsdo <- bounds namespacedIdent
-- TODO: need to attach metadata correctly here
the (EmptyRule PTerm) $ case nsdo.val of
(ns, "do") =>
do commit
actions <- Core.bounds (block (doAct fname))
let fc = virtualiseFC $
boundToFC fname (mergeBounds nsdo actions)
pure (PDoBlock fc ns (concat actions.val))
_ => fail "Not a namespaced 'do'"
validPatternVar : Name -> EmptyRule ()
validPatternVar (UN Underscore) = pure ()
validPatternVar (UN (Basic n))
= unless (lowerFirst n) $
fail "Not a pattern variable"
validPatternVar _ = fail "Not a pattern variable"
doAct : OriginDesc -> IndentInfo -> Rule (List PDo)
doAct fname indents
= do b <- bounds (do rig <- multiplicity fname
n <- bounds (name <|> UN Underscore <$ symbol "_")
-- If the name doesn't begin with a lower case letter, we should
-- treat this as a pattern, so fail
validPatternVar n.val
ty <- optional (decoratedSymbol fname ":" *> typeExpr (pnoeq pdef) fname indents)
decoratedSymbol fname "<-"
val <- expr pdef fname indents
pure (n, rig, ty, val))
atEnd indents
let (n, rig, ty, val) = b.val
pure [DoBind (boundToFC fname b) (boundToFC fname n) n.val rig ty val]
<|> do decoratedKeyword fname "let"
commit
res <- nonEmptyBlock (letBlock fname)
do b <- bounds (decoratedKeyword fname "in")
fatalLoc {c = True} b.bounds "Let-in not supported in do block. Did you mean (let ... in ...)?"
<|>
do atEnd indents
pure (mkDoLets fname res)
<|> do b <- bounds (decoratedKeyword fname "rewrite" *> expr pdef fname indents)