This repository has been archived by the owner on Oct 5, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 25
/
OldParser.elm
2175 lines (1836 loc) · 68.6 KB
/
OldParser.elm
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 Stage.Parse.Parser exposing
( customTypeDeclaration
, declaration
, exposingList
, expr
, import_
, imports
, moduleDeclaration
, moduleName
, module_
, portDeclaration
, spacesOnly
, typeAliasDeclaration
, type_
, valueDeclaration
)
import Dict exposing (Dict)
import Elm.AST.Frontend as Frontend exposing (Expr(..), LocatedExpr, LocatedPattern, Pattern(..))
import Elm.Compiler.Error
exposing
( ParseCompilerBug(..)
, ParseContext(..)
, ParseProblem(..)
)
import Elm.Data.Binding as Binding exposing (Binding)
import Elm.Data.Declaration as Declaration
exposing
( Constructor
, Declaration
, DeclarationBody
)
import Elm.Data.Exposing exposing (ExposedItem(..), Exposing(..))
import Elm.Data.FilePath exposing (FilePath)
import Elm.Data.Import exposing (Import)
import Elm.Data.Located as Located exposing (Located)
import Elm.Data.Module exposing (Module, ModuleType(..))
import Elm.Data.ModuleName exposing (ModuleName)
import Elm.Data.Qualifiedness exposing (PossiblyQualified(..))
import Elm.Data.Type.Concrete as ConcreteType exposing (ConcreteType)
import Elm.Data.TypeAnnotation exposing (TypeAnnotation)
import Elm.Data.VarName exposing (VarName)
import Hex
import List.NonEmpty exposing (NonEmpty)
import Parser.Advanced as P exposing ((|.), (|=), Parser)
import Pratt.Advanced as PP
import Set exposing (Set)
type alias Parser_ a =
Parser ParseContext ParseProblem a
type alias ExprConfig =
PP.Config ParseContext ParseProblem LocatedExpr
type alias PatternConfig =
PP.Config ParseContext ParseProblem LocatedPattern
type alias TypeConfig =
PP.Config ParseContext ParseProblem (ConcreteType PossiblyQualified)
located : Parser_ p -> Parser_ (Located p)
located p =
P.succeed
(\( startRow, startCol ) value ( endRow, endCol ) ->
Located.located
{ start = { row = startRow, col = startCol }
, end = { row = endRow, col = endCol }
}
value
)
|= P.getPosition
|= p
|= P.getPosition
module_ : FilePath -> Parser_ (Module LocatedExpr TypeAnnotation PossiblyQualified)
module_ filePath =
P.succeed
(\( moduleType_, moduleName_, exposing_ ) imports_ declarations_ ->
{ imports = imports_
, name = moduleName_
, filePath = filePath
, declarations =
declarations_
|> List.map
(\almostDeclaration ->
let
declaration_ =
almostDeclaration moduleName_
in
( declaration_.name, declaration_ )
)
|> Dict.fromList
, type_ = moduleType_
, exposing_ = exposing_
}
)
|= moduleDeclaration
|. ignorables
-- TODO what about module doc comment? is it before the imports or after?
|= imports
|= declarations
|> P.inContext (InFile filePath)
moduleDeclaration : Parser_ ( ModuleType, ModuleName, Exposing )
moduleDeclaration =
P.succeed
(\moduleType_ moduleName_ exposing_ ->
( moduleType_
, moduleName_
, exposing_
)
)
|= moduleType
|. ignorables
|= notAtBeginningOfLine moduleName
|. ignorables
|. notAtBeginningOfLine (P.keyword (P.Token "exposing" ExpectingExposingKeyword))
|. ignorables
|= notAtBeginningOfLine exposingList
imports : Parser_ (Dict ModuleName Import)
imports =
P.succeed
(List.map (\dep -> ( dep.moduleName, dep ))
>> Dict.fromList
)
|= oneOrMoreWith ignorables import_
import_ : Parser_ Import
import_ =
P.succeed
(\moduleName_ as_ exposing_ ->
{ moduleName = moduleName_
, as_ = as_
, exposing_ = exposing_
}
)
|. onlyAtBeginningOfLine (P.keyword (P.Token "import" ExpectingImportKeyword))
|. spacesOnly
-- TODO check expectation ... what about newlines here?
|= moduleName
|. ignorables
|= P.oneOf
[ P.succeed Just
|. P.keyword (P.Token "as" ExpectingAsKeyword)
|. ignorables
|= uppercaseNameWithoutDots
, P.succeed Nothing
]
|. P.oneOf
[ -- not sure if this is idiomatic
dot
|. P.problem ExpectingUppercaseNameWithoutDots
, ignorables
]
|. ignorables
|= P.oneOf
[ P.succeed Just
|. P.keyword (P.Token "exposing" ExpectingExposingKeyword)
|. ignorables
|= exposingList
, P.succeed Nothing
]
moduleType : Parser_ ModuleType
moduleType =
P.oneOf
[ plainModuleType
, portModuleType
, effectModuleType
]
plainModuleType : Parser_ ModuleType
plainModuleType =
P.succeed PlainModule
|. P.keyword (P.Token "module" ExpectingModuleKeyword)
portModuleType : Parser_ ModuleType
portModuleType =
P.succeed PortModule
|. P.keyword (P.Token "port" ExpectingPortKeyword)
|. spacesOnly
|. P.keyword (P.Token "module" ExpectingModuleKeyword)
effectModuleType : Parser_ ModuleType
effectModuleType =
-- TODO some metadata?
P.succeed EffectModule
|. P.keyword (P.Token "effect" ExpectingEffectKeyword)
|. spacesOnly
|. P.keyword (P.Token "module" ExpectingModuleKeyword)
dot : Parser_ ()
dot =
P.symbol dot_
dot_ : P.Token ParseProblem
dot_ =
P.Token "." ExpectingDot
moduleName : Parser_ String
moduleName =
P.sequence
{ start = P.Token "" (ParseCompilerBug ModuleNameStartParserFailed)
, separator = dot_
, end = P.Token "" (ParseCompilerBug ModuleNameEndParserFailed)
, spaces = P.succeed ()
, item = uppercaseNameWithoutDots
, trailing = P.Forbidden
}
|> P.andThen
(\list_ ->
if List.isEmpty list_ then
P.problem ExpectingModuleName
else
P.succeed (String.join "." list_)
)
nameWithoutDots : Parser_ ( NameType, String )
nameWithoutDots =
P.oneOf
[ P.map (Tuple.pair UppercaseName) uppercaseNameWithoutDots
, P.map (Tuple.pair LowercaseName) varName
]
uppercaseNameWithoutDots : Parser_ String
uppercaseNameWithoutDots =
P.variable
{ start = Char.isUpper
, inner = \c -> Char.isAlphaNum c || c == '_'
, reserved = Set.empty
, expecting = ExpectingUppercaseNamePart
}
exposingList : Parser_ Exposing
exposingList =
P.oneOf
[ exposingAll
, exposingSome
]
exposingAll : Parser_ Exposing
exposingAll =
P.symbol (P.Token "(..)" ExpectingExposingAllSymbol)
|> P.map (always ExposingAll)
exposingSome : Parser_ Exposing
exposingSome =
P.sequence
{ start = P.Token "(" ExpectingLeftParen
, separator = P.Token "," ExpectingComma
, end = P.Token ")" ExpectingRightParen
, spaces = ignorables
, item = exposedItem
, trailing = P.Forbidden
}
|> P.andThen
(\list_ ->
if List.isEmpty list_ then
P.problem ExposingListCantBeEmpty
else
P.succeed (ExposingSome list_)
)
exposedItem : Parser_ ExposedItem
exposedItem =
P.oneOf
[ exposedValue
, exposedTypeAndOptionallyAllConstructors
]
exposedValue : Parser_ ExposedItem
exposedValue =
P.map ExposedValue varName
|> P.inContext InExposedValue
exposedTypeAndOptionallyAllConstructors : Parser_ ExposedItem
exposedTypeAndOptionallyAllConstructors =
P.succeed
(\name hasDoublePeriod ->
if hasDoublePeriod then
ExposedTypeAndAllConstructors name
else
ExposedType name
)
|= typeOrConstructorName
|= P.oneOf
[ P.succeed True
|. P.symbol (P.Token "(..)" ExpectingExposedTypeDoublePeriod)
, P.succeed False
]
typeOrConstructorName : Parser_ String
typeOrConstructorName =
P.variable
{ start = Char.isUpper
, inner = \c -> Char.isAlphaNum c || c == '_'
, reserved = Set.empty
, expecting = ExpectingTypeOrConstructorName
}
{-| Taken from the official compiler.
-}
reservedWords : Set String
reservedWords =
Set.fromList
[ "if"
, "then"
, "else"
, "case"
, "of"
, "let"
, "in"
, "type"
, "module"
, "where"
, "import"
, "exposing"
, "as"
, "port"
]
declarations : Parser_ (List (ModuleName -> Declaration LocatedExpr TypeAnnotation PossiblyQualified))
declarations =
P.loop []
(\decls ->
P.oneOf
[ P.succeed (\decl -> P.Loop (decl :: decls))
|= declaration
|. ignorables
, P.end ExpectingEnd
|> P.map (\() -> P.Done (List.reverse decls))
]
)
declaration : Parser_ (ModuleName -> Declaration LocatedExpr TypeAnnotation PossiblyQualified)
declaration =
P.succeed
(\( name, body ) module__ ->
{ module_ = module__
, name = name
, body = body
}
)
|= declarationBody
|> P.inContext InDeclaration
declarationBody : Parser_ ( String, DeclarationBody LocatedExpr TypeAnnotation PossiblyQualified )
declarationBody =
P.oneOf
[ typeAliasDeclaration
, customTypeDeclaration
, valueDeclaration
, portDeclaration
]
valueDeclaration : Parser_ ( String, DeclarationBody LocatedExpr TypeAnnotation PossiblyQualified )
valueDeclaration =
P.succeed
(\annotationOrDeclName maybeAnnotation expr_ ->
case maybeAnnotation of
Nothing ->
( annotationOrDeclName
, Declaration.Value
{ typeAnnotation = Nothing
, expression = expr_
}
)
Just ( type__, declName ) ->
( declName
, Declaration.Value
{ typeAnnotation =
Just
{ varName = annotationOrDeclName
, type_ = type__
}
, expression = expr_
}
)
)
|= onlyAtBeginningOfLine varName
|. ignorables
|= P.oneOf
[ P.succeed (\type__ declarationName -> Just ( type__, declarationName ))
|. notAtBeginningOfLine colon
|. ignorables
|= notAtBeginningOfLine type_
|. ignorables
|= onlyAtBeginningOfLine varName
|. ignorables
, P.succeed Nothing
]
|. notAtBeginningOfLine equals
|. ignorables
|= expr
|> P.inContext InValueDeclaration
equals : Parser_ ()
equals =
P.symbol (P.Token "=" ExpectingEqualsSign)
{-|
type alias X = Int
type alias X a = Maybe a
More generally,
type alias <UserDefinedType> <VarType>* = <Type>
-}
typeAliasDeclaration : Parser_ ( String, DeclarationBody LocatedExpr TypeAnnotation PossiblyQualified )
typeAliasDeclaration =
P.succeed
(\name parameters type__ ->
( name
, Declaration.TypeAlias
{ parameters = parameters
, definition = type__
}
)
)
|. onlyAtBeginningOfLine (P.keyword (P.Token "type alias" ExpectingTypeAlias))
|. ignorables
|= uppercaseNameWithoutDots
|. P.symbol (P.Token " " ExpectingSpace)
|. ignorables
|= zeroOrMoreWith ignorables varName
|. ignorables
|. equals
|. ignorables
|= type_
|> P.inContext InTypeAlias
{-|
type X = Foo | Bar
type X a = Foo a | Bar String
More generally,
type <UserDefinedType> <VarType>* = <Constructor>[ | <Constructor>]*
Constructor := <Name>[ <Type>]*
-}
customTypeDeclaration : Parser_ ( String, DeclarationBody LocatedExpr TypeAnnotation PossiblyQualified )
customTypeDeclaration =
P.succeed
(\name parameters constructors_ ->
( name
, Declaration.CustomType
{ parameters = parameters
, constructors = constructors_
}
)
)
|. P.keyword (P.Token "type" ExpectingTypeAlias)
|. ignorables
|= uppercaseNameWithoutDots
|. P.oneOf
[ P.symbol (P.Token " " ExpectingSpace)
, P.symbol (P.Token "\n" ExpectingSpace)
]
|. ignorables
|= zeroOrMoreWith ignorables varName
|. ignorables
|. equals
|. ignorables
|= notAtBeginningOfLine constructors
|> P.inContext InCustomType
constructors : Parser_ (NonEmpty (Constructor PossiblyQualified))
constructors =
let
subsequentConstructorsLoop reversedCtors =
P.succeed (\x -> x)
|. ignorables
|= P.oneOf
[ P.succeed (\newCtor -> P.Loop (newCtor :: reversedCtors))
|. notAtBeginningOfLine (P.token (P.Token "|" ExpectingPipe))
|. ignorables
|= notAtBeginningOfLine constructor
, P.succeed (P.Done (List.reverse reversedCtors))
]
in
P.succeed
(\first rest ->
List.NonEmpty.fromCons first rest
)
|= constructor
|= P.loop [] subsequentConstructorsLoop
|> P.inContext InConstructors
constructor : Parser_ (Constructor PossiblyQualified)
constructor =
P.succeed Declaration.Constructor
|= uppercaseNameWithoutDots
|. ignorables
|= oneOrMoreWith ignorables (notAtBeginningOfLine type_)
expr : Parser_ LocatedExpr
expr =
PP.expression
{ oneOf =
[ if_
, let_
, lambda
, PP.literal literal
, always varOrConstructorValue
, list
, parenStartingExpr
, record
, case_
]
, andThenOneOf =
-- TODO test this: does `x =\n call 1\n+ something` work? (it shouldn't: no space before '+')
[ PP.infixLeft 99
(ignorablesAndCheckIndent (<) ExpectingIndentation)
(Located.merge
(\fn argument ->
Frontend.Call
{ fn = fn
, argument = argument
}
)
)
, PP.infixLeft 1
(checkIndent (<) ExpectingIndentation
|> P.andThen (\() -> P.symbol (P.Token "++" ExpectingConcatOperator))
)
(Located.merge ListConcat)
, PP.infixLeft 1
(checkIndent (<) ExpectingIndentation
|> P.andThen (\() -> P.symbol (P.Token "+" ExpectingPlusOperator))
)
(Located.merge Plus)
, PP.infixRight 1
(checkIndent (<) ExpectingIndentation
|> P.andThen (\() -> P.symbol (P.Token "::" ExpectingConsOperator))
)
(Located.merge Cons)
]
, spaces = ignorables
}
|> P.inContext InExpr
parenStartingExpr : ExprConfig -> Parser_ LocatedExpr
parenStartingExpr config =
P.succeed identity
|. leftParen
|= P.oneOf
[ P.succeed identity
|= PP.subExpression 0 config
|> P.andThen
(\e1 ->
P.oneOf
[ P.succeed identity
|. ignorables
|. comma
|= PP.subExpression 0 config
|> P.andThen
(\e2 ->
P.succeed identity
|= P.oneOf
[ -- ("x", "y", "z")
P.succeed (Frontend.Tuple3 e1 e2)
|. comma
|= PP.subExpression 0 config
, -- ("x", "y")
P.succeed (Frontend.Tuple e1 e2)
]
)
, -- ("x"), parenthesized expr
P.succeed (Located.unwrap e1)
]
)
, -- ()
-- Note that unit can't be written as ( ) - no spaces inside!
P.succeed Frontend.Unit
]
|. rightParen
|> located
leftParen : Parser_ ()
leftParen =
P.symbol (P.Token "(" ExpectingLeftParen)
rightParen : Parser_ ()
rightParen =
P.symbol (P.Token ")" ExpectingRightParen)
literal : Parser_ LocatedExpr
literal =
P.oneOf
[ literalNumber
, literalChar
, doubleQuoteStartingLiteral String
, literalBool
]
type alias NumberConfig a =
{ int : Int -> a
, hex : Int -> a
, float : Float -> a
}
number : NumberConfig a -> Parser_ a
number config =
let
finalizeFloat : { hasParsedDot : Bool, parsedIntPart : Int } -> Parser_ a
finalizeFloat { hasParsedDot, parsedIntPart } =
{- Float is just whatever the integer was plus `.` (if not parsed
yet) and scientific notation (`e`)
-}
P.oneOf
[ -- dot+decimal digits, ie. 123.5 or 123.5e8
P.succeed identity
|. (if hasParsedDot then
P.succeed ()
else
dot
)
|= P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(\chompedDecimalDigits ->
case String.toInt chompedDecimalDigits of
Just decimalDigits ->
let
decimalLength =
String.length chompedDecimalDigits
scaledDecimalDigits : Float
scaledDecimalDigits =
{- TODO would it be better to (A) scale the integer
part up and adding non-scaled decimal part
instead of (B) scaling decimal part down and adding
to non-scaled integer part?
Ie. for 123.45:
(A) parsedIntPart = 123
decimalDigits = 45
scaledDecimalDigits = 0.45
intermediate result = 123.45
... scientific notation scaling happens ...
result = ...
(B) parsedIntPart = 123
decimalDigits = 45
scaledIntPart = 12300
intermediate result = 12345
... scientific notation scaling happens ...
result = ...
It seems like (B) would have less floating point
problems?
-}
toFloat decimalDigits * 10 ^ negate (toFloat decimalLength)
floatSoFar : Float
floatSoFar =
toFloat parsedIntPart + scaledDecimalDigits
in
P.oneOf
[ scientificNotation floatSoFar
, P.succeed (config.float floatSoFar)
]
Nothing ->
-- This probably only happens on empty string
P.problem FloatCannotEndWithDecimal
)
, -- no dot+decimal digits, eg. 123e5
scientificNotation (toFloat parsedIntPart)
, -- no dot+decimal digits, no `e`, eg. 123
P.succeed (config.int parsedIntPart)
]
scientificNotationE : Parser_ ()
scientificNotationE =
P.chompIf (\c -> c == 'e' || c == 'E') ExpectingScientificNotationE
scientificNotation : Float -> Parser_ a
scientificNotation floatSoFar =
P.succeed identity
|. scientificNotationE
|= P.oneOf
[ -- explicit '+' case
P.succeed identity
|. P.chompIf (\c -> c == '+') ExpectingScientificNotationPlus
|= P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(finalizeScientificNotation
{ floatSoFar = floatSoFar
, shouldNegate = False
}
)
, -- explicit '-' case
P.succeed identity
|. P.chompIf (\c -> c == '-') ExpectingScientificNotationMinus
|= P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(finalizeScientificNotation
{ floatSoFar = floatSoFar
, shouldNegate = True
}
)
, -- just a number
P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(finalizeScientificNotation
{ floatSoFar = floatSoFar
, shouldNegate = False
}
)
]
finalizeScientificNotation : { floatSoFar : Float, shouldNegate : Bool } -> String -> Parser_ a
finalizeScientificNotation { floatSoFar, shouldNegate } exponentDigits =
case String.toInt exponentDigits of
Nothing ->
P.problem ExpectingScientificNotationExponent
Just exponent ->
let
floatExponent =
toFloat exponent
exponent_ =
if shouldNegate then
negate floatExponent
else
floatExponent
in
P.succeed (config.float (floatSoFar * 10 ^ exponent_))
in
P.oneOf
[ P.succeed identity
|. P.symbol (P.Token "0" ExpectingZero)
|= P.oneOf
[ scientificNotationE
|> P.andThen (\() -> P.problem IntZeroCannotHaveScientificNotation)
, P.succeed identity
|. P.symbol (P.Token "x" ExpectingLowercaseX)
|= P.getChompedString (P.chompWhile Char.isHexDigit)
|> P.andThen
(\chompedHex ->
{- Usage of Hex.fromString saves us from checking
whether the string is empty.
-}
case Hex.fromString (String.toLower chompedHex) of
Err _ ->
P.problem (ParseCompilerBug ParsedHexButCouldntConvert)
Ok int ->
P.succeed (config.hex int)
)
, P.succeed identity
|. dot
|= finalizeFloat
{ hasParsedDot = True
, parsedIntPart = 0
}
, P.succeed identity
|= P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(\chompedInt ->
if String.isEmpty chompedInt then
P.succeed (config.int 0)
else
P.problem IntCannotStartWithZero
)
, -- TODO is this one needed?
P.succeed (config.int 0)
]
, P.succeed identity
|= P.getChompedString (P.chompWhile Char.isDigit)
|> P.andThen
(\chompedInt ->
case String.toInt chompedInt of
Nothing ->
if String.isEmpty chompedInt then
P.problem ExpectingNumber
else
P.problem (ParseCompilerBug ParsedIntButCouldntConvert)
Just int ->
finalizeFloat
{ hasParsedDot = False
, parsedIntPart = int
}
)
]
literalNumber : Parser_ LocatedExpr
literalNumber =
let
parseLiteralNumber =
number
{ int = Int
, hex = HexInt
, float = Float
}
negateLiteral toBeNegated =
case toBeNegated of
Int int ->
Int (negate int)
HexInt int ->
HexInt (negate int)
Float float ->
Float (negate float)
_ ->
toBeNegated
in
P.oneOf
[ P.succeed negateLiteral
|. P.symbol (P.Token "-" ExpectingMinusSign)
|= parseLiteralNumber
, parseLiteralNumber
]
|> P.inContext InNumber
|> located
type StringType
= {- ' -} CharString
| {- " -} NormalString
| {- """ -} MultilineString
canContinueChompingString : StringType -> Char -> Bool
canContinueChompingString stringType char =
case stringType of
CharString ->
char /= '\''
NormalString ->
char /= '"' && char /= '\\'
MultilineString ->
-- we'll have to check for the other two double-quotes afterwards
char /= '"' && char /= '\\'
areChompedCharsOk : StringType -> String -> Bool
areChompedCharsOk stringType string =
case stringType of
CharString ->
{- We could also check for the string only being 1 character long
but we need to convert from String to Char anyway later so it's
better done there. See `singleCharacter`.
-}
not <| String.contains "\n" string
NormalString ->
not <| String.contains "\n" string
MultilineString ->
True
apostrophe_ : P.Token ParseProblem
apostrophe_ =
P.Token "'" ExpectingApostrophe
doubleQuote_ : P.Token ParseProblem
doubleQuote_ =
P.Token "\"" ExpectingDoubleQuote
apostrophe : Parser_ ()
apostrophe =
P.symbol apostrophe_
doubleQuote : Parser_ ()
doubleQuote =
P.symbol doubleQuote_
singleCharacter : StringType -> Parser_ Char
singleCharacter stringType =
stringContents stringType
|> P.andThen
(\chars ->
case String.toList chars of
[ char ] ->
P.succeed char
_ ->
P.problem MoreThanOneCharInApostrophes
)
backslash : Parser_ ()
backslash =
P.token (P.Token "\\" ExpectingBackslash)
{-| Will chomp string contents (up to and including the string boundary,
ie. all three double-quotes for a multiline string).
-}
stringContents : StringType -> Parser_ String
stringContents stringType =
let
escapedChar : Parser_ String
escapedChar =
P.oneOf
[ P.map (\_ -> '\\') (P.token (P.Token "\\" (ExpectingEscapeCharacter '\\')))
, P.map (\_ -> '"') (P.token (P.Token "\"" (ExpectingEscapeCharacter '"'))) -- " (elm-vscode workaround)
, P.map (\_ -> '\'') (P.token (P.Token "'" (ExpectingEscapeCharacter '\'')))
, P.map (\_ -> '\n') (P.token (P.Token "n" (ExpectingEscapeCharacter 'n')))
, P.map (\_ -> '\t') (P.token (P.Token "t" (ExpectingEscapeCharacter 't')))
, P.map (\_ -> '\u{000D}') (P.token (P.Token "r" (ExpectingEscapeCharacter 'r')))
, P.succeed identity
|. P.token (P.Token "u" (ExpectingEscapeCharacter 'u'))
|. P.token (P.Token "{" ExpectingLeftBrace)
|= unicodeCharacter
|. P.token (P.Token "}" ExpectingRightBrace)
]
|> P.map String.fromChar
|> P.inContext InCharEscapeMode
help acc =
P.oneOf
[ -- escaped characters have priority
P.succeed (\char -> P.Loop (char :: acc))
|. backslash
|= escapedChar
, -- all other characters except the quote mode we're in (and sometimes except newlines)
P.succeed identity
|= P.getChompedString (P.chompWhile (canContinueChompingString stringType))
|> P.andThen
(\string ->
let
end =
P.succeed (P.Done (List.reverse (string :: acc)))
loopWithExtra extra =
P.succeed (P.Loop (extra :: string :: acc))
in
if areChompedCharsOk stringType string then
case stringType of