Injective type families
[ghc.git] / compiler / hsSyn / HsTypes.hs
1 {-
2 (c) The University of Glasgow 2006
3 (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4
5
6 HsTypes: Abstract syntax: user-defined types
7 -}
8
9 {-# LANGUAGE DeriveDataTypeable #-}
10 {-# LANGUAGE FlexibleContexts #-}
11 {-# LANGUAGE FlexibleInstances #-}
12 {-# LANGUAGE StandaloneDeriving #-}
13 {-# LANGUAGE TypeSynonymInstances #-}
14 {-# LANGUAGE UndecidableInstances #-} -- Note [Pass sensitive types]
15 -- in module PlaceHolder
16 {-# LANGUAGE ConstraintKinds #-}
17 {-# LANGUAGE CPP #-}
18
19 module HsTypes (
20 HsType(..), LHsType, HsKind, LHsKind,
21 HsTyOp,LHsTyOp,
22 HsTyVarBndr(..), LHsTyVarBndr,
23 LHsTyVarBndrs(..),
24 HsWithBndrs(..),
25 HsTupleSort(..), HsExplicitFlag(..),
26 HsContext, LHsContext,
27 HsTyWrapper(..),
28 HsTyLit(..),
29 HsIPName(..), hsIPNameFS,
30
31 LBangType, BangType,
32 HsSrcBang(..), HsImplBang(..),
33 SrcStrictness(..), SrcUnpackedness(..),
34 getBangType, getBangStrictness,
35
36 ConDeclField(..), LConDeclField, pprConDeclFields,
37
38 HsWildCardInfo(..), mkAnonWildCardTy, mkNamedWildCardTy,
39 wildCardName, sameWildCard, sameNamedWildCard,
40 isAnonWildCard, isNamedWildCard,
41
42 mkHsQTvs, hsQTvBndrs, isHsKindedTyVar, hsTvbAllKinded,
43 mkExplicitHsForAllTy, mkImplicitHsForAllTy, mkQualifiedHsForAllTy,
44 mkHsForAllTy,
45 flattenTopLevelLHsForAllTy,flattenTopLevelHsForAllTy,
46 flattenHsForAllTyKeepAnns,
47 hsExplicitTvs,
48 hsTyVarName, mkHsWithBndrs, hsLKiTyVarNames,
49 hsLTyVarName, hsLTyVarNames, hsLTyVarLocName, hsLTyVarLocNames,
50 splitLHsInstDeclTy_maybe,
51 splitHsClassTy_maybe, splitLHsClassTy_maybe,
52 splitHsFunType,
53 splitHsAppTys, hsTyGetAppHead_maybe, mkHsAppTys, mkHsOpTy,
54 ignoreParens,
55
56 -- Printing
57 pprParendHsType, pprHsForAll, pprHsForAllExtra,
58 pprHsContext, pprHsContextNoArrow, pprHsContextMaybe
59 ) where
60
61 import {-# SOURCE #-} HsExpr ( HsSplice, pprSplice )
62
63 import PlaceHolder ( PostTc,PostRn,DataId,PlaceHolder(..) )
64
65 import Name( Name )
66 import RdrName( RdrName )
67 import DataCon( HsSrcBang(..), HsImplBang(..),
68 SrcStrictness(..), SrcUnpackedness(..) )
69 import TysPrim( funTyConName )
70 import Type
71 import HsDoc
72 import BasicTypes
73 import SrcLoc
74 import StaticFlags
75 import Outputable
76 import FastString
77 import Lexer ( AddAnn, mkParensApiAnn )
78 import Maybes( isJust )
79
80 import Data.Data hiding ( Fixity )
81 import Data.Maybe ( fromMaybe )
82 #if __GLASGOW_HASKELL__ < 709
83 import Data.Monoid hiding ((<>))
84 #endif
85
86 {-
87 ************************************************************************
88 * *
89 \subsection{Bang annotations}
90 * *
91 ************************************************************************
92 -}
93
94 type LBangType name = Located (BangType name)
95 type BangType name = HsType name -- Bangs are in the HsType data type
96
97 getBangType :: LHsType a -> LHsType a
98 getBangType (L _ (HsBangTy _ ty)) = ty
99 getBangType ty = ty
100
101 getBangStrictness :: LHsType a -> HsSrcBang
102 getBangStrictness (L _ (HsBangTy s _)) = s
103 getBangStrictness _ = (HsSrcBang Nothing NoSrcUnpack NoSrcStrict)
104
105 {-
106 ************************************************************************
107 * *
108 \subsection{Data types}
109 * *
110 ************************************************************************
111
112 This is the syntax for types as seen in type signatures.
113
114 Note [HsBSig binder lists]
115 ~~~~~~~~~~~~~~~~~~~~~~~~~~
116 Consider a binder (or pattern) decoarated with a type or kind,
117 \ (x :: a -> a). blah
118 forall (a :: k -> *) (b :: k). blah
119 Then we use a LHsBndrSig on the binder, so that the
120 renamer can decorate it with the variables bound
121 by the pattern ('a' in the first example, 'k' in the second),
122 assuming that neither of them is in scope already
123 See also Note [Kind and type-variable binders] in RnTypes
124 -}
125
126 type LHsContext name = Located (HsContext name)
127 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnUnit'
128
129 -- For details on above see note [Api annotations] in ApiAnnotation
130
131 type HsContext name = [LHsType name]
132
133 type LHsType name = Located (HsType name)
134 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
135 -- in a list
136
137 -- For details on above see note [Api annotations] in ApiAnnotation
138 type HsKind name = HsType name
139 type LHsKind name = Located (HsKind name)
140 -- ^ 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
141
142 -- For details on above see note [Api annotations] in ApiAnnotation
143
144 --------------------------------------------------
145 -- LHsTyVarBndrs
146 -- The quantified binders in a HsForallTy
147
148 type LHsTyVarBndr name = Located (HsTyVarBndr name)
149
150 data LHsTyVarBndrs name
151 = HsQTvs { hsq_kvs :: [Name] -- Kind variables
152 , hsq_tvs :: [LHsTyVarBndr name] -- Type variables
153 -- See Note [HsForAllTy tyvar binders]
154 }
155 deriving( Typeable )
156 deriving instance (DataId name) => Data (LHsTyVarBndrs name)
157
158 mkHsQTvs :: [LHsTyVarBndr RdrName] -> LHsTyVarBndrs RdrName
159 -- Just at RdrName because in the Name variant we should know just
160 -- what the kind-variable binders are; and we don't
161 -- We put an empty list (rather than a panic) for the kind vars so
162 -- that the pretty printer works ok on them.
163 mkHsQTvs tvs = HsQTvs { hsq_kvs = [], hsq_tvs = tvs }
164
165 emptyHsQTvs :: LHsTyVarBndrs name -- Use only when you know there are no kind binders
166 emptyHsQTvs = HsQTvs { hsq_kvs = [], hsq_tvs = [] }
167
168 hsQTvBndrs :: LHsTyVarBndrs name -> [LHsTyVarBndr name]
169 hsQTvBndrs = hsq_tvs
170
171 instance Monoid (LHsTyVarBndrs name) where
172 mempty = emptyHsQTvs
173 mappend (HsQTvs kvs1 tvs1) (HsQTvs kvs2 tvs2)
174 = HsQTvs (kvs1 ++ kvs2) (tvs1 ++ tvs2)
175
176 ------------------------------------------------
177 -- HsWithBndrs
178 -- Used to quantify the binders of a type in cases
179 -- when a HsForAll isn't appropriate:
180 -- * Patterns in a type/data family instance (HsTyPats)
181 -- * Type of a rule binder (RuleBndr)
182 -- * Pattern type signatures (SigPatIn)
183 -- In the last of these, wildcards can happen, so we must accommodate them
184
185 data HsWithBndrs name thing
186 = HsWB { hswb_cts :: thing -- Main payload (type or list of types)
187 , hswb_kvs :: PostRn name [Name] -- Kind vars
188 , hswb_tvs :: PostRn name [Name] -- Type vars
189 , hswb_wcs :: PostRn name [Name] -- Wild cards
190 }
191 deriving (Typeable)
192 deriving instance (Data name, Data thing, Data (PostRn name [Name]))
193 => Data (HsWithBndrs name thing)
194
195 mkHsWithBndrs :: thing -> HsWithBndrs RdrName thing
196 mkHsWithBndrs x = HsWB { hswb_cts = x, hswb_kvs = PlaceHolder
197 , hswb_tvs = PlaceHolder
198 , hswb_wcs = PlaceHolder }
199
200
201 --------------------------------------------------
202 -- | These names are used early on to store the names of implicit
203 -- parameters. They completely disappear after type-checking.
204 newtype HsIPName = HsIPName FastString
205 deriving( Eq, Data, Typeable )
206
207 hsIPNameFS :: HsIPName -> FastString
208 hsIPNameFS (HsIPName n) = n
209
210 instance Outputable HsIPName where
211 ppr (HsIPName n) = char '?' <> ftext n -- Ordinary implicit parameters
212
213 instance OutputableBndr HsIPName where
214 pprBndr _ n = ppr n -- Simple for now
215 pprInfixOcc n = ppr n
216 pprPrefixOcc n = ppr n
217
218 --------------------------------------------------
219 data HsTyVarBndr name
220 = UserTyVar -- no explicit kinding
221 name
222
223 | KindedTyVar
224 (Located name)
225 (LHsKind name) -- The user-supplied kind signature
226 -- ^
227 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen',
228 -- 'ApiAnnotation.AnnDcolon', 'ApiAnnotation.AnnClose'
229
230 -- For details on above see note [Api annotations] in ApiAnnotation
231 deriving (Typeable)
232 deriving instance (DataId name) => Data (HsTyVarBndr name)
233
234 -- | Does this 'HsTyVarBndr' come with an explicit kind annotation?
235 isHsKindedTyVar :: HsTyVarBndr name -> Bool
236 isHsKindedTyVar (UserTyVar {}) = False
237 isHsKindedTyVar (KindedTyVar {}) = True
238
239 -- | Do all type variables in this 'LHsTyVarBndr' come with kind annotations?
240 hsTvbAllKinded :: LHsTyVarBndrs name -> Bool
241 hsTvbAllKinded = all (isHsKindedTyVar . unLoc) . hsQTvBndrs
242
243 data HsType name
244 = HsForAllTy HsExplicitFlag -- Renamer leaves this flag unchanged, to record the way
245 -- the user wrote it originally, so that the printer can
246 -- print it as the user wrote it
247 (Maybe SrcSpan) -- Indicates whether extra constraints may be inferred.
248 -- When Nothing, no, otherwise the location of the extra-
249 -- constraints wildcard is stored. For instance, for the
250 -- signature (Eq a, _) => a -> a -> Bool, this field would
251 -- be something like (Just 1:8), with 1:8 being line 1,
252 -- column 8.
253 (LHsTyVarBndrs name)
254 (LHsContext name)
255 (LHsType name)
256 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnForall',
257 -- 'ApiAnnotation.AnnDot','ApiAnnotation.AnnDarrow'
258
259 -- For details on above see note [Api annotations] in ApiAnnotation
260
261 | HsTyVar name -- Type variable, type constructor, or data constructor
262 -- see Note [Promotions (HsTyVar)]
263 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
264
265 -- For details on above see note [Api annotations] in ApiAnnotation
266
267 | HsAppTy (LHsType name)
268 (LHsType name)
269 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
270
271 -- For details on above see note [Api annotations] in ApiAnnotation
272
273 | HsFunTy (LHsType name) -- function type
274 (LHsType name)
275 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnRarrow',
276
277 -- For details on above see note [Api annotations] in ApiAnnotation
278
279 | HsListTy (LHsType name) -- Element type
280 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'['@,
281 -- 'ApiAnnotation.AnnClose' @']'@
282
283 -- For details on above see note [Api annotations] in ApiAnnotation
284
285 | HsPArrTy (LHsType name) -- Elem. type of parallel array: [:t:]
286 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'[:'@,
287 -- 'ApiAnnotation.AnnClose' @':]'@
288
289 -- For details on above see note [Api annotations] in ApiAnnotation
290
291 | HsTupleTy HsTupleSort
292 [LHsType name] -- Element types (length gives arity)
293 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'(' or '(#'@,
294 -- 'ApiAnnotation.AnnClose' @')' or '#)'@
295
296 -- For details on above see note [Api annotations] in ApiAnnotation
297
298 | HsOpTy (LHsType name) (LHsTyOp name) (LHsType name)
299 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
300
301 -- For details on above see note [Api annotations] in ApiAnnotation
302
303 | HsParTy (LHsType name) -- See Note [Parens in HsSyn] in HsExpr
304 -- Parenthesis preserved for the precedence re-arrangement in RnTypes
305 -- It's important that a * (b + c) doesn't get rearranged to (a*b) + c!
306 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
307 -- 'ApiAnnotation.AnnClose' @')'@
308
309 -- For details on above see note [Api annotations] in ApiAnnotation
310
311 | HsIParamTy HsIPName -- (?x :: ty)
312 (LHsType name) -- Implicit parameters as they occur in contexts
313 -- ^
314 -- > (?x :: ty)
315 --
316 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
317
318 -- For details on above see note [Api annotations] in ApiAnnotation
319
320 | HsEqTy (LHsType name) -- ty1 ~ ty2
321 (LHsType name) -- Always allowed even without TypeOperators, and has special kinding rule
322 -- ^
323 -- > ty1 ~ ty2
324 --
325 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnTilde'
326
327 -- For details on above see note [Api annotations] in ApiAnnotation
328
329 | HsKindSig (LHsType name) -- (ty :: kind)
330 (LHsKind name) -- A type with a kind signature
331 -- ^
332 -- > (ty :: kind)
333 --
334 -- - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'('@,
335 -- 'ApiAnnotation.AnnDcolon','ApiAnnotation.AnnClose' @')'@
336
337 -- For details on above see note [Api annotations] in ApiAnnotation
338
339 | HsSpliceTy (HsSplice name) -- Includes quasi-quotes
340 (PostTc name Kind)
341 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'$('@,
342 -- 'ApiAnnotation.AnnClose' @')'@
343
344 -- For details on above see note [Api annotations] in ApiAnnotation
345
346 | HsDocTy (LHsType name) LHsDocString -- A documented type
347 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
348
349 -- For details on above see note [Api annotations] in ApiAnnotation
350
351 | HsBangTy HsSrcBang (LHsType name) -- Bang-style type annotations
352 -- ^ - 'ApiAnnotation.AnnKeywordId' :
353 -- 'ApiAnnotation.AnnOpen' @'{-\# UNPACK' or '{-\# NOUNPACK'@,
354 -- 'ApiAnnotation.AnnClose' @'#-}'@
355 -- 'ApiAnnotation.AnnBang' @\'!\'@
356
357 -- For details on above see note [Api annotations] in ApiAnnotation
358
359 | HsRecTy [LConDeclField name] -- Only in data type declarations
360 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @'{'@,
361 -- 'ApiAnnotation.AnnClose' @'}'@
362
363 -- For details on above see note [Api annotations] in ApiAnnotation
364
365 | HsCoreTy Type -- An escape hatch for tunnelling a *closed*
366 -- Core Type through HsSyn.
367 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
368
369 -- For details on above see note [Api annotations] in ApiAnnotation
370
371 | HsExplicitListTy -- A promoted explicit list
372 (PostTc name Kind) -- See Note [Promoted lists and tuples]
373 [LHsType name]
374 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'["@,
375 -- 'ApiAnnotation.AnnClose' @']'@
376
377 -- For details on above see note [Api annotations] in ApiAnnotation
378
379 | HsExplicitTupleTy -- A promoted explicit tuple
380 [PostTc name Kind] -- See Note [Promoted lists and tuples]
381 [LHsType name]
382 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnOpen' @"'("@,
383 -- 'ApiAnnotation.AnnClose' @')'@
384
385 -- For details on above see note [Api annotations] in ApiAnnotation
386
387 | HsTyLit HsTyLit -- A promoted numeric literal.
388 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
389
390 -- For details on above see note [Api annotations] in ApiAnnotation
391
392 | HsWrapTy HsTyWrapper (HsType name) -- only in typechecker output
393 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
394
395 -- For details on above see note [Api annotations] in ApiAnnotation
396
397 | HsWildCardTy (HsWildCardInfo name) -- A type wildcard
398 -- ^ - 'ApiAnnotation.AnnKeywordId' : None
399
400 -- For details on above see note [Api annotations] in ApiAnnotation
401 deriving (Typeable)
402 deriving instance (DataId name) => Data (HsType name)
403
404 -- Note [Literal source text] in BasicTypes for SourceText fields in
405 -- the following
406 data HsTyLit
407 = HsNumTy SourceText Integer
408 | HsStrTy SourceText FastString
409 deriving (Data, Typeable)
410
411 data HsTyWrapper
412 = WpKiApps [Kind] -- kind instantiation: [] k1 k2 .. kn
413 deriving (Data, Typeable)
414
415 type LHsTyOp name = HsTyOp (Located name)
416 type HsTyOp name = (HsTyWrapper, name)
417
418 mkHsOpTy :: LHsType name -> Located name -> LHsType name -> HsType name
419 mkHsOpTy ty1 op ty2 = HsOpTy ty1 (WpKiApps [], op) ty2
420
421 data HsWildCardInfo name
422 = AnonWildCard (PostRn name Name)
423 -- A anonymous wild card ('_'). A name is generated during renaming.
424 | NamedWildCard name
425 -- A named wild card ('_a').
426 deriving (Typeable)
427 deriving instance (DataId name) => Data (HsWildCardInfo name)
428
429 {-
430 Note [HsForAllTy tyvar binders]
431 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
432 After parsing:
433 * Implicit => empty
434 Explicit => the variables the user wrote
435
436 After renaming
437 * Implicit => the *type* variables free in the type
438 Explicit => the variables the user wrote (renamed)
439
440 Qualified currently behaves exactly as Implicit,
441 but it is deprecated to use it for implicit quantification.
442 In this case, GHC 7.10 gives a warning; see
443 Note [Context quantification] in RnTypes, and Trac #4426.
444 In GHC 7.12, Qualified will no longer bind variables
445 and this will become an error.
446
447 The kind variables bound in the hsq_kvs field come both
448 a) from the kind signatures on the kind vars (eg k1)
449 b) from the scope of the forall (eg k2)
450 Example: f :: forall (a::k1) b. T a (b::k2)
451
452
453 Note [Unit tuples]
454 ~~~~~~~~~~~~~~~~~~
455 Consider the type
456 type instance F Int = ()
457 We want to parse that "()"
458 as HsTupleTy HsBoxedOrConstraintTuple [],
459 NOT as HsTyVar unitTyCon
460
461 Why? Because F might have kind (* -> Constraint), so we when parsing we
462 don't know if that tuple is going to be a constraint tuple or an ordinary
463 unit tuple. The HsTupleSort flag is specifically designed to deal with
464 that, but it has to work for unit tuples too.
465
466 Note [Promotions (HsTyVar)]
467 ~~~~~~~~~~~~~~~~~~~~~~~~~~~
468 HsTyVar: A name in a type or kind.
469 Here are the allowed namespaces for the name.
470 In a type:
471 Var: not allowed
472 Data: promoted data constructor
473 Tv: type variable
474 TcCls before renamer: type constructor, class constructor, or promoted data constructor
475 TcCls after renamer: type constructor or class constructor
476 In a kind:
477 Var, Data: not allowed
478 Tv: kind variable
479 TcCls: kind constructor or promoted type constructor
480
481
482 Note [Promoted lists and tuples]
483 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
484 Notice the difference between
485 HsListTy HsExplicitListTy
486 HsTupleTy HsExplicitListTupleTy
487
488 E.g. f :: [Int] HsListTy
489
490 g3 :: T '[] All these use
491 g2 :: T '[True] HsExplicitListTy
492 g1 :: T '[True,False]
493 g1a :: T [True,False] (can omit ' where unambiguous)
494
495 kind of T :: [Bool] -> * This kind uses HsListTy!
496
497 E.g. h :: (Int,Bool) HsTupleTy; f is a pair
498 k :: S '(True,False) HsExplicitTypleTy; S is indexed by
499 a type-level pair of booleans
500 kind of S :: (Bool,Bool) -> * This kind uses HsExplicitTupleTy
501
502 Note [Distinguishing tuple kinds]
503 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
504
505 Apart from promotion, tuples can have one of three different kinds:
506
507 x :: (Int, Bool) -- Regular boxed tuples
508 f :: Int# -> (# Int#, Int# #) -- Unboxed tuples
509 g :: (Eq a, Ord a) => a -- Constraint tuples
510
511 For convenience, internally we use a single constructor for all of these,
512 namely HsTupleTy, but keep track of the tuple kind (in the first argument to
513 HsTupleTy, a HsTupleSort). We can tell if a tuple is unboxed while parsing,
514 because of the #. However, with -XConstraintKinds we can only distinguish
515 between constraint and boxed tuples during type checking, in general. Hence the
516 four constructors of HsTupleSort:
517
518 HsUnboxedTuple -> Produced by the parser
519 HsBoxedTuple -> Certainly a boxed tuple
520 HsConstraintTuple -> Certainly a constraint tuple
521 HsBoxedOrConstraintTuple -> Could be a boxed or a constraint
522 tuple. Produced by the parser only,
523 disappears after type checking
524 -}
525
526 data HsTupleSort = HsUnboxedTuple
527 | HsBoxedTuple
528 | HsConstraintTuple
529 | HsBoxedOrConstraintTuple
530 deriving (Data, Typeable)
531
532 data HsExplicitFlag
533 = Explicit -- An explicit forall, eg f :: forall a. a-> a
534 | Implicit -- No explicit forall, eg f :: a -> a, or f :: Eq a => a -> a
535 | Qualified -- A *nested* occurrences of (ctxt => ty), with no explicit forall
536 -- e.g. f :: (Eq a => a -> a) -> Int
537 deriving (Data, Typeable)
538
539 type LConDeclField name = Located (ConDeclField name)
540 -- ^ May have 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnComma' when
541 -- in a list
542
543 -- For details on above see note [Api annotations] in ApiAnnotation
544 data ConDeclField name -- Record fields have Haddoc docs on them
545 = ConDeclField { cd_fld_names :: [Located name],
546 cd_fld_type :: LBangType name,
547 cd_fld_doc :: Maybe LHsDocString }
548 -- ^ - 'ApiAnnotation.AnnKeywordId' : 'ApiAnnotation.AnnDcolon'
549
550 -- For details on above see note [Api annotations] in ApiAnnotation
551 deriving (Typeable)
552 deriving instance (DataId name) => Data (ConDeclField name)
553
554 -----------------------
555 -- A valid type must have a for-all at the top of the type, or of the fn arg
556 -- types
557
558 mkImplicitHsForAllTy :: LHsType RdrName -> HsType RdrName
559 mkExplicitHsForAllTy :: [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName
560 mkQualifiedHsForAllTy :: LHsContext RdrName -> LHsType RdrName -> HsType RdrName
561
562 -- | mkImplicitHsForAllTy is called when we encounter
563 -- f :: type
564 -- Wrap around a HsForallTy if one is not there already.
565 mkImplicitHsForAllTy (L _ (HsForAllTy exp extra tvs cxt ty))
566 = HsForAllTy exp' extra tvs cxt ty
567 where
568 exp' = case exp of
569 Qualified -> Implicit
570 -- Qualified is used only for a nested forall,
571 -- this is now top level
572 _ -> exp
573 mkImplicitHsForAllTy ty = mkHsForAllTy Implicit [] (noLoc []) ty
574
575 mkExplicitHsForAllTy tvs ctxt ty = mkHsForAllTy Explicit tvs ctxt ty
576 mkQualifiedHsForAllTy ctxt ty = mkHsForAllTy Qualified [] ctxt ty
577
578 -- |Smart constructor for HsForAllTy, which populates the extra-constraints
579 -- field if a wildcard is present in the context.
580 mkHsForAllTy :: HsExplicitFlag -> [LHsTyVarBndr RdrName] -> LHsContext RdrName -> LHsType RdrName -> HsType RdrName
581 mkHsForAllTy exp tvs ctxt ty
582 = HsForAllTy exp Nothing (mkHsQTvs tvs) ctxt ty
583
584 -- |When a sigtype is parsed, the type found is wrapped in an Implicit
585 -- HsForAllTy via mkImplicitHsForAllTy, to ensure that a signature always has a
586 -- forall at the outer level. For Api Annotations this nested structure is
587 -- important to ensure that all `forall` and `.` locations are retained. From
588 -- the renamer onwards this structure is flattened, to ease the renaming and
589 -- type checking process.
590 flattenTopLevelLHsForAllTy :: LHsType name -> LHsType name
591 flattenTopLevelLHsForAllTy (L l ty) = L l (flattenTopLevelHsForAllTy ty)
592
593 flattenTopLevelHsForAllTy :: HsType name -> HsType name
594 flattenTopLevelHsForAllTy (HsForAllTy exp extra tvs (L l []) ty)
595 = snd $ mk_forall_ty [] l exp extra tvs ty
596 flattenTopLevelHsForAllTy ty = ty
597
598 flattenHsForAllTyKeepAnns :: HsType name -> ([AddAnn],HsType name)
599 flattenHsForAllTyKeepAnns (HsForAllTy exp extra tvs (L l []) ty)
600 = mk_forall_ty [] l exp extra tvs ty
601 flattenHsForAllTyKeepAnns ty = ([],ty)
602
603 -- mk_forall_ty makes a pure for-all type (no context)
604 mk_forall_ty :: [AddAnn] -> SrcSpan -> HsExplicitFlag -> Maybe SrcSpan
605 -> LHsTyVarBndrs name
606 -> LHsType name -> ([AddAnn],HsType name)
607 mk_forall_ty ann _ exp1 extra1 tvs1 (L _ (HsForAllTy exp2 extra qtvs2 ctxt ty))
608 = (ann,HsForAllTy (exp1 `plus` exp2) (mergeExtra extra1 extra)
609 (tvs1 `mappend` qtvs2) ctxt ty)
610 where
611 -- Bias the merging of extra's to the top level, so that a single
612 -- wildcard context will prevail
613 mergeExtra (Just s) _ = Just s
614 mergeExtra _ e = e
615 mk_forall_ty ann l exp extra tvs (L lp (HsParTy ty))
616 = mk_forall_ty (ann ++ mkParensApiAnn lp) l exp extra tvs ty
617 mk_forall_ty ann l exp extra tvs ty
618 = (ann,HsForAllTy exp extra tvs (L l []) ty)
619 -- Even if tvs is empty, we still make a HsForAll!
620 -- In the Implicit case, this signals the place to do implicit quantification
621 -- In the Explicit case, it prevents implicit quantification
622 -- (see the sigtype production in Parser.y)
623 -- so that (forall. ty) isn't implicitly quantified
624
625 plus :: HsExplicitFlag -> HsExplicitFlag -> HsExplicitFlag
626 Qualified `plus` Qualified = Qualified
627 Explicit `plus` _ = Explicit
628 _ `plus` Explicit = Explicit
629 _ `plus` _ = Implicit
630 -- NB: Implicit `plus` Qualified = Implicit
631 -- so that f :: Eq a => a -> a ends up Implicit
632
633 ---------------------
634 hsExplicitTvs :: LHsType Name -> [Name]
635 -- The explicitly-given forall'd type variables of a HsType
636 hsExplicitTvs (L _ (HsForAllTy Explicit _ tvs _ _)) = hsLKiTyVarNames tvs
637 hsExplicitTvs _ = []
638
639 ---------------------
640 hsTyVarName :: HsTyVarBndr name -> name
641 hsTyVarName (UserTyVar n) = n
642 hsTyVarName (KindedTyVar (L _ n) _) = n
643
644 hsLTyVarName :: LHsTyVarBndr name -> name
645 hsLTyVarName = hsTyVarName . unLoc
646
647 hsLTyVarNames :: LHsTyVarBndrs name -> [name]
648 -- Type variables only
649 hsLTyVarNames qtvs = map hsLTyVarName (hsQTvBndrs qtvs)
650
651 hsLKiTyVarNames :: LHsTyVarBndrs Name -> [Name]
652 -- Kind and type variables
653 hsLKiTyVarNames (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs })
654 = kvs ++ map hsLTyVarName tvs
655
656 hsLTyVarLocName :: LHsTyVarBndr name -> Located name
657 hsLTyVarLocName = fmap hsTyVarName
658
659 hsLTyVarLocNames :: LHsTyVarBndrs name -> [Located name]
660 hsLTyVarLocNames qtvs = map hsLTyVarLocName (hsQTvBndrs qtvs)
661
662 ---------------------
663 mkAnonWildCardTy :: HsType RdrName
664 mkAnonWildCardTy = HsWildCardTy (AnonWildCard PlaceHolder)
665
666 mkNamedWildCardTy :: n -> HsType n
667 mkNamedWildCardTy = HsWildCardTy . NamedWildCard
668
669 isAnonWildCard :: HsWildCardInfo name -> Bool
670 isAnonWildCard (AnonWildCard _) = True
671 isAnonWildCard _ = False
672
673 isNamedWildCard :: HsWildCardInfo name -> Bool
674 isNamedWildCard = not . isAnonWildCard
675
676 wildCardName :: HsWildCardInfo Name -> Name
677 wildCardName (NamedWildCard n) = n
678 wildCardName (AnonWildCard n) = n
679
680 -- Two wild cards are the same when: they're both named and have the same
681 -- name, or they're both anonymous and have the same location.
682 sameWildCard :: Eq name
683 => Located (HsWildCardInfo name)
684 -> Located (HsWildCardInfo name) -> Bool
685 sameWildCard (L l1 (AnonWildCard _)) (L l2 (AnonWildCard _)) = l1 == l2
686 sameWildCard (L _ (NamedWildCard n1)) (L _ (NamedWildCard n2)) = n1 == n2
687 sameWildCard _ _ = False
688
689 sameNamedWildCard :: Eq name
690 => Located (HsWildCardInfo name)
691 -> Located (HsWildCardInfo name) -> Bool
692 sameNamedWildCard (L _ (NamedWildCard n1)) (L _ (NamedWildCard n2)) = n1 == n2
693 sameNamedWildCard _ _ = False
694
695 splitHsAppTys :: LHsType n -> [LHsType n] -> (LHsType n, [LHsType n])
696 splitHsAppTys (L _ (HsAppTy f a)) as = splitHsAppTys f (a:as)
697 splitHsAppTys (L _ (HsParTy f)) as = splitHsAppTys f as
698 splitHsAppTys f as = (f,as)
699
700 -- retrieve the name of the "head" of a nested type application
701 -- somewhat like splitHsAppTys, but a little more thorough
702 -- used to examine the result of a GADT-like datacon, so it doesn't handle
703 -- *all* cases (like lists, tuples, (~), etc.)
704 hsTyGetAppHead_maybe :: LHsType n -> Maybe (n, [LHsType n])
705 hsTyGetAppHead_maybe = go []
706 where
707 go tys (L _ (HsTyVar n)) = Just (n, tys)
708 go tys (L _ (HsAppTy l r)) = go (r : tys) l
709 go tys (L _ (HsOpTy l (_, L _ n) r)) = Just (n, l : r : tys)
710 go tys (L _ (HsParTy t)) = go tys t
711 go tys (L _ (HsKindSig t _)) = go tys t
712 go _ _ = Nothing
713
714 mkHsAppTys :: OutputableBndr n => LHsType n -> [LHsType n] -> HsType n
715 mkHsAppTys fun_ty [] = pprPanic "mkHsAppTys" (ppr fun_ty)
716 mkHsAppTys fun_ty (arg_ty:arg_tys)
717 = foldl mk_app (HsAppTy fun_ty arg_ty) arg_tys
718 where
719 mk_app fun arg = HsAppTy (noLoc fun) arg
720 -- Add noLocs for inner nodes of the application;
721 -- they are never used
722
723 splitLHsInstDeclTy_maybe
724 :: LHsType name
725 -> Maybe (LHsTyVarBndrs name, HsContext name, Located name, [LHsType name])
726 -- Split up an instance decl type, returning the pieces
727 splitLHsInstDeclTy_maybe inst_ty = do
728 let (tvs, cxt, ty) = splitLHsForAllTy inst_ty
729 (cls, tys) <- splitLHsClassTy_maybe ty
730 return (tvs, cxt, cls, tys)
731
732 splitLHsForAllTy
733 :: LHsType name
734 -> (LHsTyVarBndrs name, HsContext name, LHsType name)
735 splitLHsForAllTy poly_ty
736 = case unLoc poly_ty of
737 HsParTy ty -> splitLHsForAllTy ty
738 HsForAllTy _ _ tvs cxt ty -> (tvs, unLoc cxt, ty)
739 _ -> (emptyHsQTvs, [], poly_ty)
740 -- The type vars should have been computed by now, even if they were implicit
741
742 splitHsClassTy_maybe :: HsType name -> Maybe (name, [LHsType name])
743 splitHsClassTy_maybe ty = fmap (\(L _ n, tys) -> (n, tys)) $ splitLHsClassTy_maybe (noLoc ty)
744
745 splitLHsClassTy_maybe :: LHsType name -> Maybe (Located name, [LHsType name])
746 --- Watch out.. in ...deriving( Show )... we use this on
747 --- the list of partially applied predicates in the deriving,
748 --- so there can be zero args.
749
750 -- In TcDeriv we also use this to figure out what data type is being
751 -- mentioned in a deriving (Generic (Foo bar baz)) declaration (i.e. "Foo").
752 splitLHsClassTy_maybe ty
753 = checkl ty []
754 where
755 checkl (L l ty) args = case ty of
756 HsTyVar t -> Just (L l t, args)
757 HsAppTy l r -> checkl l (r:args)
758 HsOpTy l (_, tc) r -> checkl (fmap HsTyVar tc) (l:r:args)
759 HsParTy t -> checkl t args
760 HsKindSig ty _ -> checkl ty args
761 _ -> Nothing
762
763 -- splitHsFunType decomposes a type (t1 -> t2 ... -> tn)
764 -- Breaks up any parens in the result type:
765 -- splitHsFunType (a -> (b -> c)) = ([a,b], c)
766 -- Also deals with (->) t1 t2; that is why it only works on LHsType Name
767 -- (see Trac #9096)
768 splitHsFunType :: LHsType Name -> ([LHsType Name], LHsType Name)
769 splitHsFunType (L _ (HsParTy ty))
770 = splitHsFunType ty
771
772 splitHsFunType (L _ (HsFunTy x y))
773 | (args, res) <- splitHsFunType y
774 = (x:args, res)
775
776 splitHsFunType orig_ty@(L _ (HsAppTy t1 t2))
777 = go t1 [t2]
778 where -- Look for (->) t1 t2, possibly with parenthesisation
779 go (L _ (HsTyVar fn)) tys | fn == funTyConName
780 , [t1,t2] <- tys
781 , (args, res) <- splitHsFunType t2
782 = (t1:args, res)
783 go (L _ (HsAppTy t1 t2)) tys = go t1 (t2:tys)
784 go (L _ (HsParTy ty)) tys = go ty tys
785 go _ _ = ([], orig_ty) -- Failure to match
786
787 splitHsFunType other = ([], other)
788
789 ignoreParens :: LHsType name -> LHsType name
790 ignoreParens (L _ (HsParTy ty)) = ignoreParens ty
791 ignoreParens ty = ty
792
793 {-
794 ************************************************************************
795 * *
796 \subsection{Pretty printing}
797 * *
798 ************************************************************************
799 -}
800
801 instance (OutputableBndr name) => Outputable (HsType name) where
802 ppr ty = pprHsType ty
803
804 instance Outputable HsTyLit where
805 ppr = ppr_tylit
806
807 instance (OutputableBndr name) => Outputable (LHsTyVarBndrs name) where
808 ppr (HsQTvs { hsq_kvs = kvs, hsq_tvs = tvs })
809 = sep [ ifPprDebug $ braces (interppSP kvs), interppSP tvs ]
810
811 instance (OutputableBndr name) => Outputable (HsTyVarBndr name) where
812 ppr (UserTyVar n) = ppr n
813 ppr (KindedTyVar n k) = parens $ hsep [ppr n, dcolon, ppr k]
814
815 instance (Outputable thing) => Outputable (HsWithBndrs name thing) where
816 ppr (HsWB { hswb_cts = ty }) = ppr ty
817
818 instance (Outputable name) => Outputable (HsWildCardInfo name) where
819 ppr (AnonWildCard _) = char '_'
820 ppr (NamedWildCard n) = ppr n
821
822 pprHsForAll :: OutputableBndr name => HsExplicitFlag -> LHsTyVarBndrs name -> LHsContext name -> SDoc
823 pprHsForAll exp = pprHsForAllExtra exp Nothing
824
825 -- | Version of 'pprHsForAll' that can also print an extra-constraints
826 -- wildcard, e.g. @_ => a -> Bool@ or @(Show a, _) => a -> String@. This
827 -- underscore will be printed when the 'Maybe SrcSpan' argument is a 'Just'
828 -- containing the location of the extra-constraints wildcard. A special
829 -- function for this is needed, as the extra-constraints wildcard is removed
830 -- from the actual context and type, and stored in a separate field, thus just
831 -- printing the type will not print the extra-constraints wildcard.
832 pprHsForAllExtra :: OutputableBndr name => HsExplicitFlag -> Maybe SrcSpan -> LHsTyVarBndrs name -> LHsContext name -> SDoc
833 pprHsForAllExtra exp extra qtvs cxt
834 | show_forall = forall_part <+> pprHsContextExtra show_extra (unLoc cxt)
835 | otherwise = pprHsContextExtra show_extra (unLoc cxt)
836 where
837 show_extra = isJust extra
838 show_forall = opt_PprStyle_Debug
839 || (not (null (hsQTvBndrs qtvs)) && is_explicit)
840 is_explicit = case exp of {Explicit -> True; Implicit -> False; Qualified -> False}
841 forall_part = forAllLit <+> ppr qtvs <> dot
842
843 pprHsContext :: (OutputableBndr name) => HsContext name -> SDoc
844 pprHsContext = maybe empty (<+> darrow) . pprHsContextMaybe
845
846 pprHsContextNoArrow :: (OutputableBndr name) => HsContext name -> SDoc
847 pprHsContextNoArrow = fromMaybe empty . pprHsContextMaybe
848
849 pprHsContextMaybe :: (OutputableBndr name) => HsContext name -> Maybe SDoc
850 pprHsContextMaybe [] = Nothing
851 pprHsContextMaybe [L _ pred] = Just $ ppr_mono_ty FunPrec pred
852 pprHsContextMaybe cxt = Just $ parens (interpp'SP cxt)
853
854 -- True <=> print an extra-constraints wildcard, e.g. @(Show a, _) =>@
855 pprHsContextExtra :: (OutputableBndr name) => Bool -> HsContext name -> SDoc
856 pprHsContextExtra False = pprHsContext
857 pprHsContextExtra True
858 = \ctxt -> case ctxt of
859 [] -> char '_' <+> darrow
860 _ -> parens (sep (punctuate comma ctxt')) <+> darrow
861 where ctxt' = map ppr ctxt ++ [char '_']
862
863 pprConDeclFields :: OutputableBndr name => [LConDeclField name] -> SDoc
864 pprConDeclFields fields = braces (sep (punctuate comma (map ppr_fld fields)))
865 where
866 ppr_fld (L _ (ConDeclField { cd_fld_names = ns, cd_fld_type = ty,
867 cd_fld_doc = doc }))
868 = ppr_names ns <+> dcolon <+> ppr ty <+> ppr_mbDoc doc
869 ppr_names [n] = ppr n
870 ppr_names ns = sep (punctuate comma (map ppr ns))
871
872 {-
873 Note [Printing KindedTyVars]
874 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
875 Trac #3830 reminded me that we should really only print the kind
876 signature on a KindedTyVar if the kind signature was put there by the
877 programmer. During kind inference GHC now adds a PostTcKind to UserTyVars,
878 rather than converting to KindedTyVars as before.
879
880 (As it happens, the message in #3830 comes out a different way now,
881 and the problem doesn't show up; but having the flag on a KindedTyVar
882 seems like the Right Thing anyway.)
883 -}
884
885 -- Printing works more-or-less as for Types
886
887 pprHsType, pprParendHsType :: (OutputableBndr name) => HsType name -> SDoc
888
889 pprHsType ty = getPprStyle $ \sty -> ppr_mono_ty TopPrec (prepare sty ty)
890 pprParendHsType ty = ppr_mono_ty TyConPrec ty
891
892 -- Before printing a type
893 -- (a) Remove outermost HsParTy parens
894 -- (b) Drop top-level for-all type variables in user style
895 -- since they are implicit in Haskell
896 prepare :: PprStyle -> HsType name -> HsType name
897 prepare sty (HsParTy ty) = prepare sty (unLoc ty)
898 prepare _ ty = ty
899
900 ppr_mono_lty :: (OutputableBndr name) => TyPrec -> LHsType name -> SDoc
901 ppr_mono_lty ctxt_prec ty = ppr_mono_ty ctxt_prec (unLoc ty)
902
903 ppr_mono_ty :: (OutputableBndr name) => TyPrec -> HsType name -> SDoc
904 ppr_mono_ty ctxt_prec (HsForAllTy exp extra tvs ctxt ty)
905 = maybeParen ctxt_prec FunPrec $
906 sep [pprHsForAllExtra exp extra tvs ctxt, ppr_mono_lty TopPrec ty]
907
908 ppr_mono_ty _ (HsBangTy b ty) = ppr b <> ppr_mono_lty TyConPrec ty
909 ppr_mono_ty _ (HsRecTy flds) = pprConDeclFields flds
910 ppr_mono_ty _ (HsTyVar name) = pprPrefixOcc name
911 ppr_mono_ty prec (HsFunTy ty1 ty2) = ppr_fun_ty prec ty1 ty2
912 ppr_mono_ty _ (HsTupleTy con tys) = tupleParens std_con (pprWithCommas ppr tys)
913 where std_con = case con of
914 HsUnboxedTuple -> UnboxedTuple
915 _ -> BoxedTuple
916 ppr_mono_ty _ (HsKindSig ty kind) = parens (ppr_mono_lty TopPrec ty <+> dcolon <+> ppr kind)
917 ppr_mono_ty _ (HsListTy ty) = brackets (ppr_mono_lty TopPrec ty)
918 ppr_mono_ty _ (HsPArrTy ty) = paBrackets (ppr_mono_lty TopPrec ty)
919 ppr_mono_ty prec (HsIParamTy n ty) = maybeParen prec FunPrec (ppr n <+> dcolon <+> ppr_mono_lty TopPrec ty)
920 ppr_mono_ty _ (HsSpliceTy s _) = pprSplice s
921 ppr_mono_ty _ (HsCoreTy ty) = ppr ty
922 ppr_mono_ty _ (HsExplicitListTy _ tys) = quote $ brackets (interpp'SP tys)
923 ppr_mono_ty _ (HsExplicitTupleTy _ tys) = quote $ parens (interpp'SP tys)
924 ppr_mono_ty _ (HsTyLit t) = ppr_tylit t
925 ppr_mono_ty _ (HsWildCardTy (AnonWildCard _)) = char '_'
926 ppr_mono_ty _ (HsWildCardTy (NamedWildCard name)) = ppr name
927
928 ppr_mono_ty ctxt_prec (HsWrapTy (WpKiApps _kis) ty)
929 = ppr_mono_ty ctxt_prec ty
930 -- We are not printing kind applications. If we wanted to do so, we should do
931 -- something like this:
932 {-
933 = go ctxt_prec kis ty
934 where
935 go ctxt_prec [] ty = ppr_mono_ty ctxt_prec ty
936 go ctxt_prec (ki:kis) ty
937 = maybeParen ctxt_prec TyConPrec $
938 hsep [ go FunPrec kis ty
939 , ptext (sLit "@") <> pprParendKind ki ]
940 -}
941
942 ppr_mono_ty ctxt_prec (HsEqTy ty1 ty2)
943 = maybeParen ctxt_prec TyOpPrec $
944 ppr_mono_lty TyOpPrec ty1 <+> char '~' <+> ppr_mono_lty TyOpPrec ty2
945
946 ppr_mono_ty ctxt_prec (HsAppTy fun_ty arg_ty)
947 = maybeParen ctxt_prec TyConPrec $
948 hsep [ppr_mono_lty FunPrec fun_ty, ppr_mono_lty TyConPrec arg_ty]
949
950 ppr_mono_ty ctxt_prec (HsOpTy ty1 (_wrapper, L _ op) ty2)
951 = maybeParen ctxt_prec TyOpPrec $
952 sep [ ppr_mono_lty TyOpPrec ty1
953 , sep [pprInfixOcc op, ppr_mono_lty TyOpPrec ty2 ] ]
954 -- Don't print the wrapper (= kind applications)
955 -- c.f. HsWrapTy
956
957 ppr_mono_ty _ (HsParTy ty)
958 = parens (ppr_mono_lty TopPrec ty)
959 -- Put the parens in where the user did
960 -- But we still use the precedence stuff to add parens because
961 -- toHsType doesn't put in any HsParTys, so we may still need them
962
963 ppr_mono_ty ctxt_prec (HsDocTy ty doc)
964 = maybeParen ctxt_prec TyOpPrec $
965 ppr_mono_lty TyOpPrec ty <+> ppr (unLoc doc)
966 -- we pretty print Haddock comments on types as if they were
967 -- postfix operators
968
969 --------------------------
970 ppr_fun_ty :: (OutputableBndr name) => TyPrec -> LHsType name -> LHsType name -> SDoc
971 ppr_fun_ty ctxt_prec ty1 ty2
972 = let p1 = ppr_mono_lty FunPrec ty1
973 p2 = ppr_mono_lty TopPrec ty2
974 in
975 maybeParen ctxt_prec FunPrec $
976 sep [p1, ptext (sLit "->") <+> p2]
977
978 --------------------------
979 ppr_tylit :: HsTyLit -> SDoc
980 ppr_tylit (HsNumTy _ i) = integer i
981 ppr_tylit (HsStrTy _ s) = text (show s)