on ab17521 help sign in
elk/compiler/Parse/Module.hs
66 lines 1.9 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(..))
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 = try $ do whitespace
45 as' <|> importing'
47 as' :: IParser ImportMethod
48 as' = do
49 reserved "as"
50 whitespace
51 As <$> capVar <?> "alias for module"
53 importing' :: IParser ImportMethod
54 importing' = Open <$> listing value
56listing :: IParser a -> IParser (Listing a)
57listing item =
58 parens (choice [ const (Listing [] True) <$> string ".."
59 , Listing <$> commaSep1 item <*> return False
60 ] <?> "listing of values (x,y,z)")
62value :: IParser Value
63value = choice [ Value <$> (lowVar <|> parens symOp)
64 , ADT <$> capVar <*> listing capVar
65 ]