-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathParser.elm
More file actions
1258 lines (948 loc) · 34.2 KB
/
Parser.elm
File metadata and controls
1258 lines (948 loc) · 34.2 KB
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 Parser exposing
( Parser, run
, int, float, number, symbol, keyword, variable, end
, succeed, (|=), (|.), lazy, andThen, problem
, oneOf, map, backtrackable, commit, token
, sequence, Trailing(..), loop, Step(..)
, spaces, lineComment, multiComment, Nestable(..)
, getChompedString, chompIf, chompWhile, chompUntil, chompUntilEndOr, mapChompedString
, DeadEnd, Problem(..), deadEndsToString
, withIndent, getIndent
, getPosition, getRow, getCol, getOffset, getSource
)
{-|
# Parsers
@docs Parser, run
# Building Blocks
@docs int, float, number, symbol, keyword, variable, end
# Pipelines
@docs succeed, (|=), (|.), lazy, andThen, problem
# Branches
@docs oneOf, map, backtrackable, commit, token
# Loops
@docs sequence, Trailing, loop, Step
# Whitespace
@docs spaces, lineComment, multiComment, Nestable
# Chompers
@docs getChompedString, chompIf, chompWhile, chompUntil, chompUntilEndOr, mapChompedString
# Errors
@docs DeadEnd, Problem, deadEndsToString
# Indentation
@docs withIndent, getIndent
# Positions
@docs getPosition, getRow, getCol, getOffset, getSource
-}
import Char
import Parser.Advanced as A exposing ((|=), (|.))
import Set
-- INFIX OPERATORS - see Parser.Advanced for why 5 and 6 were chosen
infix left 5 (|=) = keeper
infix left 6 (|.) = ignorer
-- PARSERS
{-| A `Parser` helps turn a `String` into nicely structured data. For example,
we can [`run`](#run) the [`int`](#int) parser to turn `String` to `Int`:
run int "123456" == Ok 123456
run int "3.1415" == Err ...
The cool thing is that you can combine `Parser` values to handle much more
complex scenarios.
-}
type alias Parser a =
A.Parser Never Problem a
-- RUN
{-| Try a parser. Here are some examples using the [`keyword`](#keyword)
parser:
run (keyword "true") "true" == Ok ()
run (keyword "true") "True" == Err ...
run (keyword "true") "false" == Err ...
run (keyword "true") "true!" == Ok ()
Notice the last case! A `Parser` will chomp as much as possible and not worry
about the rest. Use the [`end`](#end) parser to ensure you made it to the end
of the string!
-}
run : Parser a -> String -> Result (List DeadEnd) a
run parser source =
case A.run parser source of
Ok a ->
Ok a
Err problems ->
Err (List.map problemToDeadEnd problems)
problemToDeadEnd : A.DeadEnd Never Problem -> DeadEnd
problemToDeadEnd p =
DeadEnd p.row p.col p.problem
-- PROBLEMS
{-| A parser can run into situations where there is no way to make progress.
When that happens, I record the `row` and `col` where you got stuck and the
particular `problem` you ran into. That is a `DeadEnd`!
**Note:** I count rows and columns like a text editor. The beginning is `row=1`
and `col=1`. As I chomp characters, the `col` increments. When I reach a `\n`
character, I increment the `row` and set `col=1`.
-}
type alias DeadEnd =
{ row : Int
, col : Int
, problem : Problem
}
{-| When you run into a `DeadEnd`, I record some information about why you
got stuck. This data is useful for producing helpful error messages. This is
how [`deadEndsToString`](#deadEndsToString) works!
**Note:** If you feel limited by this type (i.e. having to represent custom
problems as strings) I highly recommend switching to `Parser.Advanced`. It
lets you define your own `Problem` type. It can also track "context" which
can improve error messages a ton! This is how the Elm compiler produces
relatively nice parse errors, and I am excited to see those techniques applied
elsewhere!
-}
type Problem
= Expecting String
| ExpectingInt
| ExpectingHex
| ExpectingOctal
| ExpectingBinary
| ExpectingFloat
| ExpectingNumber
| ExpectingVariable
| ExpectingSymbol String
| ExpectingKeyword String
| ExpectingEnd
| UnexpectedChar
| Problem String
| BadRepeat
{-| Turn all the `DeadEnd` data into a string that is easier for people to
read.
**Note:** This is just a baseline of quality. It cannot do anything with colors.
It is not interactive. It just turns the raw data into strings. I really hope
folks will check out the source code for some inspiration on how to turn errors
into `Html` with nice colors and interaction! The `Parser.Advanced` module lets
you work with context as well, which really unlocks another level of quality!
The "context" technique is how the Elm compiler can say "I think I am parsing a
list, so I was expecting a closing `]` here." Telling users what the parser
_thinks_ is happening can be really helpful!
-}
deadEndsToString : List DeadEnd -> String
deadEndsToString deadEnds =
"TODO deadEndsToString"
-- PIPELINES
{-| A parser that succeeds without chomping any characters.
run (succeed 90210 ) "mississippi" == Ok 90210
run (succeed 3.141 ) "mississippi" == Ok 3.141
run (succeed () ) "mississippi" == Ok ()
run (succeed Nothing) "mississippi" == Ok Nothing
Seems weird on its own, but it is very useful in combination with other
functions. The docs for [`(|=)`](#|=) and [`andThen`](#andThen) have some neat
examples.
-}
succeed : a -> Parser a
succeed =
A.succeed
{-| **Keep** values in a parser pipeline. For example, we could say:
type alias Point = { x : Float, y : Float }
point : Parser Point
point =
succeed Point
|. symbol "("
|. spaces
|= float
|. spaces
|. symbol ","
|. spaces
|= float
|. spaces
|. symbol ")"
All the parsers in this pipeline will chomp characters and produce values. So
`symbol "("` will chomp one paren and produce a `()` value. Similarly, `float`
will chomp some digits and produce a `Float` value. The `(|.)` and `(|=)`
operators just decide whether we give the values to the `Point` function.
So in this case, we skip the `()` from `symbol "("`, we skip the `()` from
`spaces`, we keep the `Float` from `float`, etc.
-}
keeper : Parser (a -> b) -> Parser a -> Parser b
keeper =
(|=)
{-| **Skip** values in a parser pipeline. For example, maybe we want to parse
some JavaScript variables:
var : Parser String
var =
getChompedString <|
succeed ()
|. chompIf isStartChar
|. chompWhile isInnerChar
isStartChar : Char -> Bool
isStartChar char =
Char.isAlpha char || char == '_' || char == '$'
isInnerChar : Char -> Bool
isInnerChar char =
isStartChar char || Char.isDigit char
`chompIf isStartChar` can chomp one character and produce a `()` value.
`chompWhile isInnerChar` can chomp zero or more characters and produce a `()`
value. The `(|.)` operators are saying to still chomp all the characters, but
skip the two `()` values that get produced. No one cares about them.
-}
ignorer : Parser keep -> Parser ignore -> Parser keep
ignorer =
(|.)
{-| Helper to define recursive parsers. Say we want a parser for simple
boolean expressions:
true
false
(true || false)
(true || (true || false))
Notice that a boolean expression might contain *other* boolean expressions.
That means we will want to define our parser in terms of itself:
type Boolean
= MyTrue
| MyFalse
| MyOr Boolean Boolean
boolean : Parser Boolean
boolean =
oneOf
[ succeed MyTrue
|. keyword "true"
, succeed MyFalse
|. keyword "false"
, succeed MyOr
|. symbol "("
|. spaces
|= lazy (\_ -> boolean)
|. spaces
|. symbol "||"
|. spaces
|= lazy (\_ -> boolean)
|. spaces
|. symbol ")"
]
**Notice that `boolean` uses `boolean` in its definition!** In Elm, you can
only define a value in terms of itself it is behind a function call. So
`lazy` helps us define these self-referential parsers. (`andThen` can be used
for this as well!)
-}
lazy : (() -> Parser a) -> Parser a
lazy =
A.lazy
{-| Parse one thing `andThen` parse another thing. This is useful when you want
to check on what you just parsed. For example, maybe you want U.S. zip codes
and `int` is not suitable because it does not allow leading zeros. You could
say:
zipCode : Parser String
zipCode =
getChompedString (chompWhile Char.isDigit)
|> andThen checkZipCode
checkZipCode : String -> Parser String
checkZipCode code =
if String.length code == 5 then
succeed code
else
problem "a U.S. zip code has exactly 5 digits"
First we chomp digits `andThen` we check if it is a valid U.S. zip code. We
`succeed` if it has exactly five digits and report a `problem` if not.
Check out [`examples/DoubleQuoteString.elm`](https://github.com/elm/parser/blob/master/examples/DoubleQuoteString.elm)
for another example, this time using `andThen` to verify unicode code points.
**Note:** If you are using `andThen` recursively and blowing the stack, check
out the [`loop`](#loop) function to limit stack usage.
-}
andThen : (a -> Parser b) -> Parser a -> Parser b
andThen =
A.andThen
{-| Indicate that a parser has reached a dead end. "Everything was going fine
until I ran into this problem." Check out the [`andThen`](#andThen) docs to see
an example usage.
-}
problem : String -> Parser a
problem msg =
A.problem (Problem msg)
-- BACKTRACKING
{-| If you are parsing JSON, the values can be strings, floats, booleans,
arrays, objects, or null. You need a way to pick `oneOf` them! Here is a
sample of what that code might look like:
type Json
= Number Float
| Boolean Bool
| Null
json : Parser Json
json =
oneOf
[ map Number float
, map (\_ -> Boolean True) (keyword "true")
, map (\_ -> Boolean False) (keyword "false")
, map (\_ -> Null) keyword "null"
]
This parser will keep trying parsers until `oneOf` them starts chomping
characters. Once a path is chosen, it does not come back and try the others.
**Note:** I highly recommend reading [this document][semantics] to learn how
`oneOf` and `backtrackable` interact. It is subtle and important!
[semantics]: https://github.com/elm/parser/blob/master/semantics.md
-}
oneOf : List (Parser a) -> Parser a
oneOf =
A.oneOf
{-| Transform the result of a parser. Maybe you have a value that is
an integer or `null`:
nullOrInt : Parser (Maybe Int)
nullOrInt =
oneOf
[ map Just int
, map (\_ -> Nothing) (keyword "null")
]
-- run nullOrInt "0" == Ok (Just 0)
-- run nullOrInt "13" == Ok (Just 13)
-- run nullOrInt "null" == Ok Nothing
-- run nullOrInt "zero" == Err ...
-}
map : (a -> b) -> Parser a -> Parser b
map =
A.map
{-| It is quite tricky to use `backtrackable` well! It can be very useful, but
also can degrade performance and error message quality.
Read [this document](https://github.com/elm/parser/blob/master/semantics.md)
to learn how `oneOf`, `backtrackable`, and `commit` work and interact with
each other. It is subtle and important!
-}
backtrackable : Parser a -> Parser a
backtrackable =
A.backtrackable
{-| `commit` is almost always paired with `backtrackable` in some way, and it
is tricky to use well.
Read [this document](https://github.com/elm/parser/blob/master/semantics.md)
to learn how `oneOf`, `backtrackable`, and `commit` work and interact with
each other. It is subtle and important!
-}
commit : a -> Parser a
commit =
A.commit
-- TOKEN
{-| Parse exactly the given string, without any regard to what comes next.
A potential pitfall when parsing keywords is getting tricked by variables that
start with a keyword, like `let` in `letters` or `import` in `important`. This
is especially likely if you have a whitespace parser that can consume zero
characters. So the [`keyword`](#keyword) parser is defined with `token` and a
trick to peek ahead a bit:
keyword : String -> Parser ()
keyword kwd =
succeed identity
|. backtrackable (token kwd)
|= oneOf
[ map (\_ -> True) (backtrackable (chompIf isVarChar))
, succeed False
]
|> andThen (checkEnding kwd)
checkEnding : String -> Bool -> Parser ()
checkEnding kwd isBadEnding =
if isBadEnding then
problem ("expecting the `" ++ kwd ++ "` keyword")
else
commit ()
isVarChar : Char -> Bool
isVarChar char =
Char.isAlphaNum char || char == '_'
This definition is specially designed so that (1) if you really see `let` you
commit to that path and (2) if you see `letters` instead you can backtrack and
try other options. If I had just put a `backtrackable` around the whole thing
you would not get (1) anymore.
-}
token : String -> Parser ()
token str =
A.token (toToken str)
toToken : String -> A.Token Problem
toToken str =
A.Token str (Expecting str)
-- LOOPS
{-| A parser that can loop indefinitely. This can be helpful when parsing
repeated structures, like a bunch of statements:
statements : Parser (List Stmt)
statements =
loop [] statementsHelp
statementsHelp : List Stmt -> Parser (Step (List Stmt) (List Stmt))
statementsHelp revStmts =
oneOf
[ succeed (\stmt -> Loop (stmt :: revStmts))
|= statement
|. spaces
|. symbol ";"
|. spaces
, succeed ()
|> map (\_ -> Done (List.reverse revStmts))
]
-- statement : Parser Stmt
Notice that the statements are tracked in reverse as we `Loop`, and we reorder
them only once we are `Done`. This is a very common pattern with `loop`!
Check out [`examples/DoubleQuoteString.elm`](https://github.com/elm/parser/blob/master/examples/DoubleQuoteString.elm)
for another example.
**IMPORTANT NOTE:** Parsers like `succeed ()` and `chompWhile Char.isAlpha` can
succeed without consuming any characters. So in some cases you may want to use
[`getOffset`](#getOffset) to ensure that each step actually consumed characters.
Otherwise you could end up in an infinite loop!
**Note:** Anything you can write with `loop`, you can also write as a parser
that chomps some characters `andThen` calls itself with new arguments. The
problem with calling `andThen` recursively is that it grows the stack, so you
cannot do it indefinitely. So `loop` is important because enables tail-call
elimination, allowing you to parse however many repeats you want.
-}
loop : state -> (state -> Parser (Step state a)) -> Parser a
loop state callback =
A.loop state (\s -> map toAdvancedStep (callback s))
{-| Decide what steps to take next in your [`loop`](#loop).
If you are `Done`, you give the result of the whole `loop`. If you decide to
`Loop` around again, you give a new state to work from. Maybe you need to add
an item to a list? Or maybe you need to track some information about what you
just saw?
**Note:** It may be helpful to learn about [finite-state machines][fsm] to get
a broader intuition about using `state`. I.e. You may want to create a `type`
that describes four possible states, and then use `Loop` to transition between
them as you consume characters.
[fsm]: https://en.wikipedia.org/wiki/Finite-state_machine
-}
type Step state a
= Loop state
| Done a
toAdvancedStep : Step s a -> A.Step s a
toAdvancedStep step =
case step of
Loop s -> A.Loop s
Done a -> A.Done a
-- NUMBERS
{-| Parse integers.
run int "1" == Ok 1
run int "1234" == Ok 1234
run int "-789" == Err ...
run int "0123" == Err ...
run int "1.34" == Err ...
run int "1e31" == Err ...
run int "123a" == Err ...
run int "0x1A" == Err ...
If you want to handle a leading `+` or `-` you should do it with a custom
parser like this:
myInt : Parser Int
myInt =
oneOf
[ succeed negate
|. symbol "-"
|= int
, int
]
**Note:** If you want a parser for both `Int` and `Float` literals, check out
[`number`](#number) below. It will be faster than using `oneOf` to combining
`int` and `float` yourself.
-}
int : Parser Int
int =
A.int ExpectingInt ExpectingInt
{-| Parse floats.
run float "123" == Ok 123
run float "3.1415" == Ok 3.1415
run float "0.1234" == Ok 0.1234
run float ".1234" == Ok 0.1234
run float "1e-42" == Ok 1e-42
run float "6.022e23" == Ok 6.022e23
run float "6.022E23" == Ok 6.022e23
run float "6.022e+23" == Ok 6.022e23
If you want to disable literals like `.123` (like in Elm) you could write
something like this:
elmFloat : Parser Float
elmFloat =
oneOf
[ symbol "."
|. problem "floating point numbers must start with a digit, like 0.25"
, float
]
**Note:** If you want a parser for both `Int` and `Float` literals, check out
[`number`](#number) below. It will be faster than using `oneOf` to combining
`int` and `float` yourself.
-}
float : Parser Float
float =
A.float ExpectingFloat ExpectingFloat
-- NUMBER
{-| Parse a bunch of different kinds of numbers without backtracking. A parser
for Elm would need to handle integers, floats, and hexadecimal like this:
type Expr
= Variable String
| Int Int
| Float Float
| Apply Expr Expr
elmNumber : Parser Expr
elmNumber =
number
{ int = Just Int
, hex = Just Int -- 0x001A is allowed
, octal = Nothing -- 0o0731 is not
, binary = Nothing -- 0b1101 is not
, float = Just Float
}
If you wanted to implement the [`float`](#float) parser, it would be like this:
float : Parser Float
float =
number
{ int = Just toFloat
, hex = Nothing
, octal = Nothing
, binary = Nothing
, float = Just identity
}
Notice that it actually is processing `int` results! This is because `123`
looks like an integer to me, but maybe it looks like a float to you. If you had
`int = Nothing`, floats would need a decimal like `1.0` in every case. If you
like explicitness, that may actually be preferable!
**Note:** This function does not check for weird trailing characters in the
current implementation, so parsing `123abc` can succeed up to `123` and then
move on. This is helpful for people who want to parse things like `40px` or
`3m`, but it requires a bit of extra code to rule out trailing characters in
other cases.
-}
number
: { int : Maybe (Int -> a)
, hex : Maybe (Int -> a)
, octal : Maybe (Int -> a)
, binary : Maybe (Int -> a)
, float : Maybe (Float -> a)
}
-> Parser a
number i =
A.number
{ int = Result.fromMaybe ExpectingInt i.int
, hex = Result.fromMaybe ExpectingHex i.hex
, octal = Result.fromMaybe ExpectingOctal i.octal
, binary = Result.fromMaybe ExpectingBinary i.binary
, float = Result.fromMaybe ExpectingFloat i.float
, invalid = ExpectingNumber
, expecting = ExpectingNumber
}
-- SYMBOL
{-| Parse symbols like `(` and `,`.
run (symbol "[") "[" == Ok ()
run (symbol "[") "4" == Err ... (ExpectingSymbol "[") ...
**Note:** This is good for stuff like brackets and semicolons, but it probably
should not be used for binary operators like `+` and `-` because you can find
yourself in weird situations. For example, is `3--4` a typo? Or is it `3 - -4`?
I have had better luck with `chompWhile isSymbol` and sorting out which
operator it is afterwards.
-}
symbol : String -> Parser ()
symbol str =
A.symbol (A.Token str (ExpectingSymbol str))
-- KEYWORD
{-| Parse keywords like `let`, `case`, and `type`.
run (keyword "let") "let" == Ok ()
run (keyword "let") "var" == Err ... (ExpectingKeyword "let") ...
run (keyword "let") "letters" == Err ... (ExpectingKeyword "let") ...
**Note:** Notice the third case there! `keyword` actually looks ahead one
character to make sure it is not a letter, number, or underscore. The goal is
to help with parsers like this:
succeed identity
|. keyword "let"
|. spaces
|= elmVar
|. spaces
|. symbol "="
The trouble is that `spaces` may chomp zero characters (to handle expressions
like `[1,2]` and `[ 1 , 2 ]`) and in this case, it would mean `letters` could
be parsed as `let ters` and then wonder where the equals sign is! Check out the
[`token`](#token) docs if you need to customize this!
-}
keyword : String -> Parser ()
keyword kwd =
A.keyword (A.Token kwd (ExpectingKeyword kwd))
-- END
{-| Check if you have reached the end of the string you are parsing.
justAnInt : Parser Int
justAnInt =
succeed identity
|= int
|. end
-- run justAnInt "90210" == Ok 90210
-- run justAnInt "1 + 2" == Err ...
-- run int "1 + 2" == Ok 1
Parsers can succeed without parsing the whole string. Ending your parser
with `end` guarantees that you have successfully parsed the whole string.
-}
end : Parser ()
end =
A.end ExpectingEnd
-- CHOMPED STRINGS
{-| Sometimes parsers like `int` or `variable` cannot do exactly what you
need. The "chomping" family of functions is meant for that case! Maybe you
need to parse [valid PHP variables][php] like `$x` and `$txt`:
php : Parser String
php =
getChompedString <|
succeed ()
|. chompIf (\c -> c == '$')
|. chompIf (\c -> Char.isAlpha c || c == '_')
|. chompWhile (\c -> Char.isAlphaNum c || c == '_')
The idea is that you create a bunch of chompers that validate the underlying
characters. Then `getChompedString` extracts the underlying `String` efficiently.
**Note:** Maybe it is helpful to see how you can use [`getOffset`](#getOffset)
and [`getSource`](#getSource) to implement this function:
getChompedString : Parser a -> Parser String
getChompedString parser =
succeed String.slice
|= getOffset
|. parser
|= getOffset
|= getSource
[php]: https://www.w3schools.com/php/php_variables.asp
-}
getChompedString : Parser a -> Parser String
getChompedString =
A.getChompedString
{-| This works just like [`getChompedString`](#getChompedString) but gives
a bit more flexibility. For example, maybe you want to parse Elm doc comments
and get (1) the full comment and (2) all of the names listed in the docs.
You could implement `mapChompedString` like this:
mapChompedString : (String -> a -> b) -> Parser a -> Parser String
mapChompedString func parser =
succeed (\start value end src -> func (String.slice start end src) value)
|= getOffset
|= parser
|= getOffset
|= getSource
-}
mapChompedString : (String -> a -> b) -> Parser a -> Parser b
mapChompedString =
A.mapChompedString
{-| Chomp one character if it passes the test.
chompUpper : Parser ()
chompUpper =
chompIf Char.isUpper
So this can chomp a character like `T` and produces a `()` value.
-}
chompIf : (Char -> Bool) -> Parser ()
chompIf isGood =
A.chompIf isGood UnexpectedChar
{-| Chomp zero or more characters if they pass the test. This is commonly
useful for chomping whitespace or variable names:
whitespace : Parser ()
whitespace =
chompWhile (\c -> c == ' ' || c == '\t' || c == '\n' || c == '\r')
elmVar : Parser String
elmVar =
getChompedString <|
succeed ()
|. chompIf Char.isLower
|. chompWhile (\c -> Char.isAlphaNum c || c == '_')
**Note:** a `chompWhile` parser always succeeds! This can lead to tricky
situations, especially if you define your whitespace with it. In that case,
you could accidentally interpret `letx` as the keyword `let` followed by
"spaces" followed by the variable `x`. This is why the `keyword` and `number`
parsers peek ahead, making sure they are not followed by anything unexpected.
-}
chompWhile : (Char -> Bool) -> Parser ()
chompWhile =
A.chompWhile
{-| Chomp until you see a certain string. You could define C-style multi-line
comments like this:
comment : Parser ()
comment =
symbol "/*"
|. chompUntil "*/"
I recommend using [`multiComment`](#multiComment) for this particular scenario
though. It can be trickier than it looks!
-}
chompUntil : String -> Parser ()
chompUntil str =
A.chompUntil (toToken str)
{-| Chomp until you see a certain string or until you run out of characters to
chomp! You could define single-line comments like this:
elm : Parser ()
elm =
symbol "--"
|. chompUntilEndOr "\n"
A file may end with a single-line comment, so the file can end before you see
a newline. Tricky!
I recommend just using [`lineComment`](#lineComment) for this particular
scenario.
-}
chompUntilEndOr : String -> Parser ()
chompUntilEndOr =
A.chompUntilEndOr
-- INDENTATION
{-| Some languages are indentation sensitive. Python cares about tabs. Elm
cares about spaces sometimes. `withIndent` and `getIndent` allow you to manage
"indentation state" yourself, however is necessary in your scenario.
-}
withIndent : Int -> Parser a -> Parser a
withIndent =
A.withIndent
{-| When someone said `withIndent` earlier, what number did they put in there?
- `getIndent` results in `0`, the default value
- `withIndent 4 getIndent` results in `4`
So you are just asking about things you said earlier. These numbers do not leak
out of `withIndent`, so say we have:
succeed Tuple.pair
|= withIndent 4 getIndent
|= getIndent
Assuming there are no `withIndent` above this, you would get `(4,0)` from this.
-}
getIndent : Parser Int
getIndent =
A.getIndent
-- POSITION
{-| Code editors treat code like a grid, with rows and columns. The start is
`row=1` and `col=1`. As you chomp characters, the `col` increments. When you
run into a `\n` character, the `row` increments and `col` goes back to `1`.
In the Elm compiler, I track the start and end position of every expression
like this:
type alias Located a =
{ start : (Int, Int)
, value : a
, end : (Int, Int)
}
located : Parser a -> Parser (Located a)
located parser =
succeed Located
|= getPosition
|= parser
|= getPosition
So if there is a problem during type inference, I use this saved position
information to underline the exact problem!
**Note:** Tabs count as one character, so if you are parsing something like
Python, I recommend sorting that out *after* parsing. So if I wanted the `^^^^`
underline like in Elm, I would find the `row` in the source code and do
something like this:
makeUnderline : String -> Int -> Int -> String
makeUnderline row minCol maxCol =
String.toList row
|> List.indexedMap (toUnderlineChar minCol maxCol)
|> String.fromList
toUnderlineChar : Int -> Int -> Int -> Char -> Char
toUnderlineChar minCol maxCol col char =
if minCol <= col && col <= maxCol then
'^'
else if char == '\t' then
'\t'
else
' '
So it would preserve any tabs from the source line. There are tons of other
ways to do this though. The point is just that you handle the tabs after
parsing but before anyone looks at the numbers in a context where tabs may
equal 2, 4, or 8.
-}
getPosition : Parser (Int, Int)
getPosition =
A.getPosition
{-| This is a more efficient version of `map Tuple.first getPosition`. Maybe
you just want to track the line number for some reason? This lets you do that.
See [`getPosition`](#getPosition) for an explanation of rows and columns.
-}
getRow : Parser Int
getRow =
A.getRow
{-| This is a more efficient version of `map Tuple.second getPosition`. This
can be useful in combination with [`withIndent`](#withIndent) and
[`getIndent`](#getIndent), like this:
checkIndent : Parser ()
checkIndent =
succeed (\indent column -> indent <= column)
|= getIndent
|= getCol
|> andThen checkIndentHelp
checkIndentHelp : Bool -> Parser ()
checkIndentHelp isIndented =
if isIndented then
succeed ()
else
problem "expecting more spaces"
So the `checkIndent` parser only succeeds when you are "deeper" than the
current indent level. You could use this to parse Elm-style `let` expressions.
-}
getCol : Parser Int
getCol =
A.getCol