-
-
Notifications
You must be signed in to change notification settings - Fork 173
/
Parser.hs
2183 lines (1483 loc) · 43.8 KB
/
Parser.hs
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
{-# OPTIONS_GHC -Wno-unused-do-bind #-}
{-| This module translates @./dhall.abnf@ into a parser implemented using an
LL parser combinator package
This parser tries to hew as closely as possible to the ABNF grammar,
sometimes at the expense of efficiency. However, the efficiency is still
decent.
-}
module Parser
( -- * Type
Parser(..)
-- * Parser
, completeExpression
) where
import Control.Applicative (Alternative(..), optional)
import Control.Monad (MonadPlus(..), guard, replicateM)
import Crypto.Hash (Digest, SHA256)
import Data.ByteArray.Encoding (Base(..))
import Data.ByteString (ByteString)
import Data.Functor (void)
import Data.List.NonEmpty (NonEmpty(..))
import Data.String (IsString(..))
import Data.Fixed (Pico)
import Data.Ratio ((%))
import Data.Text (Text)
import Data.Void (Void)
import Numeric.Natural (Natural)
import Prelude hiding (exponent, takeWhile)
import Text.Megaparsec.Char (char)
import Syntax
( Builtin(..)
, Constant(..)
, Expression(..)
, File(..)
, FilePrefix(..)
, ImportMode(..)
, ImportType(..)
, Operator(..)
, Scheme(..)
, TextLiteral(..)
, URL(..)
, PathComponent(..)
)
import Text.Megaparsec
( MonadParsec
, Parsec
, count
, notFollowedBy
, satisfy
, takeWhileP
, takeWhile1P
, try
)
import qualified Control.Monad.Combinators.NonEmpty as Combinators.NonEmpty
import qualified Crypto.Hash as Hash
import qualified Data.ByteArray.Encoding as ByteArray.Encoding
import qualified Data.ByteString.Char8 as ByteString8
import qualified Data.ByteString.Base16 as Base16
import qualified Data.Char as Char
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Map as Map
import qualified Data.Scientific as Scientific
import qualified Data.Text as Text
import qualified Data.Text.Encoding as Text.Encoding
import qualified Data.Time as Time
import qualified Multiline
{-| @newtype@ wrapper around the `Parsec` type to improve inferred types and
error messages
-}
newtype Parser a = Parser { unParser :: Parsec Void Text a }
deriving
( Alternative
, Applicative
, Functor
, Monad
, MonadFail
, MonadParsec Void Text
, MonadPlus
, Monoid
, Semigroup
)
instance a ~ Text => IsString (Parser a) where
fromString x = Parser (fromString x)
between :: Char -> Char -> Char -> Bool
between lo hi c = lo <= c && c <= hi
takeWhile :: (Char -> Bool) -> Parser Text
takeWhile = takeWhileP Nothing
takeWhile1 :: (Char -> Bool) -> Parser Text
takeWhile1 = takeWhile1P Nothing
digitToNumber :: Char -> Int
digitToNumber c
| '0' <= c && c <= '9' = 0x0 + Char.ord c - Char.ord '0'
| 'A' <= c && c <= 'F' = 0xA + Char.ord c - Char.ord 'A'
| 'a' <= c && c <= 'f' = 0xa + Char.ord c - Char.ord 'a'
| otherwise = error "Invalid hexadecimal digit"
caseInsensitive :: Char -> Char -> Bool
caseInsensitive expected actual = Char.toUpper actual == expected
base :: Num n => [Char] -> n -> n
digits `base` b = foldl snoc 0 (map (fromIntegral . digitToNumber) digits)
where
snoc result number = result * b + number
atMost :: Int -> Parser a -> Parser [a]
atMost 0 _ = do
return []
atMost n parser = (do
x <- parser
xs <- atMost (n - 1) parser
return (x : xs) ) <|> return []
atLeast :: Int -> Parser a -> Parser [a]
atLeast lowerBound parser = do
prefix <- replicateM lowerBound parser
suffix <- many parser
return (prefix <> suffix)
range :: Int -> Int -> Parser a -> Parser [a]
range lowerBound upperBound parser = do
prefix <- replicateM lowerBound parser
suffix <- atMost (upperBound - lowerBound) parser
return (prefix <> suffix)
endOfLine :: Parser Text
endOfLine = "\n" <|> "\r\n"
validNonAscii :: Char -> Bool
validNonAscii c =
between '\x80' '\xD7FF' c
|| between '\xE000' '\xFFFD' c
|| between '\x10000' '\x1FFFD' c
|| between '\x20000' '\x2FFFD' c
|| between '\x30000' '\x3FFFD' c
|| between '\x40000' '\x4FFFD' c
|| between '\x50000' '\x5FFFD' c
|| between '\x60000' '\x6FFFD' c
|| between '\x70000' '\x7FFFD' c
|| between '\x80000' '\x8FFFD' c
|| between '\x90000' '\x9FFFD' c
|| between '\xA0000' '\xAFFFD' c
|| between '\xB0000' '\xBFFFD' c
|| between '\xC0000' '\xCFFFD' c
|| between '\xD0000' '\xDFFFD' c
|| between '\xE0000' '\xEFFFD' c
|| between '\xF0000' '\xFFFFD' c
|| between '\x100000' '\x10FFFD' c
tab :: Char
tab = '\t'
blockComment :: Parser ()
blockComment = do "{-"; blockCommentContinue
blockCommentChar :: Parser ()
blockCommentChar =
void (satisfy (between '\x20' '\x7F'))
<|> void (satisfy validNonAscii)
<|> void (char tab)
<|> void endOfLine
blockCommentContinue :: Parser ()
blockCommentContinue =
void "-}"
<|> (do blockComment; blockCommentContinue)
<|> (do blockCommentChar; blockCommentContinue)
notEndOfLine :: Parser ()
notEndOfLine = void (satisfy predicate)
where
predicate c =
between '\x20' '\x7F' c
|| validNonAscii c
|| tab == c
lineCommentPrefix :: Parser ()
lineCommentPrefix = do "--"; many notEndOfLine; return ()
lineComment :: Parser ()
lineComment = try (do lineCommentPrefix; endOfLine; return ())
whitespaceChunk :: Parser ()
whitespaceChunk =
void " "
<|> void (char tab)
<|> void endOfLine
<|> lineComment
<|> blockComment
whsp :: Parser ()
whsp = void (many whitespaceChunk)
whsp1 :: Parser ()
whsp1 = void (some whitespaceChunk)
alpha :: Char -> Bool
alpha c = between '\x41' '\x5A' c || between '\x61' '\x7A' c
digit :: Char -> Bool
digit = between '\x30' '\x39'
alphaNum :: Char -> Bool
alphaNum c = alpha c || digit c
hexUpTo :: Char -> Char -> Bool
hexUpTo upperBound c = digit c || between 'A' upperBound (Char.toUpper c)
hexDig :: Char -> Bool
hexDig = hexUpTo 'F'
simpleLabelFirstChar :: Char -> Bool
simpleLabelFirstChar c = alpha c || c == '_'
simpleLabelNextChar :: Char -> Bool
simpleLabelNextChar c = alphaNum c || c `elem` [ '-', '/', '_' ]
simpleLabel :: Parser Text
simpleLabel = try do
first <- satisfy simpleLabelFirstChar
rest <- takeWhile simpleLabelNextChar
let l = Text.cons first rest
guard (l `notElem` reservedKeywords)
return l
quotedLabelChar :: Char -> Bool
quotedLabelChar c = between '\x20' '\x5F' c || between '\x61' '\x7E' c
quotedLabel :: Parser Text
quotedLabel = takeWhile quotedLabelChar
label :: Parser Text
label = (do "`"; l <- quotedLabel; "`"; return l)
<|> simpleLabel
nonreservedLabel :: Parser Text
nonreservedLabel = do
notFollowedBy do
void builtin <|> void constant <|> keyword
notFollowedBy (satisfy simpleLabelNextChar)
label
anyLabel :: Parser Text
anyLabel = label
anyLabelOrSome :: Parser Text
anyLabelOrSome = anyLabel <|> "Some"
withComponent :: Parser PathComponent
withComponent = (Label <$> anyLabelOrSome) <|> (DescendOptional <$ "?")
doubleQuoteChunk :: Parser TextLiteral
doubleQuoteChunk =
interpolation
<|> (do char '\x5C';
c <- doubleQuoteEscaped;
return (Chunks [] (Text.singleton c))
)
<|> (do c <- satisfy doubleQuoteChar
return (Chunks [] (Text.singleton c))
)
doubleQuoteEscaped :: Parser Char
doubleQuoteEscaped = do
(do "\""; return '"' )
<|> (do "$" ; return '$' )
<|> (do "\\"; return '\\')
<|> (do "/" ; return '/' )
<|> (do "b" ; return '\b')
<|> (do "f" ; return '\f')
<|> (do "n" ; return '\n')
<|> (do "r" ; return '\r')
<|> (do "t" ; return '\t')
<|> (do "u"; unicodeEscape)
unicodeEscape :: Parser Char
unicodeEscape = do
number <- unbracedEscape <|> (do "{"; c <- bracedEscape; "}"; return c)
return (Char.chr number)
unicodeSuffix :: Parser Int
unicodeSuffix = beginsWithoutF <|> beginsWithF
where
beginsWithoutF = do
digit0 <- satisfy (hexUpTo 'E')
digits1 <- replicateM 3 (satisfy hexDig)
return ((digit0 : digits1) `base` 16)
beginsWithF = do
digit0 <- satisfy (caseInsensitive 'F')
digits1 <- replicateM 2 (satisfy hexDig)
digit2 <- satisfy (hexUpTo 'D')
return ((digit0 : digits1 <> [ digit2 ]) `base` 16)
unbracedEscape :: Parser Int
unbracedEscape = beginsUpToC <|> beginsWithD <|> beginsWithE <|> beginsWithF
where
beginsUpToC = do
digit0 <- satisfy (hexUpTo 'C')
digits1 <- replicateM 3 (satisfy hexDig)
return ((digit0 : digits1) `base` 16)
beginsWithD = do
digit0 <- satisfy (caseInsensitive 'D')
digit1 <- satisfy (between '0' '7')
digits2 <- replicateM 2 (satisfy hexDig)
return ((digit0 : digit1 : digits2) `base` 16)
beginsWithE = do
digit0 <- satisfy (caseInsensitive 'E')
digits1 <- replicateM 3 (satisfy hexDig)
return ((digit0 : digits1) `base` 16)
beginsWithF = do
digit0 <- satisfy (caseInsensitive 'F')
digits1 <- replicateM 2 (satisfy hexDig)
digit2 <- satisfy (hexUpTo 'D')
return ((digit0 : digits1 <> [ digit2 ]) `base` 16)
bracedCodepoint :: Parser Int
bracedCodepoint = planes1Through16 <|> unbracedEscape <|> threeDigits
where
planes1Through16 = do
prefix <- fmap digitToNumber (satisfy hexDig) <|> (do "10"; return 16)
suffix <- unicodeSuffix
return (prefix * 0x10000 + suffix)
threeDigits = do
digits <- range 1 3 (satisfy hexDig)
return (digits `base` 16)
bracedEscape :: Parser Int
bracedEscape = do
takeWhile (== '0')
bracedCodepoint
doubleQuoteChar :: Char -> Bool
doubleQuoteChar c = do
between '\x20' '\x21' c
|| between '\x23' '\x5B' c
|| between '\x5D' '\x7F' c
|| validNonAscii c
doubleQuoteLiteral :: Parser TextLiteral
doubleQuoteLiteral = do
char '"'
chunks <- many doubleQuoteChunk
char '"'
return (mconcat chunks)
singleQuoteContinue :: Parser TextLiteral
singleQuoteContinue =
(interpolation <> singleQuoteContinue)
<|> (escapedQuotePair <> singleQuoteContinue)
<|> (escapedInterpolation <> singleQuoteContinue)
<|> (do "''"; return mempty)
<|> (singleQuoteChar <> singleQuoteContinue)
escapedQuotePair :: Parser TextLiteral
escapedQuotePair = do "'''"; return (Chunks [] "''")
escapedInterpolation :: Parser TextLiteral
escapedInterpolation = do
"''${"
return (Chunks [] "${")
singleQuoteChar :: Parser TextLiteral
singleQuoteChar =
(do c <- satisfy predicate
return (Chunks [] (Text.singleton c))
)
<|> (do t <- endOfLine
return (Chunks [] t)
)
where
predicate c =
between '\x20' '\x7F' c
|| validNonAscii c
|| tab == c
singleQuoteLiteral :: Parser TextLiteral
singleQuoteLiteral = do
"''"
endOfLine
contents <- singleQuoteContinue
return (Multiline.toDoubleQuotes contents)
interpolation :: Parser TextLiteral
interpolation = do
"${"
e <- completeExpression
"}"
return (Chunks [("", e)] "")
textLiteral :: Parser TextLiteral
textLiteral = doubleQuoteLiteral <|> singleQuoteLiteral
bytesLiteral :: Parser ByteString
bytesLiteral = hexadecimal
where
hexadecimal = do
"0x\""
chunks <- many (count 2 (satisfy hexDig))
char '"'
case Base16.decodeBase16 $ ByteString8.pack $ concat chunks of
Left e -> fail $ Text.unpack e
Right bytes -> return bytes
reservedKeywords :: [Text]
reservedKeywords =
[ "if"
, "then"
, "else"
, "let"
, "in"
, "using"
, "missing"
, "assert"
, "as"
, "Infinity"
, "NaN"
, "merge"
, "Some"
, "toMap"
, "forall"
, "with"
, "showConstructor"
]
keyword :: Parser ()
keyword =
if_
<|> then_
<|> else_
<|> let_
<|> in_
<|> using
<|> void missing
<|> assert
<|> as
<|> _Infinity
<|> _NaN
<|> merge
<|> _Some
<|> toMap
<|> forallKeyword
<|> with
<|> showConstructor
if_ :: Parser ()
if_ = void "if"
then_ :: Parser ()
then_ = void "then"
else_ :: Parser ()
else_ = void "else"
let_ :: Parser ()
let_ = void "let"
in_ :: Parser ()
in_ = void "in"
as :: Parser ()
as = void "as"
using :: Parser ()
using = void "using"
merge :: Parser ()
merge = void "merge"
missing :: Parser ImportType
missing = try do
"missing"
notFollowedBy (satisfy simpleLabelNextChar)
return Missing
_Infinity :: Parser ()
_Infinity = void "Infinity"
_NaN :: Parser ()
_NaN = void "NaN"
_Some :: Parser ()
_Some = void "Some"
toMap :: Parser ()
toMap = void "toMap"
assert :: Parser ()
assert = void "assert"
forallKeyword :: Parser ()
forallKeyword = void "forall"
forallSymbol :: Parser ()
forallSymbol = void "∀"
forall_ :: Parser ()
forall_ = forallSymbol <|> forallKeyword
with :: Parser ()
with = void "with"
showConstructor :: Parser ()
showConstructor = void "showConstructor"
builtin :: Parser Builtin
builtin =
_NaturalFold
<|> _NaturalBuild
<|> _NaturalIsZero
<|> _NaturalEven
<|> _NaturalOdd
<|> _NaturalToInteger
<|> _NaturalShow
<|> _IntegerToDouble
<|> _IntegerShow
<|> _IntegerNegate
<|> _IntegerClamp
<|> _NaturalSubtract
<|> _DoubleShow
<|> _ListBuild
<|> _ListFold
<|> _ListLength
<|> _ListHead
<|> _ListLast
<|> _ListIndexed
<|> _ListReverse
<|> _TextShow
<|> _TextReplace
<|> _DateShow
<|> _TimeShow
<|> _TimeZoneShow
<|> _Bool
<|> _True
<|> _False
<|> _Optional
<|> _None
<|> _Natural
<|> _Integer
<|> _Double
<|> _Text
<|> _Bytes
<|> _List
<|> _Date
<|> _TimeZone
<|> _Time
_NaturalFold :: Parser Builtin
_NaturalFold = do "Natural/fold"; return NaturalFold
_NaturalBuild :: Parser Builtin
_NaturalBuild = do "Natural/build"; return NaturalBuild
_NaturalIsZero :: Parser Builtin
_NaturalIsZero = do "Natural/isZero"; return NaturalIsZero
_NaturalEven :: Parser Builtin
_NaturalEven = do "Natural/even"; return NaturalEven
_NaturalOdd :: Parser Builtin
_NaturalOdd = do "Natural/odd"; return NaturalOdd
_NaturalToInteger :: Parser Builtin
_NaturalToInteger = do "Natural/toInteger"; return NaturalToInteger
_NaturalShow :: Parser Builtin
_NaturalShow = do "Natural/show"; return NaturalShow
_IntegerToDouble :: Parser Builtin
_IntegerToDouble = do "Integer/toDouble"; return IntegerToDouble
_IntegerShow :: Parser Builtin
_IntegerShow = do "Integer/show"; return IntegerShow
_IntegerNegate :: Parser Builtin
_IntegerNegate = do "Integer/negate"; return IntegerNegate
_IntegerClamp :: Parser Builtin
_IntegerClamp = do "Integer/clamp"; return IntegerClamp
_NaturalSubtract :: Parser Builtin
_NaturalSubtract = do "Natural/subtract"; return NaturalSubtract
_DoubleShow :: Parser Builtin
_DoubleShow = do "Double/show"; return DoubleShow
_ListBuild :: Parser Builtin
_ListBuild = do "List/build"; return ListBuild
_ListFold :: Parser Builtin
_ListFold = do "List/fold"; return ListFold
_ListLength :: Parser Builtin
_ListLength = do "List/length"; return ListLength
_ListHead :: Parser Builtin
_ListHead = do "List/head"; return ListHead
_ListLast :: Parser Builtin
_ListLast = do "List/last"; return ListLast
_ListIndexed :: Parser Builtin
_ListIndexed = do "List/indexed"; return ListIndexed
_ListReverse :: Parser Builtin
_ListReverse = do "List/reverse"; return ListReverse
_TextShow :: Parser Builtin
_TextShow = do "Text/show"; return TextShow
_TextReplace :: Parser Builtin
_TextReplace = do "Text/replace"; return TextReplace
_DateShow :: Parser Builtin
_DateShow = do "Date/show"; return DateShow
_TimeShow :: Parser Builtin
_TimeShow = do "Time/show"; return TimeShow
_TimeZoneShow :: Parser Builtin
_TimeZoneShow = do "TimeZone/show"; return TimeZoneShow
_Bool :: Parser Builtin
_Bool = do "Bool"; return Bool
_True :: Parser Builtin
_True = do "True"; return Syntax.True
_False :: Parser Builtin
_False = do "False"; return Syntax.False
_Optional :: Parser Builtin
_Optional = do "Optional"; return Optional
_None :: Parser Builtin
_None = do "None"; return None
_Natural :: Parser Builtin
_Natural = do "Natural"; return Natural
_Integer :: Parser Builtin
_Integer = do "Integer"; return Integer
_Double :: Parser Builtin
_Double = do "Double"; return Double
_Text :: Parser Builtin
_Text = do "Text"; return Text
_Bytes :: Parser Builtin
_Bytes = do "Bytes"; return Bytes
_List :: Parser Builtin
_List = do "List"; return List
_Date :: Parser Builtin
_Date = do "Date"; return Date
_Time :: Parser Builtin
_Time = do "Time"; return Time
_TimeZone :: Parser Builtin
_TimeZone = do "TimeZone"; return TimeZone
_Location :: Parser ()
_Location = void "Location"
constant :: Parser Constant
constant =
_Type
<|> _Kind
<|> _Sort
_Type :: Parser Constant
_Type = do "Type"; return Type
_Kind :: Parser Constant
_Kind = do "Kind"; return Kind
_Sort :: Parser Constant
_Sort = do "Sort"; return Sort
combine :: Parser Operator
combine = do "∧" <|> "/\\"; return CombineRecordTerms
combineTypes :: Parser Operator
combineTypes = do "⩓" <|> "//\\\\"; return CombineRecordTypes
equivalent :: Parser Operator
equivalent = do "≡" <|> "==="; return Equivalent
prefer :: Parser Operator
prefer = do "⫽" <|> "//"; return Prefer
lambda :: Parser ()
lambda = do "λ" <|> "\\"; return ()
arrow :: Parser ()
arrow = do "→" <|> "->"; return ()
complete :: Parser ()
complete = do "::"; return ()
sign :: Num n => Parser (n -> n)
sign = (do "+"; return id) <|> (do "-"; return negate)
exponent :: Parser Int
exponent = do
"e"
s <- sign <|> pure id
digits <- atLeast 1 (satisfy digit)
return (s (digits `base` 10))
numericDoubleLiteral :: Parser Double
numericDoubleLiteral = do
s <- sign <|> pure id
digits0 <- atLeast 1 (satisfy digit)
let withRadix = do
"."
digits1 <- atLeast 1 (satisfy digit)
e <- exponent <|> pure 0
let c = s ((digits0 <> digits1) `base` 10)
return (Scientific.toRealFloat (Scientific.scientific c (e - length digits1)))
let withoutRadix = do
e <- exponent
let c = s (fromInteger (digits0 `base` 10))
return (Scientific.toRealFloat (Scientific.scientific c e))
withRadix <|> withoutRadix
minusInfinityLiteral :: Parser Double
minusInfinityLiteral = do
"-"
_Infinity
return (-1/0)
plusInfinityLiteral :: Parser Double
plusInfinityLiteral = do
_Infinity
return (1/0)
doubleLiteral :: Parser Double
doubleLiteral =
try minusInfinityLiteral
<|> plusInfinityLiteral
<|> (do _NaN; return (0/0))
<|> numericDoubleLiteral
naturalLiteral :: Parser Natural
naturalLiteral = binary <|> hexadecimal <|> decimal <|> zero
where
binary = do
"0b"
digits <- atLeast 1 (satisfy $ between '0' '1')
return (digits `base` 2)
hexadecimal = do
"0x"
digits <- atLeast 1 (satisfy hexDig)
return (digits `base` 16)
decimal = do
digit0 <- satisfy (between '1' '9')
digits1 <- many (satisfy digit)
return ((digit0 : digits1) `base` 10)
zero = do
"0"
return 0
integerLiteral :: Parser Integer
integerLiteral = do
s <- sign
n <- naturalLiteral
return (s (fromIntegral n))
temporalLiteral :: Parser Expression
temporalLiteral =
try (do
date <- fullDate
"T" <|> "t"
time <- partialTime
timeZone <- timeOffset
return
(RecordLiteral
[ ("date" , date)
, ("time" , time)
, ("timeZone", timeZone)
]
)
)
<|> try (do
date <- fullDate
"T" <|> "t"
time <- partialTime
return
(RecordLiteral
[ ("date", date)
, ("time", time)
]
)
)
<|> try (do
time <- partialTime
timeZone <- timeOffset
return
(RecordLiteral
[ ("time" , time)
, ("timeZone", timeZone)
]
)
)
<|> try fullDate
<|> try partialTime
<|> try timeNumOffset
dateFullYear :: Parser Integer
dateFullYear = do
digits <- replicateM 4 (satisfy digit)
return (digits `base` 10)
dateMonth :: Parser Int
dateMonth = do
digits <- replicateM 2 (satisfy digit)
let month = digits `base` 10
if 1 <= month && month <= 12
then return month
else fail "Invalid month"
dateMday :: Parser Int
dateMday = do
digits <- replicateM 2 (satisfy digit)
let day = digits `base` 10
if 1 <= day && day <= 31
then return day
else fail "Invalid day"
timeHour :: Parser Int
timeHour = do
digits <- replicateM 2 (satisfy digit)
let hour = digits `base` 10
if 0 <= hour && hour < 24
then return hour
else fail "Invalid hour"
timeMinute :: Parser Int
timeMinute = do
digits <- replicateM 2 (satisfy digit)
let minute = digits `base` 10
if 0 <= minute && minute < 60
then return minute
else fail "Invalid minute"
timeSecond :: Parser Pico
timeSecond = do
digits <- replicateM 2 (satisfy digit)
let second = digits `base` 10
if 0 <= second && second < 60
then return second
else fail "Invalid second"
timeSecFrac :: Parser (Pico, Int)
timeSecFrac = do
"."
digits <- some (satisfy digit)
let precision = length digits
return (fromRational ((digits `base` 10) % (10 ^ precision)), precision)
timeNumOffset :: Parser Expression
timeNumOffset = do
s <- sign
hour <- timeHour
":"
minute <- timeMinute
let minutes = s (hour * 60 + minute)
return (TimeZoneLiteral (Time.TimeZone minutes Prelude.False ""))
timeOffset :: Parser Expression
timeOffset =
(do "Z"
return (TimeZoneLiteral (Time.TimeZone 0 Prelude.False ""))