on 5cf643e help sign in
Idris-dev/src/Idris/Reflection.hs
1226 lines 55 kB history raw
1{-|
2Module : Idris.Reflection
3Description : Code related to Idris's reflection system. This module contains quoters and unquoters along with some supporting datatypes.
4Copyright :
5License : BSD3
6Maintainer : The Idris Community.
7-}
9{-# LANGUAGE CPP, PatternGuards #-}
10{-# OPTIONS_GHC -fwarn-incomplete-patterns -fwarn-unused-imports #-}
11module Idris.Reflection where
13import Idris.Core.Elaborate (claim, fill, focus, getNameFrom, initElaborator,
14 movelast, runElab, solve)
15import Idris.Core.Evaluate (Def(TyDecl), initContext, lookupDefExact,
16 lookupTyExact)
17import Idris.Core.TT
19import Idris.AbsSyntaxTree (ArgOpt(..), ElabD, Fixity(..), IState(idris_datatypes, idris_implicits, idris_patdefs, tt_ctxt),
20 PArg, PArg'(..), PTactic, PTactic'(..), PTerm(..),
21 initEState, pairCon, pairTy)
22import Idris.Delaborate (delab)
24#if __GLASGOW_HASKELL__ < 710
25import Control.Applicative (pure, (<$>), (<*>))
26import Data.Traversable (mapM)
27import Prelude hiding (mapM)
28#endif
29import Control.Monad (liftM, liftM2, liftM4)
30import Control.Monad.State.Strict (lift)
31import Data.List (findIndex, (\\))
32import Data.Maybe (catMaybes)
33import qualified Data.Text as T
35data RErasure = RErased | RNotErased deriving Show
37data RPlicity = RExplicit | RImplicit | RConstraint deriving Show
39data RFunArg = RFunArg { argName :: Name
40 , argTy :: Raw
41 , argPlicity :: RPlicity
42 , erasure :: RErasure
43 }
44 deriving Show
46data RTyDecl = RDeclare Name [RFunArg] Raw deriving Show
48data RTyConArg = RParameter RFunArg
49 | RIndex RFunArg
50 deriving Show
52data RCtorArg = RCtorParameter RFunArg | RCtorField RFunArg deriving Show
54data RDatatype = RDatatype Name [RTyConArg] Raw [(Name, [RCtorArg], Raw)] deriving Show
56data RConstructorDefn = RConstructor Name [RFunArg] Raw
58data RDataDefn = RDefineDatatype Name [RConstructorDefn]
60rArgOpts :: RErasure -> [ArgOpt]
61rArgOpts RErased = [InaccessibleArg]
62rArgOpts _ = []
64rFunArgToPArg :: RFunArg -> PArg
65rFunArgToPArg (RFunArg n _ RExplicit e) = PExp 0 (rArgOpts e) n Placeholder
66rFunArgToPArg (RFunArg n _ RImplicit e) = PImp 0 False (rArgOpts e) n Placeholder
67rFunArgToPArg (RFunArg n _ RConstraint e) = PConstraint 0 (rArgOpts e) n Placeholder
69data RFunClause a = RMkFunClause a a
70 | RMkImpossibleClause a
71 deriving Show
73data RFunDefn a = RDefineFun Name [RFunClause a] deriving Show
75-- | Prefix a name with the "Language.Reflection" namespace
76reflm :: String -> Name
77reflm n = sNS (sUN n) ["Reflection", "Language"]
79-- | Prefix a name with the "Language.Reflection.Elab" namespace
80tacN :: String -> Name
81tacN str = sNS (sUN str) ["Elab", "Reflection", "Language"]
83-- | Reify tactics from their reflected representation
84reify :: IState -> Term -> ElabD PTactic
85reify _ (P _ n _) | n == reflm "Intros" = return Intros
86reify _ (P _ n _) | n == reflm "Trivial" = return Trivial
87reify _ (P _ n _) | n == reflm "Implementation" = return TCImplementation
88reify _ (P _ n _) | n == reflm "Solve" = return Solve
89reify _ (P _ n _) | n == reflm "Compute" = return Compute
90reify _ (P _ n _) | n == reflm "Skip" = return Skip
91reify _ (P _ n _) | n == reflm "SourceFC" = return SourceFC
92reify _ (P _ n _) | n == reflm "Unfocus" = return Unfocus
93reify ist t@(App _ _ _)
94 | (P _ f _, args) <- unApply t = reifyApp ist f args
95reify _ t = fail ("Unknown tactic " ++ show t)
97reifyApp :: IState -> Name -> [Term] -> ElabD PTactic
98reifyApp ist t [l, r] | t == reflm "Try" = liftM2 Try (reify ist l) (reify ist r)
99reifyApp _ t [Constant (I i)]
100 | t == reflm "Search" = return (ProofSearch True True i Nothing [] [])
101reifyApp _ t [x]
102 | t == reflm "Refine" = do n <- reifyTTName x
103 return $ Refine n []
104reifyApp ist t [n, ty] | t == reflm "Claim" = do n' <- reifyTTName n
105 goal <- reifyTT ty
106 return $ Claim n' (delab ist goal)
107reifyApp ist t [l, r] | t == reflm "Seq" = liftM2 TSeq (reify ist l) (reify ist r)
108reifyApp ist t [Constant (Str n), x]
109 | t == reflm "GoalType" = liftM (GoalType n) (reify ist x)
110reifyApp _ t [n] | t == reflm "Intro" = liftM (Intro . (:[])) (reifyTTName n)
111reifyApp ist t [t'] | t == reflm "Induction" = liftM (Induction . delab ist) (reifyTT t')
112reifyApp ist t [t'] | t == reflm "Case" = liftM (CaseTac . delab ist) (reifyTT t')
113reifyApp ist t [t']
114 | t == reflm "ApplyTactic" = liftM (ApplyTactic . delab ist) (reifyTT t')
115reifyApp ist t [t']
116 | t == reflm "Reflect" = liftM (Reflect . delab ist) (reifyTT t')
117reifyApp ist t [t']
118 | t == reflm "ByReflection" = liftM (ByReflection . delab ist) (reifyTT t')
119reifyApp _ t [t']
120 | t == reflm "Fill" = liftM (Fill . PQuote) (reifyRaw t')
121reifyApp ist t [t']
122 | t == reflm "Exact" = liftM (Exact . delab ist) (reifyTT t')
123reifyApp ist t [x]
124 | t == reflm "Focus" = liftM Focus (reifyTTName x)
125reifyApp ist t [t']
126 | t == reflm "Rewrite" = liftM (Rewrite . delab ist) (reifyTT t')
127reifyApp ist t [n, t']
128 | t == reflm "LetTac" = do n' <- reifyTTName n
129 t'' <- reifyTT t'
130 return $ LetTac n' (delab ist t')
131reifyApp ist t [n, tt', t']
132 | t == reflm "LetTacTy" = do n' <- reifyTTName n
133 tt'' <- reifyTT tt'
134 t'' <- reifyTT t'
135 return $ LetTacTy n' (delab ist tt'') (delab ist t'')
136reifyApp ist t [errs]
137 | t == reflm "Fail" = fmap TFail (reifyReportParts errs)
138reifyApp _ f args = fail ("Unknown tactic " ++ show (f, args)) -- shouldn't happen
140reifyBool :: Term -> ElabD Bool
141reifyBool (P _ n _) | n == sNS (sUN "True") ["Bool", "Prelude"] = return True
142 | n == sNS (sUN "False") ["Bool", "Prelude"] = return False
143reifyBool tm = fail $ "Not a Boolean: " ++ show tm
145reifyInt :: Term -> ElabD Int
146reifyInt (Constant (I i)) = return i
147reifyInt tm = fail $ "Not an Int: " ++ show tm
149reifyPair :: (Term -> ElabD a) -> (Term -> ElabD b) -> Term -> ElabD (a, b)
150reifyPair left right (App _ (App _ (App _ (App _ (P _ n _) _) _) x) y)
151 | n == pairCon = liftM2 (,) (left x) (right y)
152reifyPair left right tm = fail $ "Not a pair: " ++ show tm
154reifyList :: (Term -> ElabD a) -> Term -> ElabD [a]
155reifyList getElt lst =
156 case unList lst of
157 Nothing -> fail "Couldn't reify a list"
158 Just xs -> mapM getElt xs
160reifyReportParts :: Term -> ElabD [ErrorReportPart]
161reifyReportParts errs =
162 case unList errs of
163 Nothing -> fail "Failed to reify errors"
164 Just errs' ->
165 let parts = mapM reifyReportPart errs' in
166 case parts of
167 Left err -> fail $ "Couldn't reify \"Fail\" tactic - " ++ show err
168 Right errs'' ->
169 return errs''
171-- | Reify terms from their reflected representation
172reifyTT :: Term -> ElabD Term
173reifyTT t@(App _ _ _)
174 | (P _ f _, args) <- unApply t = reifyTTApp f args
175reifyTT t@(P _ n _)
176 | n == reflm "Erased" = return Erased
177reifyTT t@(P _ n _)
178 | n == reflm "Impossible" = return Impossible
179reifyTT t = fail ("Unknown reflection term: " ++ show t)
181reifyTTApp :: Name -> [Term] -> ElabD Term
182reifyTTApp t [nt, n, x]
183 | t == reflm "P" = do nt' <- reifyTTNameType nt
184 n' <- reifyTTName n
185 x' <- reifyTT x
186 return $ P nt' n' x'
187reifyTTApp t [Constant (I i)]
188 | t == reflm "V" = return $ V i
189reifyTTApp t [n, b, x]
190 | t == reflm "Bind" = do n' <- reifyTTName n
191 b' <- reifyTTBinder reifyTT (reflm "TT") b
192 x' <- reifyTT x
193 return $ Bind n' b' x'
194reifyTTApp t [f, x]
195 | t == reflm "App" = do f' <- reifyTT f
196 x' <- reifyTT x
197 return $ App Complete f' x'
198reifyTTApp t [c]
199 | t == reflm "TConst" = liftM Constant (reifyTTConst c)
200reifyTTApp t [t', Constant (I i)]
201 | t == reflm "Proj" = do t'' <- reifyTT t'
202 return $ Proj t'' i
203reifyTTApp t [tt]
204 | t == reflm "TType" = liftM TType (reifyTTUExp tt)
205reifyTTApp t [tt]
206 | t == reflm "UType" = liftM UType (reifyUniverse tt)
207reifyTTApp t args = fail ("Unknown reflection term: " ++ show (t, args))
209reifyUniverse :: Term -> ElabD Universe
210reifyUniverse (P _ n _) | n == reflm "AllTypes" = return AllTypes
211 | n == reflm "UniqueType" = return UniqueType
212 | n == reflm "NullType" = return NullType
213reifyUniverse tm = fail ("Unknown reflection universe: " ++ show tm)
215-- | Reify raw terms from their reflected representation
216reifyRaw :: Term -> ElabD Raw
217reifyRaw t@(App _ _ _)
218 | (P _ f _, args) <- unApply t = reifyRawApp f args
219reifyRaw t@(P _ n _)
220 | n == reflm "RType" = return RType
221reifyRaw t = fail ("Unknown reflection raw term in reifyRaw: " ++ show t)
223reifyRawApp :: Name -> [Term] -> ElabD Raw
224reifyRawApp t [n]
225 | t == reflm "Var" = liftM Var (reifyTTName n)
226reifyRawApp t [n, b, x]
227 | t == reflm "RBind" = do n' <- reifyTTName n
228 b' <- reifyTTBinder reifyRaw (reflm "Raw") b
229 x' <- reifyRaw x
230 return $ RBind n' b' x'
231reifyRawApp t [f, x]
232 | t == reflm "RApp" = liftM2 RApp (reifyRaw f) (reifyRaw x)
233reifyRawApp t [c]
234 | t == reflm "RConstant" = liftM RConstant (reifyTTConst c)
235reifyRawApp t args = fail ("Unknown reflection raw term in reifyRawApp: " ++ show (t, args))
237reifyTTName :: Term -> ElabD Name
238reifyTTName t
239 | (P _ f _, args) <- unApply t = reifyTTNameApp f args
240reifyTTName t = fail ("Unknown reflection term name: " ++ show t)
242reifyTTNameApp :: Name -> [Term] -> ElabD Name
243reifyTTNameApp t [Constant (Str n)]
244 | t == reflm "UN" = return $ sUN n
245reifyTTNameApp t [n, ns]
246 | t == reflm "NS" = do n' <- reifyTTName n
247 ns' <- reifyTTNamespace ns
248 return $ sNS n' ns'
249reifyTTNameApp t [Constant (I i), Constant (Str n)]
250 | t == reflm "MN" = return $ sMN i n
251reifyTTNameApp t [sn]
252 | t == reflm "SN"
253 , (P _ f _, args) <- unApply sn = SN <$> reifySN f args
254 where reifySN :: Name -> [Term] -> ElabD SpecialName
255 reifySN t [Constant (I i), n1, n2]
256 | t == reflm "WhereN" = WhereN i <$> reifyTTName n1 <*> reifyTTName n2
257 reifySN t [Constant (I i), n]
258 | t == reflm "WithN" = WithN i <$> reifyTTName n
259 reifySN t [n, ss]
260 | t == reflm "ImplementationN" =
261 case unList ss of
262 Nothing -> fail "Can't reify ImplementationN strings"
263 Just ss' -> ImplementationN <$> reifyTTName n <*>
264 pure [T.pack s | Constant (Str s) <- ss']
265 reifySN t [n, Constant (Str s)]
266 | t == reflm "ParentN" =
267 ParentN <$> reifyTTName n <*> pure (T.pack s)
268 reifySN t [n]
269 | t == reflm "MethodN" =
270 MethodN <$> reifyTTName n
271 reifySN t [fc, n]
272 | t == reflm "CaseN" =
273 CaseN <$> (FC' <$> reifyFC fc) <*> reifyTTName n
274 reifySN t [n]
275 | t == reflm "ElimN" =
276 ElimN <$> reifyTTName n
277 reifySN t [n]
278 | t == reflm "ImplementationCtorN" =
279 ImplementationCtorN <$> reifyTTName n
280 reifySN t [n1, n2]
281 | t == reflm "MetaN" =
282 MetaN <$> reifyTTName n1 <*> reifyTTName n2
283 reifySN t args = fail $ "Can't reify special name " ++ show t ++ show args
284reifyTTNameApp t args = fail ("Unknown reflection term name: " ++ show (t, args))
286reifyTTNamespace :: Term -> ElabD [String]
287reifyTTNamespace t@(App _ _ _)
288 = case unApply t of
289 (P _ f _, [Constant StrType])
290 | f == sNS (sUN "Nil") ["List", "Prelude"] -> return []
291 (P _ f _, [Constant StrType, Constant (Str n), ns])
292 | f == sNS (sUN "::") ["List", "Prelude"] -> liftM (n:) (reifyTTNamespace ns)
293 _ -> fail ("Unknown reflection namespace arg: " ++ show t)
294reifyTTNamespace t = fail ("Unknown reflection namespace arg: " ++ show t)
296reifyTTNameType :: Term -> ElabD NameType
297reifyTTNameType t@(P _ n _) | n == reflm "Bound" = return $ Bound
298reifyTTNameType t@(P _ n _) | n == reflm "Ref" = return $ Ref
299reifyTTNameType t@(App _ _ _)
300 = case unApply t of
301 (P _ f _, [Constant (I tag), Constant (I num)])
302 | f == reflm "DCon" -> return $ DCon tag num False -- FIXME: Uniqueness!
303 | f == reflm "TCon" -> return $ TCon tag num
304 _ -> fail ("Unknown reflection name type: " ++ show t)
305reifyTTNameType t = fail ("Unknown reflection name type: " ++ show t)
307reifyTTBinder :: (Term -> ElabD a) -> Name -> Term -> ElabD (Binder a)
308reifyTTBinder reificator binderType t@(App _ _ _)
309 = case unApply t of
310 (P _ f _, bt:args) | forget bt == Var binderType
311 -> reifyTTBinderApp reificator f args
312 _ -> fail ("Mismatching binder reflection: " ++ show t)
313reifyTTBinder _ _ t = fail ("Unknown reflection binder: " ++ show t)
315reifyTTBinderApp :: (Term -> ElabD a) -> Name -> [Term] -> ElabD (Binder a)
316reifyTTBinderApp reif f [t]
317 | f == reflm "Lam" = liftM Lam (reif t)
318reifyTTBinderApp reif f [t, k]
319 | f == reflm "Pi" = liftM2 (Pi Nothing) (reif t) (reif k)
320reifyTTBinderApp reif f [x, y]
321 | f == reflm "Let" = liftM2 Let (reif x) (reif y)
322reifyTTBinderApp reif f [t]
323 | f == reflm "Hole" = liftM Hole (reif t)
324reifyTTBinderApp reif f [t]
325 | f == reflm "GHole" = liftM (GHole 0 []) (reif t)
326reifyTTBinderApp reif f [x, y]
327 | f == reflm "Guess" = liftM2 Guess (reif x) (reif y)
328reifyTTBinderApp reif f [t]
329 | f == reflm "PVar" = liftM PVar (reif t)
330reifyTTBinderApp reif f [t]
331 | f == reflm "PVTy" = liftM PVTy (reif t)
332reifyTTBinderApp _ f args = fail ("Unknown reflection binder: " ++ show (f, args))
334reifyTTConst :: Term -> ElabD Const
335reifyTTConst (P _ n _) | n == reflm "StrType" = return StrType
336reifyTTConst (P _ n _) | n == reflm "VoidType" = return VoidType
337reifyTTConst (P _ n _) | n == reflm "Forgot" = return Forgot
338reifyTTConst t@(App _ _ _)
339 | (P _ f _, [arg]) <- unApply t = reifyTTConstApp f arg
340reifyTTConst t = fail ("Unknown reflection constant: " ++ show t)
342reifyTTConstApp :: Name -> Term -> ElabD Const
343reifyTTConstApp f aty
344 | f == reflm "AType" = fmap AType (reifyArithTy aty)
345reifyTTConstApp f (Constant c@(I _))
346 | f == reflm "I" = return c
347reifyTTConstApp f (Constant c@(BI _))
348 | f == reflm "BI" = return c
349reifyTTConstApp f (Constant c@(Fl _))
350 | f == reflm "Fl" = return c
351reifyTTConstApp f (Constant c@(Ch _))
352 | f == reflm "Ch" = return c
353reifyTTConstApp f (Constant c@(Str _))
354 | f == reflm "Str" = return c
355reifyTTConstApp f (Constant c@(B8 _))
356 | f == reflm "B8" = return c
357reifyTTConstApp f (Constant c@(B16 _))
358 | f == reflm "B16" = return c
359reifyTTConstApp f (Constant c@(B32 _))
360 | f == reflm "B32" = return c
361reifyTTConstApp f (Constant c@(B64 _))
362 | f == reflm "B64" = return c
363reifyTTConstApp f v@(P _ _ _) =
364 lift . tfail . Msg $
365 "Can't reify the variable " ++
366 show v ++
367 " as a constant, because its value is not statically known."
368reifyTTConstApp f arg = fail ("Unknown reflection constant: " ++ show (f, arg))
370reifyArithTy :: Term -> ElabD ArithTy
371reifyArithTy (App _ (P _ n _) intTy) | n == reflm "ATInt" = fmap ATInt (reifyIntTy intTy)
372reifyArithTy (P _ n _) | n == reflm "ATDouble" = return ATFloat
373reifyArithTy x = fail ("Couldn't reify reflected ArithTy: " ++ show x)
375reifyNativeTy :: Term -> ElabD NativeTy
376reifyNativeTy (P _ n _) | n == reflm "IT8" = return IT8
377reifyNativeTy (P _ n _) | n == reflm "IT16" = return IT16
378reifyNativeTy (P _ n _) | n == reflm "IT32" = return IT32
379reifyNativeTy (P _ n _) | n == reflm "IT64" = return IT64
380reifyNativeTy x = fail $ "Couldn't reify reflected NativeTy " ++ show x
382reifyIntTy :: Term -> ElabD IntTy
383reifyIntTy (App _ (P _ n _) nt) | n == reflm "ITFixed" = fmap ITFixed (reifyNativeTy nt)
384reifyIntTy (P _ n _) | n == reflm "ITNative" = return ITNative
385reifyIntTy (P _ n _) | n == reflm "ITBig" = return ITBig
386reifyIntTy (P _ n _) | n == reflm "ITChar" = return ITChar
387reifyIntTy tm = fail $ "The term " ++ show tm ++ " is not a reflected IntTy"
389reifyTTUExp :: Term -> ElabD UExp
390reifyTTUExp t@(App _ _ _)
391 = case unApply t of
392 (P _ f _, [Constant (Str str), Constant (I i)])
393 | f == reflm "UVar" -> return $ UVar str i
394 (P _ f _, [Constant (I i)])
395 | f == reflm "UVal" -> return $ UVal i
396 _ -> fail ("Unknown reflection type universe expression: " ++ show t)
397reifyTTUExp t = fail ("Unknown reflection type universe expression: " ++ show t)
399-- | Create a reflected call to a named function/constructor
400reflCall :: String -> [Raw] -> Raw
401reflCall funName args
402 = raw_apply (Var (reflm funName)) args
404-- | Lift a term into its Language.Reflection.TT representation
405reflect :: Term -> Raw
406reflect = reflectTTQuote []
408-- | Lift a term into its Language.Reflection.Raw representation
409reflectRaw :: Raw -> Raw
410reflectRaw = reflectRawQuote []
412claimTy :: Name -> Raw -> ElabD Name
413claimTy n ty = do n' <- getNameFrom n
414 claim n' ty
415 return n'
417intToReflectedNat :: Int -> Raw
418intToReflectedNat i = if i <= 0
419 then Var (natN "Z")
420 else RApp (Var (natN "S")) (intToReflectedNat (i - 1))
421 where natN :: String -> Name
422 natN n = sNS (sUN n) ["Nat", "Prelude"]
424reflectFixity :: Fixity -> Raw
425reflectFixity (Infixl p) = RApp (Var (tacN "Infixl")) (intToReflectedNat p)
426reflectFixity (Infixr p) = RApp (Var (tacN "Infixr")) (intToReflectedNat p)
427reflectFixity (InfixN p) = RApp (Var (tacN "InfixN")) (intToReflectedNat p)
428reflectFixity (PrefixN p) = RApp (Var (tacN "PrefixN")) (intToReflectedNat p)
430-- | Convert a reflected term to a more suitable form for pattern-matching.
431-- In particular, the less-interesting bits are elaborated to _ patterns. This
432-- happens to NameTypes, universe levels, names that are bound but not used,
433-- and the type annotation field of the P constructor.
434reflectTTQuotePattern :: [Name] -> Term -> ElabD ()
435reflectTTQuotePattern unq (P _ n _)
436 | n `elem` unq = -- the unquoted names have been claimed as TT already - just use them
437 do fill (Var n) ; solve
438 | otherwise =
439 do tyannot <- claimTy (sMN 0 "pTyAnnot") (Var (reflm "TT"))
440 movelast tyannot -- use a _ pattern here
441 nt <- getNameFrom (sMN 0 "nt")
442 claim nt (Var (reflm "NameType"))
443 movelast nt -- use a _ pattern here
444 n' <- getNameFrom (sMN 0 "n")
445 claim n' (Var (reflm "TTName"))
446 fill $ reflCall "P" [Var nt, Var n', Var tyannot]
447 solve
448 focus n'; reflectNameQuotePattern n
449reflectTTQuotePattern unq (V n)
450 = do fill $ reflCall "V" [RConstant (I n)]
451 solve
452reflectTTQuotePattern unq (Bind n b x)
453 = do x' <- claimTy (sMN 0 "sc") (Var (reflm "TT"))
454 movelast x'
455 b' <- getNameFrom (sMN 0 "binder")
456 claim b' (RApp (Var (sNS (sUN "Binder") ["Reflection", "Language"]))
457 (Var (sNS (sUN "TT") ["Reflection", "Language"])))
458 if n `elem` freeNames x
459 then do fill $ reflCall "Bind"
460 [reflectName n,
461 Var b',
462 Var x']
463 solve
464 else do any <- getNameFrom (sMN 0 "anyName")
465 claim any (Var (reflm "TTName"))
466 movelast any
467 fill $ reflCall "Bind"
468 [Var any,
469 Var b',
470 Var x']
471 solve
472 focus x'; reflectTTQuotePattern unq x
473 focus b'; reflectBinderQuotePattern reflectTTQuotePattern (Var $ reflm "TT") unq b
474reflectTTQuotePattern unq (App _ f x)
475 = do f' <- claimTy (sMN 0 "f") (Var (reflm "TT")) ; movelast f'
476 x' <- claimTy (sMN 0 "x") (Var (reflm "TT")) ; movelast x'
477 fill $ reflCall "App" [Var f', Var x']
478 solve
479 focus f'; reflectTTQuotePattern unq f
480 focus x'; reflectTTQuotePattern unq x
481reflectTTQuotePattern unq (Constant c)
482 = do fill $ reflCall "TConst" [reflectConstant c]
483 solve
484reflectTTQuotePattern unq (Proj t i)
485 = lift . tfail . InternalMsg $
486 "Phase error! The Proj constructor is for optimization only and should not have been reflected during elaboration."
487reflectTTQuotePattern unq Erased
488 = do erased <- claimTy (sMN 0 "erased") (Var (reflm "TT"))
489 movelast erased
490 fill (Var erased)
491reflectTTQuotePattern unq Impossible
492 = lift . tfail . InternalMsg $
493 "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration."
494reflectTTQuotePattern unq (TType exp)
495 = do ue <- getNameFrom (sMN 0 "uexp")
496 claim ue (Var (sNS (sUN "TTUExp") ["Reflection", "Language"]))
497 movelast ue
498 fill $ reflCall "TType" [Var ue]
499 solve
500reflectTTQuotePattern unq (UType u)
501 = do uH <- getNameFrom (sMN 0 "someUniv")
502 claim uH (Var (reflm "Universe"))
503 movelast uH
504 fill $ reflCall "UType" [Var uH]
505 solve
506 focus uH
507 fill (Var (reflm (case u of
508 NullType -> "NullType"
509 UniqueType -> "UniqueType"
510 AllTypes -> "AllTypes")))
511 solve
513reflectRawQuotePattern :: [Name] -> Raw -> ElabD ()
514reflectRawQuotePattern unq (Var n)
515 -- the unquoted names already have types, just use them
516 | n `elem` unq = do fill (Var n); solve
517 | otherwise = do fill (reflCall "Var" [reflectName n]); solve
518reflectRawQuotePattern unq (RBind n b sc) =
519 do scH <- getNameFrom (sMN 0 "sc")
520 claim scH (Var (reflm "Raw"))
521 movelast scH
522 bH <- getNameFrom (sMN 0 "binder")
523 claim bH (RApp (Var (reflm "Binder"))
524 (Var (reflm "Raw")))
525 if n `elem` freeNamesR sc
526 then do fill $ reflCall "RBind" [reflectName n,
527 Var bH,
528 Var scH]
529 solve
530 else do any <- getNameFrom (sMN 0 "anyName")
531 claim any (Var (reflm "TTName"))
532 movelast any
533 fill $ reflCall "RBind" [Var any, Var bH, Var scH]
534 solve
535 focus scH; reflectRawQuotePattern unq sc
536 focus bH; reflectBinderQuotePattern reflectRawQuotePattern (Var $ reflm "Raw") unq b
537 where freeNamesR (Var n) = [n]
538 freeNamesR (RBind n (Let t v) body) = concat [freeNamesR v,
539 freeNamesR body \\ [n],
540 freeNamesR t]
541 freeNamesR (RBind n b body) = freeNamesR (binderTy b) ++
542 (freeNamesR body \\ [n])
543 freeNamesR (RApp f x) = freeNamesR f ++ freeNamesR x
544 freeNamesR RType = []
545 freeNamesR (RUType _) = []
546 freeNamesR (RConstant _) = []
547reflectRawQuotePattern unq (RApp f x) =
548 do fH <- getNameFrom (sMN 0 "f")
549 claim fH (Var (reflm "Raw"))
550 movelast fH
551 xH <- getNameFrom (sMN 0 "x")
552 claim xH (Var (reflm "Raw"))
553 movelast xH
554 fill $ reflCall "RApp" [Var fH, Var xH]
555 solve
556 focus fH; reflectRawQuotePattern unq f
557 focus xH; reflectRawQuotePattern unq x
558reflectRawQuotePattern unq RType =
559 do fill (Var (reflm "RType"))
560 solve
561reflectRawQuotePattern unq (RUType univ) =
562 do uH <- getNameFrom (sMN 0 "universe")
563 claim uH (Var (reflm "Universe"))
564 movelast uH
565 fill $ reflCall "RUType" [Var uH]
566 solve
567 focus uH; fill (reflectUniverse univ); solve
568reflectRawQuotePattern unq (RConstant c) =
569 do cH <- getNameFrom (sMN 0 "const")
570 claim cH (Var (reflm "Constant"))
571 movelast cH
572 fill (reflCall "RConstant" [Var cH]); solve
573 focus cH
574 fill (reflectConstant c); solve
576reflectBinderQuotePattern :: ([Name] -> a -> ElabD ()) -> Raw -> [Name] -> Binder a -> ElabD ()
577reflectBinderQuotePattern q ty unq (Lam t)
578 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
579 fill $ reflCall "Lam" [ty, Var t']
580 solve
581 focus t'; q unq t
582reflectBinderQuotePattern q ty unq (Pi _ t k)
583 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
584 k' <- claimTy (sMN 0 "k") ty; movelast k';
585 fill $ reflCall "Pi" [ty, Var t', Var k']
586 solve
587 focus t'; q unq t
588reflectBinderQuotePattern q ty unq (Let x y)
589 = do x' <- claimTy (sMN 0 "ty") ty; movelast x';
590 y' <- claimTy (sMN 0 "v")ty; movelast y';
591 fill $ reflCall "Let" [ty, Var x', Var y']
592 solve
593 focus x'; q unq x
594 focus y'; q unq y
595reflectBinderQuotePattern q ty unq (NLet x y)
596 = do x' <- claimTy (sMN 0 "ty") ty; movelast x'
597 y' <- claimTy (sMN 0 "v") ty; movelast y'
598 fill $ reflCall "Let" [ty, Var x', Var y']
599 solve
600 focus x'; q unq x
601 focus y'; q unq y
602reflectBinderQuotePattern q ty unq (Hole t)
603 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
604 fill $ reflCall "Hole" [ty, Var t']
605 solve
606 focus t'; q unq t
607reflectBinderQuotePattern q ty unq (GHole _ _ t)
608 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
609 fill $ reflCall "GHole" [ty, Var t']
610 solve
611 focus t'; q unq t
612reflectBinderQuotePattern q ty unq (Guess x y)
613 = do x' <- claimTy (sMN 0 "ty") ty; movelast x'
614 y' <- claimTy (sMN 0 "v") ty; movelast y'
615 fill $ reflCall "Guess" [ty, Var x', Var y']
616 solve
617 focus x'; q unq x
618 focus y'; q unq y
619reflectBinderQuotePattern q ty unq (PVar t)
620 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
621 fill $ reflCall "PVar" [ty, Var t']
622 solve
623 focus t'; q unq t
624reflectBinderQuotePattern q ty unq (PVTy t)
625 = do t' <- claimTy (sMN 0 "ty") ty; movelast t'
626 fill $ reflCall "PVTy" [ty, Var t']
627 solve
628 focus t'; q unq t
630reflectUniverse :: Universe -> Raw
631reflectUniverse u =
632 (Var (reflm (case u of
633 NullType -> "NullType"
634 UniqueType -> "UniqueType"
635 AllTypes -> "AllTypes")))
637-- | Create a reflected TT term, but leave refs to the provided name intact
638reflectTTQuote :: [Name] -> Term -> Raw
639reflectTTQuote unq (P nt n t)
640 | n `elem` unq = Var n
641 | otherwise = reflCall "P" [reflectNameType nt, reflectName n, reflectTTQuote unq t]
642reflectTTQuote unq (V n)
643 = reflCall "V" [RConstant (I n)]
644reflectTTQuote unq (Bind n b x)
645 = reflCall "Bind" [reflectName n, reflectBinderQuote reflectTTQuote (reflm "TT") unq b, reflectTTQuote unq x]
646reflectTTQuote unq (App _ f x)
647 = reflCall "App" [reflectTTQuote unq f, reflectTTQuote unq x]
648reflectTTQuote unq (Constant c)
649 = reflCall "TConst" [reflectConstant c]
650reflectTTQuote unq (TType exp) = reflCall "TType" [reflectUExp exp]
651reflectTTQuote unq (UType u) = reflCall "UType" [reflectUniverse u]
652reflectTTQuote _ (Proj _ _) =
653 error "Phase error! The Proj constructor is for optimization only and should not have been reflected during elaboration."
654reflectTTQuote unq Erased = Var (reflm "Erased")
655reflectTTQuote _ Impossible =
656 error "Phase error! The Impossible constructor is for optimization only and should not have been reflected during elaboration."
658reflectRawQuote :: [Name] -> Raw -> Raw
659reflectRawQuote unq (Var n)
660 | n `elem` unq = Var n
661 | otherwise = reflCall "Var" [reflectName n]
662reflectRawQuote unq (RBind n b r) =
663 reflCall "RBind" [reflectName n, reflectBinderQuote reflectRawQuote (reflm "Raw") unq b, reflectRawQuote unq r]
664reflectRawQuote unq (RApp f x) =
665 reflCall "RApp" [reflectRawQuote unq f, reflectRawQuote unq x]
666reflectRawQuote unq RType = Var (reflm "RType")
667reflectRawQuote unq (RUType u) =
668 reflCall "RUType" [reflectUniverse u]
669reflectRawQuote unq (RConstant cst) = reflCall "RConstant" [reflectConstant cst]
671reflectNameType :: NameType -> Raw
672reflectNameType (Bound) = Var (reflm "Bound")
673reflectNameType (Ref) = Var (reflm "Ref")
674reflectNameType (DCon x y _)
675 = reflCall "DCon" [RConstant (I x), RConstant (I y)] -- FIXME: Uniqueness!
676reflectNameType (TCon x y)
677 = reflCall "TCon" [RConstant (I x), RConstant (I y)]
679reflectName :: Name -> Raw
680reflectName (UN s)
681 = reflCall "UN" [RConstant (Str (str s))]
682reflectName (NS n ns)
683 = reflCall "NS" [ reflectName n
684 , foldr (\ n s ->
685 raw_apply ( Var $ sNS (sUN "::") ["List", "Prelude"] )
686 [ RConstant StrType, RConstant (Str n), s ])
687 ( raw_apply ( Var $ sNS (sUN "Nil") ["List", "Prelude"] )
688 [ RConstant StrType ])
689 (map str ns)
690 ]
691reflectName (MN i n)
692 = reflCall "MN" [RConstant (I i), RConstant (Str (str n))]
693reflectName (SN sn) = raw_apply (Var (reflm "SN")) [reflectSpecialName sn]
694reflectName (SymRef _) = error "The impossible happened: symbol table ref survived IBC loading"
696reflectSpecialName :: SpecialName -> Raw
697reflectSpecialName (WhereN i n1 n2) =
698 reflCall "WhereN" [RConstant (I i), reflectName n1, reflectName n2]
699reflectSpecialName (WithN i n) = reflCall "WithN" [ RConstant (I i)
700 , reflectName n
701 ]
702reflectSpecialName (ImplementationN impl ss) =
703 reflCall "ImplementationN" [ reflectName impl
704 , mkList (RConstant StrType) $
705 map (RConstant . Str . T.unpack) ss
706 ]
707reflectSpecialName (ParentN n s) =
708 reflCall "ParentN" [reflectName n, RConstant (Str (T.unpack s))]
709reflectSpecialName (MethodN n) =
710 reflCall "MethodN" [reflectName n]
711reflectSpecialName (CaseN fc n) =
712 reflCall "CaseN" [reflectFC (unwrapFC fc), reflectName n]
713reflectSpecialName (ElimN n) =
714 reflCall "ElimN" [reflectName n]
715reflectSpecialName (ImplementationCtorN n) =
716 reflCall "ImplementationCtorN" [reflectName n]
717reflectSpecialName (MetaN parent meta) =
718 reflCall "MetaN" [reflectName parent, reflectName meta]
720-- | Elaborate a name to a pattern. This means that NS and UN will be intact.
721-- MNs corresponding to will care about the string but not the number. All
722-- others become _.
723reflectNameQuotePattern :: Name -> ElabD ()
724reflectNameQuotePattern n@(UN s)
725 = do fill $ reflectName n
726 solve
727reflectNameQuotePattern n@(NS _ _)
728 = do fill $ reflectName n
729 solve
730reflectNameQuotePattern (MN _ n)
731 = do i <- getNameFrom (sMN 0 "mnCounter")
732 claim i (RConstant (AType (ATInt ITNative)))
733 movelast i
734 fill $ reflCall "MN" [Var i, RConstant (Str $ T.unpack n)]
735 solve
736reflectNameQuotePattern _ -- for all other names, match any
737 = do nameHole <- getNameFrom (sMN 0 "name")
738 claim nameHole (Var (reflm "TTName"))
739 movelast nameHole
740 fill (Var nameHole)
741 solve
743reflectBinder :: Binder Term -> Raw
744reflectBinder = reflectBinderQuote reflectTTQuote (reflm "TT") []
746reflectBinderQuote :: ([Name] -> a -> Raw) -> Name -> [Name] -> Binder a -> Raw
747reflectBinderQuote q ty unq (Lam t)
748 = reflCall "Lam" [Var ty, q unq t]
749reflectBinderQuote q ty unq (Pi _ t k)
750 = reflCall "Pi" [Var ty, q unq t, q unq k]
751reflectBinderQuote q ty unq (Let x y)
752 = reflCall "Let" [Var ty, q unq x, q unq y]
753reflectBinderQuote q ty unq (NLet x y)
754 = reflCall "Let" [Var ty, q unq x, q unq y]
755reflectBinderQuote q ty unq (Hole t)
756 = reflCall "Hole" [Var ty, q unq t]
757reflectBinderQuote q ty unq (GHole _ _ t)
758 = reflCall "GHole" [Var ty, q unq t]
759reflectBinderQuote q ty unq (Guess x y)
760 = reflCall "Guess" [Var ty, q unq x, q unq y]
761reflectBinderQuote q ty unq (PVar t)
762 = reflCall "PVar" [Var ty, q unq t]
763reflectBinderQuote q ty unq (PVTy t)
764 = reflCall "PVTy" [Var ty, q unq t]
766mkList :: Raw -> [Raw] -> Raw
767mkList ty [] = RApp (Var (sNS (sUN "Nil") ["List", "Prelude"])) ty
768mkList ty (x:xs) = RApp (RApp (RApp (Var (sNS (sUN "::") ["List", "Prelude"])) ty)
769 x)
770 (mkList ty xs)
772reflectConstant :: Const -> Raw
773reflectConstant c@(I _) = reflCall "I" [RConstant c]
774reflectConstant c@(BI _) = reflCall "BI" [RConstant c]
775reflectConstant c@(Fl _) = reflCall "Fl" [RConstant c]
776reflectConstant c@(Ch _) = reflCall "Ch" [RConstant c]
777reflectConstant c@(Str _) = reflCall "Str" [RConstant c]
778reflectConstant c@(B8 _) = reflCall "B8" [RConstant c]
779reflectConstant c@(B16 _) = reflCall "B16" [RConstant c]
780reflectConstant c@(B32 _) = reflCall "B32" [RConstant c]
781reflectConstant c@(B64 _) = reflCall "B64" [RConstant c]
782reflectConstant (AType (ATInt ITNative)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITNative")]]
783reflectConstant (AType (ATInt ITBig)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITBig")]]
784reflectConstant (AType ATFloat) = reflCall "AType" [Var (reflm "ATDouble")]
785reflectConstant (AType (ATInt ITChar)) = reflCall "AType" [reflCall "ATInt" [Var (reflm "ITChar")]]
786reflectConstant StrType = Var (reflm "StrType")
787reflectConstant (AType (ATInt (ITFixed IT8))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT8")]]]
788reflectConstant (AType (ATInt (ITFixed IT16))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT16")]]]
789reflectConstant (AType (ATInt (ITFixed IT32))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT32")]]]
790reflectConstant (AType (ATInt (ITFixed IT64))) = reflCall "AType" [reflCall "ATInt" [reflCall "ITFixed" [Var (reflm "IT64")]]]
791reflectConstant VoidType = Var (reflm "VoidType")
792reflectConstant Forgot = Var (reflm "Forgot")
793reflectConstant WorldType = Var (reflm "WorldType")
794reflectConstant TheWorld = Var (reflm "TheWorld")
796reflectUExp :: UExp -> Raw
797reflectUExp (UVar ns i) = reflCall "UVar" [RConstant (Str ns), RConstant (I i)]
798reflectUExp (UVal i) = reflCall "UVal" [RConstant (I i)]
800-- | Reflect the environment of a proof into a List (TTName, Binder TT)
801reflectEnv :: Env -> Raw
802reflectEnv = foldr consToEnvList emptyEnvList
803 where
804 consToEnvList :: (Name, Binder Term) -> Raw -> Raw
805 consToEnvList (n, b) l
806 = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"]))
807 [ envTupleType
808 , raw_apply (Var pairCon) [ (Var $ reflm "TTName")
809 , (RApp (Var $ reflm "Binder")
810 (Var $ reflm "TT"))
811 , reflectName n
812 , reflectBinder b
813 ]
814 , l
815 ]
817 emptyEnvList :: Raw
818 emptyEnvList = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"]))
819 [envTupleType]
821reifyEnv :: Term -> ElabD Env
822reifyEnv = reifyList (reifyPair reifyTTName (reifyTTBinder reifyTT (reflm "TT")))
824-- | Reflect an error into the internal datatype of Idris -- TODO
825rawBool :: Bool -> Raw
826rawBool True = Var (sNS (sUN "True") ["Bool", "Prelude"])
827rawBool False = Var (sNS (sUN "False") ["Bool", "Prelude"])
829rawNil :: Raw -> Raw
830rawNil ty = raw_apply (Var (sNS (sUN "Nil") ["List", "Prelude"])) [ty]
832rawCons :: Raw -> Raw -> Raw -> Raw
833rawCons ty hd tl = raw_apply (Var (sNS (sUN "::") ["List", "Prelude"])) [ty, hd, tl]
835rawList :: Raw -> [Raw] -> Raw
836rawList ty = foldr (rawCons ty) (rawNil ty)
838rawPairTy :: Raw -> Raw -> Raw
839rawPairTy t1 t2 = raw_apply (Var pairTy) [t1, t2]
841rawPair :: (Raw, Raw) -> (Raw, Raw) -> Raw
842rawPair (a, b) (x, y) = raw_apply (Var pairCon) [a, b, x, y]
844-- | Idris tuples nest to the right
845rawTripleTy :: Raw -> Raw -> Raw -> Raw
846rawTripleTy a b c = rawPairTy a (rawPairTy b c)
848rawTriple :: (Raw, Raw, Raw) -> (Raw, Raw, Raw) -> Raw
849rawTriple (a, b, c) (x, y, z) = rawPair (a, rawPairTy b c) (x, rawPair (b, c) (y, z))
851reflectCtxt :: [(Name, Type)] -> Raw
852reflectCtxt ctxt = rawList (rawPairTy (Var $ reflm "TTName") (Var $ reflm "TT"))
853 (map (\ (n, t) -> (rawPair (Var $ reflm "TTName", Var $ reflm "TT")
854 (reflectName n, reflect t)))
855 ctxt)
857reflectErr :: Err -> Raw
858reflectErr (Msg msg) = raw_apply (Var $ reflErrName "Msg") [RConstant (Str msg)]
859reflectErr (InternalMsg msg) = raw_apply (Var $ reflErrName "InternalMsg") [RConstant (Str msg)]
860reflectErr (CantUnify b (t1,_) (t2,_) e ctxt i) =
861 raw_apply (Var $ reflErrName "CantUnify")
862 [ rawBool b
863 , reflect t1
864 , reflect t2
865 , reflectErr e
866 , reflectCtxt ctxt
867 , RConstant (I i)]
868reflectErr (InfiniteUnify n tm ctxt) =
869 raw_apply (Var $ reflErrName "InfiniteUnify")
870 [ reflectName n
871 , reflect tm
872 , reflectCtxt ctxt
873 ]
874reflectErr (CantConvert t t' ctxt) =
875 raw_apply (Var $ reflErrName "CantConvert")
876 [ reflect t
877 , reflect t'
878 , reflectCtxt ctxt
879 ]
880reflectErr (CantSolveGoal t ctxt) =
881 raw_apply (Var $ reflErrName "CantSolveGoal")
882 [ reflect t
883 , reflectCtxt ctxt
884 ]
885reflectErr (UnifyScope n n' t ctxt) =
886 raw_apply (Var $ reflErrName "UnifyScope")
887 [ reflectName n
888 , reflectName n'
889 , reflect t
890 , reflectCtxt ctxt
891 ]
892reflectErr (CantInferType str) =
893 raw_apply (Var $ reflErrName "CantInferType") [RConstant (Str str)]
894reflectErr (NonFunctionType t t') =
895 raw_apply (Var $ reflErrName "NonFunctionType") [reflect t, reflect t']
896reflectErr (NotEquality t t') =
897 raw_apply (Var $ reflErrName "NotEquality") [reflect t, reflect t']
898reflectErr (TooManyArguments n) = raw_apply (Var $ reflErrName "TooManyArguments") [reflectName n]
899reflectErr (CantIntroduce t) = raw_apply (Var $ reflErrName "CantIntroduce") [reflect t]
900reflectErr (NoSuchVariable n) = raw_apply (Var $ reflErrName "NoSuchVariable") [reflectName n]
901reflectErr (WithFnType t) = raw_apply (Var $ reflErrName "WithFnType") [reflect t]
902reflectErr (CantMatch t) = raw_apply (Var $ reflErrName "CantMatch") [reflect t]
903reflectErr (NoTypeDecl n) = raw_apply (Var $ reflErrName "NoTypeDecl") [reflectName n]
904reflectErr (NotInjective t1 t2 t3) =
905 raw_apply (Var $ reflErrName "NotInjective")
906 [ reflect t1
907 , reflect t2
908 , reflect t3
909 ]
910reflectErr (CantResolve _ t more)
911 = raw_apply (Var $ reflErrName "CantResolve") [reflect t, reflectErr more]
912reflectErr (InvalidTCArg n t) = raw_apply (Var $ reflErrName "InvalidTCArg") [reflectName n, reflect t]
913reflectErr (CantResolveAlts ss) =
914 raw_apply (Var $ reflErrName "CantResolveAlts")
915 [rawList (Var $ reflm "TTName") (map reflectName ss)]
916reflectErr (IncompleteTerm t) = raw_apply (Var $ reflErrName "IncompleteTerm") [reflect t]
917reflectErr (NoEliminator str t)
918 = raw_apply (Var $ reflErrName "NoEliminator") [RConstant (Str str),
919 reflect t]
920reflectErr (UniverseError fc ue old new tys) =
921 -- NB: loses information, but OK because this is not likely to be rewritten
922 Var $ reflErrName "UniverseError"
923reflectErr ProgramLineComment = Var $ reflErrName "ProgramLineComment"
924reflectErr (Inaccessible n) = raw_apply (Var $ reflErrName "Inaccessible") [reflectName n]
925reflectErr (UnknownImplicit n f) = raw_apply (Var $ reflErrName "UnknownImplicit") [reflectName n, reflectName f]
926reflectErr (NonCollapsiblePostulate n) = raw_apply (Var $ reflErrName "NonCollabsiblePostulate") [reflectName n]
927reflectErr (AlreadyDefined n) = raw_apply (Var $ reflErrName "AlreadyDefined") [reflectName n]
928reflectErr (ProofSearchFail e) = raw_apply (Var $ reflErrName "ProofSearchFail") [reflectErr e]
929reflectErr (NoRewriting l r tm) = raw_apply (Var $ reflErrName "NoRewriting") [reflect l, reflect r, reflect tm]
930reflectErr (ProviderError str) =
931 raw_apply (Var $ reflErrName "ProviderError") [RConstant (Str str)]
932reflectErr (LoadingFailed str err) =
933 raw_apply (Var $ reflErrName "LoadingFailed") [RConstant (Str str)]
934reflectErr x = raw_apply (Var (sNS (sUN "Msg") ["Errors", "Reflection", "Language"])) [RConstant . Str $ "Default reflection: " ++ show x]
936-- | Reflect a file context
937reflectFC :: FC -> Raw
938reflectFC fc = raw_apply (Var (reflm "FileLoc"))
939 [ RConstant (Str (fc_fname fc))
940 , raw_apply (Var pairCon) $
941 [intTy, intTy] ++
942 map (RConstant . I)
943 [ fst (fc_start fc)
944 , snd (fc_start fc)
945 ]
946 , raw_apply (Var pairCon) $
947 [intTy, intTy] ++
948 map (RConstant . I)
949 [ fst (fc_end fc)
950 , snd (fc_end fc)
951 ]
952 ]
953 where intTy = RConstant (AType (ATInt ITNative))
955reifyFC :: Term -> ElabD FC
956reifyFC tm
957 | (P (DCon _ _ _) cn _, [Constant (Str fn), st, end]) <- unApply tm
958 , cn == reflm "FileLoc" = FC fn <$> reifyPair reifyInt reifyInt st <*> reifyPair reifyInt reifyInt end
959 | otherwise = fail $ "Not a source location: " ++ show tm
961fromTTMaybe :: Term -> Maybe Term -- WARNING: Assumes the term has type Maybe a
962fromTTMaybe (App _ (App _ (P (DCon _ _ _) (NS (UN just) _) _) ty) tm)
963 | just == txt "Just" = Just tm
964fromTTMaybe x = Nothing
966reflErrName :: String -> Name
967reflErrName n = sNS (sUN n) ["Errors", "Reflection", "Language"]
969-- | Attempt to reify a report part from TT to the internal
970-- representation. Not in Idris or ElabD monads because it should be usable
971-- from either.
972reifyReportPart :: Term -> Either Err ErrorReportPart
973reifyReportPart (App _ (P (DCon _ _ _) n _) (Constant (Str msg))) | n == reflm "TextPart" =
974 Right (TextPart msg)
975reifyReportPart (App _ (P (DCon _ _ _) n _) ttn)
976 | n == reflm "NamePart" =
977 case runElab initEState (reifyTTName ttn) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of
978 Error e -> Left . InternalMsg $
979 "could not reify name term " ++
980 show ttn ++
981 " when reflecting an error:" ++ show e
982 OK (n', _)-> Right $ NamePart n'
983reifyReportPart (App _ (P (DCon _ _ _) n _) tm)
984 | n == reflm "TermPart" =
985 case runElab initEState (reifyTT tm) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of
986 Error e -> Left . InternalMsg $
987 "could not reify reflected term " ++
988 show tm ++
989 " when reflecting an error:" ++ show e
990 OK (tm', _) -> Right $ TermPart tm'
991reifyReportPart (App _ (P (DCon _ _ _) n _) tm)
992 | n == reflm "RawPart" =
993 case runElab initEState (reifyRaw tm) (initElaborator (sMN 0 "hole") internalNS initContext emptyContext 0 Erased) of
994 Error e -> Left . InternalMsg $
995 "could not reify reflected raw term " ++
996 show tm ++
997 " when reflecting an error: " ++ show e
998 OK (tm', _) -> Right $ RawPart tm'
999reifyReportPart (App _ (P (DCon _ _ _) n _) tm)
1000 | n == reflm "SubReport" =
1001 case unList tm of
1002 Just xs -> do subParts <- mapM reifyReportPart xs
1003 Right (SubReport subParts)
1004 Nothing -> Left . InternalMsg $ "could not reify subreport " ++ show tm
1005reifyReportPart x = Left . InternalMsg $ "could not reify " ++ show x
1007reifyErasure :: Term -> ElabD RErasure
1008reifyErasure (P (DCon _ _ _) n _)
1009 | n == tacN "Erased" = return RErased
1010 | n == tacN "NotErased" = return RNotErased
1011reifyErasure tm = fail $ "Can't reify " ++ show tm ++ " as erasure info."
1013reifyPlicity :: Term -> ElabD RPlicity
1014reifyPlicity (P (DCon _ _ _) n _)
1015 | n == tacN "Explicit" = return RExplicit
1016 | n == tacN "Implicit" = return RImplicit
1017 | n == tacN "Constraint" = return RConstraint
1018reifyPlicity tm = fail $ "Couldn't reify " ++ show tm ++ " as RPlicity."
1020reifyRFunArg :: Term -> ElabD RFunArg
1021reifyRFunArg (App _ (App _ (App _ (App _ (P (DCon _ _ _) n _) argN) argTy) argPl) argE)
1022 | n == tacN "MkFunArg" = liftM4 RFunArg
1023 (reifyTTName argN)
1024 (reifyRaw argTy)
1025 (reifyPlicity argPl)
1026 (reifyErasure argE)
1027reifyRFunArg aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RArg."
1029reifyTyDecl :: Term -> ElabD RTyDecl
1030reifyTyDecl (App _ (App _ (App _ (P (DCon _ _ _) n _) tyN) args) ret)
1031 | n == tacN "Declare" =
1032 do tyN' <- reifyTTName tyN
1033 args' <- case unList args of
1034 Nothing -> fail $ "Couldn't reify " ++ show args ++ " as an arglist."
1035 Just xs -> mapM reifyRFunArg xs
1036 ret' <- reifyRaw ret
1037 return $ RDeclare tyN' args' ret'
1038reifyTyDecl tm = fail $ "Couldn't reify " ++ show tm ++ " as a type declaration."
1040reifyFunDefn :: Term -> ElabD (RFunDefn Raw)
1041reifyFunDefn (App _ (App _ (App _ (P _ n _) (P _ t _)) fnN) clauses)
1042 | n == tacN "DefineFun" && t == reflm "Raw" =
1043 do fnN' <- reifyTTName fnN
1044 clauses' <- case unList clauses of
1045 Nothing -> fail $ "Couldn't reify " ++ show clauses ++ " as a clause list"
1046 Just cs -> mapM reifyC cs
1047 return $ RDefineFun fnN' clauses'
1048 where reifyC :: Term -> ElabD (RFunClause Raw)
1049 reifyC (App _ (App _ (App _ (P (DCon _ _ _) n _) (P _ t _)) lhs) rhs)
1050 | n == tacN "MkFunClause" && t == reflm "Raw" = liftM2 RMkFunClause
1051 (reifyRaw lhs)
1052 (reifyRaw rhs)
1053 reifyC (App _ (App _ (P (DCon _ _ _) n _) (P _ t _)) lhs)
1054 | n == tacN "MkImpossibleClause" && t == reflm "Raw" = fmap RMkImpossibleClause $ reifyRaw lhs
1055 reifyC tm = fail $ "Couldn't reify " ++ show tm ++ " as a clause."
1056reifyFunDefn tm = fail $ "Couldn't reify " ++ show tm ++ " as a function declaration."
1058reifyRConstructorDefn :: Term -> ElabD RConstructorDefn
1059reifyRConstructorDefn (App _ (App _ (App _ (P _ n _) cn) args) retTy)
1060 | n == tacN "Constructor", Just args' <- unList args
1061 = RConstructor <$> reifyTTName cn <*> mapM reifyRFunArg args' <*> reifyRaw retTy
1062reifyRConstructorDefn aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RConstructorDefn"
1064reifyRDataDefn :: Term -> ElabD RDataDefn
1065reifyRDataDefn (App _ (App _ (P _ n _) tyn) ctors)
1066 | n == tacN "DefineDatatype", Just ctors' <- unList ctors
1067 = RDefineDatatype <$> reifyTTName tyn <*> mapM reifyRConstructorDefn ctors'
1068reifyRDataDefn aTm = fail $ "Couldn't reify " ++ show aTm ++ " as an RDataDefn"
1070envTupleType :: Raw
1071envTupleType
1072 = raw_apply (Var pairTy) [ (Var $ reflm "TTName")
1073 , (RApp (Var $ reflm "Binder") (Var $ reflm "TT"))
1076reflectList :: Raw -> [Raw] -> Raw
1077reflectList ty [] = RApp (Var (sNS (sUN "Nil") ["List", "Prelude"])) ty
1078reflectList ty (x:xs) = RApp (RApp (RApp (Var (sNS (sUN "::") ["List", "Prelude"])) ty)
1079 x)
1080 (reflectList ty xs)
1082-- | Apply Idris's implicit info to get a signature. The [PArg] should
1083-- come from a lookup in idris_implicits on IState.
1084getArgs :: [PArg] -> Raw -> ([RFunArg], Raw)
1085getArgs [] r = ([], r)
1086getArgs (a:as) (RBind n (Pi _ ty _) sc) =
1087 let (args, res) = getArgs as sc
1088 erased = if InaccessibleArg `elem` argopts a then RErased else RNotErased
1089 arg' = case a of
1090 PImp {} -> RFunArg n ty RImplicit erased
1091 PExp {} -> RFunArg n ty RExplicit erased
1092 PConstraint {} -> RFunArg n ty RConstraint erased
1093 PTacImplicit {} -> RFunArg n ty RImplicit erased
1094 in (arg':args, res)
1095getArgs _ r = ([], r)
1097unApplyRaw :: Raw -> (Raw, [Raw])
1098unApplyRaw tm = ua [] tm
1099 where
1100 ua args (RApp f a) = ua (a:args) f
1101 ua args t = (t, args)
1103-- | Build the reflected function definition(s) that correspond(s) to
1104-- a provided unqualifed name
1105buildFunDefns :: IState -> Name -> [RFunDefn Term]
1106buildFunDefns ist n =
1107 [ mkFunDefn name clauses
1108 | (name, (clauses, _)) <- lookupCtxtName n $ idris_patdefs ist
1111 where mkFunDefn name clauses = RDefineFun name (map mkFunClause clauses)
1113 mkFunClause ([], lhs, Impossible) = RMkImpossibleClause lhs
1114 mkFunClause ([], lhs, rhs) = RMkFunClause lhs rhs
1115 mkFunClause (((n, ty) : ns), lhs, rhs) = mkFunClause (ns, bind lhs, bind rhs) where
1116 bind Impossible = Impossible
1117 bind tm = Bind n (PVar ty) tm
1119-- | Build the reflected datatype definition(s) that correspond(s) to
1120-- a provided unqualified name
1121buildDatatypes :: IState -> Name -> [RDatatype]
1122buildDatatypes ist n =
1123 catMaybes [ mkDataType dn ti
1124 | (dn, ti) <- lookupCtxtName n datatypes
1126 where datatypes = idris_datatypes ist
1127 ctxt = tt_ctxt ist
1128 impls = idris_implicits ist
1130 ctorSig params cn = do cty <- fmap forget (lookupTyExact cn ctxt)
1131 argInfo <- lookupCtxtExact cn impls
1132 let (args, res) = getArgs argInfo cty
1133 return (cn, ctorArgsStatus args res params, res)
1135 argPos n [] res = findPos n res
1136 where findPos n app = case unApplyRaw app of
1137 (_, argL) -> findIndex (== Var n) argL
1138 argPos n (arg:args) res = if n == argName arg
1139 then Nothing
1140 else argPos n args res
1142 ctorArgsStatus :: [RFunArg] -> Raw -> [Int] -> [RCtorArg]
1143 ctorArgsStatus [] _ _ = []
1144 ctorArgsStatus (arg:args) res params =
1145 case argPos (argName arg) args res of
1146 Nothing -> RCtorField arg : ctorArgsStatus args res params
1147 Just i -> if i `elem` params
1148 then RCtorParameter arg : ctorArgsStatus args res params
1149 else RCtorField arg : ctorArgsStatus args res params
1151 mkDataType name (TI {param_pos = params, con_names = constrs}) =
1152 do (TyDecl (TCon _ _) ty) <- lookupDefExact name ctxt
1153 implInfo <- lookupCtxtExact name impls
1154 let (tcargs, tcres) = getTCArgs params implInfo (forget ty)
1155 ctors <- mapM (ctorSig params) constrs
1156 return $ RDatatype name tcargs tcres ctors
1158 getTCArgs :: [Int] -> [PArg] -> Raw -> ([RTyConArg], Raw)
1159 getTCArgs params implInfo tcTy =
1160 let (args, res) = getArgs implInfo tcTy
1161 in (tcArg args 0, res)
1162 where tcArg [] _ = []
1163 tcArg (arg:args) i | i `elem` params = RParameter arg : tcArg args (i+1)
1164 | otherwise = RIndex arg : tcArg args (i+1)
1167reflectErasure :: RErasure -> Raw
1168reflectErasure RErased = Var (tacN "Erased")
1169reflectErasure RNotErased = Var (tacN "NotErased")
1171reflectPlicity :: RPlicity -> Raw
1172reflectPlicity RExplicit = Var (tacN "Explicit")
1173reflectPlicity RImplicit = Var (tacN "Implicit")
1174reflectPlicity RConstraint = Var (tacN "Constraint")
1176reflectArg :: RFunArg -> Raw
1177reflectArg (RFunArg n ty plic erasure) =
1178 RApp (RApp (RApp (RApp (Var $ tacN "MkFunArg") (reflectName n))
1179 (reflectRaw ty))
1180 (reflectPlicity plic))
1181 (reflectErasure erasure)
1183reflectCtorArg :: RCtorArg -> Raw
1184reflectCtorArg (RCtorParameter arg) = RApp (Var $ tacN "CtorParameter") (reflectArg arg)
1185reflectCtorArg (RCtorField arg) = RApp (Var $ tacN "CtorField") (reflectArg arg)
1187reflectDatatype :: RDatatype -> Raw
1188reflectDatatype (RDatatype tyn tyConArgs tyConRes constrs) =
1189 raw_apply (Var $ tacN "MkDatatype") [ reflectName tyn
1190 , rawList (Var $ tacN "TyConArg") (map reflectConArg tyConArgs)
1191 , reflectRaw tyConRes
1192 , rawList (rawTripleTy (Var $ reflm "TTName")
1193 (RApp (Var (sNS (sUN "List") ["List", "Prelude"]))
1194 (Var $ tacN "CtorArg"))
1195 (Var $ reflm "Raw"))
1196 [ rawTriple ((Var $ reflm "TTName")
1197 ,(RApp (Var (sNS (sUN "List") ["List", "Prelude"]))
1198 (Var $ tacN "CtorArg"))
1199 ,(Var $ reflm "Raw"))
1200 (reflectName cn
1201 ,rawList (Var $ tacN "CtorArg")
1202 (map reflectCtorArg cargs)
1203 ,reflectRaw cty)
1204 | (cn, cargs, cty) <- constrs
1207 where reflectConArg (RParameter a) =
1208 RApp (Var $ tacN "TyConParameter") (reflectArg a)
1209 reflectConArg (RIndex a) =
1210 RApp (Var $ tacN "TyConIndex") (reflectArg a)
1212reflectFunClause :: RFunClause Term -> Raw
1213reflectFunClause (RMkFunClause lhs rhs) = raw_apply (Var $ tacN "MkFunClause")
1214 $ (Var $ reflm "TT") : map reflect [ lhs, rhs ]
1216reflectFunClause (RMkImpossibleClause lhs) = raw_apply (Var $ tacN "MkImpossibleClause")
1217 [ Var $ reflm "TT", reflect lhs ]
1219reflectFunDefn :: RFunDefn Term -> Raw
1220reflectFunDefn (RDefineFun name clauses) = raw_apply (Var $ tacN "DefineFun")
1221 [ Var $ reflm "TT"
1222 , reflectName name
1223 , rawList (RApp (Var $ tacN "FunClause")
1224 (Var $ reflm "TT"))
1225 (map reflectFunClause clauses)