on 577fc17 help sign in
elk/compiler/Parse/Module.hs
76 lines 2.2 kB history raw
1module Parse.Module (moduleDef, getModuleName, imports) where
3import Control.Applicative ((<$>), (<*>))
4import Data.List (intercalate)
5import Text.Parsec hiding (newline,spaces)
7import Parse.Helpers
8import AST.Module (ImportMethod(..))
9import AST.Variable (Listing(..), Value(..), openListing)
11getModuleName :: String -> Maybe String
12getModuleName source =
13 case iParse getModuleName source of
14 Right name -> Just name
15 Left _ -> Nothing
16 where
17 getModuleName = do
18 optional freshLine
19 (names, _) <- moduleDef
20 return (intercalate "." names)
22moduleDef :: IParser ([String], Listing Value)
23moduleDef = do
24 try (reserved "module")
25 whitespace
26 names <- dotSep1 capVar <?> "name of module"
27 whitespace
28 exports <- option (Listing [] True) (listing value)
29 whitespace <?> "reserved word 'where'"
30 reserved "where"
31 return (names, exports)
33imports :: IParser [(String, ImportMethod)]
34imports = option [] ((:) <$> import' <*> many (try (freshLine >> import')))
36import' :: IParser (String, ImportMethod)
37import' =
38 do reserved "import"
39 whitespace
40 name <- intercalate "." <$> dotSep1 capVar
41 (,) name <$> option (As name) method
42 where
43 method :: IParser ImportMethod
44 method = as' <|> importing'
46 as' :: IParser ImportMethod
47 as' = do
48 try (whitespace >> reserved "as")
49 whitespace
50 As <$> capVar <?> "alias for module"
52 importing' :: IParser ImportMethod
53 importing' = Open <$> listing value
55listing :: IParser a -> IParser (Listing a)
56listing item =
57 do try (whitespace >> char '(')
58 whitespace
59 listing <- choice [ const openListing <$> string ".."
60 , Listing <$> commaSep1 item <*> return False
61 ] <?> "listing of values (x,y,z)"
62 whitespace
63 char ')'
64 return listing
66value :: IParser Value
67value = val <|> tipe
68 where
69 val = Value <$> (lowVar <|> parens symOp)
71 tipe = do
72 name <- capVar
73 maybeCtors <- optionMaybe (listing capVar)
74 case maybeCtors of
75 Nothing -> return (Alias name)
76 Just ctors -> return (ADT name ctors)