on 9b0c310 help sign in
elk/src/Parse/Declaration.hs
84 lines 2.0 kB history raw
1{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
2module Parse.Declaration where
4import Control.Applicative ((<$>))
5import Text.Parsec ( (<|>), (<?>), choice, digit, optionMaybe, string, try )
7import qualified AST.Declaration as D
8import qualified Parse.Expression as Expr
9import Parse.Helpers
10import qualified Parse.Type as Type
13declaration :: IParser D.SourceDecl
14declaration =
15 addLocation (typeDecl <|> infixDecl <|> port <|> definition)
18-- TYPE ANNOTATIONS and DEFINITIONS
20definition :: IParser D.SourceDecl'
21definition =
22 D.Definition <$> (Expr.typeAnnotation <|> Expr.definition)
25-- TYPE ALIAS and UNION TYPES
27typeDecl :: IParser D.SourceDecl'
28typeDecl =
29 do try (reserved "type") <?> "type declaration"
30 forcedWS
31 isAlias <- optionMaybe (string "alias" >> forcedWS)
33 name <- capVar
34 args <- spacePrefix lowVar
35 padded equals
37 case isAlias of
38 Just _ ->
39 do tipe <- Type.expr <?> "a type"
40 return (D.TypeAlias name args tipe)
42 Nothing ->
43 do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
44 return $ D.Datatype name args tcs
47-- INFIX
49infixDecl :: IParser D.SourceDecl'
50infixDecl =
51 do assoc <-
52 choice
53 [ try (reserved "infixl") >> return D.L
54 , try (reserved "infixr") >> return D.R
55 , try (reserved "infix") >> return D.N
56 ]
57 forcedWS
58 n <- digit
59 forcedWS
60 D.Fixity assoc (read [n]) <$> anyOp
63-- PORT
65port :: IParser D.SourceDecl'
66port =
67 do try (reserved "port")
68 whitespace
69 name <- lowVar
70 whitespace
71 choice [ portAnnotation name, portDefinition name ]
72 where
73 portAnnotation name =
74 do try hasType
75 whitespace
76 tipe <- Type.expr <?> "a type"
77 return (D.Port (D.PortAnnotation name tipe))
79 portDefinition name =
80 do try equals
81 whitespace
82 expr <- Expr.expr
83 return (D.Port (D.PortDefinition name expr))