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