Refactor to combine two eqExpr functions
[ghc-hetmet.git] / compiler / coreSyn / CoreSyn.lhs
1 %
2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
4 %
5
6 \begin{code}
7
8 -- | CoreSyn holds all the main data types for use by for the Glasgow Haskell Compiler midsection
9 module CoreSyn (
10         -- * Main data types
11         Expr(..), Alt, Bind(..), AltCon(..), Arg, Note(..),
12         CoreExpr, CoreAlt, CoreBind, CoreArg, CoreBndr,
13         TaggedExpr, TaggedAlt, TaggedBind, TaggedArg, TaggedBndr(..),
14
15         -- ** 'Expr' construction
16         mkLets, mkLams,
17         mkApps, mkTyApps, mkVarApps,
18         
19         mkIntLit, mkIntLitInt,
20         mkWordLit, mkWordLitWord,
21         mkCharLit, mkStringLit,
22         mkFloatLit, mkFloatLitFloat,
23         mkDoubleLit, mkDoubleLitDouble,
24         
25         mkConApp, mkTyBind,
26         varToCoreExpr, varsToCoreExprs,
27
28         isTyVar, isId, cmpAltCon, cmpAlt, ltAlt,
29         
30         -- ** Simple 'Expr' access functions and predicates
31         bindersOf, bindersOfBinds, rhssOfBind, rhssOfAlts, 
32         collectBinders, collectTyBinders, collectValBinders, collectTyAndValBinders,
33         collectArgs, coreExprCc, flattenBinds, 
34
35         isValArg, isTypeArg, valArgCount, valBndrCount, isRuntimeArg, isRuntimeVar,
36
37         -- * Unfolding data types
38         Unfolding(..),  UnfoldingGuidance(..), UnfoldingSource(..),
39                 -- Abstract everywhere but in CoreUnfold.lhs
40         
41         -- ** Constructing 'Unfolding's
42         noUnfolding, evaldUnfolding, mkOtherCon,
43         unSaturatedOk, needSaturated, boringCxtOk, boringCxtNotOk,
44         
45         -- ** Predicates and deconstruction on 'Unfolding'
46         unfoldingTemplate, setUnfoldingTemplate, expandUnfolding_maybe,
47         maybeUnfoldingTemplate, otherCons, unfoldingArity,
48         isValueUnfolding, isEvaldUnfolding, isCheapUnfolding,
49         isExpandableUnfolding, isConLikeUnfolding, isCompulsoryUnfolding,
50         isInlineRule, isInlineRule_maybe, isClosedUnfolding, hasSomeUnfolding, 
51         isStableUnfolding, canUnfold, neverUnfoldGuidance, isInlineRuleSource,
52
53         -- * Strictness
54         seqExpr, seqExprs, seqUnfolding, 
55
56         -- * Annotated expression data types
57         AnnExpr, AnnExpr'(..), AnnBind(..), AnnAlt,
58         
59         -- ** Operations on annotations
60         deAnnotate, deAnnotate', deAnnAlt, collectAnnBndrs,
61
62         -- * Core rule data types
63         CoreRule(..),   -- CoreSubst, CoreTidy, CoreFVs, PprCore only
64         RuleName, IdUnfoldingFun,
65         
66         -- ** Operations on 'CoreRule's 
67         seqRules, ruleArity, ruleName, ruleIdName, ruleActivation_maybe,
68         setRuleIdName,
69         isBuiltinRule, isLocalRule
70     ) where
71
72 #include "HsVersions.h"
73
74 import CostCentre
75 import Var
76 import Type
77 import Coercion
78 import Name
79 import Literal
80 import DataCon
81 import BasicTypes
82 import FastString
83 import Outputable
84 import Util
85
86 import Data.Word
87
88 infixl 4 `mkApps`, `mkTyApps`, `mkVarApps`
89 -- Left associative, so that we can say (f `mkTyApps` xs `mkVarApps` ys)
90 \end{code}
91
92 %************************************************************************
93 %*                                                                      *
94 \subsection{The main data types}
95 %*                                                                      *
96 %************************************************************************
97
98 These data types are the heart of the compiler
99
100 \begin{code}
101 infixl 8 `App`  -- App brackets to the left
102
103 -- | This is the data type that represents GHCs core intermediate language. Currently
104 -- GHC uses System FC <http://research.microsoft.com/~simonpj/papers/ext-f/> for this purpose,
105 -- which is closely related to the simpler and better known System F <http://en.wikipedia.org/wiki/System_F>.
106 --
107 -- We get from Haskell source to this Core language in a number of stages:
108 --
109 -- 1. The source code is parsed into an abstract syntax tree, which is represented
110 --    by the data type 'HsExpr.HsExpr' with the names being 'RdrName.RdrNames'
111 --
112 -- 2. This syntax tree is /renamed/, which attaches a 'Unique.Unique' to every 'RdrName.RdrName'
113 --    (yielding a 'Name.Name') to disambiguate identifiers which are lexically identical. 
114 --    For example, this program:
115 --
116 -- @
117 --      f x = let f x = x + 1
118 --            in f (x - 2)
119 -- @
120 --
121 --    Would be renamed by having 'Unique's attached so it looked something like this:
122 --
123 -- @
124 --      f_1 x_2 = let f_3 x_4 = x_4 + 1
125 --                in f_3 (x_2 - 2)
126 -- @
127 --
128 -- 3. The resulting syntax tree undergoes type checking (which also deals with instantiating
129 --    type class arguments) to yield a 'HsExpr.HsExpr' type that has 'Id.Id' as it's names.
130 --
131 -- 4. Finally the syntax tree is /desugared/ from the expressive 'HsExpr.HsExpr' type into
132 --    this 'Expr' type, which has far fewer constructors and hence is easier to perform
133 --    optimization, analysis and code generation on.
134 --
135 -- The type parameter @b@ is for the type of binders in the expression tree.
136 data Expr b
137   = Var   Id                            -- ^ Variables
138   | Lit   Literal                       -- ^ Primitive literals
139   | App   (Expr b) (Arg b)              -- ^ Applications: note that the argument may be a 'Type'.
140                                         --
141                                         -- See "CoreSyn#let_app_invariant" for another invariant
142   | Lam   b (Expr b)                    -- ^ Lambda abstraction
143   | Let   (Bind b) (Expr b)             -- ^ Recursive and non recursive @let@s. Operationally
144                                         -- this corresponds to allocating a thunk for the things
145                                         -- bound and then executing the sub-expression.
146                                         -- 
147                                         -- #top_level_invariant#
148                                         -- #letrec_invariant#
149                                         --
150                                         -- The right hand sides of all top-level and recursive @let@s
151                                         -- /must/ be of lifted type (see "Type#type_classification" for
152                                         -- the meaning of /lifted/ vs. /unlifted/).
153                                         --
154                                         -- #let_app_invariant#
155                                         -- The right hand side of of a non-recursive 'Let' _and_ the argument of an 'App',
156                                         -- /may/ be of unlifted type, but only if the expression 
157                                         -- is ok-for-speculation.  This means that the let can be floated around 
158                                         -- without difficulty. For example, this is OK:
159                                         --
160                                         -- > y::Int# = x +# 1#
161                                         --
162                                         -- But this is not, as it may affect termination if the expression is floated out:
163                                         --
164                                         -- > y::Int# = fac 4#
165                                         --
166                                         -- In this situation you should use @case@ rather than a @let@. The function
167                                         -- 'CoreUtils.needsCaseBinding' can help you determine which to generate, or
168                                         -- alternatively use 'MkCore.mkCoreLet' rather than this constructor directly,
169                                         -- which will generate a @case@ if necessary
170                                         --
171                                         -- #type_let#
172                                         -- We allow a /non-recursive/ let to bind a type variable, thus:
173                                         --
174                                         -- > Let (NonRec tv (Type ty)) body
175                                         --
176                                         -- This can be very convenient for postponing type substitutions until
177                                         -- the next run of the simplifier.
178                                         --
179                                         -- At the moment, the rest of the compiler only deals with type-let
180                                         -- in a Let expression, rather than at top level.  We may want to revist
181                                         -- this choice.
182   | Case  (Expr b) b Type [Alt b]       -- ^ Case split. Operationally this corresponds to evaluating
183                                         -- the scrutinee (expression examined) to weak head normal form
184                                         -- and then examining at most one level of resulting constructor (i.e. you
185                                         -- cannot do nested pattern matching directly with this).
186                                         --
187                                         -- The binder gets bound to the value of the scrutinee,
188                                         -- and the 'Type' must be that of all the case alternatives
189                                         --
190                                         -- #case_invariants#
191                                         -- This is one of the more complicated elements of the Core language, and comes
192                                         -- with a number of restrictions:
193                                         --
194                                         -- The 'DEFAULT' case alternative must be first in the list, if it occurs at all.
195                                         --
196                                         -- The remaining cases are in order of increasing 
197                                         --      tag     (for 'DataAlts') or
198                                         --      lit     (for 'LitAlts').
199                                         -- This makes finding the relevant constructor easy, and makes comparison easier too.
200                                         --
201                                         -- The list of alternatives must be exhaustive. An /exhaustive/ case 
202                                         -- does not necessarily mention all constructors:
203                                         --
204                                         -- @
205                                         --      data Foo = Red | Green | Blue
206                                         -- ... case x of 
207                                         --      Red   -> True
208                                         --      other -> f (case x of 
209                                         --                      Green -> ...
210                                         --                      Blue  -> ... ) ...
211                                         -- @
212                                         --
213                                         -- The inner case does not need a @Red@ alternative, because @x@ can't be @Red@ at
214                                         -- that program point.
215   | Cast  (Expr b) Coercion             -- ^ Cast an expression to a particular type. This is used to implement @newtype@s
216                                         -- (a @newtype@ constructor or destructor just becomes a 'Cast' in Core) and GADTs.
217   | Note  Note (Expr b)                 -- ^ Notes. These allow general information to be
218                                         -- added to expressions in the syntax tree
219   | Type  Type                          -- ^ A type: this should only show up at the top
220                                         -- level of an Arg
221
222 -- | Type synonym for expressions that occur in function argument positions.
223 -- Only 'Arg' should contain a 'Type' at top level, general 'Expr' should not
224 type Arg b = Expr b
225
226 -- | A case split alternative. Consists of the constructor leading to the alternative,
227 -- the variables bound from the constructor, and the expression to be executed given that binding.
228 -- The default alternative is @(DEFAULT, [], rhs)@
229 type Alt b = (AltCon, [b], Expr b)
230
231 -- | A case alternative constructor (i.e. pattern match)
232 data AltCon = DataAlt DataCon   -- ^ A plain data constructor: @case e of { Foo x -> ... }@.
233                                 -- Invariant: the 'DataCon' is always from a @data@ type, and never from a @newtype@
234             | LitAlt  Literal   -- ^ A literal: @case e of { 1 -> ... }@
235             | DEFAULT           -- ^ Trivial alternative: @case e of { _ -> ... }@
236          deriving (Eq, Ord)
237
238 -- | Binding, used for top level bindings in a module and local bindings in a @let@.
239 data Bind b = NonRec b (Expr b)
240             | Rec [(b, (Expr b))]
241 \end{code}
242
243 -------------------------- CoreSyn INVARIANTS ---------------------------
244
245 Note [CoreSyn top-level invariant]
246 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
247 See #toplevel_invariant#
248
249 Note [CoreSyn letrec invariant]
250 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
251 See #letrec_invariant#
252
253 Note [CoreSyn let/app invariant]
254 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
255 See #let_app_invariant#
256
257 This is intially enforced by DsUtils.mkCoreLet and mkCoreApp
258
259 Note [CoreSyn case invariants]
260 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
261 See #case_invariants#
262
263 Note [CoreSyn let goal]
264 ~~~~~~~~~~~~~~~~~~~~~~~
265 * The simplifier tries to ensure that if the RHS of a let is a constructor
266   application, its arguments are trivial, so that the constructor can be
267   inlined vigorously.
268
269
270 Note [Type let]
271 ~~~~~~~~~~~~~~~
272 See #type_let#
273
274 \begin{code}
275
276 -- | Allows attaching extra information to points in expressions rather than e.g. identifiers.
277 data Note
278   = SCC CostCentre      -- ^ A cost centre annotation for profiling
279   | CoreNote String     -- ^ A generic core annotation, propagated but not used by GHC
280 \end{code}
281
282
283 %************************************************************************
284 %*                                                                      *
285 \subsection{Transformation rules}
286 %*                                                                      *
287 %************************************************************************
288
289 The CoreRule type and its friends are dealt with mainly in CoreRules,
290 but CoreFVs, Subst, PprCore, CoreTidy also inspect the representation.
291
292 \begin{code}
293 -- | A 'CoreRule' is:
294 --
295 -- * \"Local\" if the function it is a rule for is defined in the
296 --   same module as the rule itself.
297 --
298 -- * \"Orphan\" if nothing on the LHS is defined in the same module
299 --   as the rule itself
300 data CoreRule
301   = Rule { 
302         ru_name :: RuleName,            -- ^ Name of the rule, for communication with the user
303         ru_act  :: Activation,          -- ^ When the rule is active
304         
305         -- Rough-matching stuff
306         -- see comments with InstEnv.Instance( is_cls, is_rough )
307         ru_fn    :: Name,               -- ^ Name of the 'Id.Id' at the head of this rule
308         ru_rough :: [Maybe Name],       -- ^ Name at the head of each argument to the left hand side
309         
310         -- Proper-matching stuff
311         -- see comments with InstEnv.Instance( is_tvs, is_tys )
312         ru_bndrs :: [CoreBndr],         -- ^ Variables quantified over
313         ru_args  :: [CoreExpr],         -- ^ Left hand side arguments
314         
315         -- And the right-hand side
316         ru_rhs   :: CoreExpr,           -- ^ Right hand side of the rule
317                                         -- Occurrence info is guaranteed correct
318                                         -- See Note [OccInfo in unfoldings and rules]
319
320         -- Locality
321         ru_local :: Bool        -- ^ @True@ iff the fn at the head of the rule is
322                                 -- defined in the same module as the rule
323                                 -- and is not an implicit 'Id' (like a record selector,
324                                 -- class operation, or data constructor)
325
326                 -- NB: ru_local is *not* used to decide orphan-hood
327                 --      c.g. MkIface.coreRuleToIfaceRule
328     }
329
330   -- | Built-in rules are used for constant folding
331   -- and suchlike.  They have no free variables.
332   | BuiltinRule {               
333         ru_name  :: RuleName,   -- ^ As above
334         ru_fn    :: Name,       -- ^ As above
335         ru_nargs :: Int,        -- ^ Number of arguments that 'ru_try' consumes,
336                                 -- if it fires, including type arguments
337         ru_try  :: IdUnfoldingFun -> [CoreExpr] -> Maybe CoreExpr
338                 -- ^ This function does the rewrite.  It given too many
339                 -- arguments, it simply discards them; the returned 'CoreExpr'
340                 -- is just the rewrite of 'ru_fn' applied to the first 'ru_nargs' args
341     }
342                 -- See Note [Extra args in rule matching] in Rules.lhs
343
344 type IdUnfoldingFun = Id -> Unfolding
345 -- A function that embodies how to unfold an Id if you need
346 -- to do that in the Rule.  The reason we need to pass this info in
347 -- is that whether an Id is unfoldable depends on the simplifier phase
348
349 isBuiltinRule :: CoreRule -> Bool
350 isBuiltinRule (BuiltinRule {}) = True
351 isBuiltinRule _                = False
352
353 -- | The number of arguments the 'ru_fn' must be applied 
354 -- to before the rule can match on it
355 ruleArity :: CoreRule -> Int
356 ruleArity (BuiltinRule {ru_nargs = n}) = n
357 ruleArity (Rule {ru_args = args})      = length args
358
359 ruleName :: CoreRule -> RuleName
360 ruleName = ru_name
361
362 ruleActivation_maybe :: CoreRule -> Maybe Activation
363 ruleActivation_maybe (BuiltinRule { })       = Nothing
364 ruleActivation_maybe (Rule { ru_act = act }) = Just act
365
366 -- | The 'Name' of the 'Id.Id' at the head of the rule left hand side
367 ruleIdName :: CoreRule -> Name
368 ruleIdName = ru_fn
369
370 isLocalRule :: CoreRule -> Bool
371 isLocalRule = ru_local
372
373 -- | Set the 'Name' of the 'Id.Id' at the head of the rule left hand side
374 setRuleIdName :: Name -> CoreRule -> CoreRule
375 setRuleIdName nm ru = ru { ru_fn = nm }
376 \end{code}
377
378
379 %************************************************************************
380 %*                                                                      *
381                 Unfoldings
382 %*                                                                      *
383 %************************************************************************
384
385 The @Unfolding@ type is declared here to avoid numerous loops
386
387 \begin{code}
388 -- | Records the /unfolding/ of an identifier, which is approximately the form the
389 -- identifier would have if we substituted its definition in for the identifier.
390 -- This type should be treated as abstract everywhere except in "CoreUnfold"
391 data Unfolding
392   = NoUnfolding        -- ^ We have no information about the unfolding
393
394   | OtherCon [AltCon]  -- ^ It ain't one of these constructors.
395                        -- @OtherCon xs@ also indicates that something has been evaluated
396                        -- and hence there's no point in re-evaluating it.
397                        -- @OtherCon []@ is used even for non-data-type values
398                        -- to indicated evaluated-ness.  Notably:
399                        --
400                        -- > data C = C !(Int -> Int)
401                        -- > case x of { C f -> ... }
402                        --
403                        -- Here, @f@ gets an @OtherCon []@ unfolding.
404
405   | DFunUnfolding DataCon [CoreExpr]    
406                         -- The Unfolding of a DFunId
407                         --     df = /\a1..am. \d1..dn. MkD (op1 a1..am d1..dn)
408                         --                                 (op2 a1..am d1..dn)
409                         -- where Arity = n, the number of dict args to the dfun
410                         -- The [CoreExpr] are the superclasses and methods [op1,op2], 
411                         -- in positional order.
412                         -- They are usually variables, but can be trivial expressions
413                         -- instead (e.g. a type application).  
414
415   | CoreUnfolding {             -- An unfolding for an Id with no pragma, or perhaps a NOINLINE pragma
416                                 -- (For NOINLINE, the phase, if any, is in the InlinePragInfo for this Id.)
417         uf_tmpl       :: CoreExpr,        -- Template; occurrence info is correct
418         uf_src        :: UnfoldingSource, -- Where the unfolding came from
419         uf_is_top     :: Bool,          -- True <=> top level binding
420         uf_arity      :: Arity,         -- Number of value arguments expected
421         uf_is_value   :: Bool,          -- exprIsHNF template (cached); it is ok to discard a `seq` on
422                                         --      this variable
423         uf_is_conlike :: Bool,          -- True <=> application of constructor or CONLIKE function
424                                         --      Cached version of exprIsConLike
425         uf_is_cheap   :: Bool,          -- True <=> doesn't waste (much) work to expand inside an inlining
426                                         --      Cached version of exprIsCheap
427         uf_expandable :: Bool,          -- True <=> can expand in RULE matching
428                                         --      Cached version of exprIsExpandable
429         uf_guidance   :: UnfoldingGuidance      -- Tells about the *size* of the template.
430     }
431   -- ^ An unfolding with redundant cached information. Parameters:
432   --
433   --  uf_tmpl: Template used to perform unfolding; 
434   --           NB: Occurrence info is guaranteed correct: 
435   --               see Note [OccInfo in unfoldings and rules]
436   --
437   --  uf_is_top: Is this a top level binding?
438   --
439   --  uf_is_value: 'exprIsHNF' template (cached); it is ok to discard a 'seq' on
440   --     this variable
441   --
442   --  uf_is_cheap:  Does this waste only a little work if we expand it inside an inlining?
443   --     Basically this is a cached version of 'exprIsCheap'
444   --
445   --  uf_guidance:  Tells us about the /size/ of the unfolding template
446
447 ------------------------------------------------
448 data UnfoldingSource 
449   = InlineCompulsory   -- Something that *has* no binding, so you *must* inline it
450                        -- Only a few primop-like things have this property 
451                        -- (see MkId.lhs, calls to mkCompulsoryUnfolding).
452                        -- Inline absolutely always, however boring the context.
453
454   | InlineRule         -- From an {-# INLINE #-} pragma; See Note [InlineRules]
455
456   | InlineWrapper Id   -- This unfolding is a the wrapper in a 
457                        --     worker/wrapper split from the strictness analyser
458                        -- The Id is the worker-id
459                        -- Used to abbreviate the uf_tmpl in interface files
460                        --       which don't need to contain the RHS; 
461                        --       it can be derived from the strictness info
462
463   | InlineRhs          -- The current rhs of the function
464
465    -- For InlineRhs, the uf_tmpl is replaced each time around
466    -- For all the others we leave uf_tmpl alone
467
468
469 -- | 'UnfoldingGuidance' says when unfolding should take place
470 data UnfoldingGuidance
471   = UnfWhen {   -- Inline without thinking about the *size* of the uf_tmpl
472                 -- Used (a) for small *and* cheap unfoldings
473                 --      (b) for INLINE functions 
474                 -- See Note [INLINE for small functions] in CoreUnfold
475       ug_unsat_ok  :: Bool,     -- True <=> ok to inline even if unsaturated
476       ug_boring_ok :: Bool      -- True <=> ok to inline even if the context is boring
477     }
478
479   | UnfIfGoodArgs {     -- Arose from a normal Id; the info here is the
480                         -- result of a simple analysis of the RHS
481
482       ug_args ::  [Int],  -- Discount if the argument is evaluated.
483                           -- (i.e., a simplification will definitely
484                           -- be possible).  One elt of the list per *value* arg.
485
486       ug_size :: Int,     -- The "size" of the unfolding.
487
488       ug_res :: Int       -- Scrutinee discount: the discount to substract if the thing is in
489     }                     -- a context (case (thing args) of ...),
490                           -- (where there are the right number of arguments.)
491
492   | UnfNever        -- The RHS is big, so don't inline it
493
494 -- Constants for the UnfWhen constructor
495 needSaturated, unSaturatedOk :: Bool
496 needSaturated = False
497 unSaturatedOk = True
498
499 boringCxtNotOk, boringCxtOk :: Bool
500 boringCxtOk    = True
501 boringCxtNotOk = False
502
503 ------------------------------------------------
504 noUnfolding :: Unfolding
505 -- ^ There is no known 'Unfolding'
506 evaldUnfolding :: Unfolding
507 -- ^ This unfolding marks the associated thing as being evaluated
508
509 noUnfolding    = NoUnfolding
510 evaldUnfolding = OtherCon []
511
512 mkOtherCon :: [AltCon] -> Unfolding
513 mkOtherCon = OtherCon
514
515 seqUnfolding :: Unfolding -> ()
516 seqUnfolding (CoreUnfolding { uf_tmpl = e, uf_is_top = top, 
517                 uf_is_value = b1, uf_is_cheap = b2, 
518                 uf_expandable = b3, uf_is_conlike = b4,
519                 uf_arity = a, uf_guidance = g})
520   = seqExpr e `seq` top `seq` b1 `seq` a `seq` b2 `seq` b3 `seq` b4 `seq` seqGuidance g
521
522 seqUnfolding _ = ()
523
524 seqGuidance :: UnfoldingGuidance -> ()
525 seqGuidance (UnfIfGoodArgs ns n b) = n `seq` sum ns `seq` b `seq` ()
526 seqGuidance _                      = ()
527 \end{code}
528
529 \begin{code}
530 isInlineRuleSource :: UnfoldingSource -> Bool
531 isInlineRuleSource InlineCompulsory   = True
532 isInlineRuleSource InlineRule         = True
533 isInlineRuleSource (InlineWrapper {}) = True
534 isInlineRuleSource InlineRhs          = False
535  
536 -- | Retrieves the template of an unfolding: panics if none is known
537 unfoldingTemplate :: Unfolding -> CoreExpr
538 unfoldingTemplate = uf_tmpl
539
540 setUnfoldingTemplate :: Unfolding -> CoreExpr -> Unfolding
541 setUnfoldingTemplate unf rhs = unf { uf_tmpl = rhs }
542
543 -- | Retrieves the template of an unfolding if possible
544 maybeUnfoldingTemplate :: Unfolding -> Maybe CoreExpr
545 maybeUnfoldingTemplate (CoreUnfolding { uf_tmpl = expr })       = Just expr
546 maybeUnfoldingTemplate _                                        = Nothing
547
548 -- | The constructors that the unfolding could never be: 
549 -- returns @[]@ if no information is available
550 otherCons :: Unfolding -> [AltCon]
551 otherCons (OtherCon cons) = cons
552 otherCons _               = []
553
554 -- | Determines if it is certainly the case that the unfolding will
555 -- yield a value (something in HNF): returns @False@ if unsure
556 isValueUnfolding :: Unfolding -> Bool
557         -- Returns False for OtherCon
558 isValueUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
559 isValueUnfolding _                                          = False
560
561 -- | Determines if it possibly the case that the unfolding will
562 -- yield a value. Unlike 'isValueUnfolding' it returns @True@
563 -- for 'OtherCon'
564 isEvaldUnfolding :: Unfolding -> Bool
565         -- Returns True for OtherCon
566 isEvaldUnfolding (OtherCon _)                               = True
567 isEvaldUnfolding (CoreUnfolding { uf_is_value = is_evald }) = is_evald
568 isEvaldUnfolding _                                          = False
569
570 -- | @True@ if the unfolding is a constructor application, the application
571 -- of a CONLIKE function or 'OtherCon'
572 isConLikeUnfolding :: Unfolding -> Bool
573 isConLikeUnfolding (OtherCon _)                             = True
574 isConLikeUnfolding (CoreUnfolding { uf_is_conlike = con })  = con
575 isConLikeUnfolding _                                        = False
576
577 -- | Is the thing we will unfold into certainly cheap?
578 isCheapUnfolding :: Unfolding -> Bool
579 isCheapUnfolding (CoreUnfolding { uf_is_cheap = is_cheap }) = is_cheap
580 isCheapUnfolding _                                          = False
581
582 isExpandableUnfolding :: Unfolding -> Bool
583 isExpandableUnfolding (CoreUnfolding { uf_expandable = is_expable }) = is_expable
584 isExpandableUnfolding _                                              = False
585
586 expandUnfolding_maybe :: Unfolding -> Maybe CoreExpr
587 -- Expand an expandable unfolding; this is used in rule matching 
588 --   See Note [Expanding variables] in Rules.lhs
589 -- The key point here is that CONLIKE things can be expanded
590 expandUnfolding_maybe (CoreUnfolding { uf_expandable = True, uf_tmpl = rhs }) = Just rhs
591 expandUnfolding_maybe _                                                       = Nothing
592
593 isInlineRule :: Unfolding -> Bool
594 isInlineRule (CoreUnfolding { uf_src = src }) = isInlineRuleSource src
595 isInlineRule _                                = False
596
597 isInlineRule_maybe :: Unfolding -> Maybe (UnfoldingSource, Bool)
598 isInlineRule_maybe (CoreUnfolding { uf_src = src, uf_guidance = guide }) 
599    | isInlineRuleSource src
600    = Just (src, unsat_ok)
601    where
602      unsat_ok = case guide of
603                   UnfWhen unsat_ok _ -> unsat_ok
604                   _                  -> needSaturated
605 isInlineRule_maybe _ = Nothing
606
607 isCompulsoryUnfolding :: Unfolding -> Bool
608 isCompulsoryUnfolding (CoreUnfolding { uf_src = InlineCompulsory }) = True
609 isCompulsoryUnfolding _                                             = False
610
611 isStableUnfolding :: Unfolding -> Bool
612 -- True of unfoldings that should not be overwritten 
613 -- by a CoreUnfolding for the RHS of a let-binding
614 isStableUnfolding (CoreUnfolding { uf_src = src }) = isInlineRuleSource src
615 isStableUnfolding (DFunUnfolding {})               = True
616 isStableUnfolding _                                = False
617
618 unfoldingArity :: Unfolding -> Arity
619 unfoldingArity (CoreUnfolding { uf_arity = arity }) = arity
620 unfoldingArity _                                    = panic "unfoldingArity"
621
622 isClosedUnfolding :: Unfolding -> Bool          -- No free variables
623 isClosedUnfolding (CoreUnfolding {}) = False
624 isClosedUnfolding _                  = True
625
626 -- | Only returns False if there is no unfolding information available at all
627 hasSomeUnfolding :: Unfolding -> Bool
628 hasSomeUnfolding NoUnfolding = False
629 hasSomeUnfolding _           = True
630
631 neverUnfoldGuidance :: UnfoldingGuidance -> Bool
632 neverUnfoldGuidance UnfNever = True
633 neverUnfoldGuidance _        = False
634
635 canUnfold :: Unfolding -> Bool
636 canUnfold (CoreUnfolding { uf_guidance = g }) = not (neverUnfoldGuidance g)
637 canUnfold _                                   = False
638 \end{code}
639
640 Note [InlineRules]
641 ~~~~~~~~~~~~~~~~~
642 When you say 
643       {-# INLINE f #-}
644       f x = <rhs>
645 you intend that calls (f e) are replaced by <rhs>[e/x] So we
646 should capture (\x.<rhs>) in the Unfolding of 'f', and never meddle
647 with it.  Meanwhile, we can optimise <rhs> to our heart's content,
648 leaving the original unfolding intact in Unfolding of 'f'.
649
650 So the representation of an Unfolding has changed quite a bit
651 (see CoreSyn).  An INLINE pragma gives rise to an InlineRule 
652 unfolding.  
653
654 Moreover, it's only used when 'f' is applied to the
655 specified number of arguments; that is, the number of argument on 
656 the LHS of the '=' sign in the original source definition. 
657 For example, (.) is now defined in the libraries like this
658    {-# INLINE (.) #-}
659    (.) f g = \x -> f (g x)
660 so that it'll inline when applied to two arguments. If 'x' appeared
661 on the left, thus
662    (.) f g x = f (g x)
663 it'd only inline when applied to three arguments.  This slightly-experimental
664 change was requested by Roman, but it seems to make sense.
665
666 See also Note [Inlining an InlineRule] in CoreUnfold.
667
668
669 Note [OccInfo in unfoldings and rules]
670 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
671 In unfoldings and rules, we guarantee that the template is occ-analysed,
672 so that the occurence info on the binders is correct.  This is important,
673 because the Simplifier does not re-analyse the template when using it. If
674 the occurrence info is wrong
675   - We may get more simpifier iterations than necessary, because
676     once-occ info isn't there
677   - More seriously, we may get an infinite loop if there's a Rec
678     without a loop breaker marked
679
680
681 %************************************************************************
682 %*                                                                      *
683 \subsection{The main data type}
684 %*                                                                      *
685 %************************************************************************
686
687 \begin{code}
688 -- The Ord is needed for the FiniteMap used in the lookForConstructor
689 -- in SimplEnv.  If you declared that lookForConstructor *ignores*
690 -- constructor-applications with LitArg args, then you could get
691 -- rid of this Ord.
692
693 instance Outputable AltCon where
694   ppr (DataAlt dc) = ppr dc
695   ppr (LitAlt lit) = ppr lit
696   ppr DEFAULT      = ptext (sLit "__DEFAULT")
697
698 instance Show AltCon where
699   showsPrec p con = showsPrecSDoc p (ppr con)
700
701 cmpAlt :: Alt b -> Alt b -> Ordering
702 cmpAlt (con1, _, _) (con2, _, _) = con1 `cmpAltCon` con2
703
704 ltAlt :: Alt b -> Alt b -> Bool
705 ltAlt a1 a2 = (a1 `cmpAlt` a2) == LT
706
707 cmpAltCon :: AltCon -> AltCon -> Ordering
708 -- ^ Compares 'AltCon's within a single list of alternatives
709 cmpAltCon DEFAULT      DEFAULT     = EQ
710 cmpAltCon DEFAULT      _           = LT
711
712 cmpAltCon (DataAlt d1) (DataAlt d2) = dataConTag d1 `compare` dataConTag d2
713 cmpAltCon (DataAlt _)  DEFAULT      = GT
714 cmpAltCon (LitAlt  l1) (LitAlt  l2) = l1 `compare` l2
715 cmpAltCon (LitAlt _)   DEFAULT      = GT
716
717 cmpAltCon con1 con2 = WARN( True, text "Comparing incomparable AltCons" <+> 
718                                   ppr con1 <+> ppr con2 )
719                       LT
720 \end{code}
721
722 %************************************************************************
723 %*                                                                      *
724 \subsection{Useful synonyms}
725 %*                                                                      *
726 %************************************************************************
727
728 \begin{code}
729 -- | The common case for the type of binders and variables when
730 -- we are manipulating the Core language within GHC
731 type CoreBndr = Var
732 -- | Expressions where binders are 'CoreBndr's
733 type CoreExpr = Expr CoreBndr
734 -- | Argument expressions where binders are 'CoreBndr's
735 type CoreArg  = Arg  CoreBndr
736 -- | Binding groups where binders are 'CoreBndr's
737 type CoreBind = Bind CoreBndr
738 -- | Case alternatives where binders are 'CoreBndr's
739 type CoreAlt  = Alt  CoreBndr
740 \end{code}
741
742 %************************************************************************
743 %*                                                                      *
744 \subsection{Tagging}
745 %*                                                                      *
746 %************************************************************************
747
748 \begin{code}
749 -- | Binders are /tagged/ with a t
750 data TaggedBndr t = TB CoreBndr t       -- TB for "tagged binder"
751
752 type TaggedBind t = Bind (TaggedBndr t)
753 type TaggedExpr t = Expr (TaggedBndr t)
754 type TaggedArg  t = Arg  (TaggedBndr t)
755 type TaggedAlt  t = Alt  (TaggedBndr t)
756
757 instance Outputable b => Outputable (TaggedBndr b) where
758   ppr (TB b l) = char '<' <> ppr b <> comma <> ppr l <> char '>'
759
760 instance Outputable b => OutputableBndr (TaggedBndr b) where
761   pprBndr _ b = ppr b   -- Simple
762 \end{code}
763
764
765 %************************************************************************
766 %*                                                                      *
767 \subsection{Core-constructing functions with checking}
768 %*                                                                      *
769 %************************************************************************
770
771 \begin{code}
772 -- | Apply a list of argument expressions to a function expression in a nested fashion. Prefer to
773 -- use 'CoreUtils.mkCoreApps' if possible
774 mkApps    :: Expr b -> [Arg b]  -> Expr b
775 -- | Apply a list of type argument expressions to a function expression in a nested fashion
776 mkTyApps  :: Expr b -> [Type]   -> Expr b
777 -- | Apply a list of type or value variables to a function expression in a nested fashion
778 mkVarApps :: Expr b -> [Var] -> Expr b
779 -- | Apply a list of argument expressions to a data constructor in a nested fashion. Prefer to
780 -- use 'MkCore.mkCoreConApps' if possible
781 mkConApp      :: DataCon -> [Arg b] -> Expr b
782
783 mkApps    f args = foldl App                       f args
784 mkTyApps  f args = foldl (\ e a -> App e (Type a)) f args
785 mkVarApps f vars = foldl (\ e a -> App e (varToCoreExpr a)) f vars
786 mkConApp con args = mkApps (Var (dataConWorkId con)) args
787
788
789 -- | Create a machine integer literal expression of type @Int#@ from an @Integer@.
790 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
791 mkIntLit      :: Integer -> Expr b
792 -- | Create a machine integer literal expression of type @Int#@ from an @Int@.
793 -- If you want an expression of type @Int@ use 'MkCore.mkIntExpr'
794 mkIntLitInt   :: Int     -> Expr b
795
796 mkIntLit    n = Lit (mkMachInt n)
797 mkIntLitInt n = Lit (mkMachInt (toInteger n))
798
799 -- | Create a machine word literal expression of type  @Word#@ from an @Integer@.
800 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
801 mkWordLit     :: Integer -> Expr b
802 -- | Create a machine word literal expression of type  @Word#@ from a @Word@.
803 -- If you want an expression of type @Word@ use 'MkCore.mkWordExpr'
804 mkWordLitWord :: Word -> Expr b
805
806 mkWordLit     w = Lit (mkMachWord w)
807 mkWordLitWord w = Lit (mkMachWord (toInteger w))
808
809 -- | Create a machine character literal expression of type @Char#@.
810 -- If you want an expression of type @Char@ use 'MkCore.mkCharExpr'
811 mkCharLit :: Char -> Expr b
812 -- | Create a machine string literal expression of type @Addr#@.
813 -- If you want an expression of type @String@ use 'MkCore.mkStringExpr'
814 mkStringLit :: String -> Expr b
815
816 mkCharLit   c = Lit (mkMachChar c)
817 mkStringLit s = Lit (mkMachString s)
818
819 -- | Create a machine single precision literal expression of type @Float#@ from a @Rational@.
820 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
821 mkFloatLit :: Rational -> Expr b
822 -- | Create a machine single precision literal expression of type @Float#@ from a @Float@.
823 -- If you want an expression of type @Float@ use 'MkCore.mkFloatExpr'
824 mkFloatLitFloat :: Float -> Expr b
825
826 mkFloatLit      f = Lit (mkMachFloat f)
827 mkFloatLitFloat f = Lit (mkMachFloat (toRational f))
828
829 -- | Create a machine double precision literal expression of type @Double#@ from a @Rational@.
830 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
831 mkDoubleLit :: Rational -> Expr b
832 -- | Create a machine double precision literal expression of type @Double#@ from a @Double@.
833 -- If you want an expression of type @Double@ use 'MkCore.mkDoubleExpr'
834 mkDoubleLitDouble :: Double -> Expr b
835
836 mkDoubleLit       d = Lit (mkMachDouble d)
837 mkDoubleLitDouble d = Lit (mkMachDouble (toRational d))
838
839 -- | Bind all supplied binding groups over an expression in a nested let expression. Prefer to
840 -- use 'CoreUtils.mkCoreLets' if possible
841 mkLets        :: [Bind b] -> Expr b -> Expr b
842 -- | Bind all supplied binders over an expression in a nested lambda expression. Prefer to
843 -- use 'CoreUtils.mkCoreLams' if possible
844 mkLams        :: [b] -> Expr b -> Expr b
845
846 mkLams binders body = foldr Lam body binders
847 mkLets binds body   = foldr Let body binds
848
849
850 -- | Create a binding group where a type variable is bound to a type. Per "CoreSyn#type_let",
851 -- this can only be used to bind something in a non-recursive @let@ expression
852 mkTyBind :: TyVar -> Type -> CoreBind
853 mkTyBind tv ty      = NonRec tv (Type ty)
854
855 -- | Convert a binder into either a 'Var' or 'Type' 'Expr' appropriately
856 varToCoreExpr :: CoreBndr -> Expr b
857 varToCoreExpr v | isId v = Var v
858                 | otherwise = Type (mkTyVarTy v)
859
860 varsToCoreExprs :: [CoreBndr] -> [Expr b]
861 varsToCoreExprs vs = map varToCoreExpr vs
862 \end{code}
863
864
865 %************************************************************************
866 %*                                                                      *
867 \subsection{Simple access functions}
868 %*                                                                      *
869 %************************************************************************
870
871 \begin{code}
872 -- | Extract every variable by this group
873 bindersOf  :: Bind b -> [b]
874 bindersOf (NonRec binder _) = [binder]
875 bindersOf (Rec pairs)       = [binder | (binder, _) <- pairs]
876
877 -- | 'bindersOf' applied to a list of binding groups
878 bindersOfBinds :: [Bind b] -> [b]
879 bindersOfBinds binds = foldr ((++) . bindersOf) [] binds
880
881 rhssOfBind :: Bind b -> [Expr b]
882 rhssOfBind (NonRec _ rhs) = [rhs]
883 rhssOfBind (Rec pairs)    = [rhs | (_,rhs) <- pairs]
884
885 rhssOfAlts :: [Alt b] -> [Expr b]
886 rhssOfAlts alts = [e | (_,_,e) <- alts]
887
888 -- | Collapse all the bindings in the supplied groups into a single
889 -- list of lhs\/rhs pairs suitable for binding in a 'Rec' binding group
890 flattenBinds :: [Bind b] -> [(b, Expr b)]
891 flattenBinds (NonRec b r : binds) = (b,r) : flattenBinds binds
892 flattenBinds (Rec prs1   : binds) = prs1 ++ flattenBinds binds
893 flattenBinds []                   = []
894 \end{code}
895
896 \begin{code}
897 -- | We often want to strip off leading lambdas before getting down to
898 -- business. This function is your friend.
899 collectBinders               :: Expr b -> ([b],         Expr b)
900 -- | Collect as many type bindings as possible from the front of a nested lambda
901 collectTyBinders             :: CoreExpr -> ([TyVar],     CoreExpr)
902 -- | Collect as many value bindings as possible from the front of a nested lambda
903 collectValBinders            :: CoreExpr -> ([Id],        CoreExpr)
904 -- | Collect type binders from the front of the lambda first, 
905 -- then follow up by collecting as many value bindings as possible
906 -- from the resulting stripped expression
907 collectTyAndValBinders       :: CoreExpr -> ([TyVar], [Id], CoreExpr)
908
909 collectBinders expr
910   = go [] expr
911   where
912     go bs (Lam b e) = go (b:bs) e
913     go bs e          = (reverse bs, e)
914
915 collectTyAndValBinders expr
916   = (tvs, ids, body)
917   where
918     (tvs, body1) = collectTyBinders expr
919     (ids, body)  = collectValBinders body1
920
921 collectTyBinders expr
922   = go [] expr
923   where
924     go tvs (Lam b e) | isTyVar b = go (b:tvs) e
925     go tvs e                     = (reverse tvs, e)
926
927 collectValBinders expr
928   = go [] expr
929   where
930     go ids (Lam b e) | isId b = go (b:ids) e
931     go ids body               = (reverse ids, body)
932 \end{code}
933
934 \begin{code}
935 -- | Takes a nested application expression and returns the the function
936 -- being applied and the arguments to which it is applied
937 collectArgs :: Expr b -> (Expr b, [Arg b])
938 collectArgs expr
939   = go expr []
940   where
941     go (App f a) as = go f (a:as)
942     go e         as = (e, as)
943 \end{code}
944
945 \begin{code}
946 -- | Gets the cost centre enclosing an expression, if any.
947 -- It looks inside lambdas because @(scc \"foo\" \\x.e) = \\x. scc \"foo\" e@
948 coreExprCc :: Expr b -> CostCentre
949 coreExprCc (Note (SCC cc) _)   = cc
950 coreExprCc (Note _ e)          = coreExprCc e
951 coreExprCc (Lam _ e)           = coreExprCc e
952 coreExprCc _                   = noCostCentre
953 \end{code}
954
955 %************************************************************************
956 %*                                                                      *
957 \subsection{Predicates}
958 %*                                                                      *
959 %************************************************************************
960
961 At one time we optionally carried type arguments through to runtime.
962 @isRuntimeVar v@ returns if (Lam v _) really becomes a lambda at runtime,
963 i.e. if type applications are actual lambdas because types are kept around
964 at runtime.  Similarly isRuntimeArg.  
965
966 \begin{code}
967 -- | Will this variable exist at runtime?
968 isRuntimeVar :: Var -> Bool
969 isRuntimeVar = isId 
970
971 -- | Will this argument expression exist at runtime?
972 isRuntimeArg :: CoreExpr -> Bool
973 isRuntimeArg = isValArg
974
975 -- | Returns @False@ iff the expression is a 'Type' expression at its top level
976 isValArg :: Expr b -> Bool
977 isValArg (Type _) = False
978 isValArg _        = True
979
980 -- | Returns @True@ iff the expression is a 'Type' expression at its top level
981 isTypeArg :: Expr b -> Bool
982 isTypeArg (Type _) = True
983 isTypeArg _        = False
984
985 -- | The number of binders that bind values rather than types
986 valBndrCount :: [CoreBndr] -> Int
987 valBndrCount = count isId
988
989 -- | The number of argument expressions that are values rather than types at their top level
990 valArgCount :: [Arg b] -> Int
991 valArgCount = count isValArg
992 \end{code}
993
994
995 %************************************************************************
996 %*                                                                      *
997 \subsection{Seq stuff}
998 %*                                                                      *
999 %************************************************************************
1000
1001 \begin{code}
1002 seqExpr :: CoreExpr -> ()
1003 seqExpr (Var v)         = v `seq` ()
1004 seqExpr (Lit lit)       = lit `seq` ()
1005 seqExpr (App f a)       = seqExpr f `seq` seqExpr a
1006 seqExpr (Lam b e)       = seqBndr b `seq` seqExpr e
1007 seqExpr (Let b e)       = seqBind b `seq` seqExpr e
1008 seqExpr (Case e b t as) = seqExpr e `seq` seqBndr b `seq` seqType t `seq` seqAlts as
1009 seqExpr (Cast e co)     = seqExpr e `seq` seqType co
1010 seqExpr (Note n e)      = seqNote n `seq` seqExpr e
1011 seqExpr (Type t)        = seqType t
1012
1013 seqExprs :: [CoreExpr] -> ()
1014 seqExprs [] = ()
1015 seqExprs (e:es) = seqExpr e `seq` seqExprs es
1016
1017 seqNote :: Note -> ()
1018 seqNote (CoreNote s)   = s `seq` ()
1019 seqNote _              = ()
1020
1021 seqBndr :: CoreBndr -> ()
1022 seqBndr b = b `seq` ()
1023
1024 seqBndrs :: [CoreBndr] -> ()
1025 seqBndrs [] = ()
1026 seqBndrs (b:bs) = seqBndr b `seq` seqBndrs bs
1027
1028 seqBind :: Bind CoreBndr -> ()
1029 seqBind (NonRec b e) = seqBndr b `seq` seqExpr e
1030 seqBind (Rec prs)    = seqPairs prs
1031
1032 seqPairs :: [(CoreBndr, CoreExpr)] -> ()
1033 seqPairs [] = ()
1034 seqPairs ((b,e):prs) = seqBndr b `seq` seqExpr e `seq` seqPairs prs
1035
1036 seqAlts :: [CoreAlt] -> ()
1037 seqAlts [] = ()
1038 seqAlts ((c,bs,e):alts) = c `seq` seqBndrs bs `seq` seqExpr e `seq` seqAlts alts
1039
1040 seqRules :: [CoreRule] -> ()
1041 seqRules [] = ()
1042 seqRules (Rule { ru_bndrs = bndrs, ru_args = args, ru_rhs = rhs } : rules) 
1043   = seqBndrs bndrs `seq` seqExprs (rhs:args) `seq` seqRules rules
1044 seqRules (BuiltinRule {} : rules) = seqRules rules
1045 \end{code}
1046
1047 %************************************************************************
1048 %*                                                                      *
1049 \subsection{Annotated core}
1050 %*                                                                      *
1051 %************************************************************************
1052
1053 \begin{code}
1054 -- | Annotated core: allows annotation at every node in the tree
1055 type AnnExpr bndr annot = (annot, AnnExpr' bndr annot)
1056
1057 -- | A clone of the 'Expr' type but allowing annotation at every tree node
1058 data AnnExpr' bndr annot
1059   = AnnVar      Id
1060   | AnnLit      Literal
1061   | AnnLam      bndr (AnnExpr bndr annot)
1062   | AnnApp      (AnnExpr bndr annot) (AnnExpr bndr annot)
1063   | AnnCase     (AnnExpr bndr annot) bndr Type [AnnAlt bndr annot]
1064   | AnnLet      (AnnBind bndr annot) (AnnExpr bndr annot)
1065   | AnnCast     (AnnExpr bndr annot) Coercion
1066   | AnnNote     Note (AnnExpr bndr annot)
1067   | AnnType     Type
1068
1069 -- | A clone of the 'Alt' type but allowing annotation at every tree node
1070 type AnnAlt bndr annot = (AltCon, [bndr], AnnExpr bndr annot)
1071
1072 -- | A clone of the 'Bind' type but allowing annotation at every tree node
1073 data AnnBind bndr annot
1074   = AnnNonRec bndr (AnnExpr bndr annot)
1075   | AnnRec    [(bndr, AnnExpr bndr annot)]
1076 \end{code}
1077
1078 \begin{code}
1079 deAnnotate :: AnnExpr bndr annot -> Expr bndr
1080 deAnnotate (_, e) = deAnnotate' e
1081
1082 deAnnotate' :: AnnExpr' bndr annot -> Expr bndr
1083 deAnnotate' (AnnType t)           = Type t
1084 deAnnotate' (AnnVar  v)           = Var v
1085 deAnnotate' (AnnLit  lit)         = Lit lit
1086 deAnnotate' (AnnLam  binder body) = Lam binder (deAnnotate body)
1087 deAnnotate' (AnnApp  fun arg)     = App (deAnnotate fun) (deAnnotate arg)
1088 deAnnotate' (AnnCast e co)        = Cast (deAnnotate e) co
1089 deAnnotate' (AnnNote note body)   = Note note (deAnnotate body)
1090
1091 deAnnotate' (AnnLet bind body)
1092   = Let (deAnnBind bind) (deAnnotate body)
1093   where
1094     deAnnBind (AnnNonRec var rhs) = NonRec var (deAnnotate rhs)
1095     deAnnBind (AnnRec pairs) = Rec [(v,deAnnotate rhs) | (v,rhs) <- pairs]
1096
1097 deAnnotate' (AnnCase scrut v t alts)
1098   = Case (deAnnotate scrut) v t (map deAnnAlt alts)
1099
1100 deAnnAlt :: AnnAlt bndr annot -> Alt bndr
1101 deAnnAlt (con,args,rhs) = (con,args,deAnnotate rhs)
1102 \end{code}
1103
1104 \begin{code}
1105 -- | As 'collectBinders' but for 'AnnExpr' rather than 'Expr'
1106 collectAnnBndrs :: AnnExpr bndr annot -> ([bndr], AnnExpr bndr annot)
1107 collectAnnBndrs e
1108   = collect [] e
1109   where
1110     collect bs (_, AnnLam b body) = collect (b:bs) body
1111     collect bs body               = (reverse bs, body)
1112 \end{code}