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!
40 corePackageName = identifier <|> upperName
42 coreHierModuleNames :: Parser ([Id], Id)
43 coreHierModuleNames = do
44 parentName <- upperName
45 return $ splitModuleName parentName
47 upperName :: Parser Id
50 rest <- many (identLetter extCoreDef)
51 return $ firstChar:rest
53 coreTdefs :: Parser [Tdef]
54 coreTdefs = many coreTdef
56 coreTdef :: Parser Tdef
57 coreTdef = withSemi (try (try coreDataDecl <|> try coreNewtypeDecl))
60 withSemi p = try p `withTerminator` ";"
62 withTerminator p term = do
67 coreDataDecl :: Parser Tdef
70 tyCon <- coreQualifiedCon
71 whiteSpace -- important
76 cDefs <- braces coreCdefs
77 return $ Data tyCon tBinds cDefs
79 coreNewtypeDecl :: Parser Tdef
82 tyCon <- coreQualifiedCon
88 return $ Newtype tyCon tBinds axiom tyRep
90 coreQualifiedCon :: Parser (Mname, Id)
91 coreQualifiedCon = coreQualifiedGen upperName
93 coreQualifiedName = coreQualifiedGen identifier
95 coreQualifiedGen :: Parser String -> Parser (Mname, Id)
96 coreQualifiedGen p = (try (do
97 packageIdOrVarName <- corePackageName
98 maybeRest <- optionMaybe (char ':' >> coreHierModuleNames)
100 -- unqualified id, so backtrack
102 -- qualified name, so look for the id part
103 Just (modHierarchy, baseName) -> do
107 (Just $ M (packageIdOrVarName, modHierarchy, baseName),
110 (p >>= (\ res -> return (Nothing, res)))
113 coreMaybeMname = optionMaybe coreMname
115 coreRequiredQualifiedName = do
118 return (Just mname, theId)
122 nm <- try coreModuleName
127 coreAxiom :: Parser Axiom
128 coreAxiom = parens (do
129 coercionName <- coreQualifiedCon
135 coercionK <- try equalityKind <|> parens equalityKind
136 return (coercionName, tbs, coercionK))
138 coreTbinds :: Parser [Tbind]
139 coreTbinds = many coreTbind
141 coreTbindsGen :: CharParser () String -> Parser [Tbind]
142 -- The "try" here is important. Otherwise, when parsing:
143 -- "Node (^base:DataziTuple.Z3T)" (a cdef), we commit to
144 -- parsing (^base...) as a tbind rather than a type.
145 coreTbindsGen separator = many (try $ coreTbindGen separator)
147 coreTbind :: Parser Tbind
148 coreTbind = coreTbindGen whiteSpace
150 coreTbindGen :: CharParser () a -> Parser Tbind
151 coreTbindGen sep = (parens (do
154 kind <- symbol "::" >> coreKind
155 return (tyVar, kind))) <|>
156 (sep >> identifier >>= (return . (\ tv -> (tv,Klifted))))
158 coreCdefs :: Parser [Cdef]
159 coreCdefs = sepBy1 coreCdef (symbol ";")
161 coreCdef :: Parser Cdef
163 dataConName <- coreQualifiedCon
164 whiteSpace -- important!
165 tBinds <- try $ coreTbindsGen (symbol "@")
166 -- This should be equivalent to (many coreAty)
167 -- But it isn't. WHY??
168 tys <- sepBy coreAtySaturated whiteSpace
169 return $ Constr dataConName tBinds tys
171 coreTRep :: Parser (Maybe Ty)
172 -- note that the "=" is inside here since if there's
173 -- no rhs for the newtype, there's no "="
174 coreTRep = optionMaybe (do
178 coreType :: Parser Ty
179 coreType = coreForallTy <|> (do
181 -- whiteSpace is important!
183 -- This says: If there is at least one ("-> ty"..) thing,
184 -- use it. If not, don't consume any input.
185 maybeRest <- option [] (many1 (symbol "->" >> coreType))
186 return $ case maybeRest of
188 stuff -> foldl Tapp (Tcon tcArrow) (hd:stuff))
193 -- The "try" is necessary:
194 -- otherwise, parsing "T " fails rather
195 -- than returning "T".
196 maybeRest <- option [] (many1 (try (whiteSpace >> coreAtySaturated)))
198 -- so I'm not sure I like this... it's basically doing
199 -- typechecking (kind-checking?) in the parser.
200 -- However, the type syntax as defined in Core.hs sort of
202 ATy t -> foldl Tapp t maybeRest
203 Trans k -> app k 2 maybeRest "trans"
204 Sym k -> app k 1 maybeRest "sym"
205 Unsafe k -> app k 2 maybeRest "unsafe"
206 LeftCo k -> app k 1 maybeRest "left"
207 RightCo k -> app k 1 maybeRest "right")
208 where app k arity args _ | length args == arity = k args
210 primCoercionError (err ++
211 ("Args were: " ++ show args))
213 coreAtySaturated :: Parser Ty
214 coreAtySaturated = do
218 _ -> unexpected "coercion ty"
220 coreAty :: Parser ATyOp
221 coreAty = try coreTcon <|> ((try coreTvar <|> parens coreType)
223 coreTvar :: Parser Ty
224 coreTvar = try identifier >>= (return . Tvar)
226 coreTcon :: Parser ATyOp
227 -- TODO: Change the grammar
228 -- A Tcon can be an uppercase type constructor
229 -- or a lowercase (always qualified) coercion variable
231 -- Special case is first so that (CoUnsafe .. ..) gets parsed as
232 -- a prim. coercion app and not a Tcon app.
233 -- But the whole thing is so bogus.
235 -- the "try"s are crucial; they force
237 maybeCoercion <- choice [try symCo, try transCo, try unsafeCo,
239 return $ case maybeCoercion of
240 TransC -> Trans (\ [x,y] -> TransCoercion x y)
241 SymC -> Sym (\ [x] -> SymCoercion x)
242 UnsafeC -> Unsafe (\ [x,y] -> UnsafeCoercion x y)
243 LeftC -> LeftCo (\ [x] -> LeftCoercion x)
244 RightC -> RightCo (\ [x] -> RightCoercion x))
245 <|> (coreQualifiedCon >>= (return . ATy . Tcon))
247 data CoercionTy = TransC | SymC | UnsafeC | LeftC | RightC
249 symCo, transCo, unsafeCo :: Parser CoercionTy
250 -- Would be better not to wire these in quite this way. Sigh
251 symCo = string "ghczmprim:GHCziPrim.sym" >> return SymC
252 transCo = string "ghczmprim:GHCziPrim.trans" >> return TransC
253 unsafeCo = string "ghczmprim:GHCziPrim.CoUnsafe" >> return UnsafeC
254 leftCo = string "ghczmprim:GHCziPrim.left" >> return LeftC
255 rightCo = string "ghczmprim:GHCziPrim.right" >> return RightC
257 coreForallTy :: Parser Ty
260 tBinds <- many1 coreTbind
263 return $ foldr Tforall bodyTy tBinds
265 -- TODO: similar to coreType. should refactor
266 coreKind :: Parser Kind
269 maybeRest <- option [] (many1 (symbol "->" >> coreKind))
270 return $ foldl Karrow hd maybeRest
272 coreAtomicKind = try liftedKind <|> try unliftedKind
273 <|> try openKind {- <|> try (parens equalityKind) -}
274 <|> try (parens coreKind)
294 -- Only used internally within the parser:
295 -- represents either a Tcon, or a continuation
296 -- for a primitive coercion
301 | Unsafe ([Ty] -> Ty)
302 | LeftCo ([Ty] -> Ty)
303 | RightCo ([Ty] -> Ty)
305 coreVdefGroups :: Parser [Vdefg]
306 coreVdefGroups = option [] (do
307 theFirstVdef <- coreVdefg
309 others <- coreVdefGroups
310 return $ theFirstVdef:others)
312 coreVdefg :: Parser Vdefg
313 coreVdefg = coreRecVdef <|> coreNonrecVdef
317 braces (sepBy1 coreVdef (symbol ";")) >>= (return . Rec)
319 coreNonrecVdef = coreVdef >>= (return . Nonrec)
322 (vdefLhs, vdefTy) <- try topVbind <|> (do
323 (v, ty) <- lambdaBind
324 return (unqual v, ty))
328 vdefRhs <- coreFullExp
329 return $ Vdef (vdefLhs, vdefTy, vdefRhs)
331 coreAtomicExp :: Parser Exp
333 -- For stupid reasons, the whiteSpace is necessary.
334 -- Without it, (pt coreAppExp "w ^a:B.C ") doesn't work.
336 res <- choice [try coreDconOrVar,
342 coreFullExp = (choice [coreLam, coreLet,
343 coreCase, coreCast, coreNote, coreExternal, coreLabel]) <|> (try coreAppExp)
344 -- The "try" is necessary so that we backtrack
345 -- when we see a var (that is not an app)
350 -- it's important to have a separate coreAtomicExp (that any app exp
351 -- begins with) and to define the args in terms of many1.
352 -- previously, coreAppExp could parse either an atomic exp (an app with
353 -- 0 arguments) or an app with >= 1 arguments, but that led to ambiguity.
354 oper <- try coreAtomicExp
356 args <- many1 (whiteSpace >> ((coreAtomicExp >>= (return . Left)) <|>
357 -- note this MUST be coreAty, not coreType, because otherwise:
358 -- "A @ B c" gets parsed as "A @ (B c)"
359 ((symbol "@" >> coreAtySaturated) >>= (return . Right))))
360 return $ foldl (\ op ->
361 either (App op) (Appt op)) oper args
364 theThing <- coreQualifiedGen (try upperName <|> identifier)
365 return $ case theThing of
366 -- note that data constructors must be qualified
367 (Just _, idItself) | isUpper (head idItself)
371 coreLit :: Parser Exp
372 coreLit = parens (coreLiteral >>= (return . Lit))
374 coreLiteral :: Parser Lit
383 binds <- coreLambdaBinds
386 return $ foldr Lam body binds
393 return $ Let vdefg body
396 ty <- coreAtySaturated
397 scrut <- coreAtomicExp
399 vBind <- parens lambdaBind
401 return $ Case scrut vBind ty alts
405 -- The parens are CRUCIAL, o/w it's ambiguous
406 body <- try (parens coreFullExp)
408 ty <- try coreAtySaturated
409 return $ Cast body ty
417 -- TODO: This isn't in the grammar, but GHC
418 -- always prints "external ccall". investigate...
421 t <- coreAtySaturated
422 return $ External s t) <|>
423 -- TODO: I don't really understand what this does
425 reserved "dynexternal"
427 t <- coreAtySaturated
428 return $ External "[dynamic]" t)
430 -- TODO: Totally punting this, but it needs to go in the grammar
434 return $ External s tAddrzh
436 coreLambdaBinds = many1 coreBind
438 coreBind = coreTbinding <|> coreVbind
440 coreTbinding = try coreAtTbind >>= (return . Tb)
441 coreVbind = parens (lambdaBind >>= (return . Vb))
443 coreAtTbind = (symbol "@") >> coreTbind
445 topVbind :: Parser (Qual Var, Ty)
446 topVbind = aCoreVbind coreQualifiedName
447 lambdaBind :: Parser (Var, Ty)
448 lambdaBind = aCoreVbind identifier
457 aLit :: Parser CoreLit
458 aLit = intOrRatLit <|> charLit <|> stringLit
460 intOrRatLit :: Parser CoreLit
462 -- Int and lit combined into one to avoid ambiguity.
465 maybeRhs <- optionMaybe (symbol "%" >> anIntLit)
467 Nothing -> return $ Lint lhs
468 Just rhs -> return $ Lrational (lhs % rhs)
470 anIntLit :: Parser Integer
472 sign <- option 1 (symbol "-" >> return (-1))
476 charLit :: Parser CoreLit
477 charLit = charLiteral >>= (return . Lchar)
478 -- make sure this is right
480 stringLit :: Parser CoreLit
481 stringLit = stringLiteral >>= (return . Lstring)
482 -- make sure this is right
484 coreAlts :: Parser [Alt]
485 coreAlts = braces $ sepBy1 coreAlt (symbol ";")
487 coreAlt :: Parser Alt
488 coreAlt = conAlt <|> litAlt <|> defaultAlt
492 conName <- coreQualifiedCon
493 tBinds <- many (parens coreAtTbind)
494 whiteSpace -- necessary b/c otherwise we parse the next list as empty
495 vBinds <- many (parens lambdaBind)
498 rhs <- try coreFullExp
499 return $ Acon conName tBinds vBinds rhs
503 l <- parens coreLiteral
508 defaultAlt :: Parser Alt
513 return $ Adefault rhs
515 extCore = P.makeTokenParser extCoreDef
517 parens = P.parens extCore
518 braces = P.braces extCore
519 -- newlines are allowed anywhere
520 whiteSpace = P.whiteSpace extCore <|> (newline >> return ())
521 symbol = P.symbol extCore
522 identifier = P.identifier extCore
523 -- Keywords all begin with '%'
524 reserved s = P.reserved extCore ('%':s)
525 natural = P.natural extCore
526 charLiteral = P.charLiteral extCore
527 stringLiteral = P.stringLiteral extCore
529 -- dodgy since Core doesn't really allow comments,
530 -- but we'll pretend...
531 extCoreDef = LanguageDef {
535 , nestedComments = True
537 , identLetter = lower <|> upper <|> digit <|> (char '\'')
538 , opStart = opLetter extCoreDef
539 , opLetter = oneOf ";=@:\\%_.*#?%"
540 , reservedNames = map ('%' :)
541 ["module", "data", "newtype", "rec",
542 "let", "in", "case", "of", "cast",
543 "note", "external", "forall"]
544 , reservedOpNames = [";", "=", "@", "::", "\\", "%_",
546 , caseSensitive = True
550 -- Stuff to help with testing in ghci.
551 pTest (Left a) = error (show a)
552 pTest (Right t) = print t
554 pTest1 :: Show a => CharParser () a -> String -> IO ()
556 let res = parse pr "" s
559 pt :: Show a => CharParser () a -> String -> IO ()