d05ade3049165b0e0115454b581d3ab8e33c0fc0
[ghc-hetmet.git] / compiler / typecheck / TcTyDecls.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1999
4 %
5
6 Analysis functions over data types.  Specficially, detecting recursive types.
7
8 This stuff is only used for source-code decls; it's recorded in interface
9 files for imported data types.
10
11 \begin{code}
12 module TcTyDecls(
13         calcRecFlags, 
14         calcClassCycles, calcSynCycles
15     ) where
16
17 #include "HsVersions.h"
18
19 import TypeRep
20 import HsSyn
21 import RnHsSyn
22 import Type
23 import HscTypes
24 import TyCon
25 import Class
26 import DataCon
27 import Name
28 import NameEnv
29 import NameSet
30 import Digraph
31 import BasicTypes
32 import SrcLoc
33 import Outputable
34 \end{code}
35
36
37 %************************************************************************
38 %*                                                                      *
39         Cycles in class and type synonym declarations
40 %*                                                                      *
41 %************************************************************************
42
43 Checking for class-decl loops is easy, because we don't allow class decls
44 in interface files.
45
46 We allow type synonyms in hi-boot files, but we *trust* hi-boot files, 
47 so we don't check for loops that involve them.  So we only look for synonym
48 loops in the module being compiled.
49
50 We check for type synonym and class cycles on the *source* code.
51 Main reasons: 
52
53   a) Otherwise we'd need a special function to extract type-synonym tycons
54         from a type, whereas we have extractHsTyNames already
55
56   b) If we checked for type synonym loops after building the TyCon, we
57         can't do a hoistForAllTys on the type synonym rhs, (else we fall into
58         a black hole) which seems unclean.  Apart from anything else, it'd mean 
59         that a type-synonym rhs could have for-alls to the right of an arrow, 
60         which means adding new cases to the validity checker
61
62         Indeed, in general, checking for cycles beforehand means we need to
63         be less careful about black holes through synonym cycles.
64
65 The main disadvantage is that a cycle that goes via a type synonym in an 
66 .hi-boot file can lead the compiler into a loop, because it assumes that cycles
67 only occur entirely within the source code of the module being compiled.  
68 But hi-boot files are trusted anyway, so this isn't much worse than (say) 
69 a kind error.
70
71 [  NOTE ----------------------------------------------
72 If we reverse this decision, this comment came from tcTyDecl1, and should
73  go back there
74         -- dsHsType, not tcHsKindedType, to avoid a loop.  tcHsKindedType does hoisting,
75         -- which requires looking through synonyms... and therefore goes into a loop
76         -- on (erroneously) recursive synonyms.
77         -- Solution: do not hoist synonyms, because they'll be hoisted soon enough
78         --           when they are substituted
79
80 We'd also need to add back in this definition
81
82 synTyConsOfType :: Type -> [TyCon]
83 -- Does not look through type synonyms at all
84 -- Return a list of synonym tycons
85 synTyConsOfType ty
86   = nameEnvElts (go ty)
87   where
88      go :: Type -> NameEnv TyCon  -- The NameEnv does duplicate elim
89      go (TyVarTy v)               = emptyNameEnv
90      go (TyConApp tc tys)         = go_tc tc tys
91      go (AppTy a b)               = go a `plusNameEnv` go b
92      go (FunTy a b)               = go a `plusNameEnv` go b
93      go (PredTy (IParam _ ty))    = go ty       
94      go (PredTy (ClassP cls tys)) = go_s tys    -- Ignore class
95      go (NoteTy _ ty)             = go ty       
96      go (ForAllTy _ ty)           = go ty
97
98      go_tc tc tys | isSynTyCon tc = extendNameEnv (go_s tys) (tyConName tc) tc
99                   | otherwise     = go_s tys
100      go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
101 ---------------------------------------- END NOTE ]
102
103 \begin{code}
104 calcSynCycles :: [LTyClDecl Name] -> [SCC (LTyClDecl Name)]
105 calcSynCycles decls
106   = stronglyConnComp syn_edges
107   where
108     syn_edges = [ (ldecl, unLoc (tcdLName decl), 
109                           mk_syn_edges (tcdSynRhs decl))
110                 | ldecl@(L _ decl) <- decls ]
111
112     mk_syn_edges rhs = [ tc | tc <- nameSetToList (extractHsTyNames rhs), 
113                               not (isTyVarName tc) ]
114
115
116 calcClassCycles :: [LTyClDecl Name] -> [[LTyClDecl Name]]
117 calcClassCycles decls
118   = [decls | CyclicSCC decls <- stronglyConnComp cls_edges]
119   where
120     cls_edges = [ (ldecl, unLoc (tcdLName decl),        
121                           mk_cls_edges (unLoc (tcdCtxt decl)))
122                 | ldecl@(L _ decl) <- decls, isClassDecl decl ]
123
124     mk_cls_edges ctxt = [ cls | L _ (HsClassP cls _) <- ctxt ]
125 \end{code}
126
127
128 %************************************************************************
129 %*                                                                      *
130         Deciding which type constructors are recursive
131 %*                                                                      *
132 %************************************************************************
133
134 For newtypes, we label some as "recursive" such that
135
136     INVARIANT: there is no cycle of non-recursive newtypes
137
138 In any loop, only one newtype need be marked as recursive; it is
139 a "loop breaker".  Labelling more than necessary as recursive is OK,
140 provided the invariant is maintained.
141
142 A newtype M.T is defined to be "recursive" iff
143         (a) it is declared in an hi-boot file (see RdrHsSyn.hsIfaceDecl)
144         (b) it is declared in a source file, but that source file has a
145             companion hi-boot file which declares the type
146    or   (c) one can get from T's rhs to T via type 
147             synonyms, or non-recursive newtypes *in M*
148              e.g.  newtype T = MkT (T -> Int)
149
150 (a) is conservative; declarations in hi-boot files are always 
151         made loop breakers. That's why in (b) we can restrict attention
152         to tycons in M, because any loops through newtypes outside M
153         will be broken by those newtypes
154 (b) ensures that a newtype is not treated as a loop breaker in one place
155 and later as a non-loop-breaker.  This matters in GHCi particularly, when
156 a newtype T might be embedded in many types in the environment, and then
157 T's source module is compiled.  We don't want T's recursiveness to change.
158
159 The "recursive" flag for algebraic data types is irrelevant (never consulted)
160 for types with more than one constructor.
161
162 An algebraic data type M.T is "recursive" iff
163         it has just one constructor, and 
164         (a) it is declared in an hi-boot file (see RdrHsSyn.hsIfaceDecl)
165         (b) it is declared in a source file, but that source file has a
166             companion hi-boot file which declares the type
167  or     (c) one can get from its arg types to T via type synonyms, 
168             or by non-recursive newtypes or non-recursive product types in M
169              e.g.  data T = MkT (T -> Int) Bool
170 Just like newtype in fact
171
172 A type synonym is recursive if one can get from its
173 right hand side back to it via type synonyms.  (This is
174 reported as an error.)
175
176 A class is recursive if one can get from its superclasses
177 back to it.  (This is an error too.)
178
179 Hi-boot types
180 ~~~~~~~~~~~~~
181 A data type read from an hi-boot file will have an AbstractTyCon as its AlgTyConRhs
182 and will respond True to isHiBootTyCon. The idea is that we treat these as if one
183 could get from these types to anywhere.  So when we see
184
185         module Baz where
186         import {-# SOURCE #-} Foo( T )
187         newtype S = MkS T
188
189 then we mark S as recursive, just in case. What that means is that if we see
190
191         import Baz( S )
192         newtype R = MkR S
193
194 then we don't need to look inside S to compute R's recursiveness.  Since S is imported
195 (not from an hi-boot file), one cannot get from R back to S except via an hi-boot file,
196 and that means that some data type will be marked recursive along the way.  So R is
197 unconditionly non-recursive (i.e. there'll be a loop breaker elsewhere if necessary)
198
199 This in turn means that we grovel through fewer interface files when computing 
200 recursiveness, because we need only look at the type decls in the module being
201 compiled, plus the outer structure of directly-mentioned types.
202
203 \begin{code}
204 calcRecFlags :: ModDetails -> [TyThing] -> (Name -> RecFlag)
205 -- The 'boot_names' are the things declared in M.hi-boot, if M is the current module.
206 -- Any type constructors in boot_names are automatically considered loop breakers
207 calcRecFlags boot_details tyclss
208   = is_rec
209   where
210     is_rec n | n `elemNameSet` rec_names = Recursive
211              | otherwise                 = NonRecursive
212
213     boot_name_set = availsToNameSet (md_exports boot_details)
214     rec_names = boot_name_set     `unionNameSets` 
215                 nt_loop_breakers  `unionNameSets`
216                 prod_loop_breakers
217
218     all_tycons = [ tc | tycls <- tyclss,
219                            -- Recursion of newtypes/data types can happen via 
220                            -- the class TyCon, so tyclss includes the class tycons
221                         let tc = getTyCon tycls,
222                         not (tyConName tc `elemNameSet` boot_name_set) ]
223                            -- Remove the boot_name_set because they are going 
224                            -- to be loop breakers regardless.
225
226         -------------------------------------------------
227         --                      NOTE
228         -- These edge-construction loops rely on
229         -- every loop going via tyclss, the types and classes
230         -- in the module being compiled.  Stuff in interface 
231         -- files should be correctly marked.  If not (e.g. a
232         -- type synonym in a hi-boot file) we can get an infinite
233         -- loop.  We could program round this, but it'd make the code
234         -- rather less nice, so I'm not going to do that yet.
235
236         --------------- Newtypes ----------------------
237     new_tycons = filter isNewTyConAndNotOpen all_tycons
238     isNewTyConAndNotOpen tycon = isNewTyCon tycon && not (isOpenTyCon tycon)
239     nt_loop_breakers = mkNameSet (findLoopBreakers nt_edges)
240     is_rec_nt tc = tyConName tc  `elemNameSet` nt_loop_breakers
241         -- is_rec_nt is a locally-used helper function
242
243     nt_edges = [(t, mk_nt_edges t) | t <- new_tycons]
244
245     mk_nt_edges nt      -- Invariant: nt is a newtype
246         = concatMap (mk_nt_edges1 nt) (tcTyConsOfType (new_tc_rhs nt))
247                         -- tyConsOfType looks through synonyms
248
249     mk_nt_edges1 nt tc 
250         | tc `elem` new_tycons = [tc]           -- Loop
251                 -- At this point we know that either it's a local *data* type,
252                 -- or it's imported.  Either way, it can't form part of a newtype cycle
253         | otherwise = []
254
255         --------------- Product types ----------------------
256         -- The "prod_tycons" are the non-newtype products
257     prod_tycons = [tc | tc <- all_tycons, 
258                         not (isNewTyCon tc), isProductTyCon tc]
259     prod_loop_breakers = mkNameSet (findLoopBreakers prod_edges)
260
261     prod_edges = [(tc, mk_prod_edges tc) | tc <- prod_tycons]
262         
263     mk_prod_edges tc    -- Invariant: tc is a product tycon
264         = concatMap (mk_prod_edges1 tc) (dataConOrigArgTys (head (tyConDataCons tc)))
265
266     mk_prod_edges1 ptc ty = concatMap (mk_prod_edges2 ptc) (tcTyConsOfType ty)
267
268     mk_prod_edges2 ptc tc 
269         | tc `elem` prod_tycons   = [tc]                -- Local product
270         | tc `elem` new_tycons    = if is_rec_nt tc     -- Local newtype
271                                     then []
272                                     else mk_prod_edges1 ptc (new_tc_rhs tc)
273                 -- At this point we know that either it's a local non-product data type,
274                 -- or it's imported.  Either way, it can't form part of a cycle
275         | otherwise = []
276                         
277 new_tc_rhs tc = snd (newTyConRhs tc)    -- Ignore the type variables
278
279 getTyCon (ATyCon tc) = tc
280 getTyCon (AClass cl) = classTyCon cl
281 getTyCon other       = panic "getTyCon"
282
283 findLoopBreakers :: [(TyCon, [TyCon])] -> [Name]
284 -- Finds a set of tycons that cut all loops
285 findLoopBreakers deps
286   = go [(tc,tc,ds) | (tc,ds) <- deps]
287   where
288     go edges = [ name
289                | CyclicSCC ((tc,_,_) : edges') <- stronglyConnCompR edges,
290                  name <- tyConName tc : go edges']
291 \end{code}
292
293 These two functions know about type representations, so they could be
294 in Type or TcType -- but they are very specialised to this module, so 
295 I've chosen to put them here.
296
297 \begin{code}
298 tcTyConsOfType :: Type -> [TyCon]
299 -- tcTyConsOfType looks through all synonyms, but not through any newtypes.  
300 -- When it finds a Class, it returns the class TyCon.  The reaons it's here
301 -- (not in Type.lhs) is because it is newtype-aware.
302 tcTyConsOfType ty 
303   = nameEnvElts (go ty)
304   where
305      go :: Type -> NameEnv TyCon  -- The NameEnv does duplicate elim
306      go ty | Just ty' <- tcView ty = go ty'
307      go (TyVarTy v)                = emptyNameEnv
308      go (TyConApp tc tys)          = go_tc tc tys
309      go (AppTy a b)                = go a `plusNameEnv` go b
310      go (FunTy a b)                = go a `plusNameEnv` go b
311      go (PredTy (IParam _ ty))     = go ty
312      go (PredTy (ClassP cls tys))  = go_tc (classTyCon cls) tys
313      go (ForAllTy _ ty)            = go ty
314      go other                      = panic "tcTyConsOfType"
315
316      go_tc tc tys = extendNameEnv (go_s tys) (tyConName tc) tc
317      go_s tys = foldr (plusNameEnv . go) emptyNameEnv tys
318 \end{code}