1{-# LANGUAGE PatternGuards #-}
3module Idris.Parser where
21import Text.Parsec.Error
22import Text.Parsec.Expr
23import Text.Parsec.Language
24import Text.Parsec.String
25import qualified Text.Parsec.Token as PTok
28import Control.Monad.State
33type TokenParser a = PTok.TokenParser a
35type IParser = GenParser Char IState
37lexer :: TokenParser IState
40whiteSpace = PTok.whiteSpace lexer
41lexeme = PTok.lexeme lexer
42symbol = PTok.symbol lexer
43natural = PTok.natural lexer
44parens = PTok.parens lexer
46comma = PTok.comma lexer
47identifier = PTok.identifier lexer
48reserved = PTok.reserved lexer
49operator = PTok.operator lexer
50reservedOp = PTok.reservedOp lexer
51integer = PTok.integer lexer
52float = PTok.float lexer
53strlit = PTok.stringLiteral lexer
54chlit = PTok.charLiteral lexer
59loadModule :: FilePath -> Idris String
61 = idrisCatch (do i <- getIState
62 ibcsd <- valIBCSubDir i
63 ids <- allImportDirs i
64 fp <- liftIO $ findImport ids ibcsd f
65 if f `elem` imported i
66 then iLOG $ "Already read " ++ f
67 else do putIState (i { imported = f : imported i })
69 IDR fn -> loadSource False fn
70 LIDR fn -> loadSource True fn
72 idrisCatch (loadIBC fn)
73 (\c -> do iLOG $ fn ++ " failed " ++ show c
75 IDR sfn -> loadSource False sfn
76 LIDR sfn -> loadSource True sfn)
77 let (dir, fh) = splitFileName f
78 return (dropExtension fh))
79 (\e -> do let msg = show e
80 setErrLine (getErrLine msg)
84loadSource :: Bool -> FilePath -> Idris ()
86 = do iLOG ("Reading " ++ f)
88 let def_total = default_total i
89 file_in <- liftIO $ readFile f
90 file <- if lidr then tclift $ unlit f file_in else return file_in
91 (mname, modules, rest, pos) <- parseImports f file
93 putIState (i { default_access = Hidden })
94 mapM_ loadModule modules
95 clearIBC -- start a new .ibc file
96 mapM_ (addIBC . IBCImport) modules
97 ds' <- parseProg (defaultSyntax {syn_namespace = reverse mname })
99 let ds = namespaces mname ds'
100 logLvl 3 (dumpDecls ds)
102 logLvl 10 (show (toAlist (idris_implicits i)))
103 logLvl 3 (show (idris_infixes i))
104 -- Now add all the declarations to the context
106 when v $ iputStrLn $ "Type checking " ++ f
107 elabDecls toplevel ds
109 -- simplify every definition do give the totality checker
111 mapM_ (\n -> do logLvl 5 $ "Simplifying " ++ show n
112 updateContext (simplifyCasedef n))
113 (map snd (idris_totcheck i))
114 -- build size change graph from simplified definitions
115 iLOG "Totality checking"
117-- mapM_ buildSCG (idris_totcheck i)
118 mapM_ checkDeclTotality (idris_totcheck i)
119 iLOG ("Finished " ++ f)
120 ibcsd <- valIBCSubDir i
121 let ibc = ibcPathNoFallback ibcsd f
122 iLOG "Universe checking"
125 addHides (hide_list i)
128 idrisCatch (do writeIBC f ibc; clearIBC)
129 (\c -> return ()) -- failure is harmless
131 putIState (i { default_total = def_total,
135 namespaces [] ds = ds
136 namespaces (x:xs) ds = [PNamespace x (namespaces xs ds)]
138addHides :: [(Name, Maybe Accessibility)] -> Idris ()
139addHides xs = do i <- getIState
140 let defh = default_access i
141 let (hs, as) = partition isNothing xs
144 (map (\ (n, _) -> (n, defh)) hs ++
145 map (\ (n, Just a) -> (n, a)) as)
146 where isNothing (_, Nothing) = True
149 doHide (n, a) = do setAccessibility n a
150 addIBC (IBCAccess n a)
152parseExpr i = runParser (pFullExpr defaultSyntax) i "(input)"
153parseTac i = runParser (do t <- pTactic defaultSyntax
155 return t) i "(proof)"
157parseImports :: FilePath -> String -> Idris ([String], [String], String, SourcePos)
158parseImports fname input
160 case runParser (do whiteSpace
165 return ((mname, ps, rest, pos), i)) i fname input of
166 Left err -> fail (show err)
167 Right (x, i) -> do put i
170pHeader :: IParser [String]
171pHeader = try (do reserved "module"; i <- identifier; option ';' (lchar ';')
172 return (parseName i))
174 where parseName x = case span (/='.') x of
176 (x, '.':y) -> x : parseName y
178pushIndent :: IParser ()
179pushIndent = do pos <- getPosition
181 setState (ist { indent_stack = sourceColumn pos :
184lastIndent :: IParser Int
185lastIndent = do ist <- getState
186 case indent_stack ist of
191indent = liftM sourceColumn getPosition
193popIndent :: IParser ()
194popIndent = do ist <- getState
195 let (x : xs) = indent_stack ist
196 setState (ist { indent_stack = xs })
198openBlock :: IParser ()
199openBlock = do lchar '{'
201 setState (ist { brace_stack = Nothing : brace_stack ist })
202 <|> do ist <- getState
204 setState (ist { brace_stack = Just lvl : brace_stack ist })
206closeBlock :: IParser ()
207closeBlock = do ist <- getState
208 bs <- case brace_stack ist of
209 Nothing : xs -> (lchar '}' >> return xs) <|> (eof >> return [])
210 Just lvl : xs -> (do i <- indent
212-- trace (show (take 10 inp, i, lvl)) $
213 if i >= lvl && take 1 inp /= ")"
214 then fail "Not end of block"
215 else return xs) <|> (eof >> return [])
216 setState (ist { brace_stack = bs })
218pTerminator = do lchar ';'; popIndent
219 <|> do c <- indent; l <- lastIndent
222 else fail "Not a terminator"
224 if "}" `isPrefixOf` i || ")" `isPrefixOf` i
226 else fail "Not a terminator"
230 = do lchar '|'; return ()
231 <|> do c <- indent; l <- lastIndent
232 unless (c <= l) $ fail "Not a terminator"
236 = do lchar ';'; return ()
237 <|> do c <- indent; l <- lastIndent
238 unless (c <= l) $ fail "Not a terminator"
241 unless (h `elem` ["}", ")", "|"]) $ fail "Not a terminator"
244notEndApp = do c <- indent; l <- lastIndent
246 when (c <= l) $ fail "Terminator"
248notEndBlock = do ist <- getState
249 case brace_stack ist of
250 Just lvl : xs -> do i <- indent
252 when (i < lvl || ")" `isPrefixOf` inp) $ fail "End of block"
256pfc = do s <- getPosition
257 let (dir, file) = splitFileName (sourceName s)
261 return $ FC f (sourceLine s)
263pImport :: IParser String
264pImport = do reserved "import"; f <- identifier; option ';' (lchar ';')
269-- a program is a list of declarations, possibly with associated
270-- documentation strings
272parseProg :: SyntaxInfo -> FilePath -> String -> SourcePos ->
274parseProg syn fname input pos
276 case runParser (do setPosition pos
278 ps <- many (pDecl syn)
281 return (concat ps, i')) i fname input of
282 Left err -> fail (show err)
283 Right (x, i) -> do put i
286-- Collect PClauses with the same function name
288collect :: [PDecl] -> [PDecl]
289collect (c@(PClauses _ o _ _) : ds)
290 = clauses (cname c) [] (c : ds)
291 where clauses j@(Just n) acc (PClauses fc _ _ [PClause fc' n' l ws r w] : ds)
292 | n == n' = clauses j (PClause fc' n' l ws r (collect w) : acc) ds
293 clauses j@(Just n) acc (PClauses fc _ _ [PWith fc' n' l ws r w] : ds)
294 | n == n' = clauses j (PWith fc' n' l ws r (collect w) : acc) ds
295 clauses (Just n) acc xs = PClauses (getfc c) o n (reverse acc) : collect xs
296 clauses Nothing acc (x:xs) = collect xs
297 clauses Nothing acc [] = []
299 cname (PClauses fc _ _ [PClause _ n _ _ _ _]) = Just n
300 cname (PClauses fc _ _ [PWith _ n _ _ _ _]) = Just n
301 cname (PClauses fc _ _ [PClauseR _ _ _ _]) = Nothing
302 cname (PClauses fc _ _ [PWithR _ _ _ _]) = Nothing
303 getfc (PClauses fc _ _ _) = fc
305collect (PParams f ns ps : ds) = PParams f ns (collect ps) : collect ds
306collect (PMutual f ms : ds) = PMutual f (collect ms) : collect ds
307collect (PNamespace ns ps : ds) = PNamespace ns (collect ps) : collect ds
308collect (PClass doc f s cs n ps ds : ds')
309 = PClass doc f s cs n ps (collect ds) : collect ds'
310collect (PInstance f s cs n ps t en ds : ds')
311 = PInstance f s cs n ps t en (collect ds) : collect ds'
312collect (d : ds) = d : collect ds
315pFullExpr :: SyntaxInfo -> IParser PTerm
317 = do x <- pExpr syn; eof;
319 return $ desugar syn i x
321pDecl :: SyntaxInfo -> IParser [PDecl]
322pDecl syn = do notEndBlock
327 let d' = fmap (desugar syn i) d
335 <|> do d <- pDSL syn; return [d]
337 <|> try (do reserved "import"; fp <- identifier
338 fail "imports must be at the top of file")
340pFunDecl :: SyntaxInfo -> IParser [PDecl]
342 = try (do notEndBlock
345 let d' = fmap (desugar syn i) d
348--------- Top Level Declarations ---------
350pDecl' :: SyntaxInfo -> IParser PDecl
353 <|> try (pFunDecl' syn)
355 <|> try (pRecord syn)
356 <|> try (pSyntaxDecl syn)
358pSyntaxDecl :: SyntaxInfo -> IParser PDecl
360 = do s <- pSyntaxRule syn
362 let rs = syntax_rules i
363 let ns = syntax_keywords i
364 let ibc = ibc_write i
365 let ks = map show (names s)
366 setState (i { syntax_rules = s : rs,
367 syntax_keywords = ks ++ ns,
368 ibc_write = IBCSyntax s : map IBCKeyword ks ++ ibc
371 return (PSyntax fc s)
373 names (Rule syms _ _) = mapMaybe ename syms
374 ename (Keyword n) = Just n
377pSyntaxRule :: SyntaxInfo -> IParser Syntax
380 sty <- option AnySyntax (do reserved "term"; return TermSyntax
381 <|> do reserved "pattern"; return PatternSyntax)
383 syms <- many1 pSynSym
384 when (all expr syms) $ fail "No keywords in syntax rule"
385 let ns = mapMaybe name syms
386 when (length ns /= length (nub ns))
387 $ fail "Repeated variable in syntax rule"
389 tm <- pExpr (impOK syn)
391 return (Rule (mkSimple syms) tm sty)
395 name (Expr n) = Just n
398 -- Can't parse two full expressions (i.e. expressions with application) in a row
399 -- so change the first to a simple expression
401 mkSimple (Expr e : es) = SimpleExpr e : mkSimple' es
402 mkSimple xs = mkSimple' xs
404 mkSimple' (Expr e : Expr e1 : es) = SimpleExpr e : mkSimple' (Expr e1 : es)
405 mkSimple' (e : es) = e : mkSimple' es
408pSynSym :: IParser SSymbol
409pSynSym = try (do lchar '['; n <- pName; lchar ']'
411 <|> try (do lchar '{'; n <- pName; lchar '}'
418pFunDecl' :: SyntaxInfo -> IParser PDecl
419pFunDecl' syn = try (do doc <- option "" (pDocComment '|')
420 -- trace ("Doc: " ++ show doc) $
424 let initOpts = if default_total ist
427 opts <- pFnOpts initOpts
428 acc <- pAccessibility
429 opts' <- pFnOpts opts
431 let n = expandNS syn n_in
432 ty <- pTSig (impOK syn)
435-- ty' <- implicit syn n ty
437 return (PTy doc syn fc opts' n ty))
438 <|> try (pPattern syn)
441pUsing :: SyntaxInfo -> IParser [PDecl]
443 do reserved "using"; lchar '('; ns <- tyDeclList syn; lchar ')'
445 let uvars = using syn
446 ds <- many1 (pDecl (syn { using = uvars ++ ns }))
450pParams :: SyntaxInfo -> IParser [PDecl]
452 do reserved "parameters"; lchar '('; ns <- tyDeclList syn; lchar ')'
454 let pvars = syn_params syn
455 ds <- many1 (pDecl syn { syn_params = pvars ++ ns })
458 return [PParams fc ns (concat ds)]
460pMutual :: SyntaxInfo -> IParser [PDecl]
464 let pvars = syn_params syn
465 ds <- many1 (pDecl syn)
468 return [PMutual fc (concat ds)]
470pNamespace :: SyntaxInfo -> IParser [PDecl]
472 do reserved "namespace"; n <- identifier;
474 ds <- many1 (pDecl syn { syn_namespace = n : syn_namespace syn })
476 return [PNamespace n (concat ds)]
478--------- Fixity ---------
480pFixity :: IParser PDecl
481pFixity = do pushIndent
482 f <- fixity; i <- natural; ops <- sepBy1 operator (lchar ',')
484 let prec = fromInteger i
486 let infixes = idris_infixes istate
487 let fs = map (Fix (f prec)) ops
488 let redecls = map (alreadyDeclared infixes) fs
489 let ill = filter (not . checkValidity) redecls
491 then do setState (istate { idris_infixes = nub $ sort (fs ++ infixes)
492 , ibc_write = map IBCFix fs ++ ibc_write istate
495 return (PFix fc (f prec) ops)
496 else fail $ concatMap (\(f, (x:xs)) -> "Illegal redeclaration of fixity: \""
497 ++ show f ++ "\" overrides \"" ++ show x ++ "\"\n") ill
498 where alreadyDeclared :: [FixDecl] -> FixDecl -> (FixDecl, [FixDecl])
499 alreadyDeclared fs f = (f, filter ((extractName f ==) . extractName) fs)
501 checkValidity :: (FixDecl, [FixDecl]) -> Bool
502 checkValidity (f, fs) = all (== f) fs
504 extractName :: FixDecl -> String
505 extractName (Fix _ n) = n
507fixity :: IParser (Int -> Fixity)
508fixity = try (do reserved "infixl"; return Infixl)
509 <|> try (do reserved "infixr"; return Infixr)
510 <|> try (do reserved "infix"; return InfixN)
511 <|> try (do reserved "prefix"; return PrefixN)
513--------- Type classes ---------
515pClass :: SyntaxInfo -> IParser [PDecl]
516pClass syn = do doc <- option "" (pDocComment '|')
517 acc <- pAccessibility
518 reserved "class"; fc <- pfc; cons <- pConstList syn; n_in <- pName
519 let n = expandNS syn n_in
521 reserved "where"; openBlock
522 ds <- many $ pFunDecl syn
524 let allDs = concat ds
525 accData acc n (concatMap declared allDs)
526 return [PClass doc syn fc cons n cs allDs]
528 carg = do lchar '('; i <- pName; lchar ':'; ty <- pExpr syn; lchar ')'
533pInstance :: SyntaxInfo -> IParser [PDecl]
534pInstance syn = do reserved "instance"; fc <- pfc
536 (do lchar '['; n_in <- pfName; lchar ']'
537 let n = expandNS syn n_in
541 args <- many1 (pSimpleExpr syn)
542 let sc = PApp fc (PRef fc cn) (map pexp args)
543 let t = bindList (PPi constraint) (map (\x -> (MN 0 "c", x)) cs) sc
544 reserved "where"; openBlock
545 ds <- many $ pFunDecl syn
547 return [PInstance syn fc cs cn args t en (concat ds)]
549--------- Expressions ---------
551pExpr syn = do i <- getState
552 buildExpressionParser (table (idris_infixes i)) (pExpr' syn)
554pExpr' :: SyntaxInfo -> IParser PTerm
559pExtExpr :: SyntaxInfo -> IParser PTerm
560pExtExpr syn = do i <- getState
561 pExtensions syn (syntax_rules i)
563pSimpleExtExpr :: SyntaxInfo -> IParser PTerm
564pSimpleExtExpr syn = do i <- getState
565 pExtensions syn (filter simple (syntax_rules i))
567 simple (Rule (Expr x:xs) _ _) = False
568 simple (Rule (SimpleExpr x:xs) _ _) = False
569 simple (Rule [Keyword _] _ _) = True
570 simple (Rule [Symbol _] _ _) = True
571 simple (Rule (_:xs) _ _) = case last xs of
580 <|> try (pSimpleExpr syn)
585 <|> pComprehension syn
587pExtensions :: SyntaxInfo -> [Syntax] -> IParser PTerm
588pExtensions syn rules = choice (map (try . pExt syn) (filter valid rules))
590 valid (Rule _ _ AnySyntax) = True
591 valid (Rule _ _ PatternSyntax) = inPattern syn
592 valid (Rule _ _ TermSyntax) = not (inPattern syn)
595data SynMatch = SynTm PTerm | SynBind Name
597pExt :: SyntaxInfo -> Syntax -> IParser PTerm
598pExt syn (Rule ssym ptm _)
599 = do smap <- mapM pSymbol ssym
600 let ns = mapMaybe id smap
601 return (update ns ptm) -- updated with smap
603 pSymbol (Keyword n) = do reserved (show n); return Nothing
604 pSymbol (Expr n) = do tm <- pExpr syn
605 return $ Just (n, SynTm tm)
606 pSymbol (SimpleExpr n) = do tm <- pSimpleExpr syn
607 return $ Just (n, SynTm tm)
608 pSymbol (Binding n) = do b <- pName
609 return $ Just (n, SynBind b)
610 pSymbol (Symbol s) = do symbol s
613 dropn n ((x,t) : xs) | n == x = xs
614 | otherwise = (x,t):dropn n xs
616 updateB ns n = case lookup n ns of
617 Just (SynBind t) -> t
620 update ns (PRef fc n) = case lookup n ns of
623 update ns (PLam n ty sc) = PLam (updateB ns n) (update ns ty) (update (dropn n ns) sc)
624 update ns (PPi p n ty sc) = PPi p (updateB ns n) (update ns ty) (update (dropn n ns) sc)
625 update ns (PLet n ty val sc) = PLet (updateB ns n) (update ns ty) (update ns val)
626 (update (dropn n ns) sc)
627 update ns (PApp fc t args) = PApp fc (update ns t) (map (fmap (update ns)) args)
628 update ns (PCase fc c opts) = PCase fc (update ns c) (map (pmap (update ns)) opts)
629 update ns (PPair fc l r) = PPair fc (update ns l) (update ns r)
630 update ns (PDPair fc l t r) = PDPair fc (update ns l) (update ns t) (update ns r)
631 update ns (PAlternative a as) = PAlternative a (map (update ns) as)
632 update ns (PHidden t) = PHidden (update ns t)
633 update ns (PDoBlock ds) = PDoBlock $ upd ns ds
634 where upd ns (DoExp fc t : ds) = DoExp fc (update ns t) : upd ns ds
635 upd ns (DoBind fc n t : ds) = DoBind fc n (update ns t) : upd (dropn n ns) ds
636 upd ns (DoLet fc n ty t : ds) = DoLet fc n (update ns ty) (update ns t)
637 : upd (dropn n ns) ds
638 upd ns (DoBindP fc i t : ds) = DoBindP fc (update ns i) (update ns t)
640 upd ns (DoLetP fc i t : ds) = DoLetP fc (update ns i) (update ns t)
644pName = do i <- getState
645 iName (syntax_keywords i)
646 <|> do reserved "instance"
648 UN n <- iName (syntax_keywords i)
651-- Parser for an operator in function position, i.e. enclosed by `()', with an
652-- optional namespace.
653pOpFront = maybeWithNS pOpFrontNoNS False []
654 where pOpFrontNoNS = do lchar '('; o <- operator; lchar ')'; return o
659pTotality :: IParser Bool
661 = do reserved "total"; return True
662 <|> do reserved "partial"; return False
664pAccessibility' :: IParser Accessibility
666 = do reserved "public"; return Public
667 <|> do reserved "abstract"; return Frozen
668 <|> do reserved "private"; return Hidden
670pAccessibility :: IParser (Maybe Accessibility)
672 = do acc <- pAccessibility'; return (Just acc)
675pFnOpts :: [FnOpt] -> IParser [FnOpt]
677 = do reserved "total"; pFnOpts (TotalFn : opts)
678 <|> do reserved "partial"; pFnOpts (PartialFn : (opts \\ [TotalFn]))
679 <|> try (do lchar '%'; reserved "export"; c <- strlit;
680 pFnOpts (CExport c : opts))
681 <|> do lchar '%'; reserved "assert_total"; pFnOpts (AssertTotal : opts)
682 <|> do lchar '%'; reserved "specialise";
683 lchar '['; ns <- sepBy pfName (lchar ','); lchar ']'
684 pFnOpts (Specialise ns : opts)
687addAcc :: Name -> Maybe Accessibility -> IParser ()
688addAcc n a = do i <- getState
689 setState (i { hide_list = (n, a) : hide_list i })
692 reserved "case"; fc <- pfc; scr <- pExpr syn; reserved "of";
695 opts <- many1 (do notEndBlock
698 return x) -- sepBy1 (pCaseOpt syn) (lchar '|')
701 return (PCase fc scr opts)
704 reserved "proof"; lchar '{'
705 ts <- endBy (pTactic syn) (lchar ';')
710 reserved "tactics"; lchar '{'
711 ts <- endBy (pTactic syn) (lchar ';')
716 try (do symbol "!["; t <- pTerm; lchar ']'; return $ PQuote t)
717 <|> do lchar '?'; x <- pName; return (PMetavar x)
718 <|> do reserved "refl"; fc <- pfc;
719 tm <- option Placeholder (do lchar '{'; t <- pExpr syn; lchar '}';
722-- <|> do reserved "return"; fc <- pfc; return (PReturn fc)
726 <|> try (do x <- pfName
732 <|> try (do lchar '('
733 bracketed (noImp syn))
734 <|> try (do c <- pConstant
736 return (modifyConst syn fc (PConstant c)))
737 <|> do reserved "Set"; return PSet
738 <|> try (do symbol "()"
741 <|> try (do symbol "_|_"
744 <|> do lchar '_'; return Placeholder
745 <|> pSimpleExtExpr syn
749 <|> try (do e <- pExpr syn; lchar ')'; return e)
750-- <|> try (do reserved "typed"
751-- e <- pExpr syn; symbol ":"; t <- pExpr syn; lchar ')'
752-- return (PTyped e t))
753 <|> try (do fc <- pfc; o <- operator; e <- pExpr syn; lchar ')'
754 return $ PLam (MN 1000 "ARG") Placeholder
755 (PApp fc (PRef fc (UN o)) [pexp (PRef fc (MN 1000 "ARG")),
757 <|> try (do fc <- pfc; e <- pSimpleExpr syn; o <- operator; lchar ')'
758 return $ PLam (MN 1000 "ARG") Placeholder
759 (PApp fc (PRef fc (UN o)) [pexp e,
760 pexp (PRef fc (MN 1000 "ARG"))]))
762pCaseOpt :: SyntaxInfo -> IParser (PTerm, PTerm)
763pCaseOpt syn = do lhs <- pExpr syn; symbol "=>"; rhs <- pExpr syn
766modifyConst :: SyntaxInfo -> FC -> PTerm -> PTerm
767modifyConst syn fc (PConstant (I x))
768 | not (inPattern syn)
770 [PApp fc (PRef fc (UN "fromInteger")) [pexp (PConstant (I x))],
771 PConstant (I x), PConstant (BI (toEnum x))]
772 | otherwise = PAlternative False
773 [PConstant (I x), PConstant (BI (toEnum x))]
774modifyConst syn fc x = x
776pList syn = do lchar '['; fc <- pfc; xs <- sepBy (pExpr syn) (lchar ','); lchar ']'
777 return (mkList fc xs)
779 mkList fc [] = PRef fc (UN "Nil")
780 mkList fc (x : xs) = PApp fc (PRef fc (UN "::")) [pexp x, pexp (mkList fc xs)]
782pPair syn = try (do l <- pExpr syn
787 [Left r] -> return (PPair fc l r)
788 [Right r] -> return (PDPair fc l Placeholder r))
789 <|> try (do x <- ntuple
792 <|> do ln <- pName; lchar ':'
798 return (PDPair fc (PRef fc ln) lty r)
800 restTuple = do lchar ')'; return []
805 <|> do reservedOp "**"
809 ntuple = try (do l <- pExpr syn; fc <- pfc; lchar ','
811 return (PPair fc l rest))
812 <|> (do l <- pExpr syn; fc <- pfc; lchar ','
814 return (PPair fc l r))
816pAlt syn = do symbol "(|"; alts <- sepBy1 (pExpr' syn) (lchar ','); symbol "|)"
817 return (PAlternative False alts)
825pApp syn = do f <- pSimpleExpr syn
827 args <- many1 (do notEndApp
830 return (dslify i $ PApp fc f args)
832 dslify i (PApp fc (PRef _ f) [a])
833 | [d] <- lookupCtxt Nothing f (idris_dsls i)
834 = desugar (syn { dsl_info = d }) i (getTm a)
837pArg :: SyntaxInfo -> IParser PArg
838pArg syn = try (pImplicitArg syn)
839 <|> try (pConstraintArg syn)
840 <|> do e <- pSimpleExpr syn
843pImplicitArg syn = do lchar '{'
846 v <- option (PRef fc n) (do lchar '='
851pConstraintArg syn = do symbol "@{"
857 = do reserved "record"
859 fields <- sepBy1 pFieldSet (lchar ',')
862 rec <- option Nothing (do e <- pSimpleExpr syn
866 return (PLam (MN 0 "fldx") Placeholder
867 (applyAll fc fields (PRef fc (MN 0 "fldx"))))
868 Just v -> return (applyAll fc fields v)
869 where pFieldSet = do n <- pfName
874 applyAll fc ((n, e) : es) x
875 = applyAll fc es (PApp fc (PRef fc (mkSet n)) [pexp e, pexp x])
877mkSet (UN n) = UN ("set_" ++ n)
878mkSet (MN 0 n) = MN 0 ("set_" ++ n)
879mkSet (NS n s) = NS (mkSet n) s
881noImp syn = syn { implicitAllowed = False }
882impOK syn = syn { implicitAllowed = True }
884pTSig syn = do lchar ':'
885 cs <- if implicitAllowed syn then pConstList syn else return []
887 return (bindList (PPi constraint) (map (\x -> (MN 0 "c", x)) cs) sc)
889pLambda syn = do lchar '\\'
890 try (do xt <- tyOptDeclList syn
893 return (bindList PLam xt sc)
894 <|> (do ps <- sepBy (do fc <- pfc
896 return (fc, e)) (lchar ',')
899 return (pmList (zip [0..] ps) sc)))
900 where pmList [] sc = sc
901 pmList ((i, (fc, x)) : xs) sc
902 = PLam (MN i "lamp") Placeholder
903 (PCase fc (PRef fc (MN i "lamp"))
906pLet syn = try (do reserved "let"; n <- pName;
907 ty <- option Placeholder (do lchar ':'; pExpr' syn)
910 reserved "in"; sc <- pExpr syn
911 return (PLet n ty v sc))
912 <|> (do reserved "let"; fc <- pfc; pat <- pExpr' (syn { inPattern = True } )
913 symbol "="; v <- pExpr syn
914 reserved "in"; sc <- pExpr syn
915 return (PCase fc v [(pat, sc)]))
918 try (do lazy <- option False (do lchar '|'; return True)
920 lchar '('; xt <- tyDeclList syn; lchar ')'
921 doc <- option "" (pDocComment '^')
924 return (bindList (PPi (Exp lazy st doc)) xt sc))
925 <|> try (if implicitAllowed syn
926 then do lazy <- option False (do lchar '|'
934 return (bindList (PPi (Imp lazy st "")) xt sc)
935 else fail "No implicit arguments allowed here")
936 <|> try (do lchar '{'
942 return (bindList (PPi
943 (TacImp False Dynamic (PTactics [Trivial]) "")) xt sc))
944 <|> try (do lchar '{'
946 script <- pSimpleExpr syn
951 return (bindList (PPi (TacImp False Dynamic script "")) xt sc))
952 <|> do --lazy <- option False (do lchar '|'; return True)
959 return (PPi (Exp False Static "") (MN 42 "__pi_arg") t sc)
961pConstList :: SyntaxInfo -> IParser [PTerm]
962pConstList syn = try (do lchar '('
963 tys <- sepBy1 (pExpr' (noImp syn)) (lchar ',')
967 <|> try (do t <- pExpr (noImp syn)
972tyDeclList syn = try (sepBy1 (do x <- pfName
973 t <- pTSig (noImp syn)
976 <|> do ns <- sepBy1 pName (lchar ',')
977 t <- pTSig (noImp syn)
978 return (map (\x -> (x, t)) ns)
980tyOptDeclList syn = sepBy1 (do x <- pfName;
981 t <- option Placeholder (do lchar ':'
987bindList b ((n, t):bs) sc = b n t (bindList b bs sc)
994 qs <- sepBy1 (pDo syn) (lchar ',')
996 return (PDoBlock (map addGuard qs ++
997 [DoExp fc (PApp fc (PRef fc (UN "return"))
999 where addGuard (DoExp fc e) = DoExp fc (PApp fc (PRef fc (UN "guard"))
1007 ds <- many1 (do notEndBlock
1013 return (PDoBlock ds)
1016 = try (do reserved "let"
1018 ty <- option Placeholder (do lchar ':'
1023 return (DoLet fc i ty e))
1024 <|> try (do reserved "let"
1029 return (DoLetP fc i sc))
1030 <|> try (do i <- pName
1034 return (DoBind fc i e))
1035 <|> try (do i <- pExpr' syn
1039 return (DoBindP fc i e))
1040 <|> try (do e <- pExpr syn
1042 return (DoExp fc e))
1049 return (PIdiom fc e)
1051pConstant :: IParser Const
1052pConstant = do reserved "Integer";return BIType
1053 <|> do reserved "Int"; return IType
1054 <|> do reserved "Char"; return ChType
1055 <|> do reserved "Float"; return FlType
1056 <|> do reserved "String"; return StrType
1057 <|> do reserved "Ptr"; return PtrType
1058 <|> try (do f <- float; return $ Fl f)
1059-- <|> try (do i <- natural; lchar 'L'; return $ BI i)
1060 <|> try (do i <- natural; return $ I (fromInteger i))
1061 <|> try (do s <- strlit; return $ Str s)
1062 <|> try (do c <- chlit; return $ Ch c)
1064pStatic :: IParser Static
1065pStatic = do lchar '['
1072 = [[prefix "-" (\fc x -> PApp fc (PRef fc (UN "-"))
1073 [pexp (PApp fc (PRef fc (UN "fromInteger")) [pexp (PConstant (I 0))]), pexp x])]]
1074 ++ toTable (reverse fixes) ++
1076 [binary "=" PEq AssocLeft],
1077 [binary "->" (\fc x y -> PPi expl (MN 42 "__pi_arg") x y) AssocRight]]
1079toTable fs = map (map toBin)
1080 (groupBy (\ (Fix x _) (Fix y _) -> prec x == prec y) fs)
1081 where toBin (Fix (PrefixN _) op) = prefix op
1082 (\fc x -> PApp fc (PRef fc (UN op)) [pexp x])
1084 = binary op (\fc x y -> PApp fc (PRef fc (UN op)) [pexp x,pexp y]) (assoc f)
1085 assoc (Infixl _) = AssocLeft
1086 assoc (Infixr _) = AssocRight
1087 assoc (InfixN _) = AssocNone
1089binary name f = Infix (do reservedOp name
1091 doc <- option "" (pDocComment '^')
1093prefix name f = Prefix (do reservedOp name
1096backtick = Infix (do lchar '`'; n <- pfName
1099 return (\x y -> PApp fc (PRef fc n) [pexp x, pexp y])) AssocNone
1101--------- Data declarations ---------
1103-- (works for classes too - 'abstract' means the data/class is visible but members not)
1104accData :: Maybe Accessibility -> Name -> [Name] -> IParser ()
1105accData (Just Frozen) n ns = do addAcc n (Just Frozen)
1106 mapM_ (\n -> addAcc n (Just Hidden)) ns
1107accData a n ns = do addAcc n a
1108 mapM_ (`addAcc` a) ns
1110pRecord :: SyntaxInfo -> IParser PDecl
1111pRecord syn = do acc <- pAccessibility
1115 ty <- pTSig (impOK syn)
1116 let tyn = expandNS syn tyn_in
1120 (cdoc, cn, cty, _) <- pConstructor syn
1124 accData acc tyn [cn]
1125 let rsyn = syn { syn_namespace = show (nsroot tyn) :
1127 let fns = getRecNames rsyn cty
1128 mapM_ (\n -> addAcc n acc) fns
1129 return $ PRecord "" rsyn fc tyn ty cdoc cn cty
1131 getRecNames syn (PPi _ n _ sc) = [expandNS syn n, expandNS syn (mkSet n)]
1132 ++ getRecNames syn sc
1133 getRecNames _ _ = []
1135 toFreeze (Just Frozen) = Just Hidden
1138pDataI = do reserved "data"; return False
1139 <|> do reserved "codata"; return True
1141pData :: SyntaxInfo -> IParser PDecl
1142pData syn = try (do doc <- option "" (pDocComment '|')
1143 acc <- pAccessibility
1147 ty <- pTSig (impOK syn)
1148 let tyn = expandNS syn tyn_in
1149 option (PData doc syn fc co (PLaterdecl tyn ty)) (do
1153 cons <- many (do notEndBlock
1154 c <- pConstructor syn
1156 return c) -- (lchar '|')
1159 accData acc tyn (map (\ (_, n, _, _) -> n) cons)
1160 return $ PData doc syn fc co (PDatadecl tyn ty cons)))
1161 <|> try (do doc <- option "" (pDocComment '|')
1163 acc <- pAccessibility
1168 let ty = bindArgs (map (const PSet) args) PSet
1169 let tyn = expandNS syn tyn_in
1170 option (PData doc syn fc co (PLaterdecl tyn ty)) (do
1172 cons <- sepBy1 (pSimpleCon syn) (lchar '|')
1174 let conty = mkPApp fc (PRef fc tyn) (map (PRef fc) args)
1175 cons' <- mapM (\ (doc, x, cargs, cfc) ->
1176 do let cty = bindArgs cargs conty
1177 return (doc, x, cty, cfc)) cons
1178 accData acc tyn (map (\ (_, n, _, _) -> n) cons')
1179 return $ PData doc syn fc co (PDatadecl tyn ty cons')))
1182 mkPApp fc t xs = PApp fc t (map pexp xs)
1184bindArgs :: [PTerm] -> PTerm -> PTerm
1185bindArgs xs t = foldr (PPi expl (MN 0 "t")) t xs
1187pConstructor :: SyntaxInfo -> IParser (String, Name, PTerm, FC)
1189 = do doc <- option "" (pDocComment '|')
1190 cn_in <- pfName; fc <- pfc
1191 let cn = expandNS syn cn_in
1192 ty <- pTSig (impOK syn)
1193-- ty' <- implicit syn cn ty
1194 return (doc, cn, ty, fc)
1197pSimpleCon :: SyntaxInfo -> IParser (String, Name, [PTerm], FC)
1199 = do cn_in <- pfName
1200 let cn = expandNS syn cn_in
1202 args <- many (do notEndApp
1204 doc <- option "" (pDocComment '^')
1205 return (doc, cn, args, fc)
1207--------- DSL syntax overloading ---------
1209pDSL :: SyntaxInfo -> IParser PDecl
1210pDSL syn = do reserved "dsl"
1214 bs <- many1 (do notEndBlock
1218 popIndent; closeBlock
1219 let dsl = mkDSL bs (dsl_info syn)
1222 setState (i { idris_dsls = addDef n dsl (idris_dsls i) })
1224 where mkDSL bs dsl = let var = lookup "variable" bs
1225 first = lookup "index_first" bs
1226 next = lookup "index_next" bs
1227 leto = lookup "let" bs
1228 lambda = lookup "lambda" bs in
1229 initDSL { dsl_var = var,
1230 index_first = first,
1232 dsl_lambda = lambda,
1235checkDSL :: DSL -> IParser ()
1236checkDSL dsl = return ()
1238pOverload :: SyntaxInfo -> IParser (String, PTerm)
1239pOverload syn = do o <- identifier <|> do reserved "let"
1241 if o `notElem` overloadable
1242 then fail $ show o ++ " is not an overloading"
1247 where overloadable = ["let","lambda","index_first","index_next","variable"]
1249--------- Pattern match clauses ---------
1251pPattern :: SyntaxInfo -> IParser PDecl
1252pPattern syn = do fc <- pfc
1253 clause <- pClause syn
1254 return (PClauses fc [] (MN 2 "_") [clause]) -- collect together later
1256pCAF :: SyntaxInfo -> IParser PDecl
1257pCAF syn = do reserved "let"
1258 n_in <- pfName; let n = expandNS syn n_in
1263 return (PCAF fc n t)
1265pArgExpr syn = let syn' = syn { inPattern = True } in
1266 try (pHSimpleExpr syn') <|> pSimpleExtExpr syn'
1268pRHS :: SyntaxInfo -> Name -> IParser PTerm
1269pRHS syn n = do lchar '='; pExpr syn
1270 <|> do symbol "?="; rhs <- pExpr syn;
1272 <|> do reserved "impossible"; return PImpossible
1273 where mkN (UN x) = UN (x++"_lemma_1")
1274 mkN (NS x n) = NS (mkN x) n
1277 addLet (PLet n ty val rhs) = PLet n ty val (addLet rhs)
1278 addLet (PCase fc t cs) = PCase fc t (map addLetC cs)
1279 where addLetC (l, r) = (l, addLet r)
1280 addLet rhs = (PLet (UN "value") Placeholder rhs (PMetavar n'))
1282pClause :: SyntaxInfo -> IParser PClause
1284 = try (do pushIndent
1285 n_in <- pfName; let n = expandNS syn n_in
1286 cargs <- many (pConstraintArg syn)
1287 iargs <- many (pImplicitArg (syn { inPattern = True } ))
1289 args <- many (pArgExpr syn)
1290 wargs <- many (pWExpr syn)
1293 let ctxt = tt_ctxt ist
1294 let wsyn = syn { syn_namespace = [] }
1295 (wheres, nmap) <- choice [do x <- pWhereblock n wsyn
1300 let capp = PApp fc (PRef fc n)
1301 (iargs ++ cargs ++ map pexp args)
1303 setState (ist { lastParse = Just n })
1304 return $ PClause fc n capp wargs rhs wheres)
1305 <|> try (do pushIndent
1306 wargs <- many1 (pWExpr syn)
1308 n <- case lastParse ist of
1310 Nothing -> fail "Invalid clause"
1313 let ctxt = tt_ctxt ist
1314 let wsyn = syn { syn_namespace = [] }
1315 (wheres, nmap) <- choice [do x <- pWhereblock n wsyn
1320 return $ PClauseR fc wargs rhs wheres)
1322 <|> try (do pushIndent
1323 n_in <- pfName; let n = expandNS syn n_in
1324 cargs <- many (pConstraintArg syn)
1325 iargs <- many (pImplicitArg (syn { inPattern = True } ))
1327 args <- many (pArgExpr syn)
1328 wargs <- many (pWExpr syn)
1329 let capp = PApp fc (PRef fc n)
1330 (iargs ++ cargs ++ map pexp args)
1332 setState (ist { lastParse = Just n })
1334 wval <- pSimpleExpr syn
1336 ds <- many1 $ pFunDecl syn
1337 let withs = map (fillLHSD n capp wargs) $ concat ds
1340 return $ PWith fc n capp wargs wval withs)
1342 <|> try (do wargs <- many1 (pWExpr syn)
1345 wval <- pSimpleExpr syn
1347 ds <- many1 $ pFunDecl syn
1348 let withs = concat ds
1350 return $ PWithR fc wargs wval withs)
1355 let n = expandNS syn (UN op)
1358 wargs <- many (pWExpr syn)
1360 let wsyn = syn { syn_namespace = [] }
1361 (wheres, nmap) <- choice [do x <- pWhereblock n wsyn
1367 let capp = PApp fc (PRef fc n) [pexp l, pexp r]
1368 setState (ist { lastParse = Just n })
1369 return $ PClause fc n capp wargs rhs wheres
1371 <|> do l <- pArgExpr syn
1373 let n = expandNS syn (UN op)
1376 wargs <- many (pWExpr syn)
1378 wval <- pSimpleExpr syn
1380 ds <- many1 $ pFunDecl syn
1383 let capp = PApp fc (PRef fc n) [pexp l, pexp r]
1384 let withs = map (fillLHSD n capp wargs) $ concat ds
1385 setState (ist { lastParse = Just n })
1386 return $ PWith fc n capp wargs wval withs
1388 fillLHS n capp owargs (PClauseR fc wargs v ws)
1389 = PClause fc n capp (owargs ++ wargs) v ws
1390 fillLHS n capp owargs (PWithR fc wargs v ws)
1391 = PWith fc n capp (owargs ++ wargs) v
1392 (map (fillLHSD n capp (owargs ++ wargs)) ws)
1395 fillLHSD n c a (PClauses fc o fn cs) = PClauses fc o fn (map (fillLHS n c a) cs)
1396 fillLHSD n c a x = x
1398pWExpr :: SyntaxInfo -> IParser PTerm
1399pWExpr syn = do lchar '|'
1402pWhereblock :: Name -> SyntaxInfo -> IParser ([PDecl], [(Name, Name)])
1404 = do reserved "where"; openBlock
1405 ds <- many1 $ pDecl syn
1406 let dns = concatMap (concatMap declared) ds
1408 return (concat ds, map (\x -> (x, decoration syn x)) dns)
1410pDirective :: IParser [PDecl]
1411pDirective = try (do lchar '%'; reserved "lib"; lib <- strlit;
1412 return [PDirective (do addLib lib
1413 addIBC (IBCLib lib))])
1414 <|> try (do lchar '%'; reserved "link"; obj <- strlit;
1415 return [PDirective (do datadir <- liftIO getDataDir
1416 o <- liftIO $ findInPath [".", datadir] obj
1419 <|> try (do lchar '%'; reserved "include"; hdr <- strlit;
1420 return [PDirective (do addHdr hdr
1421 addIBC (IBCHeader hdr))])
1422 <|> try (do lchar '%'; reserved "hide"; n <- iName []
1423 return [PDirective (do setAccessibility n Hidden
1424 addIBC (IBCAccess n Hidden))])
1425 <|> try (do lchar '%'; reserved "freeze"; n <- iName []
1426 return [PDirective (do setAccessibility n Frozen
1427 addIBC (IBCAccess n Frozen))])
1428 <|> try (do lchar '%'; reserved "access"; acc <- pAccessibility'
1429 return [PDirective (do i <- getIState
1430 putIState (i { default_access = acc }))])
1431 <|> try (do lchar '%'; reserved "default"; tot <- pTotality
1433 setState (i { default_total = tot } )
1434 return [PDirective (do i <- getIState
1435 putIState (i { default_total = tot }))])
1436 <|> try (do lchar '%'; reserved "logging"; i <- natural;
1437 return [PDirective (setLogLevel (fromInteger i))])
1439pTactic :: SyntaxInfo -> IParser PTactic
1440pTactic syn = do reserved "intro"; ns <- sepBy pName (lchar ',')
1442 <|> do reserved "intros"; return Intros
1443 <|> try (do reserved "refine"; n <- pName
1445 return $ Refine n imps)
1446 <|> do reserved "refine"; n <- pName
1448 return $ Refine n []
1449 <|> do reserved "rewrite"; t <- pExpr syn;
1451 return $ Rewrite (desugar syn i t)
1452 <|> do reserved "let"; n <- pName; lchar '=';
1455 return $ LetTac n (desugar syn i t)
1456 <|> do reserved "focus"; n <- pName
1458 <|> do reserved "exact"; t <- pExpr syn;
1460 return $ Exact (desugar syn i t)
1461 <|> do reserved "try"; t <- pTactic syn;
1471 <|> do reserved "compute"; return Compute
1472 <|> do reserved "trivial"; return Trivial
1473 <|> do reserved "solve"; return Solve
1474 <|> do reserved "attack"; return Attack
1475 <|> do reserved "state"; return ProofState
1476 <|> do reserved "term"; return ProofTerm
1477 <|> do reserved "undo"; return Undo
1478 <|> do reserved "qed"; return Qed
1479 <|> do reserved "abandon"; return Abandon
1480 <|> do lchar ':'; reserved "q"; return Abandon
1482 imp = do lchar '?'; return False
1483 <|> do lchar '_'; return True
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list