on 54e4e41 help sign in
Idris-dev/src/Idris/REPLParser.hs
486 lines 20 kB history raw
2module Idris.REPLParser (parseCmd, help, allHelp) where
4import System.FilePath ((</>))
5import System.Console.ANSI (Color(..))
7import Idris.Colours
8import Idris.AbsSyntax
9import Idris.Core.TT
10import Idris.Help
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
21import Debug.Trace
22import Data.List
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
29 where trim = f . f
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"
52 , cmd_apropos)
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"
73 , nameArg RmProof)
74 , (["showproof"], NameArg, "Show proof"
75 , nameArg ShowProof)
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"
87 , cmd_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"
94 , cmd_let)
95 , (["unlet", "undefine"], ManyArgs NameArg
96 , "Remove the listed repl definitions, or all repl definitions if no names given"
97 , cmd_unlet)
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."
101 , cmd_pprint)
102 ]
104parserCommands =
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"
132 , cmd_proofsearch)
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"
135 , cmd_refine)
136 , (["debugunify"], SeqArgs ExprArg ExprArg
137 , "(Debugging) Try to unify two expressions", const $ do
138 l <- P.simpleExpr defaultSyntax
139 r <- P.simpleExpr defaultSyntax
140 eof
141 return (Right (DebugUnify l r))
142 )
143 ]
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 ]
163 <|> unrecognized
164 <|> nop
165 <|> eval
166 where nop = do eof; return (Right NOP)
167 eval = exprArg Eval ""
168 unrecognized = do
169 P.lchar ':'
170 cmd <- many anyChar
171 let cmd' = takeWhile (/=' ') cmd
172 return (Left $ "Unrecognized command: " ++ cmd')
174cmd :: [String] -> P.IdrisParser String
175cmd xs = try $ do
176 P.lchar ':'
177 docmd sorted_xs
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)
186noArgs cmd name = do
187 let emptyArgs = do
188 eof
189 return (Right cmd)
191 let failure = return (Left $ ":" ++ name ++ " takes no arguments")
193 emptyArgs <|> failure
195exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)
196exprArg cmd name = do
197 let noArg = do
198 eof
199 return $ Left ("Usage is :" ++ name ++ " <expression>")
201 let properArg = do
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
213 eof
214 return (Right (cmd arg))
215 try emptyArgs <|> oneArg <|> failure
216 where
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)
228 where
229 toPath n = foldl1' (</>) $ splitOn "." n
231namespaceArg :: ([String] -> Command) -> String -> P.IdrisParser (Either String Command)
232namespaceArg = genArg "namespace" (fmap (toNS . fst) P.identifier)
233 where
234 toNS = splitOn "."
236optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)
237optArg cmd name = do
238 let emptyArgs = do
239 eof
240 return $ Left ("Usage is :" ++ name ++ " <option>")
242 let oneArg = do
243 o <- pOption
244 P.whiteSpace
245 eof
246 return (Right (cmd o))
248 let failure = return $ Left "Unrecognized setting"
250 try emptyArgs <|> oneArg <|> failure
252 where
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
260 <|> do discard (P.symbol "evaltypes"); return EvalTypes
262proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)
263proofArg cmd name = do
264 upd <- option False $ do
265 P.lchar '!'
266 return True
267 l <- fst <$> P.natural
268 n <- fst <$> P.name;
269 return (Right (cmd upd (fromInteger l) n))
271cmd_doc :: String -> P.IdrisParser (Either String Command)
272cmd_doc name = do
273 let constant = do
274 c <- fmap fst P.constant
275 eof
276 return $ Right (DocStr (Right c) FullDocs)
278 let pType = do
279 P.reserved "Type"
280 eof
281 return $ Right (DocStr (Left $ P.mkName ("Type", "")) FullDocs)
283 let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
285 try constant <|> pType <|> fnName
287cmd_consolewidth :: String -> P.IdrisParser (Either String Command)
288cmd_consolewidth name = do
289 w <- pConsoleWidth
290 return (Right (SetConsoleWidth w))
292 where
293 pConsoleWidth :: P.IdrisParser ConsoleWidth
294 pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth
295 <|> do discard (P.symbol "infinite"); return InfinitelyWide
296 <|> do n <- fmap (fromInteger . fst) P.natural
297 return (ColsWide n)
299cmd_printdepth :: String -> P.IdrisParser (Either String Command)
300cmd_printdepth _ = do d <- optional (fmap (fromInteger . fst) P.natural)
301 return (Right $ SetPrinterDepth d)
303cmd_execute :: String -> P.IdrisParser (Either String Command)
304cmd_execute name = do
305 tm <- option maintm (P.fullExpr defaultSyntax)
306 return (Right (Execute tm))
307 where
308 maintm = PRef (fileFC "(repl)") [] (sNS (sUN "main") ["Main"])
311cmd_dynamic :: String -> P.IdrisParser (Either String Command)
312cmd_dynamic name = do
313 let optArg = do l <- many anyChar
314 if (l /= "")
315 then return $ Right (DynamicLink l)
316 else return $ Right ListDynamic
318 let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
320 try optArg <|> failure
322cmd_pprint :: String -> P.IdrisParser (Either String Command)
323cmd_pprint name = do
324 fmt <- ppFormat
325 P.whiteSpace
326 n <- fmap (fromInteger . fst) P.natural
327 P.whiteSpace
328 t <- P.fullExpr defaultSyntax
329 return (Right (PPrint fmt n t))
331 where
332 ppFormat :: P.IdrisParser OutputFmt
333 ppFormat = (discard (P.symbol "html") >> return HTMLOutput)
334 <|> (discard (P.symbol "latex") >> return LaTeXOutput)
338cmd_compile :: String -> P.IdrisParser (Either String Command)
339cmd_compile name = do
340 let defaultCodegen = Via "c"
342 let codegenOption :: P.IdrisParser Codegen
343 codegenOption = do
344 let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode
345 viaCodegen = do x <- fst <$> P.identifier
346 return (Via (map toLower x))
347 bytecodeCodegen <|> viaCodegen
349 let hasOneArg = do
350 i <- get
351 f <- fst <$> P.identifier
352 eof
353 return $ Right (Compile defaultCodegen f)
355 let hasTwoArgs = do
356 i <- get
357 codegen <- codegenOption
358 f <- fst <$> P.identifier
359 eof
360 return $ Right (Compile codegen f)
362 let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
363 try hasTwoArgs <|> try hasOneArg <|> failure
365cmd_addproof :: String -> P.IdrisParser (Either String Command)
366cmd_addproof name = do
367 n <- option Nothing $ do
368 x <- fst <$> P.name
369 return (Just x)
370 eof
371 return (Right (AddProof n))
373cmd_log :: String -> P.IdrisParser (Either String Command)
374cmd_log name = do
375 i <- fmap (fromIntegral . fst) P.natural
376 eof
377 return (Right (LogLvl i))
379cmd_let :: String -> P.IdrisParser (Either String Command)
380cmd_let name = do
381 defn <- concat <$> many (P.decl defaultSyntax)
382 return (Right (NewDefn defn))
384cmd_unlet :: String -> P.IdrisParser (Either String Command)
385cmd_unlet name = (Right . Undefine) `fmap` many (fst <$> P.name)
387cmd_loadto :: String -> P.IdrisParser (Either String Command)
388cmd_loadto name = do
389 toline <- fmap (fromInteger . fst) P.natural
390 f <- many anyChar;
391 return (Right (Load f (Just toline)))
393cmd_colour :: String -> P.IdrisParser (Either String Command)
394cmd_colour name = fmap Right pSetColourCmd
396 where
397 colours :: [(String, Maybe Color)]
398 colours = [ ("black", Just Black)
399 , ("red", Just Red)
400 , ("green", Just Green)
401 , ("yellow", Just Yellow)
402 , ("blue", Just Blue)
403 , ("magenta", Just Magenta)
404 , ("cyan", Just Cyan)
405 , ("white", Just White)
406 , ("default", Nothing)
407 ]
409 pSetColourCmd :: P.IdrisParser Command
410 pSetColourCmd = (do c <- pColourType
411 let defaultColour = IdrisColour Nothing True False False False
412 opts <- sepBy pColourMod (P.whiteSpace)
413 let colour = foldr ($) defaultColour $ reverse opts
414 return $ SetColour c colour)
415 <|> try (P.symbol "on" >> return ColourOn)
416 <|> try (P.symbol "off" >> return ColourOff)
418 pColour :: P.IdrisParser (Maybe Color)
419 pColour = doColour colours
420 where doColour [] = fail "Unknown colour"
421 doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs
423 pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)
424 pColourMod = try (P.symbol "vivid" >> return doVivid)
425 <|> try (P.symbol "dull" >> return doDull)
426 <|> try (P.symbol "underline" >> return doUnderline)
427 <|> try (P.symbol "nounderline" >> return doNoUnderline)
428 <|> try (P.symbol "bold" >> return doBold)
429 <|> try (P.symbol "nobold" >> return doNoBold)
430 <|> try (P.symbol "italic" >> return doItalic)
431 <|> try (P.symbol "noitalic" >> return doNoItalic)
432 <|> try (pColour >>= return . doSetColour)
433 where doVivid i = i { vivid = True }
434 doDull i = i { vivid = False }
435 doUnderline i = i { underline = True }
436 doNoUnderline i = i { underline = False }
437 doBold i = i { bold = True }
438 doNoBold i = i { bold = False }
439 doItalic i = i { italic = True }
440 doNoItalic i = i { italic = False }
441 doSetColour c i = i { colour = c }
443 -- | Generate the colour type names using the default Show instance.
444 colourTypes :: [(String, ColourType)]
445 colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
446 enumFromTo minBound maxBound
448 pColourType :: P.IdrisParser ColourType
449 pColourType = doColourType colourTypes
450 where doColourType [] = fail $ "Unknown colour category. Options: " ++
451 (concat . intersperse ", " . map fst) colourTypes
452 doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts
454idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
456cmd_apropos :: String -> P.IdrisParser (Either String Command)
457cmd_apropos = packageBasedCmd (some idChar) Apropos
459packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
460 -> String -> P.IdrisParser (Either String Command)
461packageBasedCmd valParser cmd name =
462 try (do P.lchar '('
463 pkgs <- sepBy (some idChar) (P.lchar ',')
464 P.lchar ')'
465 val <- valParser
466 return (Right (cmd pkgs val)))
467 <|> do val <- valParser
468 return (Right (cmd [] val))
470cmd_search :: String -> P.IdrisParser (Either String Command)
471cmd_search = packageBasedCmd
472 (P.typeExpr (defaultSyntax { implicitAllowed = True })) Search
474cmd_proofsearch :: String -> P.IdrisParser (Either String Command)
475cmd_proofsearch name = do
476 upd <- option False (do P.lchar '!'; return True)
477 l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
478 hints <- many (fst <$> P.fnName)
479 return (Right (DoProofSearch upd True l n hints))
481cmd_refine :: String -> P.IdrisParser (Either String Command)
482cmd_refine name = do
483 upd <- option False (do P.lchar '!'; return True)
484 l <- fmap (fromInteger . fst) P.natural; n <- fst <$> P.name
485 hint <- fst <$> P.fnName
486 return (Right (DoProofSearch upd False l n [hint]))