forked from leanprover/lean4
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBasic.lean
1671 lines (1422 loc) · 63.3 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
-/
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 the all 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
}
def andthen (p q : Parser) : Parser := {
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
match s with
| ⟨stack, lhsPrec, _, cache, _⟩ => ⟨stack.push Syntax.missing, lhsPrec, pos, cache, some { unexpected := msg }⟩
/-- 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. -/
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⟩ =>
if pos == iniPos then ⟨stack, lhsPrec, pos, cache, some (if mergeErrors then error1.merge error2 else error2)⟩
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 s0 := s
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 back := s.stxStack.back
if antiquotBehavior != .acceptLhs && s.stackSize == iniSz + 1 && back.isAntiquots then
let s' := q c s0
if !s'.hasError then
-- 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 > s.pos then
return s'
else if antiquotBehavior == .merge && s'.stackSize == iniSz + 1 && s'.stxStack.back.isAntiquot then
if back.isOfKind choiceKind then
s := { s with stxStack := s.stxStack.pop ++ back.getArgs }
s := s.pushSyntax s'.stxStack.back
s := s.mkNode choiceKind iniSz
s
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. -/
def orelse (p q : Parser) : Parser := {
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⟩ => ⟨stack, lhsPrec, iniPos, cache, some msg⟩
| other => other
def atomic : Parser → Parser := withFn atomicFn
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
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}"
def notFollowedBy (p : Parser) (msg : String) : Parser := {
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.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"
def quotedCharCoreFn (isQuotable : Char → 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
s.mkUnexpectedError "invalid escape sequence"
def isQuotableCharDefault (c : Char) : Bool :=
c == '\\' || c == '\"' || c == '\'' || c == 'r' || c == 'n' || c == 't'
def quotedCharFn : ParserFn :=
quotedCharCoreFn isQuotableCharDefault
/-- 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 quotedCharFn (strLitFnAux startPos) c s
else strLitFnAux startPos c s
def decimalNumberFn (startPos : String.Pos) (c : ParserContext) : ParserState → ParserState := fun s =>
let s := takeWhileFn (fun c => c.isDigit) c s
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '.' || curr == 'e' || curr == 'E' then
let s := parseOptDot s
let s := parseOptExp s
mkNodeToken scientificLitKind startPos c s
else
mkNodeToken numLitKind startPos c s
where
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
takeWhileFn (fun c => c.isDigit) 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
takeWhileFn (fun c => c.isDigit) 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 := takeWhile1Fn (fun c => c == '0' || c == '1') "binary number" c s
mkNodeToken numLitKind startPos c s
def octalNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => '0' ≤ c && c ≤ '7') "octal number" c s
mkNodeToken numLitKind startPos c s
def hexNumberFn (startPos : String.Pos) : ParserFn := fun c s =>
let s := takeWhile1Fn (fun c => ('0' ≤ c && c ≤ '9') || ('a' ≤ c && c ≤ 'f') || ('A' ≤ c && c ≤ 'F')) "hexadecimal number" 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
private def nameLitAux (startPos : String.Pos) : ParserFn := fun c s =>
let input := c.input
let s := identFnAux startPos none .anonymous c (s.next input startPos)
if s.hasError then
s
else
let stx := s.stxStack.back
match stx with
| .ident info rawStr _ _ =>
let s := s.popSyntax
s.pushSyntax (Syntax.mkNameLit rawStr.toString info)
| _ => s.mkError "invalid Name literal"
private def tokenFnAux : ParserFn := fun c s =>
let input := c.input
let i := s.pos
let curr := input.get i
if curr == '\"' then
strLitFnAux i c (s.next input i)
else if curr == '\'' && getNext input i != '\'' then
charLitFnAux i c (s.next input i)
else if curr.isDigit then
numberFnAux c s
else if curr == '`' && isIdFirstOrBeginEscape (getNext input i) then
nameLitAux i c s
else
let (_, tk) := c.tokens.matchPrefix input i
identFnAux i tk .anonymous c s
private def updateTokenCache (startPos : String.Pos) (s : ParserState) : ParserState :=
-- do not cache token parsing errors, which are rare and usually fatal and thus not worth an extra field in `TokenCache`
match s with
| ⟨stack, lhsPrec, pos, ⟨_, catCache⟩, none⟩ =>
if stack.size == 0 then s
else
let tk := stack.back
⟨stack, lhsPrec, pos, ⟨{ startPos := startPos, stopPos := pos, token := tk }, catCache⟩, none⟩
| other => other
def tokenFn (expected : List String := []) : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError expected
else
let tkc := s.cache.tokenCache
if tkc.startPos == i then
let s := s.pushSyntax tkc.token
s.setPos tkc.stopPos
else
let s := tokenFnAux c s
updateTokenCache i s
def peekTokenAux (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let iniSz := s.stackSize
let iniPos := s.pos
let s := tokenFn [] c s
if let some _ := s.errorMsg then (s.restore iniSz iniPos, .error s)
else
let stx := s.stxStack.back
(s.restore iniSz iniPos, .ok stx)
def peekToken (c : ParserContext) (s : ParserState) : ParserState × Except ParserState Syntax :=
let tkc := s.cache.tokenCache
if tkc.startPos == s.pos then
(s, .ok tkc.token)
else
peekTokenAux c s
/-- Treat keywords as identifiers. -/
def rawIdentFn : ParserFn := fun c s =>
let input := c.input
let i := s.pos
if input.atEnd i then s.mkEOIError
else identFnAux i none .anonymous c s
def satisfySymbolFn (p : String → Bool) (expected : List String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn expected c s
if s.hasError then
s
else
match s.stxStack.back with
| .atom _ sym => if p sym then s else s.mkErrorsAt expected startPos initStackSz
| _ => s.mkErrorsAt expected startPos initStackSz
def symbolFnAux (sym : String) (errorMsg : String) : ParserFn :=
satisfySymbolFn (fun s => s == sym) [errorMsg]
def symbolInfo (sym : String) : ParserInfo := {
collectTokens := fun tks => sym :: tks
firstTokens := FirstTokens.tokens [ sym ]
}
def symbolFn (sym : String) : ParserFn :=
symbolFnAux sym ("'" ++ sym ++ "'")
def symbolNoAntiquot (sym : String) : Parser :=
let sym := sym.trim
{ info := symbolInfo sym
fn := symbolFn sym }
def checkTailNoWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| .original _ _ trailing _ => trailing.stopPos == trailing.startPos
| _ => false
/-- Check if the following token is the symbol _or_ identifier `sym`. Useful for
parsing local tokens that have not been added to the token table (but may have
been so by some unrelated code).
For example, the universe `max` Function is parsed using this combinator so that
it can still be used as an identifier outside of universe (but registering it
as a token in a Term Syntax would not break the universe Parser). -/
def nonReservedSymbolFnAux (sym : String) (errorMsg : String) : ParserFn := fun c s =>
let initStackSz := s.stackSize
let startPos := s.pos
let s := tokenFn [errorMsg] c s
if s.hasError then s
else
match s.stxStack.back with
| .atom _ sym' =>
if sym == sym' then s else s.mkErrorAt errorMsg startPos initStackSz
| .ident info rawVal _ _ =>
if sym == rawVal.toString then
let s := s.popSyntax
s.pushSyntax (Syntax.atom info sym)
else
s.mkErrorAt errorMsg startPos initStackSz
| _ => s.mkErrorAt errorMsg startPos initStackSz
def nonReservedSymbolFn (sym : String) : ParserFn :=
nonReservedSymbolFnAux sym ("'" ++ sym ++ "'")
def nonReservedSymbolInfo (sym : String) (includeIdent : Bool) : ParserInfo := {
firstTokens :=
if includeIdent then
.tokens [ sym, "ident" ]
else
.tokens [ sym ]
}
def nonReservedSymbolNoAntiquot (sym : String) (includeIdent := false) : Parser :=
let sym := sym.trim
{ info := nonReservedSymbolInfo sym includeIdent,
fn := nonReservedSymbolFn sym }
partial def strAux (sym : String) (errorMsg : String) (j : String.Pos) :ParserFn :=
let rec parse (j c s) :=
if h₁ : sym.atEnd j then s
else
let i := s.pos
let input := c.input
if h₂ : input.atEnd i then s.mkError errorMsg
else if sym.get' j h₁ != input.get' i h₂ then s.mkError errorMsg
else parse (sym.next' j h₁) c (s.next' input i h₂)
parse j
def checkTailWs (prev : Syntax) : Bool :=
match prev.getTailInfo with
| .original _ _ trailing _ => trailing.stopPos > trailing.startPos
| _ => false
def checkWsBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := s.stxStack.back
if checkTailWs prev then s else s.mkError errorMsg
def checkWsBefore (errorMsg : String := "space before") : Parser := {
info := epsilonInfo
fn := checkWsBeforeFn errorMsg
}
def checkTailLinebreak (prev : Syntax) : Bool :=
match prev.getTailInfo with
| .original _ _ trailing _ => trailing.contains '\n'
| _ => false
def checkLinebreakBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := s.stxStack.back
if checkTailLinebreak prev then s else s.mkError errorMsg
def checkLinebreakBefore (errorMsg : String := "line break") : Parser := {
info := epsilonInfo
fn := checkLinebreakBeforeFn errorMsg
}
private def pickNonNone (stack : SyntaxStack) : Syntax :=
match stack.toSubarray.findRev? fun stx => !stx.isNone with
| none => Syntax.missing
| some stx => stx
def checkNoWsBeforeFn (errorMsg : String) : ParserFn := fun _ s =>
let prev := pickNonNone s.stxStack
if checkTailNoWs prev then s else s.mkError errorMsg
def checkNoWsBefore (errorMsg : String := "no space before") : Parser := {
info := epsilonInfo
fn := checkNoWsBeforeFn errorMsg
}
def unicodeSymbolFnAux (sym asciiSym : String) (expected : List String) : ParserFn :=
satisfySymbolFn (fun s => s == sym || s == asciiSym) expected
def unicodeSymbolInfo (sym asciiSym : String) : ParserInfo := {
collectTokens := fun tks => sym :: asciiSym :: tks
firstTokens := FirstTokens.tokens [ sym, asciiSym ]
}
def unicodeSymbolFn (sym asciiSym : String) : ParserFn :=
unicodeSymbolFnAux sym asciiSym ["'" ++ sym ++ "', '" ++ asciiSym ++ "'"]
def unicodeSymbolNoAntiquot (sym asciiSym : String) : Parser :=
let sym := sym.trim
let asciiSym := asciiSym.trim
{ info := unicodeSymbolInfo sym asciiSym
fn := unicodeSymbolFn sym asciiSym }
def mkAtomicInfo (k : String) : ParserInfo :=
{ firstTokens := FirstTokens.tokens [ k ] }
def numLitFn : ParserFn := fun c s =>
let initStackSz := s.stackSize
let iniPos := s.pos
let s := tokenFn ["numeral"] c s
if !s.hasError && !(s.stxStack.back.isOfKind numLitKind) then s.mkErrorAt "numeral" iniPos initStackSz else s
def numLitNoAntiquot : Parser := {
fn := numLitFn
info := mkAtomicInfo "num"
}