on master help sign in
Merge pull request #2009 from david-christiansen/wip/tactical

New-style tactics can do type declarations

commit2a2468f5818d8d54c91c3ea5dba608235eccdc8d authorDavid Christiansen <david@davidchristiansen.dk> dateWed 18 Mar 2015, 05:24 (12 years ago) parent147149b84019b6
14 files changed+293−109
idris.cabal+1 libs/prelude/Language/Reflection/Tactical.idr+14 src/Idris/AbsSyntax.hs+14−1 src/Idris/AbsSyntaxTree.hs+9−3 src/Idris/Core/TT.hs+1−1 src/Idris/Elab/Clause.hs+34−22 src/Idris/Elab/Instance.hs+5−3 src/Idris/Elab/Transform.hs+10−4 src/Idris/Elab/Type.hs+10−6 src/Idris/Elab/Utils.hs+10−8 src/Idris/Elab/Value.hs+8−3 src/Idris/ElabTerm.hs+145−58 src/Idris/Reflection.hs+18 test/tactics001/Tactics.idr+14
idris.cabal+1
@@ -730,6 +730,7 @@ Library
730730 , Idris.ProofSearch
731731 , Idris.Prover
732732 , Idris.Providers
733+ , Idris.Reflection
733734 , Idris.REPL
734735 , Idris.REPLParser
735736 , Idris.Transforms
libs/prelude/Language/Reflection/Tactical.idr+14
@@ -8,6 +8,14 @@ import Prelude.Maybe
88import Prelude.Monad
99import Language.Reflection
1010
11+data Arg : Type where
12+ Explicit : TTName -> Raw -> Arg
13+ Implicit : TTName -> Raw -> Arg
14+ Constraint : TTName -> Raw -> Arg
15+
16+data TyDecl : Type where
17+ Declare : TTName -> List Arg -> Raw -> TyDecl
18+
1119abstract
1220data Tactical : Type -> Type where
1321 -- obligatory control stuff
@@ -39,8 +47,11 @@ data Tactical : Type -> Type where
3947 prim__Claim : TTName -> Raw -> Tactical ()
4048 prim__Intro : Maybe TTName -> Tactical ()
4149
50+ prim__DeclareType : TyDecl -> Tactical ()
51+
4252 prim__Debug : {a : Type} -> Maybe String -> Tactical a
4353
54+
4455-------------
4556-- Public API
4657-------------
@@ -117,6 +128,9 @@ sourceLocation = do loc <- getSourceLocation
117128rewriteWith : Raw -> Tactical ()
118129rewriteWith rule = prim__Rewrite rule
119130
131+declareType : TyDecl -> Tactical ()
132+declareType decl = prim__DeclareType decl
133+
120134debug : Tactical a
121135debug = prim__Debug Nothing
122136
src/Idris/AbsSyntax.hs+14−1
@@ -455,6 +455,10 @@ getIState = get
455455putIState :: IState -> Idris ()
456456putIState = put
457457
458+updateIState :: (IState -> IState) -> Idris ()
459+updateIState f = do i <- getIState
460+ putIState $ f i
461+
458462withContext :: (IState -> Ctxt a) -> Name -> b -> (a -> Idris b) -> Idris b
459463withContext ctx name dflt action = do
460464 ist <- getIState
@@ -547,7 +551,16 @@ addConstraints fc (v, cs)
547551addDeferred = addDeferred' Ref
548552addDeferredTyCon = addDeferred' (TCon 0 0)
549553
550−addDeferred' :: NameType -> [(Name, (Int, Maybe Name, Type, Bool))] -> Idris ()
554+-- | Save information about a name that is not yet defined
555+addDeferred' :: NameType
556+ -> [(Name, (Int, Maybe Name, Type, Bool))]
557+ -- ^ The Name is the name being made into a metavar,
558+ -- the Int is the number of vars that are part of a
559+ -- putative proof context, the Maybe Name is the
560+ -- top-level function containing the new metavariable,
561+ -- the Type is its type, and the Bool is whether :p is
562+ -- allowed
563+ -> Idris ()
551564addDeferred' nt ns
552565 = do mapM_ (\(n, (i, _, t, _)) -> updateContext (addTyDecl n nt (tidyNames S.empty t))) ns
553566 mapM_ (\(n, _) -> when (not (n `elem` primDefs)) $ addIBC (IBCMetavar n)) ns
src/Idris/AbsSyntaxTree.hs+9−3
@@ -184,7 +184,11 @@ data IState = IState {
184184 idris_name :: Int,
185185 idris_lineapps :: [((FilePath, Int), PTerm)],
186186 -- ^ Full application LHS on source line
187− idris_metavars :: [(Name, (Maybe Name, Int, Bool))], -- ^ The currently defined but not proven metavariables
187+ idris_metavars :: [(Name, (Maybe Name, Int, Bool))],
188+ -- ^ The currently defined but not proven metavariables. The Int
189+ -- is the number of vars to display as a context, the Maybe Name
190+ -- is its top-level function, and the Bool is whether :p is
191+ -- allowed
188192 idris_coercions :: [Name],
189193 idris_errRev :: [(Term, Term)],
190194 syntax_rules :: SyntaxRules,
@@ -632,10 +636,12 @@ deriving instance NFData PDecl'
632636-- For elaborator state
633637data EState = EState {
634638 case_decls :: [PDecl],
635− delayed_elab :: [Elab' EState ()]
639+ delayed_elab :: [Elab' EState ()],
640+ new_tyDecls :: [(Name, FC, [PArg], Type)]
636641 }
637642
638−initEState = EState [] []
643+initEState :: EState
644+initEState = EState [] [] []
639645
640646type ElabD a = Elab' EState a
641647
src/Idris/Core/TT.hs+1−1
@@ -509,7 +509,7 @@ toAlist :: Ctxt a -> [(Name, a)]
509509toAlist ctxt = let allns = map snd (Map.toList ctxt) in
510510 concatMap (Map.toList) allns
511511
512−addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
512+addAlist :: [(Name, a)] -> Ctxt a -> Ctxt a
513513addAlist [] ctxt = ctxt
514514addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
515515
src/Idris/Elab/Clause.hs+34−22
@@ -455,8 +455,10 @@ checkPossible info fc tcgen fname lhs_in
455455 -- if the LHS type checks, it is possible
456456 case elaborate ctxt (sMN 0 "patLHS") infP initEState
457457 (erun fc (buildTC i info ELHS [] fname (infTerm lhs))) of
458− OK ((lhs', _, _), _) ->
459− do let lhs_tm = orderPats (getInferTerm lhs')
458+ OK (ElabResult lhs' _ _ ctxt' newDecls, _) ->
459+ do setContext ctxt'
460+ processTacticDecls newDecls
461+ let lhs_tm = orderPats (getInferTerm lhs')
460462 case recheck ctxt [] (forget lhs_tm) lhs_tm of
461463 OK _ -> return True
462464 err -> return False
@@ -579,14 +581,15 @@ elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as wherebloc
579581 logLvl 4 ("Fixed parameters: " ++ show params ++ " from " ++ show lhs_in ++
580582 "\n" ++ show (fn_ty, fn_is))
581583
582− (((lhs', dlhs, []), probs, inj), _) <-
583− tclift $ elaborate ctxt (sMN 0 "patLHS") infP initEState
584− (do res <- errAt "left hand side of " fname
585− (erun fc (buildTC i info ELHS opts fname (infTerm lhs)))
586− probs <- get_probs
587− inj <- get_inj
588− return (res, probs, inj))
589−
584+ ((ElabResult lhs' dlhs [] ctxt' newDecls, probs, inj), _) <-
585+ tclift $ elaborate ctxt (sMN 0 "patLHS") infP initEState
586+ (do res <- errAt "left hand side of " fname
587+ (erun fc (buildTC i info ELHS opts fname (infTerm lhs)))
588+ probs <- get_probs
589+ inj <- get_inj
590+ return (res, probs, inj))
591+ setContext ctxt'
592+ processTacticDecls newDecls
590593 when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
591594
592595 let lhs_tm = orderPats (getInferTerm lhs')
@@ -653,13 +656,14 @@ elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as wherebloc
653656 logLvl 2 $ "RHS: " ++ show (map fst newargs_all) ++ " " ++ showTmImpls rhs
654657 ctxt <- getContext -- new context with where block added
655658 logLvl 5 "STARTING CHECK"
656− ((rhs', defer, is, probs), _) <-
659+ ((rhs', defer, is, probs, ctxt', newDecls), _) <-
657660 tclift $ elaborate ctxt (sMN 0 "patRHS") clhsty initEState
658661 (do pbinds ist lhs_tm
659662 mapM_ setinj (nub (params ++ inj))
660663 setNextName
661− (_, _, is) <- errAt "right hand side of " fname
662− (erun fc (build i winfo ERHS opts fname rhs))
664+ (ElabResult _ _ is ctxt' newDecls) <-
665+ errAt "right hand side of " fname
666+ (erun fc (build i winfo ERHS opts fname rhs))
663667 errAt "right hand side of " fname
664668 (erun fc $ psolve lhs_tm)
665669 hs <- get_holes
@@ -668,8 +672,9 @@ elabClause info opts (cnum, PClause fc fname lhs_in_as withs rhs_in_as wherebloc
668672 tt <- get_term
669673 let (tm, ds) = runState (collectDeferred (Just fname) tt) []
670674 probs <- get_probs
671− return (tm, ds, is, probs))
672−
675+ return (tm, ds, is, probs, ctxt', newDecls))
676+ setContext ctxt'
677+ processTacticDecls newDecls
673678 when inf $ addTyInfConstraints fc (map (\(x,y,_,_,_,_,_) -> (x,y)) probs)
674679
675680 logLvl 5 "DONE CHECK"
@@ -812,10 +817,12 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
812817 let params = getParamsInType i [] fn_is fn_ty
813818 let lhs = stripLinear i $ stripUnmatchable i $ propagateParams i params fn_ty (addImplPat i lhs_in)
814819 logLvl 2 ("LHS: " ++ show lhs)
815− ((lhs', dlhs, []), _) <-
820+ (ElabResult lhs' dlhs [] ctxt' newDecls, _) <-
816821 tclift $ elaborate ctxt (sMN 0 "patLHS") infP initEState
817822 (errAt "left hand side of with in " fname
818823 (erun fc (buildTC i info ELHS opts fname (infTerm lhs))) )
824+ setContext ctxt'
825+ processTacticDecls newDecls
819826 let lhs_tm = orderPats (getInferTerm lhs')
820827 let lhs_ty = getInferType lhs'
821828 let ret_ty = getRetTy (explicitNames (normalise ctxt [] lhs_ty))
@@ -827,17 +834,19 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
827834 let wval = addImplBound i (map fst bargs) wval_in
828835 logLvl 5 ("Checking " ++ showTmImpls wval)
829836 -- Elaborate wval in this context
830− ((wval', defer, is), _) <-
837+ ((wval', defer, is, ctxt', newDecls), _) <-
831838 tclift $ elaborate ctxt (sMN 0 "withRHS")
832839 (bindTyArgs PVTy bargs infP) initEState
833840 (do pbinds i lhs_tm
834841 setNextName
835842 -- TODO: may want where here - see winfo abpve
836− (_', d, is) <- errAt "with value in " fname
843+ (ElabResult _ d is ctxt' newDecls) <- errAt "with value in " fname
837844 (erun fc (build i info ERHS opts fname (infTerm wval)))
838845 erun fc $ psolve lhs_tm
839846 tt <- get_term
840− return (tt, d, is))
847+ return (tt, d, is, ctxt', newDecls))
848+ setContext ctxt'
849+ processTacticDecls newDecls
841850 def' <- checkDef fc defer
842851 let def'' = map (\(n, (i, top, t)) -> (n, (i, top, t, False))) def'
843852 addDeferred def''
@@ -923,14 +932,17 @@ elabClause info opts (_, PWith fc fname lhs_in withs wval_in pn_in withblock)
923932 logLvl 5 ("New RHS " ++ showTmImpls rhs)
924933 ctxt <- getContext -- New context with block added
925934 i <- getIState
926− ((rhs', defer, is), _) <-
935+ ((rhs', defer, is, ctxt', newDecls), _) <-
927936 tclift $ elaborate ctxt (sMN 0 "wpatRHS") clhsty initEState
928937 (do pbinds i lhs_tm
929938 setNextName
930− (_, d, is) <- erun fc (build i info ERHS opts fname rhs)
939+ (ElabResult _ d is ctxt' newDecls) <- erun fc (build i info ERHS opts fname rhs)
931940 psolve lhs_tm
932941 tt <- get_term
933− return (tt, d, is))
942+ return (tt, d, is, ctxt', newDecls))
943+ setContext ctxt'
944+ processTacticDecls newDecls
945+
934946 def' <- checkDef fc defer
935947 let def'' = map (\(n, (i, top, t)) -> (n, (i, top, t, False))) def'
936948 addDeferred def''
src/Idris/Elab/Instance.hs+5−3
@@ -169,9 +169,11 @@ elabInstance info syn doc argDocs what fc cs n ps t expn ds = do
169169 ty' <- implicit info syn iname ty'
170170 let ty = addImpl i ty'
171171 ctxt <- getContext
172− ((tyT, _, _), _) <-
173− tclift $ elaborate ctxt iname (TType (UVal 0)) initEState
174− (errAt "type of " iname (erun fc (build i info ERHS [] iname ty)))
172+ (ElabResult tyT _ _ ctxt' newDecls, _) <-
173+ tclift $ elaborate ctxt iname (TType (UVal 0)) initEState
174+ (errAt "type of " iname (erun fc (build i info ERHS [] iname ty)))
175+ setContext ctxt'
176+ processTacticDecls newDecls
175177 ctxt <- getContext
176178 (cty, _) <- recheckC fc [] tyT
177179 let nty = normalise ctxt [] cty
src/Idris/Elab/Transform.hs+10−4
@@ -53,10 +53,12 @@ elabTransform info fc safe lhs_in@(PApp _ (PRef _ tf) _) rhs_in
5353 = do ctxt <- getContext
5454 i <- getIState
5555 let lhs = addImplPat i lhs_in
56− ((lhs', dlhs, []), _) <-
56+ (ElabResult lhs' dlhs [] ctxt' newDecls, _) <-
5757 tclift $ elaborate ctxt (sMN 0 "transLHS") infP initEState
5858 (erun fc (buildTC i info ELHS [] (sUN "transform")
5959 (infTerm lhs)))
60+ setContext ctxt'
61+ processTacticDecls newDecls
6062 let lhs_tm = orderPats (getInferTerm lhs')
6163 let lhs_ty = getInferType lhs'
6264 let newargs = pvars i lhs_tm
@@ -66,14 +68,18 @@ elabTransform info fc safe lhs_in@(PApp _ (PRef _ tf) _) rhs_in
6668 logLvl 3 ("Transform LHS " ++ show clhs_tm)
6769
6870 let rhs = addImplBound i (map fst newargs) rhs_in
69− ((rhs', defer), _) <-
71+ ((rhs', defer, ctxt', newDecls), _) <-
7072 tclift $ elaborate ctxt (sMN 0 "transRHS") clhs_ty initEState
7173 (do pbinds i lhs_tm
7274 setNextName
73− erun fc (build i info ERHS [] (sUN "transform") rhs)
75+ (ElabResult _ _ _ ctxt' newDecls) <- erun fc (build i info ERHS [] (sUN "transform") rhs)
7476 erun fc $ psolve lhs_tm
7577 tt <- get_term
76− return (runState (collectDeferred Nothing tt) []))
78+ let (rhs', defer) = runState (collectDeferred Nothing tt) []
79+ return (rhs', defer, ctxt', newDecls))
80+ setContext ctxt'
81+ processTacticDecls newDecls
82+
7783 (crhs_tm_in, crhs_ty) <- recheckC fc [] rhs'
7884 let crhs_tm = renamepats pnames crhs_tm_in
7985 logLvl 3 ("Transform RHS " ++ show crhs_tm)
src/Idris/Elab/Type.hs+10−6
@@ -65,9 +65,11 @@ buildType info syn fc opts n ty' = do
6565 logLvl 3 $ show n ++ " type pre-addimpl " ++ showTmImpls ty'
6666 logLvl 3 $ show n ++ " type " ++ show (using syn) ++ "\n" ++ showTmImpls ty
6767
68− ((tyT', defer, is), log) <-
69− tclift $ elaborate ctxt n (TType (UVal 0)) initEState
70− (errAt "type of " n (erun fc (build i info ETyDecl [] n ty)))
68+ (ElabResult tyT' defer is ctxt' newDecls, log) <-
69+ tclift $ elaborate ctxt n (TType (UVal 0)) initEState
70+ (errAt "type of " n (erun fc (build i info ETyDecl [] n ty)))
71+ setContext ctxt'
72+ processTacticDecls newDecls
7173
7274 let tyT = patToImp tyT'
7375
@@ -114,12 +116,14 @@ buildType info syn fc opts n ty' = do
114116 param_pos i ns t = []
115117
116118-- | Elaborate a top-level type declaration - for example, "foo : Int -> Int".
117−elabType :: ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm)-> [(Name, Docstring (Either Err PTerm))] ->
118− FC -> FnOpts -> Name -> PTerm -> Idris Type
119+elabType :: ElabInfo -> SyntaxInfo
120+ -> Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))]
121+ -> FC -> FnOpts -> Name -> PTerm -> Idris Type
119122elabType = elabType' False
120123
121124elabType' :: Bool -> -- normalise it
122− ElabInfo -> SyntaxInfo -> Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))] ->
125+ ElabInfo -> SyntaxInfo ->
126+ Docstring (Either Err PTerm) -> [(Name, Docstring (Either Err PTerm))] ->
123127 FC -> FnOpts -> Name -> PTerm -> Idris Type
124128elabType' norm info syn doc argDocs fc opts n ty' = {- let ty' = piBind (params info) ty_in
125129 n = liftname info n_in in -}
src/Idris/Elab/Utils.hs+10−8
@@ -22,7 +22,7 @@ import Debug.Trace
2222
2323import qualified Data.Map as Map
2424
25−recheckC = recheckC_borrowing False []
25+recheckC = recheckC_borrowing False []
2626
2727recheckC_borrowing uniq_check bs fc env t
2828 = do -- t' <- applyOpts (forget t) (doesn't work, or speed things up...)
@@ -34,9 +34,13 @@ recheckC_borrowing uniq_check bs fc env t
3434 addConstraints fc cs
3535 return (tm, ty)
3636
37−
37+checkDef :: FC -> [(Name, (Int, Maybe Name, Type))]
38+ -> Idris [(Name, (Int, Maybe Name, Type))]
3839checkDef fc ns = checkAddDef False True fc ns
3940
41+checkAddDef :: Bool -> Bool -> FC
42+ -> [(Name, (Int, Maybe Name, Type))]
43+ -> Idris [(Name, (Int, Maybe Name, Type))]
4044checkAddDef add toplvl fc [] = return []
4145checkAddDef add toplvl fc ((n, (i, top, t)) : ns)
4246 = do ctxt <- getContext
@@ -46,7 +50,7 @@ checkAddDef add toplvl fc ((n, (i, top, t)) : ns)
4650 ns' <- checkAddDef add toplvl fc ns
4751 return ((n, (i, top, t')) : ns')
4852
49−-- Get the list of (index, name) of inaccessible arguments from an elaborated
53+-- | Get the list of (index, name) of inaccessible arguments from an elaborated
5054-- type
5155inaccessibleImps :: Int -> Type -> [Bool] -> [(Int, Name)]
5256inaccessibleImps i (Bind n (Pi _ t _) sc) (inacc : ins)
@@ -54,7 +58,7 @@ inaccessibleImps i (Bind n (Pi _ t _) sc) (inacc : ins)
5458 | otherwise = inaccessibleImps (i + 1) sc ins
5559inaccessibleImps _ _ _ = []
5660
57−-- Get the list of (index, name) of inaccessible arguments from the type.
61+-- | Get the list of (index, name) of inaccessible arguments from the type.
5862inaccessibleArgs :: Int -> PTerm -> [(Int, Name)]
5963inaccessibleArgs i (PPi (Imp _ _ _ _) n Placeholder t)
6064 = (i,n) : inaccessibleArgs (i+1) t -- unbound implicit
@@ -74,10 +78,9 @@ elabCaseBlock info opts d@(PClauses f o n ps)
7478 when (AssertTotal `elem` opts) $ setFlags n [AssertTotal]
7579 rec_elabDecl info EAll info (PClauses f opts' n ps )
7680
77−-- Check that the result of type checking matches what the programmer wrote
81+-- | Check that the result of type checking matches what the programmer wrote
7882-- (i.e. - if we inferred any arguments that the user provided, make sure
7983-- they are the same!)
80−
8184checkInferred :: FC -> PTerm -> PTerm -> Idris ()
8285checkInferred fc inf user =
8386 do logLvl 6 $ "Checked to\n" ++ showTmImpls inf ++ "\n\nFROM\n\n" ++
@@ -92,9 +95,8 @@ checkInferred fc inf user =
9295 logLvl 10 $ "Checked match"
9396-- ++ "\n" ++ showImp True inf ++ "\n" ++ showImp True user)
9497
95−-- Return whether inferred term is different from given term
98+-- | Return whether inferred term is different from given term
9699-- (as above, but return a Bool)
97−
98100inferredDiff :: FC -> PTerm -> PTerm -> Idris Bool
99101inferredDiff fc inf user =
100102 do i <- getIState
src/Idris/Elab/Value.hs+8−3
@@ -63,9 +63,14 @@ elabValBind info aspat norm tm_in
6363 -- * elaboration as a Type
6464 -- * elaboration as a function a -> b
6565
66− ((tm', defer, is), _) <-
67− tclift (elaborate ctxt (sMN 0 "val") infP initEState
68− (build i info aspat [Reflection] (sMN 0 "val") (infTerm tm)))
66+ (ElabResult tm' defer is ctxt' newDecls, _) <-
67+ tclift (elaborate ctxt (sMN 0 "val") infP initEState
68+ (build i info aspat [Reflection] (sMN 0 "val") (infTerm tm)))
69+
70+ -- Extend the context with new definitions created
71+ setContext ctxt'
72+ processTacticDecls newDecls
73+
6974 let vtm = orderPats (getInferTerm tm')
7075
7176 def' <- checkDef (fileFC "(input)") defer
src/Idris/ElabTerm.hs+145−58
@@ -18,6 +18,7 @@ import Idris.Core.Typecheck (check, recheck)
1818import Idris.ErrReverse (errReverse)
1919import Idris.ElabQuasiquote (extractUnquotes)
2020import Idris.Elab.Utils
21+import Idris.Reflection
2122import qualified Util.Pretty as U
2223
2324import Control.Applicative ((<$>))
@@ -36,6 +37,32 @@ import Debug.Trace
3637data ElabMode = ETyDecl | ELHS | ERHS
3738 deriving Eq
3839
40+data ElabResult =
41+ ElabResult { resultTerm :: Term -- ^ The term resulting from elaboration
42+ , resultMetavars :: [(Name, (Int, Maybe Name, Type))]
43+ -- ^ Information about new metavariables
44+ , resultCaseDecls :: [PDecl]
45+ -- ^ Deferred declarations as the meaning of case blocks
46+ , resultContext :: Context
47+ -- ^ The potentially extended context from new definitions
48+ , resultTyDecls :: [(Name, FC, [PArg], Type)]
49+ -- ^ Meta-info about the new type declarations
50+ }
51+
52+processTacticDecls :: [(Name, FC, [PArg], Type)] -> Idris ()
53+processTacticDecls info =
54+ forM_ info $ \(n, fc, impls, ty) ->
55+ do logLvl 3 $ "Declaration from tactics: " ++ show n ++ " : " ++ show ty
56+ logLvl 3 $ " It has impls " ++ show impls
57+ updateIState $ \i -> i { idris_implicits =
58+ addDef n impls (idris_implicits i) }
59+ addIBC (IBCImp n)
60+ ds <- checkDef fc [(n, (-1, Nothing, ty))]
61+ addIBC (IBCDef n)
62+ let ds' = map (\(n, (i, top, t)) -> (n, (i, top, t, True))) ds
63+ addDeferred ds'
64+
65+
3966-- Using the elaborator, convert a term in raw syntax to a fully
4067-- elaborated, typechecked term.
4168--
@@ -45,7 +72,7 @@ data ElabMode = ETyDecl | ELHS | ERHS
4572-- Also find deferred names in the term and their types
4673
4774build :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
48− ElabD (Term, [(Name, (Int, Maybe Name, Type))], [PDecl])
75+ ElabD ElabResult
4976build ist info emode opts fn tm
5077 = do elab ist info emode opts fn tm
5178 let tmIn = tm
@@ -95,12 +122,13 @@ build ist info emode opts fn tm
95122 when tydecl (do update_term orderPats
96123 mkPat)
97124-- update_term liftPats)
98− EState is _ <- getAux
125+ EState is _ impls <- getAux
99126 tt <- get_term
100127 let (tm, ds) = runState (collectDeferred (Just fn) tt) []
101128 log <- getLog
102− if (log /= "") then trace log $ return (tm, ds, is)
103− else return (tm, ds, is)
129+ ctxt <- get_context
130+ if (log /= "") then trace log $ return (ElabResult tm ds is ctxt impls)
131+ else return (ElabResult tm ds is ctxt impls)
104132 where pattern = emode == ELHS
105133 tydecl = emode == ETyDecl
106134
@@ -115,7 +143,7 @@ build ist info emode opts fn tm
115143-- know about yet on the LHS of a pattern def)
116144
117145buildTC :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
118− ElabD (Term, [(Name, (Int, Maybe Name, Type))], [PDecl])
146+ ElabD ElabResult
119147buildTC ist info emode opts fn tm
120148 = do -- set name supply to begin after highest index in tm
121149 let ns = allNamesIn tm
@@ -136,12 +164,13 @@ buildTC ist info emode opts fn tm
136164 -- unification
137165 when (not (null dots)) $
138166 lift (Error (CantMatch (getInferTerm tm)))
139− EState is _ <- getAux
167+ EState is _ impls <- getAux
140168 tt <- get_term
141169 let (tm, ds) = runState (collectDeferred (Just fn) tt) []
142170 log <- getLog
143− if (log /= "") then trace log $ return (tm, ds, is)
144− else return (tm, ds, is)
171+ ctxt <- get_context
172+ if (log /= "") then trace log $ return (ElabResult tm ds is ctxt impls)
173+ else return (ElabResult tm ds is ctxt impls)
145174 where pattern = emode == ELHS
146175
147176-- return whether arguments of the given constructor name can be
@@ -184,9 +213,9 @@ goal_polymorphic =
184213 _ -> return True
185214 _ -> return False
186215
187−-- Returns the set of declarations we need to add to complete the definition
188−-- (most likely case blocks to elaborate)
189−
216+-- | Returns the set of declarations we need to add to complete the
217+-- definition (most likely case blocks to elaborate) as well as
218+-- declarations resulting from user tactic scripts (%runTactics)
190219elab :: IState -> ElabInfo -> ElabMode -> FnOpts -> Name -> PTerm ->
191220 ElabD ()
192221elab ist info emode opts fn tm
@@ -970,10 +999,10 @@ elab ist info emode opts fn tm
970999 = do -- First extract the unquoted subterms, replacing them with fresh
9711000 -- names in the quasiquoted term. Claim their reflections to be
9721001 -- an inferred type (to support polytypic quasiquotes).
973− qty <- goal
1002+ finalTy <- goal
9741003 (t, unq) <- extractUnquotes 0 t
9751004 let unquoteNames = map fst unq
976− mapM_ (\uqn -> claim uqn (forget qty)) unquoteNames
1005+ mapM_ (\uqn -> claim uqn (forget finalTy)) unquoteNames
9771006
9781007 -- Save the old state - we need a fresh proof state to avoid
9791008 -- capturing lexically available variables in the quoted term.
@@ -1023,18 +1052,20 @@ elab ist info emode opts fn tm
10231052 env <- get_env
10241053 loadState
10251054 let quoted = fmap (explicitNames . binderVal) $ lookup nTm env
1026−
1055+ isRaw = case unApply (normaliseAll ctxt env finalTy) of
1056+ (P _ n _, []) | n == reflm "Raw" -> True
1057+ _ -> False
10271058 case quoted of
10281059 Just q -> do ctxt <- get_context
10291060 (q', _, _) <- lift $ recheck ctxt [(uq, Lam Erased) | uq <- unquoteNames] (forget q) q
10301061 if pattern
1031− then do try' (reflectTTQuotePattern unquoteNames q')
1032− (reflectRawQuotePattern unquoteNames (forget q'))
1033− True
1034− else do try' (fill $ reflectTTQuote unquoteNames q')
1035− -- we forget q' instead of using q to ensure rechecking
1036− (fill $ reflectRawQuote unquoteNames (forget q'))
1037− True -- ignore errors like proof search does
1062+ then if isRaw
1063+ then reflectRawQuotePattern unquoteNames (forget q')
1064+ else reflectTTQuotePattern unquoteNames q'
1065+ else do if isRaw
1066+ then -- we forget q' instead of using q to ensure rechecking
1067+ fill $ reflectRawQuote unquoteNames (forget q')
1068+ else fill $ reflectTTQuote unquoteNames q'
10381069 solve
10391070
10401071 Nothing -> lift . tfail . Msg $ "Broken elaboration of quasiquote"
@@ -1075,8 +1106,8 @@ elab ist info emode opts fn tm
10751106 focus n
10761107 elab' ina (Just fc') tm
10771108 env <- get_env
1078− ctxt <- get_context
1079− runTactical (maybe fc' id fc) ctxt env (P Bound n' Erased)
1109+ runTactical (maybe fc' id fc) env (P Bound n' Erased)
1110+ EState _ _ todo <- getAux
10801111 solve
10811112 elab' ina fc x = fail $ "Unelaboratable syntactic form " ++ showTmImpls x
10821113
@@ -1543,11 +1574,17 @@ case_ ind autoSolve ist fn tm = do
15431574 else casetac (forget val)
15441575 when autoSolve solveAll
15451576
1546−runTactical :: FC -> Context -> Env -> Term -> ElabD ()
1547−runTactical fc ctxt env tm = runTacTm (eval tm) >> return ()
1577+tacN :: String -> Name
1578+tacN str = sNS (sUN str) ["Tactical", "Reflection", "Language"]
1579+
1580+runTactical :: FC -> Env -> Term -> ElabD ()
1581+runTactical fc env tm = do tm' <- eval tm
1582+ runTacTm tm'
1583+ return ()
15481584 where
1549− eval = normaliseAll ctxt env . finalise
1550− tacN str = sNS (sUN str) ["Tactical", "Reflection", "Language"]
1585+ eval tm = do ctxt <- get_context
1586+ return $ normaliseAll ctxt env (finalise tm)
1587+
15511588 returnUnit = fmap fst $ get_type_val (Var unitCon)
15521589
15531590 -- | Do a step in the reflected elaborator monad. The input is the
@@ -1585,26 +1622,31 @@ runTactical fc ctxt env tm = runTacTm (eval tm) >> return ()
15851622 = do env <- get_env
15861623 fmap fst . get_type_val $ reflectEnv env
15871624 | n == tacN "prim__Fail", [_a, errs] <- args
1588− = do parts <- reifyReportParts (eval errs)
1625+ = do errs' <- eval errs
1626+ parts <- reifyReportParts errs'
15891627 lift . tfail $ ReflectionError [parts] (Msg "")
15901628 | n == tacN "prim__PureTactical", [_a, tm] <- args
15911629 = return tm
15921630 | n == tacN "prim__BindTactical", [_a, _b, first, andThen] <- args
1593− = do let first' = eval first
1631+ = do first' <- eval first
15941632 res <- runTacTm first'
1595− let next = eval (App andThen res)
1633+ next <- eval (App andThen res)
15961634 runTacTm next
15971635 | n == tacN "prim__Try", [_a, first, alt] <- args
1598− = do let first' = eval first
1599− let alt' = eval alt
1636+ = do first' <- eval first
1637+ alt' <- eval alt
16001638 try' (runTacTm first') (runTacTm alt') True
16011639 | n == tacN "prim__Fill", [raw] <- args
16021640 = do raw' <- reifyRaw raw
16031641 apply raw' []
16041642 returnUnit
1605− | n == tacN "prim__Gensym", [eval -> Constant (Str hint)] <- args
1606− = do n <- getNameFrom (sMN 0 hint)
1607− fmap fst $ get_type_val (reflectName n)
1643+ | n == tacN "prim__Gensym", [hint] <- args
1644+ = do hintStr <- eval hint
1645+ case hintStr of
1646+ Constant (Str h) -> do
1647+ n <- getNameFrom (sMN 0 h)
1648+ fmap fst $ get_type_val (reflectName n)
1649+ _ -> fail "no hint"
16081650 | n == tacN "prim__Claim", [n, ty] <- args
16091651 = do n' <- reifyTTName n
16101652 ty' <- reifyRaw ty
@@ -1634,6 +1676,29 @@ runTactical fc ctxt env tm = runTacTm (eval tm) >> return ()
16341676 Just name -> fmap Just $ reifyTTName name
16351677 intro n
16361678 returnUnit
1679+ | n == tacN "prim__DeclareType", [decl] <- args
1680+ = do (RDeclare n args res) <- reifyTyDecl decl
1681+ ctxt <- get_context
1682+ let mkPi arg res = RBind (argName arg)
1683+ (Pi Nothing (argTy arg) (RUType AllTypes))
1684+ res
1685+ rty = foldr mkPi res args
1686+ (checked, ty') <- lift $ check ctxt [] rty
1687+ case normaliseAll ctxt [] (finalise ty') of
1688+ TType _ -> lift . tfail . InternalMsg $
1689+ show checked ++ " is not a type: it's " ++ show ty'
1690+ _ -> return ()
1691+ case lookupDefExact n ctxt of
1692+ Just _ -> lift . tfail . InternalMsg $
1693+ show n ++ " is already defined."
1694+ Nothing -> return ()
1695+ let decl = TyDecl Ref checked
1696+ ctxt' = addCtxtDef n decl ctxt
1697+ set_context ctxt'
1698+ updateAux $ \e -> e { new_tyDecls = (n, fc, map rArgToPArg args, checked) :
1699+ new_tyDecls e }
1700+ aux <- getAux
1701+ returnUnit
16371702 | n == tacN "prim__Debug", [ty, msg] <- args
16381703 = do let msg' = fromTTMaybe msg
16391704 case msg' of
@@ -2400,7 +2465,7 @@ reflectTTQuote unq (P nt n t)
24002465reflectTTQuote unq (V n)
24012466 = reflCall "V" [RConstant (I n)]
24022467reflectTTQuote unq (Bind n b x)
2403− = reflCall "Bind" [reflectName n, reflectBinderQuote reflectTTQuote unq b, reflectTTQuote unq x]
2468+ = reflCall "Bind" [reflectName n, reflectBinderQuote reflectTTQuote (reflm "TT") unq b, reflectTTQuote unq x]
24042469reflectTTQuote unq (App f x)
24052470 = reflCall "App" [reflectTTQuote unq f, reflectTTQuote unq x]
24062471reflectTTQuote unq (Constant c)
@@ -2417,7 +2482,7 @@ reflectRawQuote unq (Var n)
24172482 | n `elem` unq = Var n
24182483 | otherwise = reflCall "Var" [reflectName n]
24192484reflectRawQuote unq (RBind n b r) =
2420− reflCall "RBind" [reflectName n, reflectBinderQuote reflectRawQuote unq b, reflectRawQuote unq r]
2485+ reflCall "RBind" [reflectName n, reflectBinderQuote reflectRawQuote (reflm "Raw") unq b, reflectRawQuote unq r]
24212486reflectRawQuote unq (RApp f x) =
24222487 reflCall "RApp" [reflectRawQuote unq f, reflectRawQuote unq x]
24232488reflectRawQuote unq RType = Var (reflm "RType")
@@ -2475,27 +2540,27 @@ reflectNameQuotePattern _ -- for all other names, match any
24752540 solve
24762541
24772542reflectBinder :: Binder Term -> Raw
2478−reflectBinder = reflectBinderQuote reflectTTQuote []
2479−
2480−reflectBinderQuote :: ([Name] -> a -> Raw) -> [Name] -> Binder a -> Raw
2481−reflectBinderQuote q unq (Lam t)
2482− = reflCall "Lam" [Var (reflm "TT"), q unq t]
2483−reflectBinderQuote q unq (Pi _ t k)
2484− = reflCall "Pi" [Var (reflm "TT"), q unq t, q unq k]
2485−reflectBinderQuote q unq (Let x y)
2486− = reflCall "Let" [Var (reflm "TT"), q unq x, q unq y]
2487−reflectBinderQuote q unq (NLet x y)
2488− = reflCall "NLet" [Var (reflm "TT"), q unq x, q unq y]
2489−reflectBinderQuote q unq (Hole t)
2490− = reflCall "Hole" [Var (reflm "TT"), q unq t]
2491−reflectBinderQuote q unq (GHole _ t)
2492− = reflCall "GHole" [Var (reflm "TT"), q unq t]
2493−reflectBinderQuote q unq (Guess x y)
2494− = reflCall "Guess" [Var (reflm "TT"), q unq x, q unq y]
2495−reflectBinderQuote q unq (PVar t)
2496− = reflCall "PVar" [Var (reflm "TT"), q unq t]
2497−reflectBinderQuote q unq (PVTy t)
2498− = reflCall "PVTy" [Var (reflm "TT"), q unq t]
2543+reflectBinder = reflectBinderQuote reflectTTQuote (reflm "TT") []
2544+
2545+reflectBinderQuote :: ([Name] -> a -> Raw) -> Name -> [Name] -> Binder a -> Raw
2546+reflectBinderQuote q ty unq (Lam t)
2547+ = reflCall "Lam" [Var ty, q unq t]
2548+reflectBinderQuote q ty unq (Pi _ t k)
2549+ = reflCall "Pi" [Var ty, q unq t, q unq k]
2550+reflectBinderQuote q ty unq (Let x y)
2551+ = reflCall "Let" [Var ty, q unq x, q unq y]
2552+reflectBinderQuote q ty unq (NLet x y)
2553+ = reflCall "NLet" [Var ty, q unq x, q unq y]
2554+reflectBinderQuote q ty unq (Hole t)
2555+ = reflCall "Hole" [Var ty, q unq t]
2556+reflectBinderQuote q ty unq (GHole _ t)
2557+ = reflCall "GHole" [Var ty, q unq t]
2558+reflectBinderQuote q ty unq (Guess x y)
2559+ = reflCall "Guess" [Var ty, q unq x, q unq y]
2560+reflectBinderQuote q ty unq (PVar t)
2561+ = reflCall "PVar" [Var ty, q unq t]
2562+reflectBinderQuote q ty unq (PVTy t)
2563+ = reflCall "PVTy" [Var ty, q unq t]
24992564
25002565mkList :: Raw -> [Raw] -> Raw
25012566mkList ty [] = RApp (Var (sNS (sUN "Nil") ["List", "Prelude"])) ty
@@ -2790,6 +2855,28 @@ reifyReportPart (App (P (DCon _ _ _) n _) tm)
27902855 Nothing -> Left . InternalMsg $ "could not reify subreport " ++ show tm
27912856reifyReportPart x = Left . InternalMsg $ "could not reify " ++ show x
27922857
2858+reifyTyDecl :: Term -> ElabD RTyDecl
2859+reifyTyDecl (App (App (App (P (DCon _ _ _) n _) tyN) args) ret)
2860+ | n == tacN "Declare" =
2861+ do tyN' <- reifyTTName tyN
2862+ args' <- case unList args of
2863+ Nothing -> fail $ "Couldn't reify " ++ show args ++ " as an arglist."
2864+ Just xs -> mapM reifyRArg xs
2865+ ret' <- reifyRaw ret
2866+ return $ RDeclare tyN' args' ret'
2867+ where reifyRArg :: Term -> ElabD RArg
2868+ reifyRArg (App (App (P (DCon _ _ _) n _) argN) argTy)
2869+ | n == tacN "Explicit" = liftM2 RExplicit
2870+ (reifyTTName argN)
2871+ (reifyRaw argTy)
2872+ | n == tacN "Implicit" = liftM2 RImplicit
2873+ (reifyTTName argN)
2874+ (reifyRaw argTy) | n == tacN "Constraint" = liftM2 RConstraint
2875+ (reifyTTName argN)
2876+ (reifyRaw argTy)
2877+ reifyRArg aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RArg."
2878+reifyTyDecl tm = fail $ "Couldn't reify " ++ show tm ++ " as a type declaration."
2879+
27932880envTupleType :: Raw
27942881envTupleType
27952882 = raw_apply (Var pairTy) [ (Var $ reflm "TTName")
src/Idris/Reflection.hsnew file+18
@@ -0,0 +1,18 @@
1+{-|
2+Handy tools for doing reflection.
3+-}
4+module Idris.Reflection where
5+
6+import Idris.Core.TT
7+import Idris.AbsSyntaxTree (PArg'(..), PArg, PTerm(Placeholder))
8+
9+data RArg = RExplicit { argName :: Name, argTy :: Raw }
10+ | RImplicit { argName :: Name, argTy :: Raw }
11+ | RConstraint { argName :: Name, argTy :: Raw }
12+
13+data RTyDecl = RDeclare Name [RArg] Raw
14+
15+rArgToPArg :: RArg -> PArg
16+rArgToPArg (RExplicit n _) = PExp 0 [] n Placeholder
17+rArgToPArg (RImplicit n _) = PImp 0 False [] n Placeholder
18+rArgToPArg (RConstraint n _) = PConstraint 0 [] n Placeholder
test/tactics001/Tactics.idr+14
@@ -2,6 +2,9 @@ module Tactics
22
33import Language.Reflection.Tactical
44
5+import Data.Vect
6+
7+
58%default total
69
710-- Test that basic proofs with new-style tactics work
@@ -25,3 +28,14 @@ plusSuccRightSuccNew (S j) k =
2528 %runTactics (do rewriteWith `(sym $ plusSuccRightSuccNew ~(Var "j") ~(Var (UN "k")))
2629 fill $ refl `(Nat : Type) `(S (S (plus ~(Var (UN "j")) ~(Var (UN "k")))))
2730 solve)
31+
32+-- Test that side effects in new tactics work
33+
34+mkDecl : ()
35+mkDecl = %runTactics (do declareType $ Declare (NS (UN "repUnit") ["Tactics"])
36+ [Implicit (UN "z") `(Nat)]
37+ `(Vect ~(Var (UN "z")) ())
38+ fill `(() : ())
39+ solve)
40+
41+repUnit = pure ()