on 17618de help sign in
elk/src/Parse/Declaration.hs
99 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.Expression as Expr
8import Parse.Helpers as Help
9import qualified Parse.Type as Type
13declaration :: IParser Decl.Source
14declaration =
15 commentOr $ addLocation $
16 choice
17 [ typeDecl
18 , infixDecl
19 , portDecl
20 , definition
21 ]
24commentOr :: IParser a -> IParser (Decl.CommentOr a)
25commentOr parser =
26 choice
27 [ Decl.Comment <$> addLocation Help.docComment
28 , Decl.Whatever <$> parser
29 ]
33-- TYPE ANNOTATIONS and DEFINITIONS
36definition :: IParser Decl.Raw
37definition =
38 do def <- Expr.def <?> "a value definition"
39 return $ Decl.Def def
43-- TYPE ALIAS and UNION TYPES
46typeDecl :: IParser Decl.Raw
47typeDecl =
48 do try (reserved "type") <?> "a type declaration"
49 forcedWS
50 isAlias <- optionMaybe (string "alias" >> forcedWS)
52 name <- capVar
53 args <- spacePrefix lowVar
54 padded equals
56 case isAlias of
57 Just _ ->
58 do tipe <- Type.expr <?> "a type"
59 return $ Decl.Alias (Decl.Type name args tipe)
61 Nothing ->
62 do tcs <- pipeSep1 Type.constructor <?> "a constructor for a union type"
63 return $ Decl.Union (Decl.Type name args tcs)
67-- INFIX
70infixDecl :: IParser Decl.Raw
71infixDecl =
72 expecting "an infix declaration" $
73 do assoc <-
74 choice
75 [ try (reserved "infixl") >> return Decl.L
76 , try (reserved "infixr") >> return Decl.R
77 , try (reserved "infix") >> return Decl.N
78 ]
79 forcedWS
80 n <- digit
81 forcedWS
82 op <- anyOp
83 return $ Decl.Fixity (Decl.Infix op assoc (read [n]))
87-- FOREIGN
90portDecl :: IParser Decl.Raw
91portDecl =
92 expecting "a port declaration" $
93 do try (reserved "port")
94 forcedWS
95 name <- Help.lowVar
96 padded hasType
97 tipe <- Type.expr
98 return $ Decl.Port name tipe