-
Notifications
You must be signed in to change notification settings - Fork 437
/
Basic.lean
1980 lines (1696 loc) · 77.7 KB
/
Basic.lean
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
/-
Copyright (c) 2019 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Leonardo de Moura, Sebastian Ullrich
-/
prelude
import Lean.Parser.Types
/-!
# Basic Lean parser infrastructure
The Lean parser was developed with the following primary goals in mind:
* flexibility: Lean's grammar is complex and includes indentation and other whitespace sensitivity. It should be
possible to introduce such custom "tweaks" locally without having to adjust the fundamental parsing approach.
* extensibility: Lean's grammar can be extended on the fly within a Lean file, and with Lean 4 we want to extend this
to cover embedding domain-specific languages that may look nothing like Lean, down to using a separate set of tokens.
* losslessness: The parser should produce a concrete syntax tree that preserves all whitespace and other "sub-token"
information for the use in tooling.
* performance: The overhead of the parser building blocks, and the overall parser performance on average-complexity
input, should be comparable with that of the previous parser hand-written in C++. No fancy optimizations should be
necessary for this.
Given these constraints, we decided to implement a combinatoric, non-monadic, lexer-less, memoizing recursive-descent
parser. Using combinators instead of some more formal and introspectible grammar representation ensures ultimate
flexibility as well as efficient extensibility: there is (almost) no pre-processing necessary when extending the grammar
with a new parser. However, because all the results the combinators produce are of the homogeneous `Syntax` type, the
basic parser type is not actually a monad but a monomorphic linear function `ParserState → ParserState`, avoiding
constructing and deconstructing countless monadic return values. Instead of explicitly returning syntax objects, parsers
push (zero or more of) them onto a syntax stack inside the linear state. Chaining parsers via `>>` accumulates their
output on the stack. Combinators such as `node` then pop off all syntax objects produced during their invocation and
wrap them in a single `Syntax.node` object that is again pushed on this stack. Instead of calling `node` directly, we
usually use the macro `leading_parser p`, which unfolds to `node k p` where the new syntax node kind `k` is the name of the
declaration being defined.
The lack of a dedicated lexer ensures we can modify and replace the lexical grammar at any point, and simplifies
detecting and propagating whitespace. The parser still has a concept of "tokens", however, and caches the most recent
one for performance: when `tokenFn` is called twice at the same position in the input, it will reuse the result of the
first call. `tokenFn` recognizes some built-in variable-length tokens such as identifiers as well as any fixed token in
the `ParserContext`'s `TokenTable` (a trie); however, the same cache field and strategy could be reused by custom token
parsers. Tokens also play a central role in the `prattParser` combinator, which selects a *leading* parser followed by
zero or more *trailing* parsers based on the current token (via `peekToken`); see the documentation of `prattParser`
for more details. Tokens are specified via the `symbol` parser, or with `symbolNoWs` for tokens that should not be preceded by whitespace.
The `Parser` type is extended with additional metadata over the mere parsing function to propagate token information:
`collectTokens` collects all tokens within a parser for registering. `firstTokens` holds information about the "FIRST"
token set used to speed up parser selection in `prattParser`. This approach of combining static and dynamic information
in the parser type is inspired by the paper "Deterministic, Error-Correcting Combinator Parsers" by Swierstra and Duponcheel.
If multiple parsers accept the same current token, `prattParser` tries all of them using the backtracking `longestMatchFn` combinator.
This is the only case where standard parsers might execute arbitrary backtracking. Repeated invocations of the same category or concrete
parser at the same position are cached where possible; see `withCache`.
Finally, error reporting follows the standard combinatoric approach of collecting a single unexpected token/... and zero
or more expected tokens (see `Error` below). Expected tokens are e.g. set by `symbol` and merged by `<|>`. Combinators
running multiple parsers should check if an error message is set in the parser state (`hasError`) and act accordingly.
Error recovery is left to the designer of the specific language; for example, Lean's top-level `parseCommand` loop skips
tokens until the next command keyword on error.
-/
namespace Lean.Parser
def dbgTraceStateFn (label : String) (p : ParserFn) : ParserFn :=
fun c s =>
let sz := s.stxStack.size
let s' := p c s
dbg_trace "{label}
pos: {s'.pos}
err: {s'.errorMsg}
out: {s'.stxStack.extract sz s'.stxStack.size}"
s'
def dbgTraceState (label : String) : Parser → Parser := withFn (dbgTraceStateFn label)
@[noinline]def epsilonInfo : ParserInfo :=
{ firstTokens := FirstTokens.epsilon }
def checkStackTopFn (p : Syntax → Bool) (msg : String) : ParserFn := fun _ s =>
if p s.stxStack.back then s
else s.mkUnexpectedError msg
def checkStackTop (p : Syntax → Bool) (msg : String) : Parser := {
info := epsilonInfo,
fn := checkStackTopFn p msg
}
def andthenFn (p q : ParserFn) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s else q c s
@[noinline] def andthenInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens,
collectKinds := p.collectKinds ∘ q.collectKinds,
firstTokens := p.firstTokens.seq q.firstTokens
}
/-- The `andthen(p, q)` combinator, usually written as adjacency in syntax declarations (`p q`),
parses `p` followed by `q`.
The arity of this parser is the sum of the arities of `p` and `q`:
that is, it accumulates all the nodes produced by `p` followed by the nodes from `q` into the list
of arguments to the surrounding parse node. -/
def andthen (p q : Parser) : Parser where
info := andthenInfo p.info q.info
fn := andthenFn p.fn q.fn
instance : AndThen Parser where
andThen a b := andthen a (b ())
def nodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkNode n iniSz
def trailingNodeFn (n : SyntaxNodeKind) (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := p c s
s.mkTrailingNode n iniSz
@[noinline] def nodeInfo (n : SyntaxNodeKind) (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens,
collectKinds := fun s => (p.collectKinds s).insert n,
firstTokens := p.firstTokens
}
def node (n : SyntaxNodeKind) (p : Parser) : Parser := {
info := nodeInfo n p.info,
fn := nodeFn n p.fn
}
def errorFn (msg : String) : ParserFn := fun _ s =>
s.mkUnexpectedError msg
def error (msg : String) : Parser := {
info := epsilonInfo,
fn := errorFn msg
}
def errorAtSavedPosFn (msg : String) (delta : Bool) : ParserFn := fun c s =>
match c.savedPos? with
| none => s
| some pos =>
let pos := if delta then c.input.next pos else pos
s.mkUnexpectedErrorAt msg pos
/-- Generate an error at the position saved with the `withPosition` combinator.
If `delta == true`, then it reports at saved position+1.
This useful to make sure a parser consumed at least one character. -/
@[builtin_doc] def errorAtSavedPos (msg : String) (delta : Bool) : Parser := {
fn := errorAtSavedPosFn msg delta
}
/-- Succeeds if `c.prec <= prec` -/
def checkPrecFn (prec : Nat) : ParserFn := fun c s =>
if c.prec <= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
def checkPrec (prec : Nat) : Parser := {
info := epsilonInfo
fn := checkPrecFn prec
}
/-- Succeeds if `c.lhsPrec >= prec` -/
def checkLhsPrecFn (prec : Nat) : ParserFn := fun _ s =>
if s.lhsPrec >= prec then s
else s.mkUnexpectedError "unexpected token at this precedence level; consider parenthesizing the term"
def checkLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo
fn := checkLhsPrecFn prec
}
def setLhsPrecFn (prec : Nat) : ParserFn := fun _ s =>
if s.hasError then s
else { s with lhsPrec := prec }
def setLhsPrec (prec : Nat) : Parser := {
info := epsilonInfo
fn := setLhsPrecFn prec
}
private def addQuotDepth (i : Int) (p : Parser) : Parser :=
adaptCacheableContext (fun c => { c with quotDepth := c.quotDepth + i |>.toNat }) p
def incQuotDepth (p : Parser) : Parser := addQuotDepth 1 p
def decQuotDepth (p : Parser) : Parser := addQuotDepth (-1) p
def suppressInsideQuot : Parser → Parser :=
adaptCacheableContext fun c =>
-- if we are already within a quotation, don't change anything
if c.quotDepth == 0 then { c with suppressInsideQuot := true } else c
def leadingNode (n : SyntaxNodeKind) (prec : Nat) (p : Parser) : Parser :=
checkPrec prec >> node n p >> setLhsPrec prec
def trailingNodeAux (n : SyntaxNodeKind) (p : Parser) : TrailingParser := {
info := nodeInfo n p.info
fn := trailingNodeFn n p.fn
}
def trailingNode (n : SyntaxNodeKind) (prec lhsPrec : Nat) (p : Parser) : TrailingParser :=
checkPrec prec >> checkLhsPrec lhsPrec >> trailingNodeAux n p >> setLhsPrec prec
def mergeOrElseErrors (s : ParserState) (error1 : Error) (iniPos : String.Pos) (mergeErrors : Bool) : ParserState :=
match s with
| ⟨stack, lhsPrec, pos, cache, some error2, errs⟩ =>
if pos == iniPos then
⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2), errs⟩
else s
| other => other
-- When `p` in `p <|> q` parses exactly one antiquotation, ...
inductive OrElseOnAntiquotBehavior where
| acceptLhs -- return it
| takeLongest -- return result of `q` instead if it made more progress
| merge -- ... and create choice node if both made the same progress
deriving BEq
def orelseFnCore (p q : ParserFn) (antiquotBehavior := OrElseOnAntiquotBehavior.merge) : ParserFn := fun c s => Id.run do
let iniSz := s.stackSize
let iniPos := s.pos
let mut s := p c s
match s.errorMsg with
| some errorMsg =>
if s.pos == iniPos then
mergeOrElseErrors (q c (s.restore iniSz iniPos)) errorMsg iniPos true
else
s
| none =>
let pBack := s.stxStack.back
if antiquotBehavior == .acceptLhs || s.stackSize != iniSz + 1 || !pBack.isAntiquots then
return s
let pPos := s.pos
s := s.restore iniSz iniPos
s := q c s
if s.hasError then
return s.restore iniSz pPos |>.pushSyntax pBack
-- If `q` made more progress than `p`, we prefer its result.
-- Thus `(structInstField| $id := $val) is interpreted as
-- `(structInstField| $id:ident := $val:term), not
-- `(structInstField| $id:structInstField <ERROR: expected ')'>.
if s.pos > pPos then
return s
if s.pos < pPos || antiquotBehavior != .merge || s.stackSize != iniSz + 1 || !s.stxStack.back.isAntiquots then
return s.restore iniSz pPos |>.pushSyntax pBack
-- Pop off result of `q`, push result(s) of `p` and `q` in that order, turn them into a choice node
let qBack := s.stxStack.back
s := s.popSyntax
let pushAntiquots stx s :=
if stx.isOfKind choiceKind then
-- Flatten existing choice node
{ s with stxStack := s.stxStack ++ stx.getArgs }
else
s.pushSyntax stx
s := pushAntiquots pBack s
s := pushAntiquots qBack s
s.mkNode choiceKind iniSz
def orelseFn (p q : ParserFn) : ParserFn :=
orelseFnCore p q
@[noinline] def orelseInfo (p q : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ q.collectTokens
collectKinds := p.collectKinds ∘ q.collectKinds
firstTokens := p.firstTokens.merge q.firstTokens
}
/--
Run `p`, falling back to `q` if `p` failed without consuming any input.
NOTE: In order for the pretty printer to retrace an `orelse`, `p` must be a call to `node` or some other parser
producing a single node kind. Nested `orelse` calls are flattened for this, i.e. `(node k1 p1 <|> node k2 p2) <|> ...`
is fine as well. -/
@[builtin_doc] def orelse (p q : Parser) : Parser where
info := orelseInfo p.info q.info
fn := orelseFn p.fn q.fn
instance : OrElse Parser where
orElse a b := orelse a (b ())
@[noinline] def noFirstTokenInfo (info : ParserInfo) : ParserInfo := {
collectTokens := info.collectTokens
collectKinds := info.collectKinds
}
def atomicFn (p : ParserFn) : ParserFn := fun c s =>
let iniPos := s.pos
match p c s with
| ⟨stack, lhsPrec, _, cache, some msg, errs⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg, errs⟩
| other => other
/-- The `atomic(p)` parser parses `p`, returns the same result as `p` and fails iff `p` fails,
but if `p` fails after consuming some tokens `atomic(p)` will fail without consuming tokens.
This is important for the `p <|> q` combinator, because it is not backtracking, and will fail if
`p` fails after consuming some tokens. To get backtracking behavior, use `atomic(p) <|> q` instead.
This parser has the same arity as `p` - it produces the same result as `p`. -/
@[builtin_doc] def atomic : Parser → Parser := withFn atomicFn
/-- Information about the state of the parse prior to the failing parser's execution -/
structure RecoveryContext where
/-- The position prior to the failing parser -/
initialPos : String.Pos
/-- The syntax stack height prior to the failing parser's execution -/
initialSize : Nat
deriving BEq, DecidableEq, Repr
/--
Recover from errors in `p` using `recover` to consume input until a known-good state has appeared.
If `recover` fails itself, then no recovery is performed.
`recover` is provided with information about the failing parser's effects , and it is run in the
state immediately after the failure. -/
def recoverFn (p : ParserFn) (recover : RecoveryContext → ParserFn) : ParserFn := fun c s =>
let iniPos := s.pos
let iniSz := s.stxStack.size
let s' := p c s
if let some msg := s'.errorMsg then
let s' := recover ⟨iniPos, iniSz⟩ c {s' with errorMsg := none}
if s'.hasError then s'
else {s' with
pos := s'.pos,
lhsPrec := s'.lhsPrec,
cache := s'.cache,
errorMsg := none,
recoveredErrors := s'.recoveredErrors.push (s'.pos, s'.stxStack, msg) }
else s'
/--
Recover from errors in `parser` using `handler` to consume input until a known-good state has appeared.
If `handler` fails itself, then no recovery is performed.
`handler` is provided with information about the failing parser's effects , and it is run in the
state immediately after the failure.
The interactions between <|> and `recover'` are subtle, especially for syntactic
categories that admit user extension. Consider avoiding it in these cases. -/
@[builtin_doc] def recover' (parser : Parser) (handler : RecoveryContext → Parser) : Parser where
info := parser.info
fn := recoverFn parser.fn fun s => handler s |>.fn
/--
Recover from errors in `parser` using `handler` to consume input until a known-good state has appeared.
If `handler` fails itself, then no recovery is performed.
`handler` is run in the state immediately after the failure.
The interactions between <|> and `recover` are subtle, especially for syntactic
categories that admit user extension. Consider avoiding it in these cases. -/
@[builtin_doc] def recover (parser handler : Parser) : Parser := recover' parser fun _ => handler
def optionalFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
let s := if s.hasError && s.pos == iniPos then s.restore iniSz iniPos else s
s.mkNode nullKind iniSz
@[noinline] def optionaInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens
collectKinds := p.collectKinds
firstTokens := p.firstTokens.toOptional
}
def optionalNoAntiquot (p : Parser) : Parser := {
info := optionaInfo p.info
fn := optionalFn p.fn
}
def lookaheadFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then s else s.restore iniSz iniPos
/-- `lookahead(p)` runs `p` and fails if `p` does, but it produces no parse nodes and rewinds the
position to the original state on success. So for example `lookahead("=>")` will ensure that the
next token is `"=>"`, without actually consuming this token.
This parser has arity 0 - it does not capture anything. -/
@[builtin_doc] def lookahead : Parser → Parser := withFn lookaheadFn
def notFollowedByFn (p : ParserFn) (msg : String) : ParserFn := fun c s =>
let iniSz := s.stackSize
let iniPos := s.pos
let s := p c s
if s.hasError then
s.restore iniSz iniPos
else
let s := s.restore iniSz iniPos
s.mkUnexpectedError s!"unexpected {msg}"
/-- `notFollowedBy(p, "foo")` succeeds iff `p` fails;
if `p` succeeds then it fails with the message `"unexpected foo"`.
This parser has arity 0 - it does not capture anything. -/
@[builtin_doc] def notFollowedBy (p : Parser) (msg : String) : Parser where
fn := notFollowedByFn p.fn msg
partial def manyAux (p : ParserFn) : ParserFn := fun c s => Id.run do
let iniSz := s.stackSize
let iniPos := s.pos
let mut s := p c s
if s.hasError then
return if iniPos == s.pos then s.restore iniSz iniPos else s
if iniPos == s.pos then
return s.mkUnexpectedError "invalid 'many' parser combinator application, parser did not consume anything"
if s.stackSize > iniSz + 1 then
s := s.mkNode nullKind iniSz
manyAux p c s
def manyFn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := manyAux p c s
s.mkNode nullKind iniSz
def manyNoAntiquot (p : Parser) : Parser := {
info := noFirstTokenInfo p.info
fn := manyFn p.fn
}
def many1Fn (p : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
let s := andthenFn p (manyAux p) c s
s.mkNode nullKind iniSz
def many1NoAntiquot : Parser → Parser := withFn many1Fn
private partial def sepByFnAux (p : ParserFn) (sep : ParserFn) (allowTrailingSep : Bool) (iniSz : Nat) (pOpt : Bool) : ParserFn :=
let rec parse (pOpt : Bool) (c s) := Id.run do
let sz := s.stackSize
let pos := s.pos
let mut s := p c s
if s.hasError then
if s.pos > pos then
return s.mkNode nullKind iniSz
else if pOpt then
s := s.restore sz pos
return s.mkNode nullKind iniSz
else
-- append `Syntax.missing` to make clear that List is incomplete
s := s.pushSyntax Syntax.missing
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
let sz := s.stackSize
let pos := s.pos
s := sep c s
if s.hasError then
s := s.restore sz pos
return s.mkNode nullKind iniSz
if s.stackSize > sz + 1 then
s := s.mkNode nullKind sz
parse allowTrailingSep c s
parse pOpt
def sepByFn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz true c s
def sepBy1Fn (allowTrailingSep : Bool) (p : ParserFn) (sep : ParserFn) : ParserFn := fun c s =>
let iniSz := s.stackSize
sepByFnAux p sep allowTrailingSep iniSz false c s
@[noinline] def sepByInfo (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens
collectKinds := p.collectKinds ∘ sep.collectKinds
}
@[noinline] def sepBy1Info (p sep : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens ∘ sep.collectTokens
collectKinds := p.collectKinds ∘ sep.collectKinds
firstTokens := p.firstTokens
}
def sepByNoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepByInfo p.info sep.info
fn := sepByFn allowTrailingSep p.fn sep.fn
}
def sepBy1NoAntiquot (p sep : Parser) (allowTrailingSep : Bool := false) : Parser := {
info := sepBy1Info p.info sep.info
fn := sepBy1Fn allowTrailingSep p.fn sep.fn
}
/-- Apply `f` to the syntax object produced by `p` -/
def withResultOfFn (p : ParserFn) (f : Syntax → Syntax) : ParserFn := fun c s =>
let s := p c s
if s.hasError then s
else
let stx := s.stxStack.back
s.popSyntax.pushSyntax (f stx)
@[noinline] def withResultOfInfo (p : ParserInfo) : ParserInfo := {
collectTokens := p.collectTokens
collectKinds := p.collectKinds
}
def withResultOf (p : Parser) (f : Syntax → Syntax) : Parser := {
info := withResultOfInfo p.info
fn := withResultOfFn p.fn f
}
def many1Unbox (p : Parser) : Parser :=
withResultOf (many1NoAntiquot p) fun stx => if stx.getNumArgs == 1 then stx.getArg 0 else stx
partial def satisfyFn (p : Char → Bool) (errorMsg : String := "unexpected character") : ParserFn := fun c s =>
let i := s.pos
if h : c.input.atEnd i then s.mkEOIError
else if p (c.input.get' i h) then s.next' c.input i h
else s.mkUnexpectedError errorMsg
partial def takeUntilFn (p : Char → Bool) : ParserFn := fun c s =>
let i := s.pos
if h : c.input.atEnd i then s
else if p (c.input.get' i h) then s
else takeUntilFn p c (s.next' c.input i h)
def takeWhileFn (p : Char → Bool) : ParserFn :=
takeUntilFn (fun c => !p c)
def takeWhile1Fn (p : Char → Bool) (errorMsg : String) : ParserFn :=
andthenFn (satisfyFn p errorMsg) (takeWhileFn p)
variable (pushMissingOnError : Bool) in
partial def finishCommentBlock (nesting : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then eoi s
else
let curr := input.get' i h
let i := input.next' i h
if curr == '-' then
if h : input.atEnd i then eoi s
else
let curr := input.get' i h
if curr == '/' then -- "-/" end of comment
if nesting == 1 then s.next' input i h
else finishCommentBlock (nesting-1) c (s.next' input i h)
else
finishCommentBlock nesting c (s.setPos i)
else if curr == '/' then
if h : input.atEnd i then eoi s
else
let curr := input.get' i h
if curr == '-' then finishCommentBlock (nesting+1) c (s.next' input i h)
else finishCommentBlock nesting c (s.setPos i)
else finishCommentBlock nesting c (s.setPos i)
where
eoi s := s.mkUnexpectedError (pushMissing := pushMissingOnError) "unterminated comment"
/-- Consume whitespace and comments -/
partial def whitespace : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then s
else
let curr := input.get' i h
if curr == '\t' then
s.mkUnexpectedError (pushMissing := false) "tabs are not allowed; please configure your editor to expand them"
else if curr == '\r' then
s.mkUnexpectedError (pushMissing := false) "isolated carriage returns are not allowed"
else if curr.isWhitespace then whitespace c (s.next' input i h)
else if curr == '-' then
let i := input.next' i h
let curr := input.get i
if curr == '-' then andthenFn (takeUntilFn (fun c => c = '\n')) whitespace c (s.next input i)
else s
else if curr == '/' then
let i := input.next' i h
let curr := input.get i
if curr == '-' then
let i := input.next i
let curr := input.get i
if curr == '-' || curr == '!' then s -- "/--" and "/-!" doc comment are actual tokens
else andthenFn (finishCommentBlock (pushMissingOnError := false) 1) whitespace c (s.next input i)
else s
else s
def mkEmptySubstringAt (s : String) (p : String.Pos) : Substring := {
str := s, startPos := p, stopPos := p
}
private def rawAux (startPos : String.Pos) (trailingWs : Bool) : ParserFn := fun c s =>
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
if trailingWs then
let s := whitespace c s
let stopPos' := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := stopPos' : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val
s.pushSyntax atom
else
let trailing := mkEmptySubstringAt input stopPos
let atom := mkAtom (SourceInfo.original leading startPos trailing (startPos + val)) val
s.pushSyntax atom
/-- Match an arbitrary Parser and return the consumed String in a `Syntax.atom`. -/
def rawFn (p : ParserFn) (trailingWs := false) : ParserFn := fun c s =>
let startPos := s.pos
let s := p c s
if s.hasError then s else rawAux startPos trailingWs c s
def chFn (c : Char) (trailingWs := false) : ParserFn :=
rawFn (satisfyFn (fun d => c == d) ("'" ++ toString c ++ "'")) trailingWs
def rawCh (c : Char) (trailingWs := false) : Parser := {
fn := chFn c trailingWs
}
def hexDigitFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then s.mkEOIError
else
let curr := input.get' i h
let i := input.next' i h
if curr.isDigit || ('a' <= curr && curr <= 'f') || ('A' <= curr && curr <= 'F') then s.setPos i
else s.mkUnexpectedError "invalid hexadecimal numeral"
/--
Parses the whitespace after the `\` when there is a string gap.
Raises an error if the whitespace does not contain exactly one newline character.
-/
partial def stringGapFn (seenNewline : Bool) : ParserFn := fun c s =>
let i := s.pos
if h : c.input.atEnd i then s -- let strLitFnAux handle the EOI error if !seenNewline
else
let curr := c.input.get' i h
if curr == '\n' then
if seenNewline then
-- Having more than one newline in a string gap is visually confusing
s.mkUnexpectedError "unexpected additional newline in string gap"
else
stringGapFn true c (s.next' c.input i h)
else if curr.isWhitespace then
stringGapFn seenNewline c (s.next' c.input i h)
else if seenNewline then
s
else
s.mkUnexpectedError "expecting newline in string gap"
/--
Parses a string quotation after a `\`.
- `isQuotable` determines which characters are valid escapes
- `inString` enables features that are only valid within strings,
in particular `"\" newline whitespace*` gaps.
-/
def quotedCharCoreFn (isQuotable : Char → Bool) (inString : Bool) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then s.mkEOIError
else
let curr := input.get' i h
if isQuotable curr then
s.next' input i h
else if curr == 'x' then
andthenFn hexDigitFn hexDigitFn c (s.next' input i h)
else if curr == 'u' then
andthenFn hexDigitFn (andthenFn hexDigitFn (andthenFn hexDigitFn hexDigitFn)) c (s.next' input i h)
else if inString && curr == '\n' then
stringGapFn false c s
else
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault false
/--
Like `quotedCharFn` but enables escapes that are only valid inside strings.
In particular, string gaps (`"\" newline whitespace*`).
-/
def quotedStringFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault true
/-- Push `(Syntax.node tk <new-atom>)` onto syntax stack if parse was successful. -/
def mkNodeToken (n : SyntaxNodeKind) (startPos : String.Pos) : ParserFn := fun c s => Id.run do
if s.hasError then
return s
let input := c.input
let stopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let val := input.extract startPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
s.pushSyntax (Syntax.mkLit n val info)
def charLitFnAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then s.mkEOIError
else
let curr := input.get' i h
let s := s.setPos (input.next' i h)
let s := if curr == '\\' then quotedCharFn c s else s
if s.hasError then s
else
let i := s.pos
let curr := input.get i
let s := s.setPos (input.next i)
if curr == '\'' then mkNodeToken charLitKind startPos c s
else s.mkUnexpectedError "missing end of character literal"
partial def strLitFnAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then s.mkUnexpectedErrorAt "unterminated string literal" startPos
else
let curr := input.get' i h
let s := s.setPos (input.next' i h)
if curr == '\"' then
mkNodeToken strLitKind startPos c s
else if curr == '\\' then andthenFn quotedStringFn (strLitFnAux startPos) c s
else strLitFnAux startPos c s
/--
Raw strings have the syntax `r##...#"..."#...##` with zero or more `#`'s.
If we are looking at a valid start to a raw string (`r##...#"`),
returns true.
We assume `i` begins at the position immediately after `r`.
-/
partial def isRawStrLitStart (input : String) (i : String.Pos) : Bool :=
if h : input.atEnd i then false
else
let curr := input.get' i h
if curr == '#' then
isRawStrLitStart input (input.next' i h)
else
curr == '"'
/--
Parses a raw string literal assuming `isRawStrLitStart` has returned true.
The `startPos` is the start of the raw string (at the `r`).
The parser state is assumed to be immediately after the `r`.
-/
partial def rawStrLitFnAux (startPos : String.Pos) : ParserFn := initState 0
where
/--
Gives the "unterminated raw string literal" error.
-/
errorUnterminated (s : ParserState) := s.mkUnexpectedErrorAt "unterminated raw string literal" startPos
/--
Parses the `#`'s and `"` at the beginning of the raw string.
The `num` variable counts the number of `#`s after the `r`.
-/
initState (num : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then errorUnterminated s
else
let curr := input.get' i h
let s := s.setPos (input.next' i h)
if curr == '#' then
initState (num + 1) c s
else if curr == '"' then
normalState num c s
else
-- This should not occur, since we assume `isRawStrLitStart` succeeded.
errorUnterminated s
/--
Parses characters after the first `"`. If we need to start counting `#`'s to decide if we are closing
the raw string literal, we switch to `closingState`.
-/
normalState (num : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then errorUnterminated s
else
let curr := input.get' i h
let s := s.setPos (input.next' i h)
if curr == '\"' then
if num == 0 then
mkNodeToken strLitKind startPos c s
else
closingState num 0 c s
else
normalState num c s
/--
Parses `#` characters immediately after a `"`.
The `closingNum` variable counts the number of `#`s seen after the `"`.
Note: `num > 0` since the `num = 0` case is entirely handled by `normalState`.
-/
closingState (num : Nat) (closingNum : Nat) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then errorUnterminated s
else
let curr := input.get' i h
let s := s.setPos (input.next' i h)
if curr == '#' then
if closingNum + 1 == num then
mkNodeToken strLitKind startPos c s
else
closingState num (closingNum + 1) c s
else if curr == '\"' then
closingState num 0 c s
else
normalState num c s
/--
Parses a sequence of the form `many (many '_' >> many1 digit)`, but if `needDigit` is true the parsed result must be nonempty.
Note: this does not report that it is expecting `_` if we reach EOI or an unexpected character.
Rationale: this error happens if there is already a `_`, and while sequences of `_` are allowed, it's a bit perverse to suggest extending the sequence.
-/
partial def takeDigitsFn (isDigit : Char → Bool) (expecting : String) (needDigit : Bool) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if h : input.atEnd i then
if needDigit then
s.mkEOIError [expecting]
else
s
else
let curr := input.get' i h
if curr == '_' then takeDigitsFn isDigit expecting true c (s.next' c.input i h)
else if isDigit curr then takeDigitsFn isDigit expecting false c (s.next' c.input i h)
else if needDigit then s.mkUnexpectedError "unexpected character" (expected := [expecting])
else s
def decimalNumberFn (startPos : String.Pos) (c : ParserContext) : ParserState → ParserState := fun s =>
let s := takeDigitsFn (fun c => c.isDigit) "decimal number" false c s
let input := c.input
let i := s.pos
if h : input.atEnd i then
mkNodeToken numLitKind startPos c s
else
let curr := input.get' i h
if curr == '.' || curr == 'e' || curr == 'E' then
parseScientific s
else
mkNodeToken numLitKind startPos c s
where
parseScientific s :=
let s := parseOptDot s
let s := parseOptExp s
mkNodeToken scientificLitKind startPos c s
parseOptDot s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
let curr := input.get i
if curr.isDigit then
takeDigitsFn (fun c => c.isDigit) "decimal number" false c (s.setPos i)
else
s.setPos i
else
s
parseOptExp s :=
let input := c.input
let i := s.pos
let curr := input.get i
if curr == 'e' || curr == 'E' then
let i := input.next i
let i := if input.get i == '-' || input.get i == '+' then input.next i else i
let curr := input.get i
if curr.isDigit then
takeDigitsFn (fun c => c.isDigit) "decimal number" false c (s.setPos i)
else
s.mkUnexpectedError "missing exponent digits in scientific literal"
else
s
def binNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeDigitsFn (fun c => c == '0' || c == '1') "binary number" true c s
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeDigitsFn (fun c => '0' ≤ c && c ≤ '7') "octal number" true c s
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeDigitsFn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" true c s
mkNodeToken numLitKind startPos c s
def numberFnAux : ParserFn := fun c s =>
let input := c.input
let startPos := s.pos
if h : input.atEnd startPos then s.mkEOIError
else
let curr := input.get' startPos h
if curr == '0' then
let i := input.next' startPos h
let curr := input.get i
if curr == 'b' || curr == 'B' then
binNumberFn startPos c (s.next input i)
else if curr == 'o' || curr == 'O' then
octalNumberFn startPos c (s.next input i)
else if curr == 'x' || curr == 'X' then
hexNumberFn startPos c (s.next input i)
else
decimalNumberFn startPos c (s.setPos i)
else if curr.isDigit then
decimalNumberFn startPos c (s.next input startPos)
else
s.mkError "numeral"
def isIdCont : String → ParserState → Bool := fun input s =>
let i := s.pos
let curr := input.get i
if curr == '.' then
let i := input.next i
if input.atEnd i then
false
else
let curr := input.get i
isIdFirst curr || isIdBeginEscape curr
else
false
private def isToken (idStartPos idStopPos : String.Pos) (tk : Option Token) : Bool :=
match tk with
| none => false
| some tk =>
-- if a token is both a symbol and a valid identifier (i.e. a keyword),
-- we want it to be recognized as a symbol
tk.endPos ≥ idStopPos - idStartPos
def mkTokenAndFixPos (startPos : String.Pos) (tk : Option Token) : ParserFn := fun c s =>
match tk with
| none => s.mkErrorAt "token" startPos
| some tk =>
if c.forbiddenTk? == some tk then
s.mkErrorAt "forbidden token" startPos
else
let input := c.input
let leading := mkEmptySubstringAt input startPos
let stopPos := startPos + tk
let s := s.setPos stopPos
let s := whitespace c s
let wsStopPos := s.pos
let trailing := { str := input, startPos := stopPos, stopPos := wsStopPos : Substring }
let atom := mkAtom (SourceInfo.original leading startPos trailing stopPos) tk
s.pushSyntax atom
def mkIdResult (startPos : String.Pos) (tk : Option Token) (val : Name) : ParserFn := fun c s =>
let stopPos := s.pos
if isToken startPos stopPos tk then
mkTokenAndFixPos startPos tk c s
else
let input := c.input
let rawVal := { str := input, startPos := startPos, stopPos := stopPos : Substring }
let s := whitespace c s
let trailingStopPos := s.pos
let leading := mkEmptySubstringAt input startPos
let trailing := { str := input, startPos := stopPos, stopPos := trailingStopPos : Substring }
let info := SourceInfo.original leading startPos trailing stopPos
let atom := mkIdent info rawVal val
s.pushSyntax atom
partial def identFnAux (startPos : String.Pos) (tk : Option Token) (r : Name) : ParserFn :=
let rec parse (r : Name) (c s) :=
let input := c.input
let i := s.pos
if h : input.atEnd i then
s.mkEOIError
else
let curr := input.get' i h
if isIdBeginEscape curr then
let startPart := input.next' i h
let s := takeUntilFn isIdEndEscape c (s.setPos startPart)
if h : input.atEnd s.pos then
s.mkUnexpectedErrorAt "unterminated identifier escape" startPart
else
let stopPart := s.pos
let s := s.next' c.input s.pos h
let r := .str r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else if isIdFirst curr then
let startPart := i
let s := takeWhileFn isIdRest c (s.next input i)
let stopPart := s.pos
let r := .str r (input.extract startPart stopPart)
if isIdCont input s then
let s := s.next input s.pos
parse r c s
else
mkIdResult startPos tk r c s
else
mkTokenAndFixPos startPos tk c s
parse r
private def isIdFirstOrBeginEscape (c : Char) : Bool :=
isIdFirst c || isIdBeginEscape c