2 % (c) The University of Glasgow 2006
3 % (c) The GRASP/AQUA Project, Glasgow University, 1992-1998
6 The Desugarer: turning HsSyn into Core.
9 module Desugar ( deSugar, deSugarExpr ) where
21 import CoqPass ( coqPassCoreToString, coqPassCoreToCore )
27 import DsExpr () -- Forces DsExpr to be compiled; DsBinds only
28 -- depends on DsExpr.hi-boot.
34 import CoreMonad ( endPass, CoreToDo(..) )
46 %************************************************************************
48 %* The main function: deSugar
50 %************************************************************************
53 -- | Main entry point to the desugarer.
54 deSugar :: HscEnv -> ModLocation -> TcGblEnv -> IO (Messages, Maybe ModGuts)
55 -- Can modify PCS by faulting in more declarations
59 tcg_env@(TcGblEnv { tcg_mod = mod,
61 tcg_type_env = type_env,
62 tcg_imports = imports,
63 tcg_exports = exports,
65 tcg_rdr_env = rdr_env,
66 tcg_fix_env = fix_env,
67 tcg_inst_env = inst_env,
68 tcg_fam_inst_env = fam_inst_env,
72 tcg_imp_specs = imp_specs,
73 tcg_ev_binds = ev_binds,
78 tcg_fam_insts = fam_insts,
79 tcg_hpc = other_hpc_info })
81 = do { let dflags = hsc_dflags hsc_env
82 ; showPass dflags "Desugar"
84 -- Desugar the program
85 ; let export_set = availsToNameSet exports
86 ; let auto_scc = mkAutoScc dflags mod export_set
87 ; let target = hscTarget dflags
88 ; let hpcInfo = emptyHpcInfo other_hpc_info
92 return (emptyMessages,
93 Just ([], nilOL, [], [], NoStubs, hpcInfo, emptyModBreaks))
95 (binds_cvr,ds_hpc_info, modBreaks)
97 || target == HscInterpreted)
98 && (not (isHsBoot hsc_src))
99 then addCoverageTicksToBinds dflags mod mod_loc
100 (typeEnvTyCons type_env) binds
101 else return (binds, hpcInfo, emptyModBreaks)
102 initDs hsc_env mod rdr_env type_env $ do
103 do { ds_ev_binds <- dsEvBinds ev_binds
104 ; core_prs <- dsTopLHsBinds auto_scc binds_cvr
105 ; (spec_prs, spec_rules) <- dsImpSpecs imp_specs
106 ; (ds_fords, foreign_prs) <- dsForeigns fords
107 ; ds_rules <- mapMaybeM dsRule rules
108 ; ds_vects <- mapM dsVect vects
109 ; return ( ds_ev_binds
110 , foreign_prs `appOL` core_prs `appOL` spec_prs
111 , spec_rules ++ ds_rules, ds_vects
112 , ds_fords, ds_hpc_info, modBreaks) }
115 Nothing -> return (msgs, Nothing) ;
116 Just (ds_ev_binds, all_prs, all_rules, ds_vects, ds_fords,ds_hpc_info, modBreaks) -> do
118 { -- Add export flags to bindings
119 keep_alive <- readIORef keep_var
120 ; let (rules_for_locals, rules_for_imps)
121 = partition isLocalRule all_rules
122 final_prs = addExportFlagsAndRules target
123 export_set keep_alive rules_for_locals (fromOL all_prs)
125 final_pgm = combineEvBinds ds_ev_binds final_prs
126 -- Notice that we put the whole lot in a big Rec, even the foreign binds
127 -- When compiling PrelFloat, which defines data Float = F# Float#
128 -- we want F# to be in scope in the foreign marshalling code!
129 -- You might think it doesn't matter, but the simplifier brings all top-level
130 -- things into the in-scope set before simplifying; so we get no unfolding for F#!
132 -- Lint result if necessary, and print
133 ; dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared, before opt" $
134 (vcat [ pprCoreBindings final_pgm
135 , pprRules rules_for_imps ])
137 ; (ds_binds, ds_rules_for_imps) <- simpleOptPgm dflags final_pgm rules_for_imps
138 -- The simpleOptPgm gets rid of type
139 -- bindings plus any stupid dead code
141 ; dumpIfSet_dyn dflags Opt_D_coqpass "Coq Pass Output" $ text $ coqPassCoreToString ds_binds
143 ; ds_binds' <- if dopt Opt_F_coqpass dflags
144 then return $ coqPassCoreToCore ds_binds
147 ; dumpIfSet_dyn dflags Opt_D_dump_coqpass "After Coq Pass" (text $ showSDoc $ pprCoreBindings ds_binds')
149 ; endPass dflags CoreDesugar ds_binds' ds_rules_for_imps
151 ; let used_names = mkUsedNames tcg_env
152 ; deps <- mkDependencies tcg_env
154 ; let mod_guts = ModGuts {
156 mg_boot = isHsBoot hsc_src,
157 mg_exports = exports,
159 mg_used_names = used_names,
160 mg_dir_imps = imp_mods imports,
161 mg_rdr_env = rdr_env,
162 mg_fix_env = fix_env,
167 mg_fam_insts = fam_insts,
168 mg_inst_env = inst_env,
169 mg_fam_inst_env = fam_inst_env,
170 mg_rules = ds_rules_for_imps,
172 mg_foreign = ds_fords,
173 mg_hpc_info = ds_hpc_info,
174 mg_modBreaks = modBreaks,
175 mg_vect_decls = ds_vects,
176 mg_vect_info = noVectInfo
178 ; return (msgs, Just mod_guts)
181 dsImpSpecs :: [LTcSpecPrag] -> DsM (OrdList (Id,CoreExpr), [CoreRule])
183 = do { spec_prs <- mapMaybeM (dsSpec Nothing) imp_specs
184 ; let (spec_binds, spec_rules) = unzip spec_prs
185 ; return (concatOL spec_binds, spec_rules) }
187 combineEvBinds :: [DsEvBind] -> [(Id,CoreExpr)] -> [CoreBind]
188 -- Top-level bindings can include coercion bindings, but not via superclasses
189 -- See Note [Top-level evidence]
190 combineEvBinds [] val_prs
192 combineEvBinds (LetEvBind (NonRec b r) : bs) val_prs
193 | isId b = combineEvBinds bs ((b,r):val_prs)
194 | otherwise = NonRec b r : combineEvBinds bs val_prs
195 combineEvBinds (LetEvBind (Rec prs) : bs) val_prs
196 = combineEvBinds bs (prs ++ val_prs)
197 combineEvBinds (CaseEvBind x _ _ : _) _
198 = pprPanic "topEvBindPairs" (ppr x)
201 Note [Top-level evidence]
202 ~~~~~~~~~~~~~~~~~~~~~~~~~
203 Top-level evidence bindings may be mutually recursive with the top-level value
204 bindings, so we must put those in a Rec. But we can't put them *all* in a Rec
205 because the occurrence analyser doesn't teke account of type/coercion variables
206 when computing dependencies.
208 So we pull out the type/coercion variables (which are in dependency order),
213 mkAutoScc :: DynFlags -> Module -> NameSet -> AutoScc
214 mkAutoScc dflags mod exports
215 | not opt_SccProfilingOn -- No profiling
217 -- Add auto-scc on all top-level things
218 | dopt Opt_AutoSccsOnAllToplevs dflags
219 = AddSccs mod (\id -> not $ isDerivedOccName $ getOccName id)
220 -- See #1641. This is pretty yucky, but I can't see a better way
221 -- to identify compiler-generated Ids, and at least this should
223 -- Only on exported things
224 | dopt Opt_AutoSccsOnExportedToplevs dflags
225 = AddSccs mod (\id -> idName id `elemNameSet` exports)
229 deSugarExpr :: HscEnv
230 -> Module -> GlobalRdrEnv -> TypeEnv
232 -> IO (Messages, Maybe CoreExpr)
233 -- Prints its own errors; returns Nothing if error occurred
235 deSugarExpr hsc_env this_mod rdr_env type_env tc_expr = do
236 let dflags = hsc_dflags hsc_env
237 showPass dflags "Desugar"
240 (msgs, mb_core_expr) <- initDs hsc_env this_mod rdr_env type_env $
244 Nothing -> return (msgs, Nothing)
248 dumpIfSet_dyn dflags Opt_D_dump_ds "Desugared" (pprCoreExpr expr)
250 return (msgs, Just expr)
253 %************************************************************************
255 %* Add rules and export flags to binders
257 %************************************************************************
260 addExportFlagsAndRules
261 :: HscTarget -> NameSet -> NameSet -> [CoreRule]
262 -> [(Id, t)] -> [(Id, t)]
263 addExportFlagsAndRules target exports keep_alive rules prs
266 add_one bndr = add_rules name (add_export name bndr)
270 ---------- Rules --------
271 -- See Note [Attach rules to local ids]
272 -- NB: the binder might have some existing rules,
273 -- arising from specialisation pragmas
275 | Just rules <- lookupNameEnv rule_base name
276 = bndr `addIdSpecialisations` rules
279 rule_base = extendRuleBaseList emptyRuleBase rules
281 ---------- Export flag --------
282 -- See Note [Adding export flags]
284 | dont_discard name = setIdExported bndr
287 dont_discard :: Name -> Bool
288 dont_discard name = is_exported name
289 || name `elemNameSet` keep_alive
291 -- In interactive mode, we don't want to discard any top-level
292 -- entities at all (eg. do not inline them away during
293 -- simplification), and retain them all in the TypeEnv so they are
294 -- available from the command line.
296 -- isExternalName separates the user-defined top-level names from those
297 -- introduced by the type checker.
298 is_exported :: Name -> Bool
299 is_exported | target == HscInterpreted = isExternalName
300 | otherwise = (`elemNameSet` exports)
304 Note [Adding export flags]
305 ~~~~~~~~~~~~~~~~~~~~~~~~~~
306 Set the no-discard flag if either
307 a) the Id is exported
308 b) it's mentioned in the RHS of an orphan rule
309 c) it's in the keep-alive set
311 It means that the binding won't be discarded EVEN if the binding
312 ends up being trivial (v = w) -- the simplifier would usually just
313 substitute w for v throughout, but we don't apply the substitution to
314 the rules (maybe we should?), so this substitution would make the rule
317 You might wonder why exported Ids aren't already marked as such;
318 it's just because the type checker is rather busy already and
319 I didn't want to pass in yet another mapping.
321 Note [Attach rules to local ids]
322 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
323 Find the rules for locally-defined Ids; then we can attach them
324 to the binders in the top-level bindings
327 - It makes the rules easier to look up
328 - It means that transformation rules and specialisations for
329 locally defined Ids are handled uniformly
330 - It keeps alive things that are referred to only from a rule
331 (the occurrence analyser knows about rules attached to Ids)
332 - It makes sure that, when we apply a rule, the free vars
333 of the RHS are more likely to be in scope
334 - The imported rules are carried in the in-scope set
335 which is extended on each iteration by the new wave of
336 local binders; any rules which aren't on the binding will
340 %************************************************************************
342 %* Desugaring transformation rules
344 %************************************************************************
347 dsRule :: LRuleDecl Id -> DsM (Maybe CoreRule)
348 dsRule (L loc (HsRule name act vars lhs _tv_lhs rhs _fv_rhs))
350 do { let bndrs' = [var | RuleBndr (L _ var) <- vars]
352 ; lhs' <- unsetOptM Opt_EnableRewriteRules $
353 unsetOptM Opt_WarnIdentities $
354 dsLExpr lhs -- Note [Desugaring RULE left hand sides]
356 ; rhs' <- dsLExpr rhs
358 -- Substitute the dict bindings eagerly,
359 -- and take the body apart into a (f args) form
360 ; case decomposeRuleLhs bndrs' lhs' of {
361 Left msg -> do { warnDs msg; return Nothing } ;
362 Right (final_bndrs, fn_id, args) -> do
364 { let is_local = isLocalId fn_id
365 -- NB: isLocalId is False of implicit Ids. This is good becuase
366 -- we don't want to attach rules to the bindings of implicit Ids,
367 -- because they don't show up in the bindings until just before code gen
368 fn_name = idName fn_id
369 final_rhs = simpleOptExpr rhs' -- De-crap it
370 rule = mkRule False {- Not auto -} is_local
371 name act fn_name final_bndrs args final_rhs
376 Note [Desugaring RULE left hand sides]
377 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
378 For the LHS of a RULE we do *not* want to desugar
379 [x] to build (\cn. x `c` n)
380 We want to leave explicit lists simply as chains
381 of cons's. We can achieve that slightly indirectly by
382 switching off EnableRewriteRules. See DsExpr.dsExplicitList.
384 That keeps the desugaring of list comprehensions simple too.
386 Nor do we want to warn of conversion identities on the LHS;
387 the rule is precisly to optimise them:
388 {-# RULES "fromRational/id" fromRational = id :: Rational -> Rational #-}
391 %************************************************************************
393 %* Desugaring vectorisation declarations
395 %************************************************************************
398 dsVect :: LVectDecl Id -> DsM CoreVect
399 dsVect (L loc (HsVect v rhs))
401 do { rhs' <- fmapMaybeM dsLExpr rhs
402 ; return $ Vect (unLoc v) rhs'
404 -- dsVect (L loc (HsVect v Nothing))
405 -- = return $ Vect v Nothing
406 -- dsVect (L loc (HsVect v (Just rhs)))
407 -- = putSrcSpanDs loc $
408 -- do { rhs' <- dsLExpr rhs
409 -- ; return $ Vect v (Just rhs')