2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1997-1998
5 \section[BasicTypes]{Miscellanous types}
7 This module defines a miscellaneously collection of very simple
11 \item have no other obvious home
12 \item don't depend on any other complicated types
13 \item are used in more than one "part" of the compiler
17 {-# LANGUAGE DeriveDataTypeable #-}
20 Version, bumpVersion, initialVersion,
28 Fixity(..), FixityDirection(..),
29 defaultFixity, maxPrecedence,
30 negateFixity, funTyFixity,
33 IPName(..), ipNameName, mapIPName,
35 RecFlag(..), isRec, isNonRec, boolToRecFlag,
39 TopLevelFlag(..), isTopLevel, isNotTopLevel,
45 TupCon(..), tupleParens,
47 OccInfo(..), seqOccInfo, zapFragileOcc, isOneOcc,
48 isDeadOcc, isLoopBreaker, isNonRuleLoopBreaker, isNoOcc,
51 InsideLam, insideLam, notInsideLam,
52 OneBranch, oneBranch, notOneBranch,
57 HsBang(..), isBanged, isMarkedUnboxed,
58 StrictnessMark(..), isMarkedStrict,
62 CompilerPhase(..), PhaseNum,
63 Activation(..), isActive, isActiveIn,
64 isNeverActive, isAlwaysActive, isEarlyActive,
65 RuleMatchInfo(..), isConLike, isFunLike,
67 InlinePragma(..), defaultInlinePragma, alwaysInlinePragma,
68 neverInlinePragma, dfunInlinePragma,
69 isDefaultInlinePragma,
70 isInlinePragma, isInlinablePragma, isAnyInlinePragma,
71 inlinePragmaSpec, inlinePragmaSat,
72 inlinePragmaActivation, inlinePragmaRuleMatchInfo,
73 setInlinePragmaActivation, setInlinePragmaRuleMatchInfo,
75 SuccessFlag(..), succeeded, failed, successIf
81 import Data.Data hiding (Fixity)
84 %************************************************************************
86 \subsection[Arity]{Arity}
88 %************************************************************************
94 %************************************************************************
96 \subsection[FunctionOrData]{FunctionOrData}
98 %************************************************************************
101 data FunctionOrData = IsFunction | IsData
102 deriving (Eq, Ord, Data, Typeable)
104 instance Outputable FunctionOrData where
105 ppr IsFunction = text "(function)"
106 ppr IsData = text "(data)"
110 %************************************************************************
112 \subsection[Version]{Module and identifier version numbers}
114 %************************************************************************
119 bumpVersion :: Version -> Version
122 initialVersion :: Version
126 %************************************************************************
130 %************************************************************************
134 -- reason/explanation from a WARNING or DEPRECATED pragma
135 data WarningTxt = WarningTxt [FastString]
136 | DeprecatedTxt [FastString]
137 deriving (Eq, Data, Typeable)
139 instance Outputable WarningTxt where
140 ppr (WarningTxt ws) = doubleQuotes (vcat (map ftext ws))
141 ppr (DeprecatedTxt ds) = text "Deprecated:" <+>
142 doubleQuotes (vcat (map ftext ds))
145 %************************************************************************
147 \subsection{Implicit parameter identity}
149 %************************************************************************
151 The @IPName@ type is here because it is used in TypeRep (i.e. very
152 early in the hierarchy), but also in HsSyn.
155 newtype IPName name = IPName name -- ?x
156 deriving( Eq, Ord, Data, Typeable )
157 -- Ord is used in the IP name cache finite map
158 -- (used in HscTypes.OrigIParamCache)
160 ipNameName :: IPName name -> name
161 ipNameName (IPName n) = n
163 mapIPName :: (a->b) -> IPName a -> IPName b
164 mapIPName f (IPName n) = IPName (f n)
166 instance Outputable name => Outputable (IPName name) where
167 ppr (IPName n) = char '?' <> ppr n -- Ordinary implicit parameters
170 %************************************************************************
174 %************************************************************************
177 type RuleName = FastString
180 %************************************************************************
182 \subsection[Fixity]{Fixity info}
184 %************************************************************************
187 ------------------------
188 data Fixity = Fixity Int FixityDirection
189 deriving (Data, Typeable)
191 instance Outputable Fixity where
192 ppr (Fixity prec dir) = hcat [ppr dir, space, int prec]
194 instance Eq Fixity where -- Used to determine if two fixities conflict
195 (Fixity p1 dir1) == (Fixity p2 dir2) = p1==p2 && dir1 == dir2
197 ------------------------
198 data FixityDirection = InfixL | InfixR | InfixN
199 deriving (Eq, Data, Typeable)
201 instance Outputable FixityDirection where
202 ppr InfixL = ptext (sLit "infixl")
203 ppr InfixR = ptext (sLit "infixr")
204 ppr InfixN = ptext (sLit "infix")
206 ------------------------
209 defaultFixity :: Fixity
210 defaultFixity = Fixity maxPrecedence InfixL
212 negateFixity, funTyFixity :: Fixity
214 negateFixity = Fixity 6 InfixL -- Fixity of unary negate
215 funTyFixity = Fixity 0 InfixR -- Fixity of '->'
223 @(compareFixity op1 op2)@ tells which way to arrange appication, or
224 whether there's an error.
227 compareFixity :: Fixity -> Fixity
228 -> (Bool, -- Error please
229 Bool) -- Associate to the right: a op1 (b op2 c)
230 compareFixity (Fixity prec1 dir1) (Fixity prec2 dir2)
231 = case prec1 `compare` prec2 of
234 EQ -> case (dir1, dir2) of
235 (InfixR, InfixR) -> right
236 (InfixL, InfixL) -> left
239 right = (False, True)
240 left = (False, False)
241 error_please = (True, False)
245 %************************************************************************
247 \subsection[Top-level/local]{Top-level/not-top level flag}
249 %************************************************************************
256 isTopLevel, isNotTopLevel :: TopLevelFlag -> Bool
258 isNotTopLevel NotTopLevel = True
259 isNotTopLevel TopLevel = False
261 isTopLevel TopLevel = True
262 isTopLevel NotTopLevel = False
264 instance Outputable TopLevelFlag where
265 ppr TopLevel = ptext (sLit "<TopLevel>")
266 ppr NotTopLevel = ptext (sLit "<NotTopLevel>")
270 %************************************************************************
272 Top-level/not-top level flag
274 %************************************************************************
280 deriving( Eq, Data, Typeable )
282 isBoxed :: Boxity -> Bool
284 isBoxed Unboxed = False
288 %************************************************************************
290 Recursive/Non-Recursive flag
292 %************************************************************************
295 data RecFlag = Recursive
297 deriving( Eq, Data, Typeable )
299 isRec :: RecFlag -> Bool
300 isRec Recursive = True
301 isRec NonRecursive = False
303 isNonRec :: RecFlag -> Bool
304 isNonRec Recursive = False
305 isNonRec NonRecursive = True
307 boolToRecFlag :: Bool -> RecFlag
308 boolToRecFlag True = Recursive
309 boolToRecFlag False = NonRecursive
311 instance Outputable RecFlag where
312 ppr Recursive = ptext (sLit "Recursive")
313 ppr NonRecursive = ptext (sLit "NonRecursive")
316 %************************************************************************
318 Instance overlap flag
320 %************************************************************************
324 = NoOverlap -- This instance must not overlap another
326 | OverlapOk -- Silently ignore this instance if you find a
327 -- more specific one that matches the constraint
328 -- you are trying to resolve
330 -- Example: constraint (Foo [Int])
331 -- instances (Foo [Int])
333 -- (Foo [a]) OverlapOk
334 -- Since the second instance has the OverlapOk flag,
335 -- the first instance will be chosen (otherwise
336 -- its ambiguous which to choose)
338 | Incoherent -- Like OverlapOk, but also ignore this instance
339 -- if it doesn't match the constraint you are
340 -- trying to resolve, but could match if the type variables
341 -- in the constraint were instantiated
343 -- Example: constraint (Foo [b])
344 -- instances (Foo [Int]) Incoherent
346 -- Without the Incoherent flag, we'd complain that
347 -- instantiating 'b' would change which instance
351 instance Outputable OverlapFlag where
352 ppr NoOverlap = empty
353 ppr OverlapOk = ptext (sLit "[overlap ok]")
354 ppr Incoherent = ptext (sLit "[incoherent]")
358 %************************************************************************
362 %************************************************************************
365 data TupCon = TupCon Boxity Arity
367 instance Eq TupCon where
368 (TupCon b1 a1) == (TupCon b2 a2) = b1==b2 && a1==a2
370 tupleParens :: Boxity -> SDoc -> SDoc
371 tupleParens Boxed p = parens p
372 tupleParens Unboxed p = ptext (sLit "(#") <+> p <+> ptext (sLit "#)")
375 %************************************************************************
377 \subsection[Generic]{Generic flag}
379 %************************************************************************
381 This is the "Embedding-Projection pair" datatype, it contains
382 two pieces of code (normally either RenamedExpr's or Id's)
383 If we have a such a pair (EP from to), the idea is that 'from' and 'to'
384 represents functions of type
393 T and Tring are arbitrary, but typically T is the 'main' type while
394 Tring is the 'representation' type. (This just helps us remember
395 whether to use 'from' or 'to'.
398 data EP a = EP { fromEP :: a, -- :: T -> Tring
399 toEP :: a } -- :: Tring -> T
402 Embedding-projection pairs are used in several places:
404 First of all, each type constructor has an EP associated with it, the
405 code in EP converts (datatype T) from T to Tring and back again.
407 Secondly, when we are filling in Generic methods (in the typechecker,
408 tcMethodBinds), we are constructing bimaps by induction on the structure
409 of the type of the method signature.
412 %************************************************************************
414 \subsection{Occurrence information}
416 %************************************************************************
418 This data type is used exclusively by the simplifier, but it appears in a
419 SubstResult, which is currently defined in VarEnv, which is pretty near
420 the base of the module hierarchy. So it seemed simpler to put the
421 defn of OccInfo here, safely at the bottom
424 -- | Identifier occurrence information
426 = NoOccInfo -- ^ There are many occurrences, or unknown occurences
428 | IAmDead -- ^ Marks unused variables. Sometimes useful for
429 -- lambda and case-bound variables.
434 !InterestingCxt -- ^ Occurs exactly once, not inside a rule
436 -- | This identifier breaks a loop of mutually recursive functions. The field
437 -- marks whether it is only a loop breaker due to a reference in a rule
438 | IAmALoopBreaker -- Note [LoopBreaker OccInfo]
439 !RulesOnly -- True <=> This is a weak or rules-only loop breaker
440 -- See OccurAnal Note [Weak loop breakers]
442 type RulesOnly = Bool
445 Note [LoopBreaker OccInfo]
446 ~~~~~~~~~~~~~~~~~~~~~~~~~~
447 An OccInfo of (IAmLoopBreaker False) is used by the occurrence
448 analyser in two ways:
449 (a) to mark loop-breakers in a group of recursive
450 definitions (hence the name)
451 (b) to mark binders that must not be inlined in this phase
452 (perhaps it has a NOINLINE pragma)
453 Things with (IAmLoopBreaker False) do not get an unfolding
454 pinned on to them, so they are completely opaque.
456 See OccurAnal Note [Weak loop breakers] for (IAmLoopBreaker True).
460 isNoOcc :: OccInfo -> Bool
461 isNoOcc NoOccInfo = True
464 seqOccInfo :: OccInfo -> ()
465 seqOccInfo occ = occ `seq` ()
468 type InterestingCxt = Bool -- True <=> Function: is applied
469 -- Data value: scrutinised by a case with
470 -- at least one non-DEFAULT branch
473 type InsideLam = Bool -- True <=> Occurs inside a non-linear lambda
474 -- Substituting a redex for this occurrence is
475 -- dangerous because it might duplicate work.
476 insideLam, notInsideLam :: InsideLam
481 type OneBranch = Bool -- True <=> Occurs in only one case branch
482 -- so no code-duplication issue to worry about
483 oneBranch, notOneBranch :: OneBranch
487 isLoopBreaker :: OccInfo -> Bool
488 isLoopBreaker (IAmALoopBreaker _) = True
489 isLoopBreaker _ = False
491 isNonRuleLoopBreaker :: OccInfo -> Bool
492 isNonRuleLoopBreaker (IAmALoopBreaker False) = True -- Loop-breaker that breaks a non-rule cycle
493 isNonRuleLoopBreaker _ = False
495 nonRuleLoopBreaker :: OccInfo
496 nonRuleLoopBreaker = IAmALoopBreaker False
498 isDeadOcc :: OccInfo -> Bool
499 isDeadOcc IAmDead = True
502 isOneOcc :: OccInfo -> Bool
503 isOneOcc (OneOcc {}) = True
506 zapFragileOcc :: OccInfo -> OccInfo
507 zapFragileOcc (OneOcc {}) = NoOccInfo
508 zapFragileOcc occ = occ
512 instance Outputable OccInfo where
513 -- only used for debugging; never parsed. KSW 1999-07
514 ppr NoOccInfo = empty
515 ppr (IAmALoopBreaker ro) = ptext (sLit "LoopBreaker") <> if ro then char '!' else empty
516 ppr IAmDead = ptext (sLit "Dead")
517 ppr (OneOcc inside_lam one_branch int_cxt)
518 = ptext (sLit "Once") <> pp_lam <> pp_br <> pp_args
520 pp_lam | inside_lam = char 'L'
522 pp_br | one_branch = empty
523 | otherwise = char '*'
524 pp_args | int_cxt = char '!'
527 instance Show OccInfo where
528 showsPrec p occ = showsPrecSDoc p (ppr occ)
531 %************************************************************************
533 Strictness indication
535 %************************************************************************
537 The strictness annotations on types in data type declarations
538 e.g. data T = MkT !Int !(Bool,Bool)
541 -------------------------
542 -- HsBang describes what the *programmer* wrote
543 -- This info is retained in the DataCon.dcStrictMarks field
544 data HsBang = HsNoBang
548 | HsUnpack -- {-# UNPACK #-} ! (GHC extension, meaning "unbox")
550 | HsUnpackFailed -- An UNPACK pragma that we could not make
551 -- use of, because the type isn't unboxable;
552 -- equivalant to HsStrict except for checkValidDataCon
553 deriving (Eq, Data, Typeable)
555 instance Outputable HsBang where
557 ppr HsStrict = char '!'
558 ppr HsUnpack = ptext (sLit "{-# UNPACK #-} !")
559 ppr HsUnpackFailed = ptext (sLit "{-# UNPACK (failed) #-} !")
561 isBanged :: HsBang -> Bool
562 isBanged HsNoBang = False
565 isMarkedUnboxed :: HsBang -> Bool
566 isMarkedUnboxed HsUnpack = True
567 isMarkedUnboxed _ = False
569 -------------------------
570 -- StrictnessMark is internal only, used to indicate strictness
571 -- of the DataCon *worker* fields
572 data StrictnessMark = MarkedStrict | NotMarkedStrict
574 instance Outputable StrictnessMark where
575 ppr MarkedStrict = ptext (sLit "!")
576 ppr NotMarkedStrict = empty
578 isMarkedStrict :: StrictnessMark -> Bool
579 isMarkedStrict NotMarkedStrict = False
580 isMarkedStrict _ = True -- All others are strict
584 %************************************************************************
586 Default method specfication
588 %************************************************************************
590 The DefMethSpec enumeration just indicates what sort of default method
591 is used for a class. It is generated from source code, and present in
592 interface files; it is converted to Class.DefMeth before begin put in a
596 data DefMethSpec = NoDM -- No default method
597 | VanillaDM -- Default method given with polymorphic code
598 | GenericDM -- Default method given with generic code
600 instance Outputable DefMethSpec where
602 ppr VanillaDM = ptext (sLit "{- Has default method -}")
603 ppr GenericDM = ptext (sLit "{- Has generic default method -}")
606 %************************************************************************
608 \subsection{Success flag}
610 %************************************************************************
613 data SuccessFlag = Succeeded | Failed
615 instance Outputable SuccessFlag where
616 ppr Succeeded = ptext (sLit "Succeeded")
617 ppr Failed = ptext (sLit "Failed")
619 successIf :: Bool -> SuccessFlag
620 successIf True = Succeeded
621 successIf False = Failed
623 succeeded, failed :: SuccessFlag -> Bool
624 succeeded Succeeded = True
625 succeeded Failed = False
627 failed Succeeded = False
632 %************************************************************************
634 \subsection{Activation}
636 %************************************************************************
638 When a rule or inlining is active
641 type PhaseNum = Int -- Compilation phase
642 -- Phases decrease towards zero
643 -- Zero is the last phase
647 | InitialPhase -- The first phase -- number = infinity!
649 instance Outputable CompilerPhase where
650 ppr (Phase n) = int n
651 ppr InitialPhase = ptext (sLit "InitialPhase")
653 data Activation = NeverActive
655 | ActiveBefore PhaseNum -- Active only *before* this phase
656 | ActiveAfter PhaseNum -- Active in this phase and later
657 deriving( Eq, Data, Typeable ) -- Eq used in comparing rules in HsDecls
659 data RuleMatchInfo = ConLike -- See Note [CONLIKE pragma]
661 deriving( Eq, Data, Typeable, Show )
662 -- Show needed for Lexer.x
664 data InlinePragma -- Note [InlinePragma]
666 { inl_inline :: InlineSpec
668 , inl_sat :: Maybe Arity -- Just n <=> Inline only when applied to n
669 -- explicit (non-type, non-dictionary) args
670 -- That is, inl_sat describes the number of *source-code*
671 -- arguments the thing must be applied to. We add on the
672 -- number of implicit, dictionary arguments when making
673 -- the InlineRule, and don't look at inl_sat further
675 , inl_act :: Activation -- Says during which phases inlining is allowed
677 , inl_rule :: RuleMatchInfo -- Should the function be treated like a constructor?
678 } deriving( Eq, Data, Typeable )
680 data InlineSpec -- What the user's INLINE pragama looked like
685 deriving( Eq, Data, Typeable, Show )
686 -- Show needed for Lexer.x
691 This data type mirrors what you can write in an INLINE or NOINLINE pragma in
694 If you write nothing at all, you get defaultInlinePragma:
696 inl_act = AlwaysActive
699 It's not possible to get that combination by *writing* something, so
700 if an Id has defaultInlinePragma it means the user didn't specify anything.
702 If inl_inline = True, then the Id should have an InlineRule unfolding.
704 Note [CONLIKE pragma]
705 ~~~~~~~~~~~~~~~~~~~~~
706 The ConLike constructor of a RuleMatchInfo is aimed at the following.
708 {-# RULE "r/cons" forall a as. r (a:as) = f (a+1) #-}
709 g b bs = let x = b:bs in ..x...x...(r x)...
710 Now, the rule applies to the (r x) term, because GHC "looks through"
711 the definition of 'x' to see that it is (b:bs).
714 {-# RULE "r/f" forall v. r (f v) = f (v+1) #-}
715 g v = let x = f v in ..x...x...(r x)...
716 Normally the (r x) would *not* match the rule, because GHC would be
717 scared about duplicating the redex (f v), so it does not "look
718 through" the bindings.
720 However the CONLIKE modifier says to treat 'f' like a constructor in
721 this situation, and "look through" the unfolding for x. So (r x)
722 fires, yielding (f (v+1)).
724 This is all controlled with a user-visible pragma:
725 {-# NOINLINE CONLIKE [1] f #-}
727 The main effects of CONLIKE are:
729 - The occurrence analyser (OccAnal) and simplifier (Simplify) treat
730 CONLIKE thing like constructors, by ANF-ing them
732 - New function coreUtils.exprIsExpandable is like exprIsCheap, but
733 additionally spots applications of CONLIKE functions
735 - A CoreUnfolding has a field that caches exprIsExpandable
737 - The rule matcher consults this field. See
738 Note [Expanding variables] in Rules.lhs.
741 isConLike :: RuleMatchInfo -> Bool
742 isConLike ConLike = True
745 isFunLike :: RuleMatchInfo -> Bool
746 isFunLike FunLike = True
749 isEmptyInlineSpec :: InlineSpec -> Bool
750 isEmptyInlineSpec EmptyInlineSpec = True
751 isEmptyInlineSpec _ = False
753 defaultInlinePragma, alwaysInlinePragma, neverInlinePragma, dfunInlinePragma
755 defaultInlinePragma = InlinePragma { inl_act = AlwaysActive
757 , inl_inline = EmptyInlineSpec
758 , inl_sat = Nothing }
760 alwaysInlinePragma = defaultInlinePragma { inl_inline = Inline }
761 neverInlinePragma = defaultInlinePragma { inl_act = NeverActive }
763 inlinePragmaSpec :: InlinePragma -> InlineSpec
764 inlinePragmaSpec = inl_inline
766 -- A DFun has an always-active inline activation so that
767 -- exprIsConApp_maybe can "see" its unfolding
768 -- (However, its actual Unfolding is a DFunUnfolding, which is
769 -- never inlined other than via exprIsConApp_maybe.)
770 dfunInlinePragma = defaultInlinePragma { inl_act = AlwaysActive
771 , inl_rule = ConLike }
773 isDefaultInlinePragma :: InlinePragma -> Bool
774 isDefaultInlinePragma (InlinePragma { inl_act = activation
775 , inl_rule = match_info
776 , inl_inline = inline })
777 = isEmptyInlineSpec inline && isAlwaysActive activation && isFunLike match_info
779 isInlinePragma :: InlinePragma -> Bool
780 isInlinePragma prag = case inl_inline prag of
784 isInlinablePragma :: InlinePragma -> Bool
785 isInlinablePragma prag = case inl_inline prag of
789 isAnyInlinePragma :: InlinePragma -> Bool
790 -- INLINE or INLINABLE
791 isAnyInlinePragma prag = case inl_inline prag of
796 inlinePragmaSat :: InlinePragma -> Maybe Arity
797 inlinePragmaSat = inl_sat
799 inlinePragmaActivation :: InlinePragma -> Activation
800 inlinePragmaActivation (InlinePragma { inl_act = activation }) = activation
802 inlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo
803 inlinePragmaRuleMatchInfo (InlinePragma { inl_rule = info }) = info
805 setInlinePragmaActivation :: InlinePragma -> Activation -> InlinePragma
806 setInlinePragmaActivation prag activation = prag { inl_act = activation }
808 setInlinePragmaRuleMatchInfo :: InlinePragma -> RuleMatchInfo -> InlinePragma
809 setInlinePragmaRuleMatchInfo prag info = prag { inl_rule = info }
811 instance Outputable Activation where
812 ppr AlwaysActive = brackets (ptext (sLit "ALWAYS"))
813 ppr NeverActive = brackets (ptext (sLit "NEVER"))
814 ppr (ActiveBefore n) = brackets (char '~' <> int n)
815 ppr (ActiveAfter n) = brackets (int n)
817 instance Outputable RuleMatchInfo where
818 ppr ConLike = ptext (sLit "CONLIKE")
819 ppr FunLike = ptext (sLit "FUNLIKE")
821 instance Outputable InlineSpec where
822 ppr Inline = ptext (sLit "INLINE")
823 ppr NoInline = ptext (sLit "NOINLINE")
824 ppr Inlinable = ptext (sLit "INLINABLE")
825 ppr EmptyInlineSpec = empty
827 instance Outputable InlinePragma where
828 ppr (InlinePragma { inl_inline = inline, inl_act = activation
829 , inl_rule = info, inl_sat = mb_arity })
830 = ppr inline <> pp_act inline activation <+> pp_sat <+> pp_info
832 pp_act Inline AlwaysActive = empty
833 pp_act NoInline NeverActive = empty
834 pp_act _ act = ppr act
836 pp_sat | Just ar <- mb_arity = parens (ptext (sLit "sat-args=") <> int ar)
838 pp_info | isFunLike info = empty
839 | otherwise = ppr info
841 isActive :: CompilerPhase -> Activation -> Bool
842 isActive InitialPhase AlwaysActive = True
843 isActive InitialPhase (ActiveBefore {}) = True
844 isActive InitialPhase _ = False
845 isActive (Phase p) act = isActiveIn p act
847 isActiveIn :: PhaseNum -> Activation -> Bool
848 isActiveIn _ NeverActive = False
849 isActiveIn _ AlwaysActive = True
850 isActiveIn p (ActiveAfter n) = p <= n
851 isActiveIn p (ActiveBefore n) = p > n
853 isNeverActive, isAlwaysActive, isEarlyActive :: Activation -> Bool
854 isNeverActive NeverActive = True
855 isNeverActive _ = False
857 isAlwaysActive AlwaysActive = True
858 isAlwaysActive _ = False
860 isEarlyActive AlwaysActive = True
861 isEarlyActive (ActiveBefore {}) = True
862 isEarlyActive _ = False