on 267f708 help sign in
elk/src/Parse/Declaration.hs
100 lines 2.1 kB history raw
1{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
2module Parse.Declaration where
4import Text.Parsec ( (<?>), choice, digit, optionMaybe, string, try )
6import qualified AST.Declaration as Decl
7import qualified Parse.Binop as Binop
8import qualified Parse.Expression as Expr
9import Parse.Helpers as Help
10import qualified Parse.Type as Type
14declaration :: IParser Decl.Source
15declaration =
16 commentOr $ addLocation $
17 choice
18 [ typeDecl
19 , infixDecl
20 , portDecl
21 , definition
22 ]
25commentOr :: IParser a -> IParser (Decl.CommentOr a)
26commentOr parser =
27 choice
28 [ Decl.Comment <$> addLocation Help.docComment
29 , Decl.Whatever <$> parser
30 ]
34-- TYPE ANNOTATIONS and DEFINITIONS
37definition :: IParser Decl.Raw
38definition =
39 do def <- Expr.def <?> "a value definition"
40 return $ Decl.Def def
44-- TYPE ALIAS and UNION TYPES
47typeDecl :: IParser Decl.Raw
48typeDecl =
49 do try (reserved "type") <?> "a type declaration"
50 forcedWS
51 isAlias <- optionMaybe (string "alias" >> forcedWS)
53 name <- capVar
54 args <- spacePrefix lowVar
55 padded equals
57 case isAlias of
58 Just _ ->
59 do tipe <- Type.expr <?> "a type"
60 return $ Decl.Alias (Decl.Type name args tipe)
62 Nothing ->
63 do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
64 return $ Decl.Union (Decl.Type name args tcs)
68-- INFIX
71infixDecl :: IParser Decl.Raw
72infixDecl =
73 expecting "an infix declaration" $
74 do assoc <-
75 choice
76 [ try (reserved "infixl") >> return Decl.L
77 , try (reserved "infixr") >> return Decl.R
78 , try (reserved "infix") >> return Decl.N
79 ]
80 forcedWS
81 n <- digit
82 forcedWS
83 op <- Binop.infixOp
84 return $ Decl.Fixity (Decl.Infix op assoc (read [n]))
88-- FOREIGN
91portDecl :: IParser Decl.Raw
92portDecl =
93 expecting "a port declaration" $
94 do try (reserved "port")
95 forcedWS
96 name <- Help.lowVar
97 padded hasType
98 tipe <- Type.expr
99 return $ Decl.Port name tipe