on 200475f help sign in
879 lines 29 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FunctionalDependencies, DeriveFunctor #-}
3{-| TT is the core language of Idris. The language has:
5 * Full dependent types
7 * A hierarchy of universes, with cumulativity: Type : Type1, Type1 : Type2, ...
9 * Pattern matching letrec binding
11 * (primitive types defined externally)
13 Some technical stuff:
15 * Typechecker is kept as simple as possible - no unification, just a checker for incomplete terms.
17 * We have a simple collection of tactics which we use to elaborate source
18 programs with implicit syntax into fully explicit terms.
19-}
21module Core.TT where
23import Control.Monad.State
24import Debug.Trace
25import qualified Data.Map as Map
26import Data.Char
27import Data.List
28import qualified Data.Binary as B
29import Data.Binary hiding (get, put)
31import Util.Pretty hiding (Str)
33data Option = TTypeInTType
34 | CheckConv
35 deriving Eq
37-- | Source location. These are typically produced by the parser 'Idris.Parser.pfc'
38data FC = FC { fc_fname :: String, -- ^ Filename
39 fc_line :: Int -- ^ Line number
40 }
41 deriving Eq
42{-!
43deriving instance Binary FC
44!-}
46instance Sized FC where
47 size (FC f l) = 1 + length f
49instance Show FC where
50 show (FC f l) = f ++ ":" ++ show l
52data Err = Msg String
53 | InternalMsg String
54 | CantUnify Bool Term Term Err [(Name, Type)] Int
55 -- Int is 'score' - how much we did unify
56 -- Bool indicates recoverability, True indicates more info may make
57 -- unification succeed
58 | InfiniteUnify Name Term [(Name, Type)]
59 | CantConvert Term Term [(Name, Type)]
60 | NonFunctionType Term Term
61 | CantIntroduce Term
62 | NoSuchVariable Name
63 | NoTypeDecl Name
64 | NotInjective Term Term Term
65 | CantResolve Term
66 | CantResolveAlts [String]
67 | IncompleteTerm Term
68 | UniverseError
69 | ProgramLineComment
70 | Inaccessible Name
71 | NonCollapsiblePostulate Name
72 | AlreadyDefined Name
73 | ProofSearchFail Err
74 | NoRewriting Term
75 | At FC Err
76 | ProviderError String
77 deriving Eq
79instance Sized Err where
80 size (Msg msg) = length msg
81 size (InternalMsg msg) = length msg
82 size (CantUnify _ left right err _ score) = size left + size right + size err
83 size (InfiniteUnify _ right _) = size right
84 size (CantConvert left right _) = size left + size right
85 size (NoSuchVariable name) = size name
86 size (NoTypeDecl name) = size name
87 size (NotInjective l c r) = size l + size c + size r
88 size (CantResolve trm) = size trm
89 size (NoRewriting trm) = size trm
90 size (CantResolveAlts _) = 1
91 size (IncompleteTerm trm) = size trm
92 size UniverseError = 1
93 size ProgramLineComment = 1
94 size (At fc err) = size fc + size err
95 size (ProviderError msg) = length msg
96 size _ = 1
98score :: Err -> Int
99score (CantUnify _ _ _ m _ s) = s + score m
100score (CantResolve _) = 20
101score (NoSuchVariable _) = 1000
102score (ProofSearchFail _) = 10000
103score _ = 0
105instance Show Err where
106 show (Msg s) = s
107 show (InternalMsg s) = "Internal error: " ++ show s
108 show (CantUnify _ l r e sc i) = "CantUnify " ++ show l ++ " " ++ show r ++ " "
109 ++ show e ++ " in " ++ show sc ++ " " ++ show i
110 show (Inaccessible n) = show n ++ " is not an accessible pattern variable"
111 show (ProviderError msg) = "Type provider error: " ++ msg
112 show _ = "Error"
114instance Pretty Err where
115 pretty (Msg m) = text m
116 pretty (CantUnify _ l r e _ i) =
117 if size l + size r > breakingSize then
118 text "Cannot unify" <+> colon $$
119 nest nestingSize (pretty l <+> text "and" <+> pretty r) $$
120 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
121 else
122 text "Cannot unify" <+> colon <+> pretty l <+> text "and" <+> pretty r $$
123 nest nestingSize (text "where" <+> pretty e <+> text "with" <+> (text . show $ i))
124 pretty (ProviderError msg) = text msg
125 pretty _ = text "Error"
127data TC a = OK a
128 | Error Err
129 deriving (Eq, Functor)
131instance Pretty a => Pretty (TC a) where
132 pretty (OK ok) = pretty ok
133 pretty (Error err) =
134 if size err > breakingSize then
135 text "Error" <+> colon $$ (nest nestingSize $ pretty err)
136 else
137 text "Error" <+> colon <+> pretty err
139instance Show a => Show (TC a) where
140 show (OK x) = show x
141 show (Error str) = "Error: " ++ show str
143-- at some point, this instance should also carry type checking options
144-- (e.g. Type:Type)
146instance Monad TC where
147 return = OK
148 x >>= k = case x of
149 OK v -> k v
150 Error e -> Error e
151 fail e = Error (InternalMsg e)
153tfail :: Err -> TC a
154tfail e = Error e
156trun :: FC -> TC a -> TC a
157trun fc (OK a) = OK a
158trun fc (Error e) = Error (At fc e)
160instance MonadPlus TC where
161 mzero = fail "Unknown error"
162 (OK x) `mplus` _ = OK x
163 _ `mplus` (OK y) = OK y
164 err `mplus` _ = err
166discard :: Monad m => m a -> m ()
167discard f = f >> return ()
169showSep :: String -> [String] -> String
170showSep sep [] = ""
171showSep sep [x] = x
172showSep sep (x:xs) = x ++ sep ++ showSep sep xs
174pmap f (x, y) = (f x, f y)
176traceWhen True msg a = trace msg a
177traceWhen False _ a = a
179-- RAW TERMS ----------------------------------------------------------------
181-- | Names are hierarchies of strings, describing scope (so no danger of
182-- duplicate names, but need to be careful on lookup).
183data Name = UN String -- ^ User-provided name
184 | NS Name [String] -- ^ Root, namespaces
185 | MN Int String -- ^ Machine chosen names
186 | NErased -- ^ Name of somethng which is never used in scope
187 deriving (Eq, Ord)
188{-!
189deriving instance Binary Name
190!-}
192instance Sized Name where
193 size (UN n) = 1
194 size (NS n els) = 1 + length els
195 size (MN i n) = 1
196 size NErased = 1
198instance Pretty Name where
199 pretty (UN n) = text n
200 pretty (NS n s) = pretty n
201 pretty (MN i s) = lbrace <+> text s <+> (text . show $ i) <+> rbrace
203instance Show Name where
204 show (UN n) = n
205 show (NS n s) = showSep "." (reverse s) ++ "." ++ show n
206 show (MN i s) = "{" ++ s ++ show i ++ "}"
207 show NErased = "_"
209-- |Contexts allow us to map names to things. A root name maps to a collection
210-- of things in different namespaces with that name.
211type Ctxt a = Map.Map Name (Map.Map Name a)
212emptyContext = Map.empty
214tcname (UN ('@':_)) = True
215tcname (NS n _) = tcname n
216tcname _ = False
218implicitable (NS n _) = implicitable n
219implicitable (UN (x:xs)) = isLower x
220implicitable _ = False
222nsroot (NS n _) = n
223nsroot n = n
225addDef :: Name -> a -> Ctxt a -> Ctxt a
226addDef n v ctxt = case Map.lookup (nsroot n) ctxt of
227 Nothing -> Map.insert (nsroot n)
228 (Map.insert n v Map.empty) ctxt
229 Just xs -> Map.insert (nsroot n)
230 (Map.insert n v xs) ctxt
232{-| Look up a name in the context, given an optional namespace.
233 The name (n) may itself have a (partial) namespace given.
235 Rules for resolution:
237 - if an explicit namespace is given, return the names which match it. If none
238 match, return all names.
240 - if the name has has explicit namespace given, return the names which match it
241 and ignore the given namespace.
243 - otherwise, return all names.
245-}
247lookupCtxtName :: Name -> Ctxt a -> [(Name, a)]
248lookupCtxtName n ctxt = case Map.lookup (nsroot n) ctxt of
249 Just xs -> filterNS (Map.toList xs)
250 Nothing -> []
251 where
252 filterNS [] = []
253 filterNS ((found, v) : xs)
254 | nsmatch n found = (found, v) : filterNS xs
255 | otherwise = filterNS xs
257 nsmatch (NS n ns) (NS p ps) = ns `isPrefixOf` ps
258 nsmatch (NS _ _) _ = False
259 nsmatch looking found = True
261lookupCtxt :: Name -> Ctxt a -> [a]
262lookupCtxt n ctxt = map snd (lookupCtxtName n ctxt)
264updateDef :: Name -> (a -> a) -> Ctxt a -> Ctxt a
265updateDef n f ctxt
266 = let ds = lookupCtxtName n ctxt in
267 foldr (\ (n, t) c -> addDef n (f t) c) ctxt ds
269toAlist :: Ctxt a -> [(Name, a)]
270toAlist ctxt = let allns = map snd (Map.toList ctxt) in
271 concat (map (Map.toList) allns)
273addAlist :: Show a => [(Name, a)] -> Ctxt a -> Ctxt a
274addAlist [] ctxt = ctxt
275addAlist ((n, tm) : ds) ctxt = addDef n tm (addAlist ds ctxt)
277data Const = I Int | BI Integer | Fl Double | Ch Char | Str String
278 | IType | BIType | FlType | ChType | StrType
280 | B8 Word8 | B16 Word16 | B32 Word32 | B64 Word64
281 | B8Type | B16Type | B32Type | B64Type
283 | PtrType | VoidType | Forgot
284 deriving (Eq, Ord)
285{-!
286deriving instance Binary Const
287!-}
289instance Sized Const where
290 size _ = 1
292instance Pretty Const where
293 pretty (I i) = text . show $ i
294 pretty (BI i) = text . show $ i
295 pretty (Fl f) = text . show $ f
296 pretty (Ch c) = text . show $ c
297 pretty (Str s) = text s
298 pretty IType = text "Int"
299 pretty BIType = text "BigInt"
300 pretty FlType = text "Float"
301 pretty ChType = text "Char"
302 pretty StrType = text "String"
303 pretty PtrType = text "Ptr"
304 pretty VoidType = text "Void"
305 pretty Forgot = text "Forgot"
306 pretty B8Type = text "Bits8"
307 pretty B16Type = text "Bits16"
308 pretty B32Type = text "Bits32"
309 pretty B64Type = text "Bits64"
311data Raw = Var Name
312 | RBind Name (Binder Raw) Raw
313 | RApp Raw Raw
314 | RType
315 | RForce Raw
316 | RConstant Const
317 deriving (Show, Eq)
319instance Sized Raw where
320 size (Var name) = 1
321 size (RBind name bind right) = 1 + size bind + size right
322 size (RApp left right) = 1 + size left + size right
323 size RType = 1
324 size (RForce raw) = 1 + size raw
325 size (RConstant const) = size const
327instance Pretty Raw where
328 pretty = text . show
330{-!
331deriving instance Binary Raw
332!-}
334-- | All binding forms are represented in a unform fashion.
335data Binder b = Lam { binderTy :: b {-^ type annotation for bound variable-}}
336 | Pi { binderTy :: b }
337 | Let { binderTy :: b,
338 binderVal :: b {-^ value for bound variable-}}
339 | NLet { binderTy :: b,
340 binderVal :: b }
341 | Hole { binderTy :: b}
342 | GHole { binderTy :: b}
343 | Guess { binderTy :: b,
344 binderVal :: b }
345 | PVar { binderTy :: b }
346 | PVTy { binderTy :: b }
347 deriving (Show, Eq, Ord, Functor)
348{-!
349deriving instance Binary Binder
350!-}
352instance Sized a => Sized (Binder a) where
353 size (Lam ty) = 1 + size ty
354 size (Pi ty) = 1 + size ty
355 size (Let ty val) = 1 + size ty + size val
356 size (NLet ty val) = 1 + size ty + size val
357 size (Hole ty) = 1 + size ty
358 size (GHole ty) = 1 + size ty
359 size (Guess ty val) = 1 + size ty + size val
360 size (PVar ty) = 1 + size ty
361 size (PVTy ty) = 1 + size ty
363fmapMB :: Monad m => (a -> m b) -> Binder a -> m (Binder b)
364fmapMB f (Let t v) = liftM2 Let (f t) (f v)
365fmapMB f (NLet t v) = liftM2 NLet (f t) (f v)
366fmapMB f (Guess t v) = liftM2 Guess (f t) (f v)
367fmapMB f (Lam t) = liftM Lam (f t)
368fmapMB f (Pi t) = liftM Pi (f t)
369fmapMB f (Hole t) = liftM Hole (f t)
370fmapMB f (GHole t) = liftM GHole (f t)
371fmapMB f (PVar t) = liftM PVar (f t)
372fmapMB f (PVTy t) = liftM PVTy (f t)
374raw_apply :: Raw -> [Raw] -> Raw
375raw_apply f [] = f
376raw_apply f (a : as) = raw_apply (RApp f a) as
378raw_unapply :: Raw -> (Raw, [Raw])
379raw_unapply t = ua [] t where
380 ua args (RApp f a) = ua (a:args) f
381 ua args t = (t, args)
383data RawFun = RawFun { rtype :: Raw,
384 rval :: Raw
385 }
386 deriving Show
388data RawDatatype = RDatatype Name Raw [(Name, Raw)]
389 deriving Show
391data RDef = RFunction RawFun
392 | RConst Raw
393 | RData RawDatatype
394 deriving Show
396type RProgram = [(Name, RDef)]
398-- WELL TYPED TERMS ---------------------------------------------------------
400-- | Universe expressions for universe checking
401data UExp = UVar Int -- ^ universe variable
402 | UVal Int -- ^ explicit universe level
403 deriving (Eq, Ord)
405instance Sized UExp where
406 size _ = 1
408-- We assume that universe levels have been checked, so anything external
409-- can just have the same universe variable and we won't get any new
410-- cycles.
412instance Binary UExp where
413 put x = return ()
414 get = return (UVar (-1))
416instance Show UExp where
417 show (UVar x) | x < 26 = [toEnum (x + fromEnum 'a')]
418 | otherwise = toEnum ((x `mod` 26) + fromEnum 'a') : show (x `div` 26)
419 show (UVal x) = show x
420-- show (UMax l r) = "max(" ++ show l ++ ", " ++ show r ++")"
422-- | Universe constraints
423data UConstraint = ULT UExp UExp -- ^ Strictly less than
424 | ULE UExp UExp -- ^ Less than or equal to
425 deriving Eq
427instance Show UConstraint where
428 show (ULT x y) = show x ++ " < " ++ show y
429 show (ULE x y) = show x ++ " <= " ++ show y
431type UCs = (Int, [UConstraint])
433data NameType = Bound | Ref | DCon Int Int | TCon Int Int
434 deriving (Show, Ord)
435{-!
436deriving instance Binary NameType
437!-}
439instance Sized NameType where
440 size _ = 1
442instance Pretty NameType where
443 pretty = text . show
445instance Eq NameType where
446 Bound == Bound = True
447 Ref == Ref = True
448 DCon _ a == DCon _ b = (a == b) -- ignore tag
449 TCon _ a == TCon _ b = (a == b) -- ignore tag
450 _ == _ = False
452-- | Terms in the core language
453data TT n = P NameType n (TT n) -- ^ named references
454 | V Int -- ^ a resolved de Bruijn-indexed variable
455 | Bind n (Binder (TT n)) (TT n) -- ^ a binding
456 | App (TT n) (TT n) -- ^ function, function type, arg
457 | Constant Const -- ^ constant
458 | Proj (TT n) Int -- ^ argument projection; runtime only
459 | Erased -- ^ an erased term
460 | Impossible -- ^ special case for totality checking
461 | TType UExp -- ^ the type of types at some level
462 deriving (Ord, Functor)
463{-!
464deriving instance Binary TT
465!-}
467class TermSize a where
468 termsize :: Name -> a -> Int
470instance TermSize a => TermSize [a] where
471 termsize n [] = 0
472 termsize n (x : xs) = termsize n x + termsize n xs
474instance TermSize (TT Name) where
475 termsize n (P _ x _)
476 | x == n = 1000000 -- recursive => really big
477 | otherwise = 1
478 termsize n (V _) = 1
479 termsize n (Bind n' (Let t v) sc)
480 = let rn = if n == n' then MN 0 "noname" else n in
481 termsize rn v + termsize rn sc
482 termsize n (App f a) = termsize n f + termsize n a
483 termsize n _ = 1
485instance Sized a => Sized (TT a) where
486 size (P name n trm) = 1 + size name + size n + size trm
487 size (V v) = 1
488 size (Bind nm binder bdy) = 1 + size nm + size binder + size bdy
489 size (App l r) = 1 + size l + size r
490 size (Constant c) = size c
491 size Erased = 1
492 size (TType u) = 1 + size u
494instance Pretty a => Pretty (TT a) where
495 pretty _ = text "test"
497type EnvTT n = [(n, Binder (TT n))]
499data Datatype n = Data { d_typename :: n,
500 d_typetag :: Int,
501 d_type :: (TT n),
502 d_cons :: [(n, TT n)] }
503 deriving (Show, Functor, Eq)
505instance Eq n => Eq (TT n) where
506 (==) (P xt x _) (P yt y _) = x == y
507 (==) (V x) (V y) = x == y
508 (==) (Bind _ xb xs) (Bind _ yb ys) = xb == yb && xs == ys
509 (==) (App fx ax) (App fy ay) = fx == fy && ax == ay
510 (==) (TType _) (TType _) = True -- deal with constraints later
511 (==) (Constant x) (Constant y) = x == y
512 (==) (Proj x i) (Proj y j) = x == y && i == j
513 (==) Erased _ = True
514 (==) _ Erased = True
515 (==) _ _ = False
517-- * A few handy operations on well typed terms:
519-- | A term is injective iff it is a data constructor, type constructor,
520-- constant, the type Type, pi-binding, or an application of an injective
521-- term.
522isInjective :: TT n -> Bool
523isInjective (P (DCon _ _) _ _) = True
524isInjective (P (TCon _ _) _ _) = True
525isInjective (Constant _) = True
526isInjective (TType x) = True
527isInjective (Bind _ (Pi _) sc) = True
528isInjective (App f a) = isInjective f
529isInjective _ = False
531-- | Count the number of instances of a de Bruijn index in a term
532vinstances :: Int -> TT n -> Int
533vinstances i (V x) | i == x = 1
534vinstances i (App f a) = vinstances i f + vinstances i a
535vinstances i (Bind x b sc) = instancesB b + vinstances (i + 1) sc
536 where instancesB (Let t v) = vinstances i v
537 instancesB _ = 0
538vinstances i t = 0
540instantiate :: TT n -> TT n -> TT n
541instantiate e = subst 0 where
542 subst i (V x) | i == x = e
543 subst i (Bind x b sc) = Bind x (fmap (subst i) b) (subst (i+1) sc)
544 subst i (App f a) = App (subst i f) (subst i a)
545 subst i (Proj x idx) = Proj (subst i x) idx
546 subst i t = t
548explicitNames :: TT n -> TT n
549explicitNames (Bind x b sc) = let b' = fmap explicitNames b in
550 Bind x b'
551 (explicitNames (instantiate
552 (P Bound x (binderTy b')) sc))
553explicitNames (App f a) = App (explicitNames f) (explicitNames a)
554explicitNames (Proj x idx) = Proj (explicitNames x) idx
555explicitNames t = t
557pToV :: Eq n => n -> TT n -> TT n
558pToV n = pToV' n 0
559pToV' n i (P _ x _) | n == x = V i
560pToV' n i (Bind x b sc)
561-- We can assume the inner scope has been pToVed already, so continue to
562-- resolve names from the *outer* scope which may happen to have the same id.
563-- | n == x = Bind x (fmap (pToV' n i) b) sc
564 | otherwise = Bind x (fmap (pToV' n i) b) (pToV' n (i+1) sc)
565pToV' n i (App f a) = App (pToV' n i f) (pToV' n i a)
566pToV' n i (Proj t idx) = Proj (pToV' n i t) idx
567pToV' n i t = t
569-- | Convert several names. First in the list comes out as V 0
570pToVs :: Eq n => [n] -> TT n -> TT n
571pToVs ns tm = pToVs' ns tm 0 where
572 pToVs' [] tm i = tm
573 pToVs' (n:ns) tm i = pToV' n i (pToVs' ns tm (i+1))
575vToP :: TT n -> TT n
576vToP = vToP' [] where
577 vToP' env (V i) = let (n, b) = (env !! i) in
578 P Bound n (binderTy b)
579 vToP' env (Bind n b sc) = let b' = fmap (vToP' env) b in
580 Bind n b' (vToP' ((n, b'):env) sc)
581 vToP' env (App f a) = App (vToP' env f) (vToP' env a)
582 vToP' env t = t
584finalise :: Eq n => TT n -> TT n
585finalise (Bind x b sc) = Bind x (fmap finalise b) (pToV x (finalise sc))
586finalise (App f a) = App (finalise f) (finalise a)
587finalise t = t
589subst :: Eq n => n -> TT n -> TT n -> TT n
590subst n v tm = instantiate v (pToV n tm)
592substNames :: Eq n => [(n, TT n)] -> TT n -> TT n
593substNames [] t = t
594substNames ((n, tm) : xs) t = subst n tm (substNames xs t)
596substTerm :: Eq n => TT n -> TT n -> TT n -> TT n
597substTerm old new = st where
598 st t | t == old = new
599 st (App f a) = App (st f) (st a)
600 st (Bind x b sc) = Bind x (fmap st b) (st sc)
601 st t = t
603-- Returns true if V 0 and bound name n do not occur in the term
605noOccurrence :: Eq n => n -> TT n -> Bool
606noOccurrence n t = no' 0 t
607 where
608 no' i (V x) = not (i == x)
609 no' i (P Bound x _) = not (n == x)
610 no' i (Bind n b sc) = noB' i b && no' (i+1) sc
611 where noB' i (Let t v) = no' i t && no' i v
612 noB' i (Guess t v) = no' i t && no' i v
613 noB' i b = no' i (binderTy b)
614 no' i (App f a) = no' i f && no' i a
615 no' i (Proj x _) = no' i x
616 no' i _ = True
618-- | Returns all names used free in the term
619freeNames :: Eq n => TT n -> [n]
620freeNames (P _ n _) = [n]
621freeNames (Bind n (Let t v) sc) = nub $ freeNames v ++ (freeNames sc \\ [n])
622 ++ freeNames t
623freeNames (Bind n b sc) = nub $ freeNames (binderTy b) ++ (freeNames sc \\ [n])
624freeNames (App f a) = nub $ freeNames f ++ freeNames a
625freeNames (Proj x i) = nub $ freeNames x
626freeNames _ = []
628-- | Return the arity of a (normalised) type
629arity :: TT n -> Int
630arity (Bind n (Pi t) sc) = 1 + arity sc
631arity _ = 0
633-- | Deconstruct an application; returns the function and a list of arguments
634unApply :: TT n -> (TT n, [TT n])
635unApply t = ua [] t where
636 ua args (App f a) = ua (a:args) f
637 ua args t = (t, args)
639mkApp :: TT n -> [TT n] -> TT n
640mkApp f [] = f
641mkApp f (a:as) = mkApp (App f a) as
643forget :: TT Name -> Raw
644forget tm = fe [] tm
645 where
646 fe env (P _ n _) = Var n
647 fe env (V i) = Var (env !! i)
648 fe env (Bind n b sc) = RBind n (fmap (fe env) b)
649 (fe (n:env) sc)
650 fe env (App f a) = RApp (fe env f) (fe env a)
651 fe env (Constant c)
652 = RConstant c
653 fe env (TType i) = RType
654 fe env Erased = RConstant Forgot
656bindAll :: [(n, Binder (TT n))] -> TT n -> TT n
657bindAll [] t =t
658bindAll ((n, b) : bs) t = Bind n b (bindAll bs t)
660bindTyArgs :: (TT n -> Binder (TT n)) -> [(n, TT n)] -> TT n -> TT n
661bindTyArgs b xs = bindAll (map (\ (n, ty) -> (n, b ty)) xs)
663getArgTys :: TT n -> [(n, TT n)]
664getArgTys (Bind n (Pi t) sc) = (n, t) : getArgTys sc
665getArgTys _ = []
667getRetTy :: TT n -> TT n
668getRetTy (Bind n (PVar _) sc) = getRetTy sc
669getRetTy (Bind n (PVTy _) sc) = getRetTy sc
670getRetTy (Bind n (Pi _) sc) = getRetTy sc
671getRetTy sc = sc
673uniqueName :: Name -> [Name] -> Name
674uniqueName n hs | n `elem` hs = uniqueName (nextName n) hs
675 | otherwise = n
677uniqueBinders :: [Name] -> TT Name -> TT Name
678uniqueBinders ns (Bind n b sc)
679 = let n' = uniqueName n ns in
680 Bind n' (fmap (uniqueBinders (n':ns)) b) (uniqueBinders ns sc)
681uniqueBinders ns (App f a) = App (uniqueBinders ns f) (uniqueBinders ns a)
682uniqueBinders ns t = t
685nextName (NS x s) = NS (nextName x) s
686nextName (MN i n) = MN (i+1) n
687nextName (UN x) = let (num', nm') = span isDigit (reverse x)
688 nm = reverse nm'
689 num = readN (reverse num') in
690 UN (nm ++ show (num+1))
691 where
692 readN "" = 0
693 readN x = read x
695type Term = TT Name
696type Type = Term
698type Env = EnvTT Name
700-- an environment with de Bruijn indices 'normalised' so that they all refer to
701-- this environment
703newtype WkEnvTT n = Wk (EnvTT n)
704type WkEnv = WkEnvTT Name
706instance (Eq n, Show n) => Show (TT n) where
707 show t = showEnv [] t
709instance Show Const where
710 show (I i) = show i
711 show (BI i) = show i ++ "L"
712 show (Fl f) = show f
713 show (Ch c) = show c
714 show (Str s) = show s
715 show (B8 x) = show x
716 show (B16 x) = show x
717 show (B32 x) = show x
718 show (B64 x) = show x
719 show IType = "Int"
720 show BIType = "Integer"
721 show FlType = "Float"
722 show ChType = "Char"
723 show StrType = "String"
724 show PtrType = "Ptr"
725 show B8Type = "Bits8"
726 show B16Type = "Bits16"
727 show B32Type = "Bits32"
728 show B64Type = "Bits64"
729 show VoidType = "Void"
731showEnv env t = showEnv' env t False
732showEnvDbg env t = showEnv' env t True
734prettyEnv env t = prettyEnv' env t False
735 where
736 prettyEnv' env t dbg = prettySe 10 env t dbg
738 bracket outer inner p
739 | inner > outer = lparen <> p <> rparen
740 | otherwise = p
742 prettySe p env (P nt n t) debug =
743 pretty n <+>
744 if debug then
745 lbrack <+> pretty nt <+> colon <+> prettySe 10 env t debug <+> rbrack
746 else
747 empty
748 prettySe p env (V i) debug
749 | i < length env =
750 if debug then
751 text . show . fst $ env!!i
752 else
753 lbrack <+> text (show i) <+> rbrack
754 | otherwise = text "unbound" <+> text (show i) <+> text "!"
755 prettySe p env (Bind n b@(Pi t) sc) debug
756 | noOccurrence n sc && not debug =
757 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
758 prettySe p env (Bind n b sc) debug =
759 bracket p 2 $ prettySb env n b debug <> prettySe 10 ((n, b):env) sc debug
760 prettySe p env (App f a) debug =
761 bracket p 1 $ prettySe 1 env f debug <+> prettySe 0 env a debug
762 prettySe p env (Proj x i) debug =
763 prettySe 1 env x debug <+> text ("!" ++ show i)
764 prettySe p env (Constant c) debug = pretty c
765 prettySe p env Erased debug = text "[_]"
766 prettySe p env (TType i) debug = text "Type" <+> (text . show $ i)
768 prettySb env n (Lam t) = prettyB env "λ" "=>" n t
769 prettySb env n (Hole t) = prettyB env "?defer" "." n t
770 prettySb env n (Pi t) = prettyB env "(" ") ->" n t
771 prettySb env n (PVar t) = prettyB env "pat" "." n t
772 prettySb env n (PVTy t) = prettyB env "pty" "." n t
773 prettySb env n (Let t v) = prettyBv env "let" "in" n t v
774 prettySb env n (Guess t v) = prettyBv env "??" "in" n t v
776 prettyB env op sc n t debug =
777 text op <> pretty n <+> colon <+> prettySe 10 env t debug <> text sc
779 prettyBv env op sc n t v debug =
780 text op <> pretty n <+> colon <+> prettySe 10 env t debug <+> text "=" <+>
781 prettySe 10 env v debug <> text sc
784showEnv' env t dbg = se 10 env t where
785 se p env (P nt n t) = show n
786 ++ if dbg then "{" ++ show nt ++ " : " ++ se 10 env t ++ "}" else ""
787 se p env (V i) | i < length env = (show $ fst $ env!!i) ++
788 if dbg then "{" ++ show i ++ "}" else ""
789 | otherwise = "!!V " ++ show i ++ "!!"
790 se p env (Bind n b@(Pi t) sc)
791 | noOccurrence n sc && not dbg = bracket p 2 $ se 1 env t ++ " -> " ++ se 10 ((n,b):env) sc
792 se p env (Bind n b sc) = bracket p 2 $ sb env n b ++ se 10 ((n,b):env) sc
793 se p env (App f a) = bracket p 1 $ se 1 env f ++ " " ++ se 0 env a
794 se p env (Proj x i) = se 1 env x ++ "!" ++ show i
795 se p env (Constant c) = show c
796 se p env Erased = "[__]"
797 se p env Impossible = "[impossible]"
798 se p env (TType i) = "Type " ++ show i
800 sb env n (Lam t) = showb env "\\ " " => " n t
801 sb env n (Hole t) = showb env "? " ". " n t
802 sb env n (GHole t) = showb env "?defer " ". " n t
803 sb env n (Pi t) = showb env "(" ") -> " n t
804 sb env n (PVar t) = showb env "pat " ". " n t
805 sb env n (PVTy t) = showb env "pty " ". " n t
806 sb env n (Let t v) = showbv env "let " " in " n t v
807 sb env n (Guess t v) = showbv env "?? " " in " n t v
809 showb env op sc n t = op ++ show n ++ " : " ++ se 10 env t ++ sc
810 showbv env op sc n t v = op ++ show n ++ " : " ++ se 10 env t ++ " = " ++
811 se 10 env v ++ sc
813 bracket outer inner str | inner > outer = "(" ++ str ++ ")"
814 | otherwise = str
816-- | Check whether a term has any holes in it - impure if so
817pureTerm :: TT Name -> Bool
818pureTerm (App f a) = pureTerm f && pureTerm a
819pureTerm (Bind n b sc) = notClassName n && pureBinder b && pureTerm sc where
820 pureBinder (Hole _) = False
821 pureBinder (Guess _ _) = False
822 pureBinder (Let t v) = pureTerm t && pureTerm v
823 pureBinder t = pureTerm (binderTy t)
825 notClassName (MN _ "class") = False
826 notClassName _ = True
828pureTerm _ = True
830-- | Weaken a term by adding i to each de Bruijn index (i.e. lift it over i bindings)
831weakenTm :: Int -> TT n -> TT n
832weakenTm i t = wk i 0 t
833 where wk i min (V x) | x >= min = V (i + x)
834 wk i m (App f a) = App (wk i m f) (wk i m a)
835 wk i m (Bind x b sc) = Bind x (wkb i m b) (wk i (m + 1) sc)
836 wk i m t = t
837 wkb i m t = fmap (wk i m) t
839-- | Weaken an environment so that all the de Bruijn indices are correct according
840-- to the latest bound variable
842weakenEnv :: EnvTT n -> EnvTT n
843weakenEnv env = wk (length env - 1) env
844 where wk i [] = []
845 wk i ((n, b) : bs) = (n, weakenTmB i b) : wk (i - 1) bs
846 weakenTmB i (Let t v) = Let (weakenTm i t) (weakenTm i v)
847 weakenTmB i (Guess t v) = Guess (weakenTm i t) (weakenTm i v)
848 weakenTmB i t = t { binderTy = weakenTm i (binderTy t) }
850weakenTmEnv :: Int -> EnvTT n -> EnvTT n
851weakenTmEnv i = map (\ (n, b) -> (n, fmap (weakenTm i) b))
853orderPats :: Term -> Term
854orderPats tm = op [] tm
855 where
856 op ps (Bind n (PVar t) sc) = op ((n, PVar t) : ps) sc
857 op ps (Bind n (Hole t) sc) = op ((n, Hole t) : ps) sc
858 op ps sc = bindAll (map (\ (n, t) -> (n, t)) (sortP ps)) sc
860 sortP ps = pick [] (reverse ps)
862 namesIn (P _ n _) = [n]
863 namesIn (Bind n b t) = nub $ nb b ++ (namesIn t \\ [n])
864 where nb (Let t v) = nub (namesIn t) ++ nub (namesIn v)
865 nb (Guess t v) = nub (namesIn t) ++ nub (namesIn v)
866 nb t = namesIn (binderTy t)
867 namesIn (App f a) = nub (namesIn f ++ namesIn a)
868 namesIn _ = []
870 pick acc [] = reverse acc
871 pick acc ((n, t) : ps) = pick (insert n t acc) ps
873 insert n t [] = [(n, t)]
874 insert n t ((n',t') : ps)
875 | n `elem` (namesIn (binderTy t') ++
876 concatMap namesIn (map (binderTy . snd) ps))
877 = (n', t') : insert n t ps
878 | otherwise = (n,t):(n',t'):ps