on 76ec3fe help sign in
Idris-dev/src/Idris/REPLParser.hs
462 lines 18 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 . dropWhile isSpace
30type CommandTable = [ ( [String], CmdArg, String
31 , String -> P.IdrisParser (Either String Command) ) ]
33help :: [([String], CmdArg, String)]
34help = (["<expr>"], NoArg, "Evaluate an expression") :
35 [ (map (':' :) names, args, text) | (names, args, text, _) <- parserCommandsForHelp ]
37allHelp :: [([String], CmdArg, String)]
38allHelp = [ (map (':' :) names, args, text)
39 | (names, args, text, _) <- parserCommandsForHelp ++ parserCommands ]
41parserCommandsForHelp :: CommandTable
42parserCommandsForHelp =
43 [ exprArgCmd ["t", "type"] Check "Check the type of an expression"
44 , exprArgCmd ["core"] Core "View the core language representation of a term"
45 , nameArgCmd ["miss", "missing"] Missing "Show missing clauses"
46 , (["doc"], NameArg, "Show internal documentation", cmd_doc)
47 , (["mkdoc"], NamespaceArg, "Generate IdrisDoc for namespace(s) and dependencies"
48 , genArg "namespace" (many anyChar) MakeDoc)
49 , (["apropos"], SeqArgs (OptionalArg PkgArgs) NameArg, " Search names, types, and documentation"
50 , cmd_apropos)
51 , (["s", "search"], SeqArgs (OptionalArg PkgArgs) ExprArg
52 , " Search for values by type", cmd_search)
53 , nameArgCmd ["wc", "whocalls"] WhoCalls "List the callers of some name"
54 , nameArgCmd ["cw", "callswho"] CallsWho "List the callees of some name"
55 , nameArgCmd ["total"] TotCheck "Check the totality of a name"
56 , noArgCmd ["r", "reload"] Reload "Reload current file"
57 , (["l", "load"], FileArg, "Load a new file"
58 , strArg (\f -> Load f Nothing))
59 , (["cd"], FileArg, "Change working directory"
60 , strArg ChangeDirectory)
61 , (["module"], ModuleArg, "Import an extra module", moduleArg ModImport) -- NOTE: dragons
62 , noArgCmd ["e", "edit"] Edit "Edit current file using $EDITOR or $VISUAL"
63 , noArgCmd ["m", "metavars"] Metavars "Show remaining proof obligations (metavariables)"
64 , (["p", "prove"], MetaVarArg, "Prove a metavariable"
65 , nameArg Prove)
66 , (["a", "addproof"], NameArg, "Add proof to source file", cmd_addproof)
67 , (["rmproof"], NameArg, "Remove proof from proof stack"
68 , nameArg RmProof)
69 , (["showproof"], NameArg, "Show proof"
70 , nameArg ShowProof)
71 , noArgCmd ["proofs"] Proofs "Show available proofs"
72 , exprArgCmd ["x"] ExecVal "Execute IO actions resulting from an expression using the interpreter"
73 , (["c", "compile"], FileArg, "Compile to an executable [codegen] <filename>", cmd_compile)
74 , (["exec", "execute"], OptionalArg ExprArg, "Compile to an executable and run", cmd_execute)
75 , (["dynamic"], FileArg, "Dynamically load a C library (similar to %dynamic)", cmd_dynamic)
76 , (["dynamic"], NoArg, "List dynamically loaded C libraries", cmd_dynamic)
77 , noArgCmd ["?", "h", "help"] Help "Display this help text"
78 , optArgCmd ["set"] SetOpt "Set an option (errorcontext, showimplicits)"
79 , optArgCmd ["unset"] UnsetOpt "Unset an option"
80 , (["color", "colour"], ColourArg
81 , "Turn REPL colours on or off; set a specific colour"
82 , cmd_colour)
83 , (["consolewidth"], ConsoleWidthArg, "Set the width of the console", cmd_consolewidth)
84 , noArgCmd ["q", "quit"] Quit "Exit the Idris system"
85 , noArgCmd ["w", "warranty"] Warranty "Displays warranty information"
86 , (["let"], ManyArgs DeclArg
87 , "Evaluate a declaration, such as a function definition, instance implementation, or fixity declaration"
88 , cmd_let)
89 , (["unlet", "undefine"], ManyArgs NameArg
90 , "Remove the listed repl definitions, or all repl definitions if no names given"
91 , cmd_unlet)
92 , nameArgCmd ["printdef"] PrintDef "Show the definition of a function"
93 , (["pp", "pprint"], (SeqArgs OptionArg (SeqArgs NumberArg NameArg))
94 , "Pretty prints an Idris function in either LaTeX or HTML and for a specified width."
95 , cmd_pprint)
96 ]
98parserCommands =
99 [ noArgCmd ["u", "universes"] Universes "Display universe constraints"
100 , noArgCmd ["errorhandlers"] ListErrorHandlers "List registered error handlers"
102 , nameArgCmd ["d", "def"] Defn "Display a name's internal definitions"
103 , nameArgCmd ["transinfo"] TransformInfo "Show relevant transformation rules for a name"
104 , nameArgCmd ["di", "dbginfo"] DebugInfo "Show debugging information for a name"
106 , exprArgCmd ["patt"] Pattelab "(Debugging) Elaborate pattern expression"
107 , exprArgCmd ["spec"] Spec "?"
108 , exprArgCmd ["hnf"] HNF "?"
109 , exprArgCmd ["inline"] TestInline "?"
110 , proofArgCmd ["cs", "casesplit"] CaseSplitAt
111 ":cs <line> <name> splits the pattern variable on the line"
112 , proofArgCmd ["apc", "addproofclause"] AddProofClauseFrom
113 ":apc <line> <name> adds a pattern-matching proof clause to name on line"
114 , proofArgCmd ["ac", "addclause"] AddClauseFrom
115 ":ac <line> <name> adds a clause for the definition of the name on the line"
116 , proofArgCmd ["am", "addmissing"] AddMissing
117 ":am <line> <name> adds all missing pattern matches for the name on the line"
118 , proofArgCmd ["mw", "makewith"] MakeWith
119 ":mw <line> <name> adds a with clause for the definition of the name on the line"
120 , proofArgCmd ["ml", "makelemma"] MakeLemma "?"
121 , (["log"], NumberArg, "Set logging verbosity level", cmd_log)
122 , (["lto", "loadto"], SeqArgs NumberArg FileArg
123 , "Load file up to line number", cmd_loadto)
124 , (["ps", "proofsearch"], NoArg
125 , ":ps <line> <name> <names> does proof search for name on line, with names as hints"
126 , cmd_proofsearch)
127 , (["ref", "refine"], NoArg
128 , ":ref <line> <name> <name'> attempts to partially solve name on line, with name' as hint, introducing metavariables for arguments that aren't inferrable"
129 , cmd_refine)
130 , (["debugunify"], SeqArgs ExprArg ExprArg
131 , "(Debugging) Try to unify two expressions", const $ do
132 l <- P.simpleExpr defaultSyntax
133 r <- P.simpleExpr defaultSyntax
134 eof
135 return (Right (DebugUnify l r))
136 )
137 ]
139noArgCmd names command doc =
140 (names, NoArg, doc, noArgs command)
141nameArgCmd names command doc =
142 (names, NameArg, doc, fnNameArg command)
143exprArgCmd names command doc =
144 (names, ExprArg, doc, exprArg command)
145metavarArgCmd names command doc =
146 (names, MetaVarArg, doc, fnNameArg command)
147optArgCmd names command doc =
148 (names, OptionArg, doc, optArg command)
149proofArgCmd names command doc =
150 (names, NoArg, doc, proofArg command)
152pCmd :: P.IdrisParser (Either String Command)
153pCmd = choice [ do c <- cmd names; parser c
154 | (names, _, _, parser) <- parserCommandsForHelp ++ parserCommands ]
155 <|> unrecognized
156 <|> nop
157 <|> eval
158 where nop = do eof; return (Right NOP)
159 eval = exprArg Eval ""
160 unrecognized = do
161 P.lchar ':'
162 cmd <- many anyChar
163 let cmd' = takeWhile (/=' ') cmd
164 return (Left $ "Unrecognized command: " ++ cmd')
166cmd :: [String] -> P.IdrisParser String
167cmd xs = try $ do
168 P.lchar ':'
169 docmd sorted_xs
171 where docmd [] = fail "Could not parse command"
172 docmd (x:xs) = try (P.reserved x >> return x) <|> docmd xs
174 sorted_xs = sortBy (\x y -> compare (length y) (length x)) xs
177noArgs :: Command -> String -> P.IdrisParser (Either String Command)
178noArgs cmd name = do
179 let emptyArgs = do
180 eof
181 return (Right cmd)
183 let failure = return (Left $ ":" ++ name ++ " takes no arguments")
185 emptyArgs <|> failure
187exprArg :: (PTerm -> Command) -> String -> P.IdrisParser (Either String Command)
188exprArg cmd name = do
189 let noArg = do
190 eof
191 return $ Left ("Usage is :" ++ name ++ " <expression>")
193 let properArg = do
194 t <- P.fullExpr defaultSyntax
195 return $ Right (cmd t)
196 try noArg <|> properArg
200genArg :: String -> P.IdrisParser a -> (a -> Command)
201 -> String -> P.IdrisParser (Either String Command)
202genArg argName argParser cmd name = do
203 let emptyArgs = do eof; failure
204 oneArg = do arg <- argParser
205 eof
206 return (Right (cmd arg))
207 try emptyArgs <|> oneArg <|> failure
208 where
209 failure = return $ Left ("Usage is :" ++ name ++ " <" ++ argName ++ ">")
211nameArg, fnNameArg :: (Name -> Command) -> String -> P.IdrisParser (Either String Command)
212nameArg = genArg "name" P.name
213fnNameArg = genArg "functionname" P.fnName
215strArg :: (String -> Command) -> String -> P.IdrisParser (Either String Command)
216strArg = genArg "string" (many anyChar)
218moduleArg :: (FilePath -> Command) -> String -> P.IdrisParser (Either String Command)
219moduleArg = genArg "module" (fmap toPath P.identifier)
220 where
221 toPath n = foldl1' (</>) $ splitOn "." n
223optArg :: (Opt -> Command) -> String -> P.IdrisParser (Either String Command)
224optArg cmd name = do
225 let emptyArgs = do
226 eof
227 return $ Left ("Usage is :" ++ name ++ " <option>")
229 let oneArg = do
230 o <- pOption
231 P.whiteSpace
232 eof
233 return (Right (cmd o))
235 let failure = return $ Left "Unrecognized setting"
237 try emptyArgs <|> oneArg <|> failure
239 where
240 pOption :: P.IdrisParser Opt
241 pOption = do discard (P.symbol "errorcontext"); return ErrContext
242 <|> do discard (P.symbol "showimplicits"); return ShowImpl
243 <|> do discard (P.symbol "originalerrors"); return ShowOrigErr
244 <|> do discard (P.symbol "autosolve"); return AutoSolve
245 <|> do discard (P.symbol "nobanner") ; return NoBanner
246 <|> do discard (P.symbol "warnreach"); return WarnReach
248proofArg :: (Bool -> Int -> Name -> Command) -> String -> P.IdrisParser (Either String Command)
249proofArg cmd name = do
250 upd <- option False $ do
251 P.lchar '!'
252 return True
253 l <- P.natural
254 n <- P.name;
255 return (Right (cmd upd (fromInteger l) n))
257cmd_doc :: String -> P.IdrisParser (Either String Command)
258cmd_doc name = do
259 let constant = do
260 c <- P.constant
261 eof
262 return $ Right (DocStr (Right c) FullDocs)
264 let fnName = fnNameArg (\n -> DocStr (Left n) FullDocs) name
266 try constant <|> fnName
268cmd_consolewidth :: String -> P.IdrisParser (Either String Command)
269cmd_consolewidth name = do
270 w <- pConsoleWidth
271 return (Right (SetConsoleWidth w))
273 where
274 pConsoleWidth :: P.IdrisParser ConsoleWidth
275 pConsoleWidth = do discard (P.symbol "auto"); return AutomaticWidth
276 <|> do discard (P.symbol "infinite"); return InfinitelyWide
277 <|> do n <- fmap fromInteger P.natural; return (ColsWide n)
279cmd_execute :: String -> P.IdrisParser (Either String Command)
280cmd_execute name = do
281 tm <- option maintm (P.fullExpr defaultSyntax)
282 return (Right (Execute tm))
283 where
284 maintm = PRef (fileFC "(repl)") (sNS (sUN "main") ["Main"])
287cmd_dynamic :: String -> P.IdrisParser (Either String Command)
288cmd_dynamic name = do
289 let emptyArgs = noArgs ListDynamic name
291 let oneArg = do l <- many anyChar
292 return $ Right (DynamicLink l)
294 let failure = return $ Left $ "Usage is :" ++ name ++ " [<library>]"
296 try emptyArgs <|> try oneArg <|> failure
298cmd_pprint :: String -> P.IdrisParser (Either String Command)
299cmd_pprint name = do
300 fmt <- ppFormat
301 P.whiteSpace
302 n <- fmap fromInteger P.natural
303 P.whiteSpace
304 t <- P.fullExpr defaultSyntax
305 return (Right (PPrint fmt n t))
307 where
308 ppFormat :: P.IdrisParser OutputFmt
309 ppFormat = (discard (P.symbol "html") >> return HTMLOutput)
310 <|> (discard (P.symbol "latex") >> return LaTeXOutput)
314cmd_compile :: String -> P.IdrisParser (Either String Command)
315cmd_compile name = do
316 let defaultCodegen = Via "c"
318 let codegenOption :: P.IdrisParser Codegen
319 codegenOption = do
320 let bytecodeCodegen = discard (P.symbol "bytecode") *> return Bytecode
321 viaCodegen = do x <- P.identifier
322 return (Via (map toLower x))
323 bytecodeCodegen <|> viaCodegen
325 let hasOneArg = do
326 i <- get
327 f <- P.identifier
328 eof
329 return $ Right (Compile defaultCodegen f)
331 let hasTwoArgs = do
332 i <- get
333 codegen <- codegenOption
334 f <- P.identifier
335 eof
336 return $ Right (Compile codegen f)
338 let failure = return $ Left $ "Usage is :" ++ name ++ " [<codegen>] <filename>"
339 try hasTwoArgs <|> try hasOneArg <|> failure
341cmd_addproof :: String -> P.IdrisParser (Either String Command)
342cmd_addproof name = do
343 n <- option Nothing $ do
344 x <- P.name;
345 return (Just x)
346 eof
347 return (Right (AddProof n))
349cmd_log :: String -> P.IdrisParser (Either String Command)
350cmd_log name = do
351 i <- P.natural
352 eof
353 return (Right (LogLvl (fromIntegral i)))
355cmd_let :: String -> P.IdrisParser (Either String Command)
356cmd_let name = do
357 defn <- concat <$> many (P.decl defaultSyntax)
358 return (Right (NewDefn defn))
360cmd_unlet :: String -> P.IdrisParser (Either String Command)
361cmd_unlet name = (Right . Undefine) `fmap` many P.name
363cmd_loadto :: String -> P.IdrisParser (Either String Command)
364cmd_loadto name = do
365 toline <- P.natural
366 f <- many anyChar;
367 return (Right (Load f (Just (fromInteger toline))))
369cmd_colour :: String -> P.IdrisParser (Either String Command)
370cmd_colour name = fmap Right pSetColourCmd
372 where
373 colours :: [(String, Maybe Color)]
374 colours = [ ("black", Just Black)
375 , ("red", Just Red)
376 , ("green", Just Green)
377 , ("yellow", Just Yellow)
378 , ("blue", Just Blue)
379 , ("magenta", Just Magenta)
380 , ("cyan", Just Cyan)
381 , ("white", Just White)
382 , ("default", Nothing)
383 ]
385 pSetColourCmd :: P.IdrisParser Command
386 pSetColourCmd = (do c <- pColourType
387 let defaultColour = IdrisColour Nothing True False False False
388 opts <- sepBy pColourMod (P.whiteSpace)
389 let colour = foldr ($) defaultColour $ reverse opts
390 return $ SetColour c colour)
391 <|> try (P.symbol "on" >> return ColourOn)
392 <|> try (P.symbol "off" >> return ColourOff)
394 pColour :: P.IdrisParser (Maybe Color)
395 pColour = doColour colours
396 where doColour [] = fail "Unknown colour"
397 doColour ((s, c):cs) = (try (P.symbol s) >> return c) <|> doColour cs
399 pColourMod :: P.IdrisParser (IdrisColour -> IdrisColour)
400 pColourMod = try (P.symbol "vivid" >> return doVivid)
401 <|> try (P.symbol "dull" >> return doDull)
402 <|> try (P.symbol "underline" >> return doUnderline)
403 <|> try (P.symbol "nounderline" >> return doNoUnderline)
404 <|> try (P.symbol "bold" >> return doBold)
405 <|> try (P.symbol "nobold" >> return doNoBold)
406 <|> try (P.symbol "italic" >> return doItalic)
407 <|> try (P.symbol "noitalic" >> return doNoItalic)
408 <|> try (pColour >>= return . doSetColour)
409 where doVivid i = i { vivid = True }
410 doDull i = i { vivid = False }
411 doUnderline i = i { underline = True }
412 doNoUnderline i = i { underline = False }
413 doBold i = i { bold = True }
414 doNoBold i = i { bold = False }
415 doItalic i = i { italic = True }
416 doNoItalic i = i { italic = False }
417 doSetColour c i = i { colour = c }
419 -- | Generate the colour type names using the default Show instance.
420 colourTypes :: [(String, ColourType)]
421 colourTypes = map (\x -> ((map toLower . reverse . drop 6 . reverse . show) x, x)) $
422 enumFromTo minBound maxBound
424 pColourType :: P.IdrisParser ColourType
425 pColourType = doColourType colourTypes
426 where doColourType [] = fail $ "Unknown colour category. Options: " ++
427 (concat . intersperse ", " . map fst) colourTypes
428 doColourType ((s,ct):cts) = (try (P.symbol s) >> return ct) <|> doColourType cts
430idChar = oneOf (['a'..'z'] ++ ['A'..'Z'] ++ ['0'..'9'] ++ ['_'])
432cmd_apropos :: String -> P.IdrisParser (Either String Command)
433cmd_apropos = packageBasedCmd (some idChar) Apropos
435packageBasedCmd :: P.IdrisParser a -> ([String] -> a -> Command)
436 -> String -> P.IdrisParser (Either String Command)
437packageBasedCmd valParser cmd name = do
438 pkgs <- option [] . try $ do
439 P.lchar '('
440 pks <- sepBy (some idChar) (P.lchar ',')
441 P.lchar ')'
442 return pks
443 val <- valParser
444 return (Right (cmd pkgs val))
446cmd_search :: String -> P.IdrisParser (Either String Command)
447cmd_search = packageBasedCmd
448 (P.typeExpr (defaultSyntax { implicitAllowed = True })) Search
450cmd_proofsearch :: String -> P.IdrisParser (Either String Command)
451cmd_proofsearch name = do
452 upd <- option False (do P.lchar '!'; return True)
453 l <- P.natural; n <- P.name;
454 hints <- many P.fnName
455 return (Right (DoProofSearch upd True (fromInteger l) n hints))
457cmd_refine :: String -> P.IdrisParser (Either String Command)
458cmd_refine name = do
459 upd <- option False (do P.lchar '!'; return True)
460 l <- P.natural; n <- P.name;
461 hint <- P.fnName
462 return (Right (DoProofSearch upd False (fromInteger l) n [hint]))