1 {-# OPTIONS -Wall -fno-warn-missing-signatures #-}
3 module ParsecParser (parseCore) where
10 import Text.ParserCombinators.Parsec
11 import qualified Text.ParserCombinators.Parsec.Token as P
12 import Text.ParserCombinators.Parsec.Language
16 parseCore :: FilePath -> IO (Either ParseError Module)
17 parseCore = parseFromFile coreModule
19 coreModule :: Parser Module
23 mName <- coreModuleName
25 tdefs <- option [] coreTdefs
26 vdefGroups <- coreVdefGroups
28 return $ Module mName tdefs vdefGroups
30 coreModuleName :: Parser AnMname
32 pkgName <- corePackageName
34 (modHierarchy,baseName) <- coreHierModuleNames
35 return $ M (pkgName, modHierarchy, baseName)
37 corePackageName :: Parser Pname
38 -- Package names can be lowercase or uppercase!
39 corePackageName = (identifier <|> upperName) >>= (return . P)
41 coreHierModuleNames :: Parser ([Id], Id)
42 coreHierModuleNames = do
43 parentName <- upperName
44 return $ splitModuleName parentName
46 upperName :: Parser Id
49 rest <- many (identLetter extCoreDef)
50 return $ firstChar:rest
52 coreTdefs :: Parser [Tdef]
53 coreTdefs = many coreTdef
55 coreTdef :: Parser Tdef
56 coreTdef = withSemi (try (try coreDataDecl <|> try coreNewtypeDecl))
59 withSemi p = try p `withTerminator` ";"
61 withTerminator p term = do
66 coreDataDecl :: Parser Tdef
69 tyCon <- coreQualifiedCon
70 whiteSpace -- important
75 cDefs <- braces coreCdefs
76 return $ Data tyCon tBinds cDefs
78 coreNewtypeDecl :: Parser Tdef
81 tyCon <- coreQualifiedCon
83 coercionName <- coreQualifiedCon
87 return $ Newtype tyCon coercionName tBinds tyRep
89 coreQualifiedCon :: Parser (Mname, Id)
90 coreQualifiedCon = coreQualifiedGen upperName
92 coreQualifiedName = coreQualifiedGen identifier
94 coreQualifiedGen :: Parser String -> Parser (Mname, Id)
95 coreQualifiedGen p = (try (do
96 packageIdOrVarName <- corePackageName
97 maybeRest <- optionMaybe (char ':' >> coreHierModuleNames)
99 -- unqualified id, so backtrack
101 -- qualified name, so look for the id part
102 Just (modHierarchy, baseName) -> do
106 (Just $ M (packageIdOrVarName, modHierarchy, baseName),
109 (p >>= (\ res -> return (Nothing, res)))
111 coreTbinds :: Parser [Tbind]
112 coreTbinds = many coreTbind
114 coreTbindsGen :: CharParser () String -> Parser [Tbind]
115 -- The "try" here is important. Otherwise, when parsing:
116 -- "Node (^base:DataziTuple.Z3T)" (a cdef), we commit to
117 -- parsing (^base...) as a tbind rather than a type.
118 coreTbindsGen separator = many (try $ coreTbindGen separator)
120 coreTbind :: Parser Tbind
121 coreTbind = coreTbindGen whiteSpace
123 coreTbindGen :: CharParser () a -> Parser Tbind
124 coreTbindGen sep = (parens (do
127 kind <- symbol "::" >> coreKind
128 return (tyVar, kind))) <|>
129 (sep >> identifier >>= (return . (\ tv -> (tv,Klifted))))
131 coreCdefs :: Parser [Cdef]
132 coreCdefs = sepBy1 coreCdef (symbol ";")
134 coreCdef :: Parser Cdef
136 dataConName <- coreQualifiedCon
137 whiteSpace -- important!
138 tBinds <- try $ coreTbindsGen (symbol "@")
139 -- This should be equivalent to (many coreAty)
140 -- But it isn't. WHY??
141 tys <- sepBy coreAtySaturated whiteSpace
142 return $ Constr dataConName tBinds tys
144 coreTRep :: Parser Ty
145 -- note that the "=" is inside here since if there's
146 -- no rhs for the newtype, there's no "="
147 coreTRep = symbol "=" >> try coreType
149 coreType :: Parser Ty
150 coreType = coreForallTy <|> (do
152 -- whiteSpace is important!
154 -- This says: If there is at least one ("-> ty"..) thing,
155 -- use it. If not, don't consume any input.
156 maybeRest <- option [] (many1 (symbol "->" >> coreType))
157 return $ case maybeRest of
159 stuff -> foldl Tapp (Tcon tcArrow) (hd:stuff))
164 -- The "try" is necessary:
165 -- otherwise, parsing "T " fails rather
166 -- than returning "T".
167 maybeRest <- option [] (many1 (try (whiteSpace >> coreAtySaturated)))
169 -- so I'm not sure I like this... it's basically doing
170 -- typechecking (kind-checking?) in the parser.
171 -- However, the type syntax as defined in Core.hs sort of
173 ATy t -> foldl Tapp t maybeRest
174 Trans k -> app k 2 maybeRest "trans"
175 Sym k -> app k 1 maybeRest "sym"
176 Unsafe k -> app k 2 maybeRest "unsafe"
177 LeftCo k -> app k 1 maybeRest "left"
178 RightCo k -> app k 1 maybeRest "right"
179 InstCo k -> app k 2 maybeRest "inst")
180 where app k arity args _ | length args == arity = k args
182 primCoercionError (err ++
183 ("Args were: " ++ show args))
185 coreAtySaturated :: Parser Ty
186 coreAtySaturated = do
190 _ -> unexpected "coercion ty"
192 coreAty :: Parser ATyOp
193 coreAty = try coreTcon <|> ((try coreTvar <|> parens coreType)
195 coreTvar :: Parser Ty
196 coreTvar = try identifier >>= (return . Tvar)
198 coreTcon :: Parser ATyOp
199 -- TODO: Change the grammar
200 -- A Tcon can be an uppercase type constructor
201 -- or a lowercase (always qualified) coercion variable
203 -- Special case is first so that (CoUnsafe .. ..) gets parsed as
204 -- a prim. coercion app and not a Tcon app.
205 -- But the whole thing is so bogus.
207 -- the "try"s are crucial; they force
209 maybeCoercion <- choice [try symCo, try transCo, try unsafeCo,
210 try instCo, try leftCo, rightCo]
211 return $ case maybeCoercion of
212 TransC -> Trans (\ [x,y] -> TransCoercion x y)
213 SymC -> Sym (\ [x] -> SymCoercion x)
214 UnsafeC -> Unsafe (\ [x,y] -> UnsafeCoercion x y)
215 LeftC -> LeftCo (\ [x] -> LeftCoercion x)
216 RightC -> RightCo (\ [x] -> RightCoercion x)
217 InstC -> InstCo (\ [x,y] -> InstCoercion x y))
218 <|> (coreQualifiedCon >>= (return . ATy . Tcon))
220 data CoercionTy = TransC | InstC | SymC | UnsafeC | LeftC | RightC
222 symCo, transCo, unsafeCo, instCo, leftCo, rightCo :: Parser CoercionTy
223 symCo = string "%sym" >> return SymC
224 transCo = string "%trans" >> return TransC
225 unsafeCo = string "%unsafe" >> return UnsafeC
226 leftCo = string "%left" >> return LeftC
227 rightCo = string "%right" >> return RightC
228 instCo = string "%inst" >> return InstC
230 coreForallTy :: Parser Ty
233 tBinds <- many1 coreTbind
236 return $ foldr Tforall bodyTy tBinds
238 -- TODO: similar to coreType. should refactor
239 coreKind :: Parser Kind
242 maybeRest <- option [] (many1 (symbol "->" >> coreKind))
243 return $ foldl Karrow hd maybeRest
245 coreAtomicKind = try liftedKind <|> try unliftedKind
246 <|> try openKind <|> try (do
247 (from,to) <- parens equalityKind
248 return $ Keq from to)
249 <|> try (parens coreKind)
269 -- Only used internally within the parser:
270 -- represents either a Tcon, or a continuation
271 -- for a primitive coercion
276 | Unsafe ([Ty] -> Ty)
277 | LeftCo ([Ty] -> Ty)
278 | RightCo ([Ty] -> Ty)
279 | InstCo ([Ty] -> Ty)
281 coreVdefGroups :: Parser [Vdefg]
282 coreVdefGroups = option [] (do
283 theFirstVdef <- coreVdefg
285 others <- coreVdefGroups
286 return $ theFirstVdef:others)
288 coreVdefg :: Parser Vdefg
289 coreVdefg = coreRecVdef <|> coreNonrecVdef
293 braces (sepBy1 coreVdef (symbol ";")) >>= (return . Rec)
295 coreNonrecVdef = coreVdef >>= (return . Nonrec)
298 (vdefLhs, vdefTy) <- try topVbind <|> (do
299 (v, ty) <- lambdaBind
300 return (unqual v, ty))
304 vdefRhs <- coreFullExp
305 return $ Vdef (vdefLhs, vdefTy, vdefRhs)
307 coreAtomicExp :: Parser Exp
309 -- For stupid reasons, the whiteSpace is necessary.
310 -- Without it, (pt coreAppExp "w a:B.C ") doesn't work.
312 res <- choice [try coreDconOrVar,
318 coreFullExp = (choice [coreLam, coreLet,
319 coreCase, coreCast, coreNote, coreExternal, coreLabel]) <|> (try coreAppExp)
320 -- The "try" is necessary so that we backtrack
321 -- when we see a var (that is not an app)
326 -- it's important to have a separate coreAtomicExp (that any app exp
327 -- begins with) and to define the args in terms of many1.
328 -- previously, coreAppExp could parse either an atomic exp (an app with
329 -- 0 arguments) or an app with >= 1 arguments, but that led to ambiguity.
330 oper <- try coreAtomicExp
332 args <- many1 (whiteSpace >> ((coreAtomicExp >>= (return . Left)) <|>
333 -- note this MUST be coreAty, not coreType, because otherwise:
334 -- "A @ B c" gets parsed as "A @ (B c)"
335 ((symbol "@" >> coreAtySaturated) >>= (return . Right))))
336 return $ foldl (\ op ->
337 either (App op) (Appt op)) oper args
340 theThing <- coreQualifiedGen (try upperName <|> identifier)
341 return $ case theThing of
342 -- note that data constructors must be qualified
343 (Just _, idItself) | isUpper (head idItself)
347 coreLit :: Parser Exp
348 coreLit = parens (coreLiteral >>= (return . Lit))
350 coreLiteral :: Parser Lit
359 binds <- coreLambdaBinds
362 return $ foldr Lam body binds
369 return $ Let vdefg body
372 ty <- coreAtySaturated
373 scrut <- coreAtomicExp
375 vBind <- parens lambdaBind
377 return $ Case scrut vBind ty alts
381 -- The parens are CRUCIAL, o/w it's ambiguous
382 body <- try (parens coreFullExp)
384 ty <- try coreAtySaturated
385 return $ Cast body ty
393 -- TODO: This isn't in the grammar, but GHC
394 -- always prints "external ccall". investigate...
397 t <- coreAtySaturated
398 return $ External s t) <|>
399 -- TODO: I don't really understand what this does
401 reserved "dynexternal"
403 t <- coreAtySaturated
404 return $ External "[dynamic]" t)
406 -- TODO: Totally punting this, but it needs to go in the grammar
410 return $ External s tAddrzh
412 coreLambdaBinds = many1 coreBind
414 coreBind = coreTbinding <|> coreVbind
416 coreTbinding = try coreAtTbind >>= (return . Tb)
417 coreVbind = parens (lambdaBind >>= (return . Vb))
419 coreAtTbind = (symbol "@") >> coreTbind
421 topVbind :: Parser (Qual Var, Ty)
422 topVbind = aCoreVbind coreQualifiedName
423 lambdaBind :: Parser (Var, Ty)
424 lambdaBind = aCoreVbind identifier
433 aLit :: Parser CoreLit
434 aLit = intOrRatLit <|> charLit <|> stringLit
436 intOrRatLit :: Parser CoreLit
438 -- Int and lit combined into one to avoid ambiguity.
441 maybeRhs <- optionMaybe (symbol "%" >> anIntLit)
443 Nothing -> return $ Lint lhs
444 Just rhs -> return $ Lrational (lhs % rhs)
446 intLit :: Parser Integer
447 intLit = anIntLit <|> parens anIntLit
449 anIntLit :: Parser Integer
451 sign <- option 1 (symbol "-" >> return (-1))
455 charLit :: Parser CoreLit
456 charLit = charLiteral >>= (return . Lchar)
457 -- make sure this is right
459 stringLit :: Parser CoreLit
460 stringLit = stringLiteral >>= (return . Lstring)
461 -- make sure this is right
463 coreAlts :: Parser [Alt]
464 coreAlts = braces $ sepBy1 coreAlt (symbol ";")
466 coreAlt :: Parser Alt
467 coreAlt = conAlt <|> litAlt <|> defaultAlt
471 conName <- coreQualifiedCon
472 tBinds <- many (parens coreAtTbind)
473 whiteSpace -- necessary b/c otherwise we parse the next list as empty
474 vBinds <- many (parens lambdaBind)
477 rhs <- try coreFullExp
478 return $ Acon conName tBinds vBinds rhs
482 l <- parens coreLiteral
487 defaultAlt :: Parser Alt
492 return $ Adefault rhs
494 extCore = P.makeTokenParser extCoreDef
496 parens = P.parens extCore
497 braces = P.braces extCore
498 -- newlines are allowed anywhere
499 whiteSpace = P.whiteSpace extCore <|> (newline >> return ())
500 symbol = P.symbol extCore
501 identifier = P.identifier extCore
502 -- Keywords all begin with '%'
503 reserved s = P.reserved extCore ('%':s)
504 natural = P.natural extCore
505 charLiteral = P.charLiteral extCore
506 stringLiteral = P.stringLiteral extCore
508 -- dodgy since Core doesn't really allow comments,
509 -- but we'll pretend...
510 extCoreDef = LanguageDef {
514 , nestedComments = True
516 , identLetter = lower <|> upper <|> digit <|> (char '\'')
517 , opStart = opLetter extCoreDef
518 , opLetter = oneOf ";=@:\\%_.*#?%"
519 , reservedNames = map ('%' :)
520 ["module", "data", "newtype", "rec",
521 "let", "in", "case", "of", "cast",
522 "note", "external", "forall"]
523 , reservedOpNames = [";", "=", "@", "::", "\\", "%_",
525 , caseSensitive = True
529 -- Stuff to help with testing in ghci.
530 pTest (Left a) = error (show a)
531 pTest (Right t) = print t
533 pTest1 :: Show a => CharParser () a -> String -> IO ()
535 let res = parse pr "" s
538 pt :: Show a => CharParser () a -> String -> IO ()