2module Idris.REPLParser (parseCmd, help, allHelp) where
4import System.FilePath ((</>))
5import System.Console.ANSI (Color(..))
11import qualified Idris.Parser as P
13import Control.Applicative
14import Control.Monad.State.Strict
16import Text.Parser.Combinators
17import Text.Parser.Char(anyChar,oneOf)
18import Text.Trifecta(Result, parseString)
19import Text.Trifecta.Delta
23import Data.List.Split(splitOn)
24import Data.Char(isSpace, toLower)
25import qualified Data.ByteString.UTF8 as UTF8
27parseCmd :: IState -> String -> String -> Result (Either String Command)
28parseCmd i inputname = P.runparser pCmd i inputname . trim
30 where f = reverse . dropWhile isSpace
32type CommandTable = [ ( [String], CmdArg, String
33 , String -> P.IdrisParser (Either String Command) ) ]
35help :: [([String], CmdArg, String)]
36help = (["<expr>"], NoArg, "Evaluate an expression") :
37 [ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
39allHelp :: [([String], CmdArg, String)]
40allHelp = [ (map (':' :) names, args, text)
41 | (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
43parserCommandsForHelp :: CommandTable
44parserCommandsForHelp =
45 [ exprArgCmd ["t", "type"] Check "Check the type of an expression"
46 , exprArgCmd ["core"] Core "View the core language representation of a term"
47 , nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
48 , (["doc"], NameArg, "Show internal documentation", cmd_doc)
49 , (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
50 , genArg "namespace" (many anyChar) MakeDoc)
51 , (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
53 , (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
54 , " Search for values by type", cmd_search)
55 , nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
56 , nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
57 , namespaceArgCmd ["browse"] Browse "List the contents of some namespace"
58 , nameArgCmd ["total"] TotCheck "Check the totality of a name"
59 , noArgCmd ["r", "reload"] Reload "Reload current file"
60 , (["l", "load"], FileArg, "Load a new file"
61 , strArg (\f -> Load f Nothing))
62 , (["cd"], FileArg, "Change working directory"
63 , strArg ChangeDirectory)
64 , (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
65 , noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
66 , noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables or holes)"
67 , (["p", "prove"], MetaVarArg, "Prove a metavariable"
68 , nameArg (Prove False))
69 , (["elab"], MetaVarArg, "Build a metavariable using the elaboration shell"
70 , nameArg (Prove True))
71 , (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
72 , (["rmproof"], NameArg, "Remove proof from proof stack"
74 , (["showproof"], NameArg, "Show proof"
76 , noArgCmd ["proofs"] Proofs "Show available proofs"
77 , exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
78 , (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
79 , (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
80 , (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
81 , (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
82 , noArgCmd ["?", "h", "help"] Help "Display this help text"
83 , optArgCmd ["set"] SetOpt "Set an option (errorcontext, showimplicits)"
84 , optArgCmd ["unset"] UnsetOpt "Unset an option"
85 , (["color", "colour"], ColourArg
86 , "Turn REPL colours on or off; set a specific colour"
88 , (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
89 , (["printerdepth"], OptionalArg NumberArg, "Set the maximum pretty-printer depth (no arg for infinite)", cmd_printdepth)
90 , noArgCmd ["q", "quit"] Quit "Exit the Idris system"
91 , noArgCmd ["w", "warranty"] Warranty "Displays warranty information"
92 , (["let"], ManyArgs DeclArg
93 , "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
95 , (["unlet", "undefine"], ManyArgs NameArg
96 , "Remove the listed repl definitions, or all repl definitions if no names given"
98 , nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
99 , (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
100 , "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
105 [ noArgCmd ["u", "universes"] Universes "Display universe constraints"
106 , noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
108 , nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
109 , nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
110 , nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
112 , exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
113 , exprArgCmd ["spec"] Spec "?"
114 , exprArgCmd ["whnf"] WHNF "(Debugging) Show weak head normal form of an expression"
115 , exprArgCmd ["inline"] TestInline "?"
116 , proofArgCmd ["cs", "casesplit"] CaseSplitAt
117 ":cs <line> <name> splits the pattern variable on the line"
118 , proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
119 ":apc <line> <name> adds a pattern-matching proof clause to name on line"
120 , proofArgCmd ["ac", "addclause"] AddClauseFrom
121 ":ac <line> <name> adds a clause for the definition of the name on the line"
122 , proofArgCmd ["am", "addmissing"] AddMissing
123 ":am <line> <name> adds all missing pattern matches for the name on the line"
124 , proofArgCmd ["mw", "makewith"] MakeWith
125 ":mw <line> <name> adds a with clause for the definition of the name on the line"
126 , proofArgCmd ["ml", "makelemma"] MakeLemma "?"
127 , (["log"], NumberArg, "Set logging verbosity level", cmd_log)
128 , (["lto", "loadto"], SeqArgs NumberArg FileArg
129 , "Load file up to line number", cmd_loadto)
130 , (["ps", "proofsearch"], NoArg
131 , ":ps <line> <name> <names> does proof search for name on line, with names as hints"
133 , (["ref", "refine"], NoArg
134 , ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
136 , (["debugunify"], SeqArgs ExprArg ExprArg
137 , "(Debugging) Try to unify two expressions", const $ do
138 l <- P.simpleExpr defaultSyntax
139 r <- P.simpleExpr defaultSyntax
141 return (Right (DebugUnify l r))
145noArgCmd names command doc =
146 (names, NoArg, doc, noArgs command)
147nameArgCmd names command doc =
148 (names, NameArg, doc, fnNameArg command)
149namespaceArgCmd names command doc =
150 (names, NamespaceArg, doc, namespaceArg command)
151exprArgCmd names command doc =
152 (names, ExprArg, doc, exprArg command)
153metavarArgCmd names command doc =
154 (names, MetaVarArg, doc, fnNameArg command)
155optArgCmd names command doc =
156 (names, OptionArg, doc, optArg command)
157proofArgCmd names command doc =
158 (names, NoArg, doc, proofArg command)
160pCmd :: P.IdrisParser (Either String Command)
161pCmd = choice [ do c <- cmd names; parser c
162 | (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
166 where nop = do eof; return (Right NOP)
167 eval = exprArg Eval ""
171 let cmd' = takeWhile (/=' ') cmd
172 return (Left $ "Unrecognized command: " ++ cmd')
174cmd :: [String] -> P.IdrisParser String
179 where docmd [] = fail "Could not parse command"
180 docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs
182 sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
185noArgs :: Command -> String -> P.IdrisParser (Either String Command)
191 let failure = return (Left $ ":" ++ name ++ " takes no arguments")
193 emptyArgs <|> failure
195exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)
199 return $ Left ("Usage is :" ++ name ++ " <expression>")
202 t <- P.fullExpr defaultSyntax
203 return $ Right (cmd t)
204 try noArg <|> properArg
208genArg :: String -> P.IdrisParser a -> (a -> Command)
209 -> String -> P.IdrisParser (Either String Command)
210genArg argName argParser cmd name = do
211 let emptyArgs = do eof; failure
212 oneArg = do arg <- argParser
214 return (Right (cmd arg))
215 try emptyArgs <|> oneArg <|> failure
217 failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
219nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command)
220nameArg = genArg "name" $ fst <$> P.name
221fnNameArg = genArg "functionname" $ fst <$> P.fnName
223strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command)
224strArg = genArg "string" (many anyChar)
226moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command)
227moduleArg = genArg "module" (fmap (toPath . fst) P.identifier)
229 toPath n = foldl1' (</>) $ splitOn "." n
231namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command)
232namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier)
236optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)
240 return $ Left ("Usage is :" ++ name ++ " <option>")
246 return (Right (cmd o))
248 let failure = return $ Left "Unrecognized setting"
250 try emptyArgs <|> oneArg <|> failure
253 pOption :: P.IdrisParser Opt
254 pOption = do discard (P.symbol "errorcontext"); return ErrContext
255 <|> do discard (P.symbol "showimplicits"); return ShowImpl
256 <|> do discard (P.symbol "originalerrors"); return ShowOrigErr
257 <|> do discard (P.symbol "autosolve"); return AutoSolve
258 <|> do discard (P.symbol "nobanner") ; return NoBanner
259 <|> do discard (P.symbol "warnreach"); return WarnReach
261proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)
262proofArg cmd name = do
263 upd <- option False $ do
266 l <- fst <$> P.natural
268 return (Right (cmd upd (fromInteger l) n))
270cmd_doc :: String -> P.IdrisParser (Either String Command)
273 c <- fmap fst P.constant
275 return $ Right (DocStr (Right c) FullDocs)
280 return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs)
282 let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
284 try constant <|> pType <|> fnName
286cmd_consolewidth :: String -> P.IdrisParser (Either String Command)
287cmd_consolewidth name = do
289 return (Right (SetConsoleWidth w))
292 pConsoleWidth :: P.IdrisParser ConsoleWidth
293 pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth
294 <|> do discard (P.symbol "infinite"); return InfinitelyWide
295 <|> do n <- fmap (fromInteger . fst) P.natural
298cmd_printdepth :: String -> P.IdrisParser (Either String Command)
299cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural)
300 return (Right $ SetPrinterDepth d)
302cmd_execute :: String -> P.IdrisParser (Either String Command)
304 tm <- option maintm (P.fullExpr defaultSyntax)
305 return (Right (Execute tm))
307 maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
310cmd_dynamic :: String -> P.IdrisParser (Either String Command)
312 let optArg = do l <- many anyChar
314 then return $ Right (DynamicLink l)
315 else return $ Right ListDynamic
317 let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
319 try optArg <|> failure
321cmd_pprint :: String -> P.IdrisParser (Either String Command)
325 n <- fmap (fromInteger . fst) P.natural
327 t <- P.fullExpr defaultSyntax
328 return (Right (PPrint fmt n t))
331 ppFormat :: P.IdrisParser OutputFmt
332 ppFormat = (discard (P.symbol "html") >> return HTMLOutput)
333 <|> (discard (P.symbol "latex") >> return LaTeXOutput)
337cmd_compile :: String -> P.IdrisParser (Either String Command)
339 let defaultCodegen = Via "c"
341 let codegenOption :: P.IdrisParser Codegen
343 let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode
344 viaCodegen = do x <- fst <$> P.identifier
345 return (Via (map toLower x))
346 bytecodeCodegen <|> viaCodegen
350 f <- fst <$> P.identifier
352 return $ Right (Compile defaultCodegen f)
356 codegen <- codegenOption
357 f <- fst <$> P.identifier
359 return $ Right (Compile codegen f)
361 let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
362 try hasTwoArgs <|> try hasOneArg <|> failure
364cmd_addproof :: String -> P.IdrisParser (Either String Command)
365cmd_addproof name = do
366 n <- option Nothing $ do
370 return (Right (AddProof n))
372cmd_log :: String -> P.IdrisParser (Either String Command)
374 i <- fmap (fromIntegral . fst) P.natural
376 return (Right (LogLvl i))
378cmd_let :: String -> P.IdrisParser (Either String Command)
380 defn <- concat <$> many (P.decl defaultSyntax)
381 return (Right (NewDefn defn))
383cmd_unlet :: String -> P.IdrisParser (Either String Command)
384cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name)
386cmd_loadto :: String -> P.IdrisParser (Either String Command)
388 toline <- fmap (fromInteger . fst) P.natural
390 return (Right (Load f (Just toline)))
392cmd_colour :: String -> P.IdrisParser (Either String Command)
393cmd_colour name = fmap Right pSetColourCmd
396 colours :: [(String, Maybe Color)]
397 colours = [ ("black", Just Black)
399 , ("green", Just Green)
400 , ("yellow", Just Yellow)
401 , ("blue", Just Blue)
402 , ("magenta", Just Magenta)
403 , ("cyan", Just Cyan)
404 , ("white", Just White)
405 , ("default", Nothing)
408 pSetColourCmd :: P.IdrisParser Command
409 pSetColourCmd = (do c <- pColourType
410 let defaultColour = IdrisColour Nothing True False False False
411 opts <- sepBy pColourMod (P.whiteSpace)
412 let colour = foldr ($) defaultColour $ reverse opts
413 return $ SetColour c colour)
414 <|> try (P.symbol "on" >> return ColourOn)
415 <|> try (P.symbol "off" >> return ColourOff)
417 pColour :: P.IdrisParser (Maybe Color)
418 pColour = doColour colours
419 where doColour [] = fail "Unknown colour"
420 doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs
422 pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)
423 pColourMod = try (P.symbol "vivid" >> return doVivid)
424 <|> try (P.symbol "dull" >> return doDull)
425 <|> try (P.symbol "underline" >> return doUnderline)
426 <|> try (P.symbol "nounderline" >> return doNoUnderline)
427 <|> try (P.symbol "bold" >> return doBold)
428 <|> try (P.symbol "nobold" >> return doNoBold)
429 <|> try (P.symbol "italic" >> return doItalic)
430 <|> try (P.symbol "noitalic" >> return doNoItalic)
431 <|> try (pColour >>= return . doSetColour)
432 where doVivid i = i { vivid = True }
433 doDull i = i { vivid = False }
434 doUnderline i = i { underline = True }
435 doNoUnderline i = i { underline = False }
436 doBold i = i { bold = True }
437 doNoBold i = i { bold = False }
438 doItalic i = i { italic = True }
439 doNoItalic i = i { italic = False }
440 doSetColour c i = i { colour = c }
442 -- | Generate the colour type names using the default Show instance.
443 colourTypes :: [(String, ColourType)]
444 colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
445 enumFromTo minBound maxBound
447 pColourType :: P.IdrisParser ColourType
448 pColourType = doColourType colourTypes
449 where doColourType [] = fail $ "Unknown colour category. Options: " ++
450 (concat . intersperse ", " . map fst) colourTypes
451 doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts
453idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
455cmd_apropos :: String -> P.IdrisParser (Either String Command)
456cmd_apropos = packageBasedCmd (some idChar) Apropos
458packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
459 -> String -> P.IdrisParser (Either String Command)
460packageBasedCmd valParser cmd name =
462 pkgs <- sepBy (some idChar) (P.lchar ',')
465 return (Right (cmd pkgs val)))
466 <|> do val <- valParser
467 return (Right (cmd [] val))
469cmd_search :: String -> P.IdrisParser (Either String Command)
470cmd_search = packageBasedCmd
471 (P.typeExpr (defaultSyntax { implicitAllowed = True })) Search
473cmd_proofsearch :: String -> P.IdrisParser (Either String Command)
474cmd_proofsearch name = do
475 upd <- option False (do P.lchar '!'; return True)
476 l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
477 hints <- many (fst <$> P.fnName)
478 return (Right (DoProofSearch upd True l n hints))
480cmd_refine :: String -> P.IdrisParser (Either String Command)
482 upd <- option False (do P.lchar '!'; return True)
483 l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
484 hint <- fst <$> P.fnName
485 return (Right (DoProofSearch upd False l n [hint]))
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