-
Notifications
You must be signed in to change notification settings - Fork 33
/
Parser.hs
658 lines (492 loc) · 21.6 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
{-# LANGUAGE ApplicativeDo #-}
{-# LANGUAGE BlockArguments #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE NamedFieldPuns #-}
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE RecordWildCards #-}
{-# LANGUAGE RecursiveDo #-}
{-| This module contains the logic for parsing Grace files using @Earley@.
The main reason for not using @attoparsec@ or @megaparsec@ is because
LR parsers are easier to maintain due to not needing to left-factor the
grammar.
The main reason for not using @happy@ is because it uses a separate code
generation step, which leads to worse type errors and poor support for
interactive type-checking.
-}
module Grace.Parser
( -- * Parsing
parse
-- * Errors related to parsing
, ParseError(..)
) where
import Control.Applicative (many, optional, some, (<|>))
import Control.Applicative.Combinators (endBy, sepBy)
import Control.Applicative.Combinators.NonEmpty (sepBy1)
import Data.Functor (void, ($>))
import Data.List.NonEmpty (NonEmpty(..), some1)
import Data.Scientific (Scientific)
import Data.Text (Text)
import Grace.Input (Input(..))
import Grace.Lexer (LocatedToken(LocatedToken), ParseError(..), Token)
import Grace.Location (Location(..), Offset(..))
import Grace.Syntax (Binding(..), Syntax(..))
import Grace.Type (Type(..))
import Text.Earley (Grammar, Prod, Report(..), rule, (<?>))
import qualified Data.List.NonEmpty as NonEmpty
import qualified Data.Sequence as Seq
import qualified Data.Text as Text
import qualified Grace.Domain as Domain
import qualified Grace.Lexer as Lexer
import qualified Grace.Monotype as Monotype
import qualified Grace.Syntax as Syntax
import qualified Grace.Type as Type
import qualified Text.Earley as Earley
import qualified Text.URI as URI
type Parser r = Prod r Text LocatedToken
matchLabel :: Token -> Maybe Text
matchLabel (Lexer.Label l) = Just l
matchLabel _ = Nothing
matchAlternative :: Token -> Maybe Text
matchAlternative (Lexer.Alternative a) = Just a
matchAlternative _ = Nothing
matchReal :: Token -> Maybe Scientific
matchReal (Lexer.RealLiteral n) = Just n
matchReal _ = Nothing
matchInt :: Token -> Maybe Int
matchInt (Lexer.Int n) = Just n
matchInt _ = Nothing
matchText :: Token -> Maybe Text
matchText (Lexer.TextLiteral t) = Just t
matchText _ = Nothing
matchFile :: Token -> Maybe FilePath
matchFile (Lexer.File f) = Just f
matchFile _ = Nothing
matchURI :: Token -> Maybe URI.URI
matchURI (Lexer.URI t) = Just t
matchURI _ = Nothing
terminal :: (Token -> Maybe a) -> Parser r a
terminal match = Earley.terminal match'
where
match' locatedToken_ = match (Lexer.token locatedToken_)
label :: Parser r Text
label = terminal matchLabel
alternative :: Parser r Text
alternative = terminal matchAlternative
int :: Parser r Int
int = terminal matchInt
text :: Parser r Text
text = terminal matchText
token :: Token -> Parser r ()
token t = void (Earley.satisfy predicate <?> render t)
where
predicate locatedToken_ = Lexer.token locatedToken_ == t
locatedTerminal :: (Token -> Maybe a) -> Parser r (Offset, a)
locatedTerminal match = Earley.terminal match'
where
match' locatedToken_@LocatedToken{ start } = do
a <- match (Lexer.token locatedToken_)
return (start, a)
locatedLabel :: Parser r (Offset, Text)
locatedLabel = locatedTerminal matchLabel
locatedAlternative :: Parser r (Offset, Text)
locatedAlternative = locatedTerminal matchAlternative
locatedReal :: Parser r (Offset, Scientific)
locatedReal = locatedTerminal matchReal
locatedInt :: Parser r (Offset, Int)
locatedInt = locatedTerminal matchInt
locatedText :: Parser r (Offset, Text)
locatedText = locatedTerminal matchText
locatedFile :: Parser r (Offset, FilePath)
locatedFile = locatedTerminal matchFile
locatedURI :: Parser r (Offset, URI.URI)
locatedURI = locatedTerminal matchURI
locatedToken :: Token -> Parser r Offset
locatedToken expectedToken =
Earley.terminal capture <?> render expectedToken
where
capture LocatedToken{ Lexer.token = actualToken, .. }
| expectedToken == actualToken = Just start
| otherwise = Nothing
-- | This render function is currently never used since `Location.renderError`
-- does not display expected tokens at all, but I maintain this anyway in
-- case someone wants to modify the code to display them.
render :: Token -> Text
render t = case t of
Lexer.Alternative _ -> "an alternative"
Lexer.Alternatives -> "Alternatives"
Lexer.And -> "&&"
Lexer.Arrow -> "->"
Lexer.At -> "@"
Lexer.Bar -> "|"
Lexer.Bool -> "Bool"
Lexer.CloseAngle -> ">"
Lexer.CloseBrace -> "}"
Lexer.CloseBracket -> "]"
Lexer.CloseParenthesis -> ")"
Lexer.Colon -> ":"
Lexer.Comma -> ","
Lexer.Dash -> "-"
Lexer.Dot -> "."
Lexer.Real -> "Real"
Lexer.RealLiteral _ -> "a real number literal"
Lexer.RealEqual -> "Real/equal"
Lexer.RealLessThan -> "Real/lessThan"
Lexer.RealNegate -> "Real/negate"
Lexer.RealShow -> "Real/show"
Lexer.Else -> "else"
Lexer.Equals -> "="
Lexer.Exists -> "exists"
Lexer.False_ -> "False"
Lexer.Fields -> "Fields"
Lexer.File _ -> "a file"
Lexer.Forall -> "forall"
Lexer.If -> "if"
Lexer.In -> "in"
Lexer.Int _ -> "an integer literal"
Lexer.Integer -> "Integer"
Lexer.IntegerAbs -> "Integer/clamp"
Lexer.IntegerEven -> "Integer/even"
Lexer.IntegerNegate -> "Integer/negate"
Lexer.IntegerOdd -> "Integer/odd"
Lexer.JSON -> "JSON"
Lexer.JSONFold -> "JSON/fold"
Lexer.Label _ -> "a label"
Lexer.Lambda -> "\\"
Lexer.Let -> "let"
Lexer.List -> "list"
Lexer.ListDrop -> "List/drop"
Lexer.ListEqual -> "List/equal"
Lexer.ListFold -> "List/fold"
Lexer.ListHead -> "List/head"
Lexer.ListIndexed -> "List/indexed"
Lexer.ListLast -> "List/last"
Lexer.ListLength -> "List/length"
Lexer.ListMap -> "List/map"
Lexer.ListReverse -> "List/reverse"
Lexer.ListTake -> "List/take"
Lexer.Merge -> "merge"
Lexer.Natural -> "Natural"
Lexer.NaturalFold -> "Natural/fold"
Lexer.Null -> "null"
Lexer.OpenAngle -> "<"
Lexer.OpenBrace -> "{"
Lexer.OpenBracket -> "<"
Lexer.OpenParenthesis -> "("
Lexer.Optional -> "List"
Lexer.Or -> "||"
Lexer.Plus -> "+"
Lexer.Text -> "Text"
Lexer.TextEqual -> "Text/equal"
Lexer.TextLiteral _ -> "a text literal"
Lexer.Then -> "then"
Lexer.Type -> "Type"
Lexer.Times -> "*"
Lexer.True_ -> "True"
Lexer.URI _ -> "a URI"
grammar :: Grammar r (Parser r (Syntax Offset Input))
grammar = mdo
expression <- rule
( do location <- locatedToken Lexer.Lambda
locatedNames <- some1 locatedLabel
token Lexer.Arrow
body0 <- expression
return do
let cons (nameLocation, name) body = Syntax.Lambda{..}
foldr cons body0 locatedNames
<|> do bindings <- some1 binding
token Lexer.In
body <- expression
return do
let Syntax.Binding{ nameLocation = location } =
NonEmpty.head bindings
Syntax.Let{..}
<|> do location <- locatedToken Lexer.If
predicate <- expression
token Lexer.Then
ifTrue <- expression
token Lexer.Else
ifFalse <- expression
return Syntax.If{..}
<|> do annotated <- operatorExpression
token Lexer.Colon
annotation <- quantifiedType
return Syntax.Annotation
{ location = Syntax.location annotated
, ..
}
<|> do operatorExpression
)
operatorExpression <- rule plusExpression
let op token_ operator subExpression = do
let snoc left (operatorLocation, right) =
Syntax.Operator{ location = Syntax.location left, ..}
e0 <- subExpression
ses <- many do
s <- locatedToken token_
e <- subExpression;
return (s, e)
return (foldl snoc e0 ses)
plusExpression <- rule (op Lexer.Plus Syntax.Plus timesExpression)
timesExpression <- rule (op Lexer.Times Syntax.Times orExpression)
orExpression <- rule (op Lexer.Or Syntax.Or andExpression)
andExpression <- rule (op Lexer.And Syntax.And applicationExpression)
let application function argument =
Syntax.Application{ location = Syntax.location function, .. }
applicationExpression <- rule
( do es <- some1 fieldExpression
return (foldl application (NonEmpty.head es) (NonEmpty.tail es))
<|> do location <- locatedToken Lexer.Merge
~(handlers :| es) <- some1 fieldExpression
return do
let nil = Syntax.Merge{..}
foldl application nil es
)
fieldExpression <- rule do
let snoc record0 record (fieldLocation, field) =
Syntax.Field{ location = Syntax.location record0, .. }
record <- primitiveExpression
fields <- many (do token Lexer.Dot; l <- locatedRecordLabel; return l)
return (foldl (snoc record) record fields)
primitiveExpression <- rule
( do ~(location, name) <- locatedLabel
return Syntax.Variable{ index = 0, .. }
<|> do ~(location, name) <- locatedLabel
token Lexer.At
index <- int
return Syntax.Variable{..}
<|> do ~(location, name) <- locatedAlternative
return Syntax.Alternative{..}
<|> do location <- locatedToken Lexer.OpenBracket
optional (token Lexer.Comma)
elements <- expression `sepBy` token Lexer.Comma
optional (token Lexer.Comma)
token Lexer.CloseBracket
return Syntax.List{ elements = Seq.fromList elements, .. }
<|> do location <- locatedToken Lexer.OpenBrace
optional (token Lexer.Comma)
fieldValues <- fieldValue `sepBy` token Lexer.Comma
optional (token Lexer.Comma)
token Lexer.CloseBrace
return Syntax.Record{..}
<|> do location <- locatedToken Lexer.True_
return Syntax.Scalar{ scalar = Syntax.Bool True, .. }
<|> do location <- locatedToken Lexer.False_
return Syntax.Scalar{ scalar = Syntax.Bool False, .. }
<|> do location <- locatedToken Lexer.Null
return Syntax.Scalar{ scalar = Syntax.Null, .. }
<|> do sign <- (token Lexer.Dash $> negate) <|> pure id
~(location, n) <- locatedReal
return Syntax.Scalar{ scalar = Syntax.Real (sign n), .. }
<|> do token Lexer.Dash
~(location, n) <- locatedInt
return Syntax.Scalar
{ scalar = Syntax.Integer (fromIntegral (negate n))
, ..
}
<|> do ~(location, n) <- locatedInt
return Syntax.Scalar
{ scalar = Syntax.Natural (fromIntegral n)
, ..
}
<|> do location <- locatedToken Lexer.RealEqual
return Syntax.Builtin{ builtin = Syntax.RealEqual, .. }
<|> do location <- locatedToken Lexer.RealLessThan
return Syntax.Builtin{ builtin = Syntax.RealLessThan, .. }
<|> do location <- locatedToken Lexer.RealNegate
return Syntax.Builtin{ builtin = Syntax.RealNegate, .. }
<|> do location <- locatedToken Lexer.RealShow
return Syntax.Builtin{ builtin = Syntax.RealShow, .. }
<|> do location <- locatedToken Lexer.ListDrop
return Syntax.Builtin{ builtin = Syntax.ListDrop, .. }
<|> do location <- locatedToken Lexer.ListEqual
return Syntax.Builtin{ builtin = Syntax.ListEqual, .. }
<|> do location <- locatedToken Lexer.ListFold
return Syntax.Builtin{ builtin = Syntax.ListFold, .. }
<|> do location <- locatedToken Lexer.ListHead
return Syntax.Builtin{ builtin = Syntax.ListHead, .. }
<|> do location <- locatedToken Lexer.ListIndexed
return Syntax.Builtin{ builtin = Syntax.ListIndexed, .. }
<|> do location <- locatedToken Lexer.ListLast
return Syntax.Builtin{ builtin = Syntax.ListLast, .. }
<|> do location <- locatedToken Lexer.ListLength
return Syntax.Builtin{ builtin = Syntax.ListLength, .. }
<|> do location <- locatedToken Lexer.ListMap
return Syntax.Builtin{ builtin = Syntax.ListMap, .. }
<|> do location <- locatedToken Lexer.ListReverse
return Syntax.Builtin{ builtin = Syntax.ListReverse, .. }
<|> do location <- locatedToken Lexer.ListTake
return Syntax.Builtin{ builtin = Syntax.ListTake, .. }
<|> do location <- locatedToken Lexer.IntegerAbs
return Syntax.Builtin{ builtin = Syntax.IntegerAbs, .. }
<|> do location <- locatedToken Lexer.IntegerEven
return Syntax.Builtin{ builtin = Syntax.IntegerEven, .. }
<|> do location <- locatedToken Lexer.IntegerNegate
return Syntax.Builtin{ builtin = Syntax.IntegerNegate, .. }
<|> do location <- locatedToken Lexer.IntegerOdd
return Syntax.Builtin{ builtin = Syntax.IntegerOdd, .. }
<|> do location <- locatedToken Lexer.JSONFold
return Syntax.Builtin{ builtin = Syntax.JSONFold, .. }
<|> do location <- locatedToken Lexer.NaturalFold
return Syntax.Builtin{ builtin = Syntax.NaturalFold, .. }
<|> do location <- locatedToken Lexer.TextEqual
return Syntax.Builtin{ builtin = Syntax.TextEqual, .. }
<|> do ~(location, t) <- locatedText
return Syntax.Scalar{ scalar = Syntax.Text t, .. }
<|> do ~(location, file) <- locatedFile
return Syntax.Embed{ embedded = Path file, .. }
<|> do ~(location, uri) <- locatedURI
return Syntax.Embed{ embedded = URI uri, .. }
<|> do token Lexer.OpenParenthesis
e <- expression
token Lexer.CloseParenthesis
return e
)
binding <- rule
( do nameLocation <- locatedToken Lexer.Let
name <- label
token Lexer.Equals
assignment <- expression
return do
let annotation = Nothing
Syntax.Binding{..}
<|> do nameLocation <- locatedToken Lexer.Let
name <- label
token Lexer.Colon
annotation <- fmap Just quantifiedType
token Lexer.Equals
assignment <- expression
return Syntax.Binding{..}
)
recordLabel <- rule (label <|> alternative <|> text)
locatedRecordLabel <- rule (locatedLabel <|> locatedText)
fieldValue <- rule do
field <- recordLabel
token Lexer.Colon
value <- expression
return (field, value)
domain <- rule
( do token Lexer.Type
return Domain.Type
<|> do token Lexer.Fields
return Domain.Fields
<|> do token Lexer.Alternatives
return Domain.Alternatives
)
quantifiedType <- rule do
let quantify (forallOrExists, location, (typeVariableOffset, typeVariable), domain_) type_ =
forallOrExists location typeVariableOffset typeVariable domain_ type_
fss <- many
( do location <- locatedToken Lexer.Forall
fs <- some do
token Lexer.OpenParenthesis
locatedTypeVariable <- locatedLabel
token Lexer.Colon
domain_ <- domain
token Lexer.CloseParenthesis
return \location_ -> quantify (Type.Forall, location_, locatedTypeVariable, domain_)
token Lexer.Dot
return (map ($ location) fs)
<|> do location <- locatedToken Lexer.Exists
fs <- some do
token Lexer.OpenParenthesis
locatedTypeVariable <- locatedLabel
token Lexer.Colon
domain_ <- domain
token Lexer.CloseParenthesis
return \location_ -> quantify (Type.Exists, location_, locatedTypeVariable, domain_)
token Lexer.Dot
return (map ($ location) fs)
)
t <- functionType
return (foldr ($) t (concat fss))
functionType <- rule do
let function input output =
Type.Function{ location = Type.location input, ..}
ts <- applicationType `sepBy1` token Lexer.Arrow
return (foldr function (NonEmpty.last ts) (NonEmpty.init ts))
applicationType <- rule
( do location <- locatedToken Lexer.List
type_ <- primitiveType
return Type.List{..}
<|> do location <- locatedToken Lexer.Optional
type_ <- primitiveType
return Type.Optional{..}
<|> do primitiveType
)
primitiveType <- rule
( do location <- locatedToken Lexer.Bool
return Type.Scalar{ scalar = Monotype.Bool, .. }
<|> do location <- locatedToken Lexer.Real
return Type.Scalar{ scalar = Monotype.Real, .. }
<|> do location <- locatedToken Lexer.Integer
return Type.Scalar{ scalar = Monotype.Integer, .. }
<|> do location <- locatedToken Lexer.JSON
return Type.Scalar{ scalar = Monotype.JSON, .. }
<|> do location <- locatedToken Lexer.Natural
return Type.Scalar{ scalar = Monotype.Natural, .. }
<|> do location <- locatedToken Lexer.Text
return Type.Scalar{ scalar = Monotype.Text, .. }
<|> do ~(location, name) <- locatedLabel
return Type.VariableType{..}
<|> do let record location fields = Type.Record{..}
locatedOpenBrace <- locatedToken Lexer.OpenBrace
optional (token Lexer.Comma)
fieldTypes <- fieldType `endBy` token Lexer.Comma
toFields <-
( do text_ <- recordLabel
pure (\fs -> Type.Fields fs (Monotype.VariableFields text_))
<|> do pure (\fs -> Type.Fields fs Monotype.EmptyFields)
<|> do f <- fieldType
pure (\fs -> Type.Fields (fs <> [ f ]) Monotype.EmptyFields)
)
optional (token Lexer.Comma)
token Lexer.CloseBrace
return (record locatedOpenBrace (toFields fieldTypes))
<|> do let union location alternatives = Type.Union{..}
locatedOpenAngle <- locatedToken Lexer.OpenAngle
optional (token Lexer.Bar)
alternativeTypes <- alternativeType `endBy` token Lexer.Bar
toAlternatives <-
( do text_ <- label
return (\as -> Type.Alternatives as (Monotype.VariableAlternatives text_))
<|> do pure (\as -> Type.Alternatives as Monotype.EmptyAlternatives)
<|> do a <- alternativeType
return (\as -> Type.Alternatives (as <> [ a ]) Monotype.EmptyAlternatives)
)
optional (token Lexer.Bar)
token Lexer.CloseAngle
return (union locatedOpenAngle (toAlternatives alternativeTypes))
<|> do token Lexer.OpenParenthesis
t <- quantifiedType
token Lexer.CloseParenthesis
return t
)
fieldType <- rule do
field <- recordLabel
token Lexer.Colon
t <- quantifiedType
return (field, t)
alternativeType <- rule do
a <- alternative
token Lexer.Colon
t <- quantifiedType
return (a, t)
return expression
-- | Parse a complete expression
parse
:: String
-- ^ Name of the input (used for error messages)
-> Text
-- ^ Source code
-> Either ParseError (Syntax Offset Input)
parse name code = do
tokens <- Lexer.lex name code
case Earley.fullParses (Earley.parser grammar) tokens of
([], Report{..}) -> do
let offset =
case unconsumed of
[] -> Offset (Text.length code)
locatedToken_ : _ -> Lexer.start locatedToken_
Left (ParsingFailed (Location{..}))
(result : _, _) -> do
return result