on d87affe help sign in
elk/src/Parse/Type.hs
76 lines 2.1 kB history raw
1{-# OPTIONS_GHC -Wall -fno-warn-unused-do-bind #-}
2module Parse.Type where
4import Control.Applicative ((<$>),(<*>),(<*))
5import Data.List (intercalate)
6import Text.Parsec ((<|>), (<?>), char, many, optionMaybe, string, try)
8import qualified AST.Type as T
9import qualified AST.Variable as Var
10import Parse.Helpers
12tvar :: IParser T.RawType
13tvar = T.Var <$> lowVar <?> "type variable"
16tuple :: IParser T.RawType
17tuple = do ts <- parens (commaSep expr)
18 return $ case ts of
19 [t] -> t
20 _ -> T.tupleOf ts
22record :: IParser T.RawType
23record =
24 do char '{' ; whitespace
25 rcrd <- extended <|> normal
26 dumbWhitespace ; char '}'
27 return rcrd
28 where
29 normal = flip T.Record Nothing <$> commaSep field
31 -- extended record types require at least one field
32 extended = do
33 ext <- try (lowVar <* (whitespace >> string "|"))
34 whitespace
35 flip T.Record (Just (T.Var ext)) <$> commaSep1 field
37 field = do
38 lbl <- rLabel
39 whitespace >> hasType >> whitespace
40 (,) lbl <$> expr
42capTypeVar :: IParser String
43capTypeVar = intercalate "." <$> dotSep1 capVar
45constructor0 :: IParser T.RawType
46constructor0 =
47 do name <- capTypeVar
48 return (T.Type (Var.Raw name))
50term :: IParser T.RawType
51term = tuple <|> record <|> tvar <|> constructor0
53app :: IParser T.RawType
54app =
55 do f <- constructor0 <|> try tupleCtor <?> "type constructor"
56 args <- spacePrefix term
57 return $ case args of
58 [] -> f
59 _ -> T.App f args
60 where
61 tupleCtor = do
62 n <- length <$> parens (many (char ','))
63 let ctor = "_Tuple" ++ show (if n == 0 then 0 else n+1)
64 return (T.Type (Var.Raw ctor))
66expr :: IParser T.RawType
67expr =
68 do t1 <- app <|> term
69 arr <- optionMaybe $ try (whitespace >> arrow)
70 case arr of
71 Just _ -> T.Lambda t1 <$> (whitespace >> expr)
72 Nothing -> return t1
74constructor :: IParser (String, [T.RawType])
75constructor = (,) <$> (capTypeVar <?> "another type constructor")
76 <*> spacePrefix term