summaryrefslogtreecommitdiff
path: root/src/Language/Fiddle/Parser.hs
blob: 415852c9fa276743ff3a9bf6e5c85a57ce55d901 (plain) (blame)
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
{-# LANGUAGE LambdaCase #-}
{-# LANGUAGE ScopedTypeVariables #-}

module Language.Fiddle.Parser
  ( fiddleUnit,
    parseFiddleText,
  )
where

import Control.Monad (void)
import Data.Functor.Identity
import Data.Kind (Type)
import Data.Text (Text)
import Language.Fiddle.Ast
import Language.Fiddle.Tokenizer
import Language.Fiddle.Types
import Text.Parsec hiding (token)
import qualified Text.Parsec
import Text.Printf

type F = Either ParseError

type S = [Token SourceSpan]

type P = ParsecT S () Identity

type A = Commented SourceSpan

type Pa (a :: Stage -> (Type -> Type) -> Type -> Type) = P (a 'Parsed F (Commented SourceSpan))

type PaS (a :: (Type -> Type) -> Type -> Type) = P (a F (Commented SourceSpan))

noQMd :: F (QMd Parsed t)
noQMd = pure Vacant

commentP :: P Comment
commentP =
  token $ \case
    (TokComment c) -> Just (NormalComment c)
    (TokDocComment c) -> Just (DocComment c)
    _ -> Nothing

isComment :: Token s -> Bool
isComment (Token t _) =
  case t of
    (TokComment _) -> True
    (TokDocComment _) -> True
    _ -> False

-- Removes trailing comments from a list of tokens. Comments that don't preceed
-- an actual language token have minimal semantic value and are thus discarded.
stripTrailingComments :: [Token s] -> [Token s]
stripTrailingComments = reverse . dropWhile isComment . reverse

directedP :: (Annotated (t Parsed)) => Pa t -> PaS (Directed t 'Parsed)
directedP subparser = withMetaLeaveComments $ do
  coms <- many commentP
  Directed <$> many directiveP <*> pushComments coms subparser

pushComments :: (Annotated t) => [Comment] -> PaS t -> PaS t
pushComments coms subparse = do
  setAnnot (\(Commented coms' a) -> Commented (coms ++ coms') a) <$> subparse

directiveP :: PaS Directive
directiveP =
  withMeta $
    Directive <$> defer directiveBodyTokens directiveBodyP

directiveBodyP :: PaS DirectiveBody
directiveBodyP = withMeta $ do
  DirectiveBody <$> many (directiveElementP <* (void (tok TokComma) <|> eof))

directiveElementP :: PaS DirectiveElement
directiveElementP = withMeta $ do
  identifier1 <- nextTextP
  choice
    [ do
        tok_ TokColon
        let backend = identifier1
        key <- nextTextP
        choice
          [ do
              tok_ TokEq
              DirectiveElementKeyValue (Just backend) key <$> directiveExpressionP,
            do
              return (DirectiveElementKey (Just backend) key)
          ],
      do
        tok_ TokEq
        let key = identifier1
        DirectiveElementKeyValue Nothing key <$> directiveExpressionP,
      return $ DirectiveElementKey Nothing identifier1
    ]

nextTextP :: PaS Identifier
nextTextP = withMeta $ Identifier <$> token textOf

directiveExpressionP :: PaS DirectiveExpression
directiveExpressionP = withMeta $ do
  choice
    [ do
        token $ \case
          (TokString str) -> Just $ DirectiveString str
          (TokLitNum num) -> Just $ DirectiveNumber num
          _ -> Nothing
    ]

fiddleUnit :: Pa FiddleUnit
fiddleUnit = do
  withMeta
    ( FiddleUnit Vacant <$> many1 (directedP fiddleDeclP <* tok TokSemi)
    )
    <* many commentP

stringTokenP :: P Text
stringTokenP =
  token
    ( \case
        (TokString str) -> Just str
        _ -> Nothing
    )

importListP :: PaS ImportList
importListP = withMeta $ do
  tok_ TokLParen
  ImportList
    <$> many (ident <* (tok TokComma <|> lookAhead (tok TokRParen)))
    <* tok TokRParen

importStatementP :: Pa ImportStatement
importStatementP =
  withMeta $
    ImportStatement
      <$> stringTokenP
      <*> optionMaybe importListP
      <*> pure Vacant

nameToIdent :: PaS Identifier -> PaS Name
nameToIdent ifn = withMeta $ Name . pure <$> ident

fiddleDeclP :: Pa FiddleDecl
fiddleDeclP = do
  withMeta $ do
    t <- tokenType <$> anyToken
    case t of
      KWOption -> OptionDecl <$> nextTextP <*> nextTextP
      KWPackage ->
        PackageDecl noQMd
          <$> name
          <*> defer body packageBodyP
      KWUsing -> UsingDecl Witness <$> name
      KWLocation -> LocationDecl noQMd <$> ident <*> (tok TokEq >> constExpressionP)
      KWBits -> BitsDecl noQMd <$> nameToIdent ident <*> (tok TokColon >> bitTypeP)
      KWImport -> ImportDecl <$> importStatementP
      KWType ->
        ObjTypeDecl noQMd
          <$> nameToIdent ident
          <*> ( do
                  tok_ TokColon
                  bt <- bodyTypeP
                  defer body (objTypeBodyP bt)
              )
      KWInstance ->
        ObjectDecl noQMd
          <$> ident
          <*> (tok KWAt *> expressionP)
          <*> (tok TokColon *> objTypeP)
      _ ->
        fail $
          printf "Unexpected token %s. Expected top-level declaration." (show t)

objTypeP :: Pa ObjType
objTypeP = do
  base <- withMeta baseObjP
  recur' <- recur
  return $ recur' base
  where
    recur :: P (ObjType Parsed F A -> ObjType Parsed F A)
    recur =
      ( do
          withMeta $ do
            expr <- tok TokLBracket *> constExpressionP <* tok TokRBracket
            recur' <- recur
            return (\met base -> recur' (ArrayObjType base expr met))
      )
        <|> return id

    baseObjP :: P (A -> ObjType Parsed F A)
    baseObjP =
      (ReferencedObjType noQMd <$> name)
        <|> ( do
                t <- bodyTypeP
                AnonymousObjType Witness <$> defer body (objTypeBodyP t)
            )

asConstP :: Pa (Expression u) -> Pa (ConstExpression u)
asConstP fn = withMeta $ ConstExpression . RightV <$> fn

exprInParenP :: Pa (Expression u)
exprInParenP = tok TokLParen *> expressionP <* tok TokRParen

objTypeBodyP :: BodyType F (Commented SourceSpan) -> Pa ObjTypeBody
objTypeBodyP bt =
  withMeta $
    ObjTypeBody bt <$> many (directedP objTypeDeclP <* tok TokSemi)

objTypeDeclP :: Pa ObjTypeDecl
objTypeDeclP =
  withMeta $
    ( do
        tok_ KWAssertPos
        AssertPosStatement Witness <$> exprInParenP
    )
      <|> ( do
              tok_ KWReserved
              ReservedDecl Witness <$> exprInParenP
          )
      <|> ( do
              bt <- bodyTypeP
              TypeSubStructure <$> defer body (objTypeBodyP bt) <*> optionMaybe ident
          )
      <|> ( do
              modifier <- Perhaps <$> optionMaybe modifierP
              tok_ KWReg
              RegisterDecl Vacant modifier . Perhaps
                <$> optionMaybe ident
                <*> fmap RightV exprInParenP
                <*> optionMaybe (tok TokColon *> registerBodyP)
          )

modifierP :: PaS Modifier
modifierP =
  withMeta $
    ModifierKeyword
      <$> choice
        [ tok KWRo >> return Ro,
          tok KWRw >> return Rw,
          tok KWWo >> return Wo
        ]

bitBodyTypeP :: PaS BodyType
bitBodyTypeP =
  withMeta $
    (tok KWStruct >> return Struct)
      <|> (tok KWUnion >> return Union)

bodyTypeP :: PaS BodyType
bodyTypeP =
  withMeta $
    (tok KWStruct >> return Struct) <|> (tok KWUnion >> return Union)

registerBodyP :: Pa RegisterBody
registerBodyP = withMeta $ RegisterBody <$> bitBodyTypeP <*> defer body deferredRegisterBodyP

deferredRegisterBodyP :: Pa DeferredRegisterBody
deferredRegisterBodyP =
  withMetaLeaveComments $
    DeferredRegisterBody <$> many (directedP registerBitsDeclP <* tok TokSemi)

registerBitsDeclP :: Pa RegisterBitsDecl
registerBitsDeclP =
  withMeta $
    ( do
        tok KWReserved >> ReservedBits <$> exprInParenP
    )
      <|> (BitsSubStructure <$> registerBodyP <*> optionMaybe ident)
      <|> ( DefinedBits Vacant . Perhaps
              <$> optionMaybe modifierP
              <*> ident
              <*> (tok TokColon >> registerBitsTypeRefP)
          )

registerBitsTypeRefP :: Pa RegisterBitsTypeRef
registerBitsTypeRefP = do
  base <- baseTypeRef
  recur' <- recurP
  return (recur' base)
  where
    recurP :: P (RegisterBitsTypeRef Parsed F A -> RegisterBitsTypeRef Parsed F A)
    recurP =
      ( do
          withMeta $ do
            expr <- tok TokLBracket *> constExpressionP <* tok TokRBracket
            recur' <- recurP
            return (\met base -> recur' (RegisterBitsArray base expr met))
      )
        <|> return id

    baseTypeRef =
      withMeta $
        (RegisterBitsJustBits <$> asConstP exprInParenP)
          <|> (RegisterBitsAnonymousType Witness <$> anonymousBitsTypeP)
          <|> (RegisterBitsReference noQMd <$> name)

anonymousBitsTypeP :: Pa AnonymousBitsType
anonymousBitsTypeP = withMeta $ do
  tok_ KWEnum
  AnonymousEnumBody <$> exprInParenP <*> defer body enumBodyP

bitTypeP :: Pa BitType
bitTypeP = withMeta $ rawBits <|> enumType
  where
    rawBits = RawBits <$> (tok TokLParen *> expressionP <* tok TokRParen)
    enumType = do
      tok_ KWEnum
      expr <- exprInParenP
      EnumBitType expr <$> defer body enumBodyP

enumBodyP :: Pa EnumBody
enumBodyP =
  withMeta $
    EnumBody <$> many (directedP enumConstantDeclP <* tok TokComma)

enumConstantDeclP :: Pa EnumConstantDecl
enumConstantDeclP =
  withMeta $
    (tok KWReserved >> EnumConstantReserved <$> (tok TokEq >> expressionP))
      <|> (EnumConstantDecl <$> ident <*> (tok TokEq >> constExpressionP))

constExpressionP :: Pa (ConstExpression u)
constExpressionP = withMeta $ ConstExpression . RightV <$> expressionP

expressionP :: Pa (Expression u)
expressionP =
  withMeta $
    token
      ( \case
          (TokLitNum num) -> Just (LitNum $ LeftV num)
          _ -> Nothing
      )
      <|> (Var <$> name)

body :: P [Token SourceSpan]
body = do
  (_, b, _) <- body'
  return b

directiveBodyTokens :: P [Token SourceSpan]
directiveBodyTokens = do
  _ <- tokKeepComment TokDirectiveStart
  ret <- concat <$> manyTill ((: []) <$> anyToken) (lookAhead $ tokKeepComment TokDirectiveEnd)
  _ <- tokKeepComment TokDirectiveEnd
  return ret

body' :: P (Token SourceSpan, [Token SourceSpan], Token SourceSpan)
body' = do
  l <- tokKeepComment TokLBrace
  ret <-
    concat
      <$> manyTill
        ( ((\(b0, b1, b2) -> [b0] ++ b1 ++ [b2]) <$> body') <|> fmap (: []) anyToken
        )
        (lookAhead $ tokKeepComment TokRBrace)
  r <- tokKeepComment TokRBrace

  _ <- lookAhead anyToken

  return (l, stripTrailingComments ret, r)

-- A deferred parsing takes a part of a text file (such as a body) and returns a
-- deferred computation for parsing that section.
--
-- This is useful because it allows for parse errors to be detected in multiple
-- locations. This is because for things like bodies (stuff inside { ... }), we
-- can parse the stuff inside the body as it's own, separate parsing.
defer :: P [Token SourceSpan] -> P b -> P (F b)
defer p0 pb = do
  sourcePos <- getPosition

  Text.Parsec.runParser
    ( do
        setPosition sourcePos
        pb <* eof
    )
    ()
    (sourceName sourcePos)
    <$> p0

packageBodyP :: Pa PackageBody
packageBodyP =
  withMetaLeaveComments $
    PackageBody
      <$> many
        ( directedP $
            fiddleDeclP
              <* ( tok TokSemi <|> fail "Expected ';'"
                 )
        )

ident :: PaS Identifier
ident =
  withMeta $
    token $ \case
      (TokIdent identTok) -> Just (Identifier identTok)
      _ -> Nothing

name :: PaS Name
name = withMeta $ do
  i <- ident
  is <- many $ do
    tok_ TokDot
    ident
  return $ Name (i :| is)

-- Takes a some parsable thing p and automatically parses the comments before
-- and after and sets the positions and adds it to the annotation.
withMeta :: P (Commented SourceSpan -> b) -> P b
withMeta p = do
  comments' <- many commentP
  start <- getPosition
  fn <- p
  end <- getPosition
  return $ fn (Commented comments' (SourceSpan start end))

-- Takes a some parsable thing p and automatically parses the comments before
-- and after and sets the positions and adds it to the annotation.
withMetaLeaveComments :: P (Commented SourceSpan -> b) -> P b
withMetaLeaveComments p = do
  start <- getPosition
  fn <- p
  end <- getPosition
  return $ fn (Commented [] (SourceSpan start end))

token :: (T -> Maybe a) -> ParsecT S u Identity a
token fn =
  Text.Parsec.token
    (\(Token t _) -> show t)
    (\(Token _ (SourceSpan s1 _)) -> s1)
    (\(Token t _) -> fn t)

tokKeepComment :: T -> P (Token SourceSpan)
tokKeepComment t' = do
  Text.Parsec.token
    (\(Token t _) -> show t)
    (\(Token _ (SourceSpan s1 _)) -> s1)
    (\aToken@(Token t _) -> if t == t' then Just aToken else Nothing)

tok_ :: T -> P ()
tok_ = void . tok

tok :: T -> P (Token SourceSpan)
tok t' = do
  _ <- many commentP
  Text.Parsec.token
    (\(Token t _) -> show t)
    (\(Token _ (SourceSpan s1 _)) -> s1)
    (\tt@(Token t _) -> if t == t' then Just tt else Nothing)

parseFiddleText :: String -> Text -> F (FiddleUnit 'Parsed F (Commented SourceSpan))
parseFiddleText srcName txt =
  runIdentity
    . Text.Parsec.runParserT
      (fiddleUnit <* eof)
      ()
      srcName
    . stripTrailingComments
    =<< tokenize srcName txt