[project @ 1999-06-23 10:33:03 by simonmar]
[ghc-hetmet.git] / ghc / compiler / main / CmdLineOpts.lhs
1 %
2 % (c) The AQUA Project, Glasgow University, 1996-98
3 %
4 \section[CmdLineOpts]{Things to do with command-line options}
5
6 \begin{code}
7 module CmdLineOpts (
8         CoreToDo(..),
9         SimplifierSwitch(..),
10         StgToDo(..),
11         SwitchResult(..),
12         classifyOpts,
13
14         intSwitchSet,
15         switchIsOn,
16
17         src_filename,
18
19         -- debugging opts
20         opt_D_dump_absC,
21         opt_D_dump_asm,
22         opt_D_dump_cpranal,
23         opt_D_dump_cse,
24         opt_D_dump_deriv,
25         opt_D_dump_ds,
26         opt_D_dump_flatC,
27         opt_D_dump_foreign,
28         opt_D_dump_inlinings,
29         opt_D_dump_occur_anal,
30         opt_D_dump_parsed,
31         opt_D_dump_realC,
32         opt_D_dump_rn,
33         opt_D_dump_rules,
34         opt_D_dump_simpl,
35         opt_D_dump_simpl_iterations,
36         opt_D_dump_simpl_stats,
37         opt_D_dump_spec,
38         opt_D_dump_stg,
39         opt_D_dump_stranal,
40         opt_D_dump_tc,
41         opt_D_dump_usagesp,
42         opt_D_dump_worker_wrapper,
43         opt_D_show_passes,
44         opt_D_dump_rn_trace,
45         opt_D_dump_rn_stats,
46         opt_D_source_stats,
47         opt_D_verbose_core2core,
48         opt_D_verbose_stg2stg,
49         opt_DoCoreLinting,
50         opt_DoStgLinting,
51         opt_DoUSPLinting,
52         opt_PprStyle_Debug,
53         opt_PprStyle_NoPrags,
54         opt_PprUserLength,
55
56         -- warning opts
57         opt_WarnDuplicateExports,
58         opt_WarnHiShadows,
59         opt_WarnIncompletePatterns,
60         opt_WarnMissingMethods,
61         opt_WarnMissingSigs,
62         opt_WarnNameShadowing,
63         opt_WarnOverlappingPatterns,
64         opt_WarnSimplePatterns,
65         opt_WarnTypeDefaults,
66         opt_WarnUnusedBinds,
67         opt_WarnUnusedImports,
68         opt_WarnUnusedMatches,
69
70         -- profiling opts
71         opt_AutoSccsOnAllToplevs,
72         opt_AutoSccsOnExportedToplevs,
73         opt_AutoSccsOnIndividualCafs,
74         opt_AutoSccsOnDicts,
75         opt_SccGroup,
76         opt_SccProfilingOn,
77         opt_DoTickyProfiling,
78
79         -- language opts
80         opt_AllStrict,
81         opt_DictsStrict,
82         opt_MaxContextReductionDepth,
83         opt_AllowOverlappingInstances,
84         opt_AllowUndecidableInstances,
85         opt_GlasgowExts,
86         opt_IrrefutableTuples,
87         opt_NumbersStrict,
88         opt_Parallel,
89
90         -- optimisation opts
91         opt_DoEtaReduction,
92         opt_DoSemiTagging,
93         opt_FoldrBuildOn,
94         opt_LiberateCaseThreshold,
95         opt_NoPreInlining,
96         opt_StgDoLetNoEscapes,
97         opt_UnfoldCasms,
98         opt_UsageSPOn,
99         opt_UnboxStrictFields,
100         opt_SimplNoPreInlining,
101         opt_SimplDoEtaReduction,
102         opt_SimplDoCaseElim,
103         opt_SimplDoLambdaEtaExpansion,
104         opt_SimplCaseOfCase,
105         opt_SimplCaseMerge,
106         opt_SimplLetToCase,
107         opt_SimplPedanticBottoms,
108
109         -- Unfolding control
110         opt_UF_HiFileThreshold,
111         opt_UF_CreationThreshold,
112         opt_UF_UseThreshold,
113         opt_UF_ScrutConDiscount,
114         opt_UF_FunAppDiscount,
115         opt_UF_PrimArgDiscount,
116         opt_UF_KeenessFactor,
117         opt_UF_CheapOp,
118         opt_UF_DearOp,
119         opt_UF_NoRepLit,
120
121         -- misc opts
122         opt_CompilingPrelude,
123         opt_EmitCExternDecls,
124         opt_EnsureSplittableC,
125         opt_GranMacros,
126         opt_HiMap,
127         opt_HiVersion,
128         opt_HistorySize,
129         opt_IgnoreAsserts,
130         opt_IgnoreIfacePragmas,
131         opt_NoHiCheck,
132         opt_NoImplicitPrelude,
133         opt_OmitBlackHoling,
134         opt_OmitInterfacePragmas,
135         opt_ProduceC,
136         opt_ProduceExportCStubs,
137         opt_ProduceExportHStubs,
138         opt_ProduceHi,
139         opt_ProduceS,
140         opt_NoPruneDecls,
141         opt_ReportCompile,
142         opt_SourceUnchanged,
143         opt_Static,
144         opt_Unregisterised,
145         opt_Verbose,
146
147         -- Code generation
148         opt_UseVanillaRegs,
149         opt_UseFloatRegs,
150         opt_UseDoubleRegs,
151         opt_UseLongRegs
152     ) where
153
154 #include "HsVersions.h"
155
156 import Array    ( array, (//) )
157 import GlaExts
158 import Argv
159 import Constants        -- Default values for some flags
160
161 import FastString       ( headFS )
162 import Maybes           ( assocMaybe, firstJust, maybeToBool )
163 import Panic            ( panic, panic# )
164
165 #if __GLASGOW_HASKELL__ < 301
166 import ArrBase  ( Array(..) )
167 #else
168 import PrelArr  ( Array(..) )
169 #endif
170 \end{code}
171
172 A command-line {\em switch} is (generally) either on or off; e.g., the
173 ``verbose'' (-v) switch is either on or off.  (The \tr{-G<group>}
174 switch is an exception; it's set to a string, or nothing.)
175
176 A list of {\em ToDo}s is things to be done in a particular part of
177 processing.  A (fictitious) example for the Core-to-Core simplifier
178 might be: run the simplifier, then run the strictness analyser, then
179 run the simplifier again (three ``todos'').
180
181 There are three ``to-do processing centers'' at the moment.  In the
182 main loop (\tr{main/Main.lhs}), in the Core-to-Core processing loop
183 (\tr{simplCore/SimplCore.lhs), and in the STG-to-STG processing loop
184 (\tr{simplStg/SimplStg.lhs}).
185
186
187 %************************************************************************
188 %*                                                                      *
189 \subsection{Datatypes associated with command-line options}
190 %*                                                                      *
191 %************************************************************************
192
193 \begin{code}
194 data SwitchResult
195   = SwBool      Bool            -- on/off
196   | SwString    FAST_STRING     -- nothing or a String
197   | SwInt       Int             -- nothing or an Int
198 \end{code}
199
200 \begin{code}
201 data CoreToDo           -- These are diff core-to-core passes,
202                         -- which may be invoked in any order,
203                         -- as many times as you like.
204
205   = CoreDoSimplify      -- The core-to-core simplifier.
206         (SimplifierSwitch -> SwitchResult)
207                         -- Each run of the simplifier can take a different
208                         -- set of simplifier-specific flags.
209   | CoreDoFloatInwards
210   | CoreDoFullLaziness
211   | CoreLiberateCase
212   | CoreDoPrintCore
213   | CoreDoStaticArgs
214   | CoreDoStrictness
215   | CoreDoWorkerWrapper
216   | CoreDoSpecialising
217   | CoreDoUSPInf
218   | CoreDoCPResult 
219   | CoreCSE
220 \end{code}
221
222 \begin{code}
223 data StgToDo
224   = StgDoStaticArgs
225   | StgDoUpdateAnalysis
226   | StgDoLambdaLift
227   | StgDoMassageForProfiling  -- should be (next to) last
228   -- There's also setStgVarInfo, but its absolute "lastness"
229   -- is so critical that it is hardwired in (no flag).
230   | D_stg_stats
231 \end{code}
232
233 \begin{code}
234 data SimplifierSwitch
235   = MaxSimplifierIterations Int
236   | SimplInlinePhase Int
237 \end{code}
238
239 %************************************************************************
240 %*                                                                      *
241 \subsection{Classifying command-line options}
242 %*                                                                      *
243 %************************************************************************
244
245 \begin{code}
246 lookUp           :: FAST_STRING -> Bool
247 lookup_int       :: String -> Maybe Int
248 lookup_def_int   :: String -> Int -> Int
249 lookup_def_float :: String -> Float -> Float
250 lookup_str       :: String -> Maybe String
251
252 lookUp     sw = maybeToBool (assoc_opts sw)
253         
254 lookup_str sw = firstJust (map (startsWith sw) unpacked_opts)
255
256 lookup_int sw = case (lookup_str sw) of
257                   Nothing -> Nothing
258                   Just xx -> Just (read xx)
259
260 lookup_def_int sw def = case (lookup_str sw) of
261                             Nothing -> def              -- Use default
262                             Just xx -> read xx
263
264 lookup_def_float sw def = case (lookup_str sw) of
265                             Nothing -> def              -- Use default
266                             Just xx -> read xx
267
268 assoc_opts    = assocMaybe [ (a, True) | a <- argv ]
269 unpacked_opts = map _UNPK_ argv
270
271 {-
272  Putting the compiler options into temporary at-files
273  may turn out to be necessary later on if we turn hsc into
274  a pure Win32 application where I think there's a command-line
275  length limit of 255. unpacked_opts understands the @ option.
276
277 assoc_opts    = assocMaybe [ (_PK_ a, True) | a <- unpacked_opts ]
278
279 unpacked_opts :: [String]
280 unpacked_opts =
281   concat $
282   map (expandAts) $
283   map _UNPK_ argv
284   where
285    expandAts ('@':fname) = words (unsafePerformIO (readFile fname))
286    expandAts l = [l]
287 -}
288 \end{code}
289
290 \begin{code}
291 src_filename :: FAST_STRING
292 src_filename = case argv of
293                   filename : rest | headFS filename /= '-' -> filename
294                   otherwise -> panic "no filename"
295 \end{code}
296
297 \begin{code}
298 -- debugging opts
299 opt_D_dump_absC                 = lookUp  SLIT("-ddump-absC")
300 opt_D_dump_asm                  = lookUp  SLIT("-ddump-asm")
301 opt_D_dump_cpranal              = lookUp  SLIT("-ddump-cpranalyse")
302 opt_D_dump_deriv                = lookUp  SLIT("-ddump-deriv")
303 opt_D_dump_ds                   = lookUp  SLIT("-ddump-ds")
304 opt_D_dump_flatC                = lookUp  SLIT("-ddump-flatC")
305 opt_D_dump_foreign              = lookUp  SLIT("-ddump-foreign-stubs")
306 opt_D_dump_inlinings            = lookUp  SLIT("-ddump-inlinings")
307 opt_D_dump_occur_anal           = lookUp  SLIT("-ddump-occur-anal")
308 opt_D_dump_parsed               = lookUp  SLIT("-ddump-parsed")
309 opt_D_dump_realC                = lookUp  SLIT("-ddump-realC")
310 opt_D_dump_rn                   = lookUp  SLIT("-ddump-rn")
311 opt_D_dump_simpl                = lookUp  SLIT("-ddump-simpl")
312 opt_D_dump_simpl_iterations     = lookUp  SLIT("-ddump-simpl-iterations")
313 opt_D_dump_spec                 = lookUp  SLIT("-ddump-spec")
314 opt_D_dump_stg                  = lookUp  SLIT("-ddump-stg")
315 opt_D_dump_stranal              = lookUp  SLIT("-ddump-stranal")
316 opt_D_dump_tc                   = lookUp  SLIT("-ddump-tc")
317 opt_D_dump_rules                = lookUp  SLIT("-ddump-rules")
318 opt_D_dump_usagesp              = lookUp  SLIT("-ddump-usagesp")
319 opt_D_dump_cse                  = lookUp  SLIT("-ddump-cse")
320 opt_D_dump_worker_wrapper       = lookUp  SLIT("-ddump-workwrap")
321 opt_D_show_passes               = lookUp  SLIT("-dshow-passes")
322 opt_D_dump_rn_trace             = lookUp  SLIT("-ddump-rn-trace")
323 opt_D_dump_rn_stats             = lookUp  SLIT("-ddump-rn-stats")
324 opt_D_dump_simpl_stats          = lookUp  SLIT("-ddump-simpl-stats")
325 opt_D_source_stats              = lookUp  SLIT("-dsource-stats")
326 opt_D_verbose_core2core         = lookUp  SLIT("-dverbose-simpl")
327 opt_D_verbose_stg2stg           = lookUp  SLIT("-dverbose-stg")
328 opt_DoCoreLinting               = lookUp  SLIT("-dcore-lint")
329 opt_DoStgLinting                = lookUp  SLIT("-dstg-lint")
330 opt_DoUSPLinting                = lookUp  SLIT("-dusagesp-lint")
331 opt_PprStyle_NoPrags            = lookUp  SLIT("-dppr-noprags")
332 opt_PprStyle_Debug              = lookUp  SLIT("-dppr-debug")
333 opt_PprUserLength               = lookup_def_int "-dppr-user-length" 5 --ToDo: give this a name
334
335 -- warning opts
336 opt_WarnDuplicateExports        = lookUp  SLIT("-fwarn-duplicate-exports")
337 opt_WarnHiShadows               = lookUp  SLIT("-fwarn-hi-shadowing")
338 opt_WarnIncompletePatterns      = lookUp  SLIT("-fwarn-incomplete-patterns")
339 opt_WarnMissingMethods          = lookUp  SLIT("-fwarn-missing-methods")
340 opt_WarnMissingSigs             = lookUp  SLIT("-fwarn-missing-signatures")
341 opt_WarnNameShadowing           = lookUp  SLIT("-fwarn-name-shadowing")
342 opt_WarnOverlappingPatterns     = lookUp  SLIT("-fwarn-overlapping-patterns")
343 opt_WarnSimplePatterns          = lookUp  SLIT("-fwarn-simple-patterns")
344 opt_WarnTypeDefaults            = lookUp  SLIT("-fwarn-type-defaults")
345 opt_WarnUnusedBinds             = lookUp  SLIT("-fwarn-unused-binds")
346 opt_WarnUnusedImports           = lookUp  SLIT("-fwarn-unused-imports")
347 opt_WarnUnusedMatches           = lookUp  SLIT("-fwarn-unused-matches")
348
349 -- profiling opts
350 opt_AutoSccsOnAllToplevs        = lookUp  SLIT("-fauto-sccs-on-all-toplevs")
351 opt_AutoSccsOnExportedToplevs   = lookUp  SLIT("-fauto-sccs-on-exported-toplevs")
352 opt_AutoSccsOnIndividualCafs    = lookUp  SLIT("-fauto-sccs-on-individual-cafs")
353 opt_AutoSccsOnDicts             = lookUp  SLIT("-fauto-sccs-on-dicts")
354 opt_SccGroup                    = lookup_str "-G="
355 opt_SccProfilingOn              = lookUp  SLIT("-fscc-profiling")
356 opt_DoTickyProfiling            = lookUp  SLIT("-fticky-ticky")
357
358 -- language opts
359 opt_AllStrict                   = lookUp  SLIT("-fall-strict")
360 opt_DictsStrict                 = lookUp  SLIT("-fdicts-strict")
361 opt_AllowOverlappingInstances   = lookUp  SLIT("-fallow-overlapping-instances")
362 opt_AllowUndecidableInstances   = lookUp  SLIT("-fallow-undecidable-instances")
363 opt_GlasgowExts                 = lookUp  SLIT("-fglasgow-exts")
364 opt_IrrefutableTuples           = lookUp  SLIT("-firrefutable-tuples")
365 opt_MaxContextReductionDepth    = lookup_def_int "-fcontext-stack" mAX_CONTEXT_REDUCTION_DEPTH
366 opt_NumbersStrict               = lookUp  SLIT("-fnumbers-strict")
367 opt_Parallel                    = lookUp  SLIT("-fparallel")
368
369 -- optimisation opts
370 opt_DoEtaReduction              = lookUp  SLIT("-fdo-eta-reduction")
371 opt_DoSemiTagging               = lookUp  SLIT("-fsemi-tagging")
372 opt_FoldrBuildOn                = lookUp  SLIT("-ffoldr-build-on")
373 opt_LiberateCaseThreshold       = lookup_def_int "-fliberate-case-threshold" (10::Int)
374 opt_NoPreInlining               = lookUp  SLIT("-fno-pre-inlining")
375 opt_StgDoLetNoEscapes           = lookUp  SLIT("-flet-no-escape")
376 opt_UnfoldCasms                 = lookUp SLIT("-funfold-casms-in-hi-file")
377 opt_UsageSPOn                   = lookUp  SLIT("-fusagesp-on")
378 opt_UnboxStrictFields           = lookUp  SLIT("-funbox-strict-fields")
379
380   {-
381    It's a bit unfortunate to have to re-introduce this chap, but on Win32
382    platforms we do need a way of distinguishing between the case when we're
383    compiling a static version of the Prelude and one that's going to be
384    put into a DLL. Why? Because the compiler's wired in modules need to
385    be attributed as either coming from a DLL or not.
386   -}
387 opt_CompilingPrelude            = lookUp  SLIT("-fcompiling-prelude")
388 opt_EmitCExternDecls            = lookUp  SLIT("-femit-extern-decls")
389 opt_EnsureSplittableC           = lookUp  SLIT("-fglobalise-toplev-names")
390 opt_GranMacros                  = lookUp  SLIT("-fgransim")
391 opt_HiMap                       = lookup_str "-himap="       -- file saying where to look for .hi files
392 opt_HiVersion                   = lookup_def_int "-fhi-version=" 0 -- what version we're compiling.
393 opt_HistorySize                 = lookup_def_int "-fhistory-size" 20
394 opt_IgnoreAsserts               = lookUp  SLIT("-fignore-asserts")
395 opt_IgnoreIfacePragmas          = lookUp  SLIT("-fignore-interface-pragmas")
396 opt_NoHiCheck                   = lookUp  SLIT("-fno-hi-version-check")
397 opt_NoImplicitPrelude           = lookUp  SLIT("-fno-implicit-prelude")
398 opt_OmitBlackHoling             = lookUp  SLIT("-dno-black-holing")
399 opt_OmitInterfacePragmas        = lookUp  SLIT("-fomit-interface-pragmas")
400 opt_ProduceC                    = lookup_str "-C="
401 opt_ProduceExportCStubs         = lookup_str "-F="
402 opt_ProduceExportHStubs         = lookup_str "-FH="
403 opt_ProduceHi                   = lookup_str "-hifile=" -- the one to produce this time 
404
405 -- Simplifier switches
406 opt_SimplNoPreInlining          = lookUp SLIT("-fno-pre-inlining")
407         -- NoPreInlining is there just to see how bad things
408         -- get if you don't do it!
409 opt_SimplDoEtaReduction         = lookUp SLIT("-fdo-eta-reduction")
410 opt_SimplDoCaseElim             = lookUp SLIT("-fdo-case-elim")
411 opt_SimplDoLambdaEtaExpansion   = lookUp SLIT("-fdo-lambda-eta-expansion")
412 opt_SimplCaseOfCase             = lookUp SLIT("-fcase-of-case")
413 opt_SimplCaseMerge              = lookUp SLIT("-fcase-merge")
414 opt_SimplLetToCase              = lookUp SLIT("-flet-to-case")
415 opt_SimplPedanticBottoms        = lookUp SLIT("-fpedantic-bottoms")
416
417 -- Unfolding control
418 opt_UF_HiFileThreshold          = lookup_def_int "-funfolding-interface-threshold" (30::Int)
419 opt_UF_CreationThreshold        = lookup_def_int "-funfolding-creation-threshold"  (30::Int)
420 opt_UF_UseThreshold             = lookup_def_int "-funfolding-use-threshold"       (8::Int)     -- Discounts can be big
421 opt_UF_ScrutConDiscount         = lookup_def_int "-funfolding-con-discount"        (3::Int)
422 opt_UF_FunAppDiscount           = lookup_def_int "-funfolding-fun-discount"        (6::Int)     -- It's great to inline a fn
423 opt_UF_PrimArgDiscount          = lookup_def_int "-funfolding-prim-discount"       (1::Int)
424 opt_UF_KeenessFactor            = lookup_def_float "-funfolding-keeness-factor"    (2.0::Float)
425
426 opt_UF_CheapOp  = ( 0 :: Int)   -- Only one instruction; and the args are charged for
427 opt_UF_DearOp   = ( 4 :: Int)
428 opt_UF_NoRepLit = ( 20 :: Int)  -- Strings can be pretty big
429                         
430 opt_ProduceS                    = lookup_str "-S="
431 opt_ReportCompile               = lookUp SLIT("-freport-compile")
432 opt_NoPruneDecls                = lookUp SLIT("-fno-prune-decls")
433 opt_SourceUnchanged             = lookUp SLIT("-fsource-unchanged")
434 opt_Static                      = lookUp SLIT("-static")
435 opt_Unregisterised              = lookUp SLIT("-funregisterised")
436 opt_Verbose                     = lookUp SLIT("-v")
437
438 opt_UseVanillaRegs | opt_Unregisterised = 0
439                    | otherwise          = mAX_Real_Vanilla_REG
440 opt_UseFloatRegs   | opt_Unregisterised = 0
441                    | otherwise          = mAX_Real_Float_REG
442 opt_UseDoubleRegs  | opt_Unregisterised = 0
443                    | otherwise          = mAX_Real_Double_REG
444 opt_UseLongRegs    | opt_Unregisterised = 0
445                    | otherwise          = mAX_Real_Long_REG
446 \end{code}
447
448 \begin{code}
449 classifyOpts :: ([CoreToDo],    -- Core-to-Core processing spec
450                  [StgToDo])     -- STG-to-STG   processing spec
451
452 classifyOpts = sep argv [] [] -- accumulators...
453   where
454     sep :: [FAST_STRING]                 -- cmd-line opts (input)
455         -> [CoreToDo] -> [StgToDo]       -- to_do accumulators
456         -> ([CoreToDo], [StgToDo])       -- result
457
458     sep [] core_td stg_td -- all done!
459       = (reverse core_td, reverse stg_td)
460
461 #       define CORE_TD(to_do) sep opts (to_do:core_td) stg_td
462 #       define STG_TD(to_do)  sep opts core_td (to_do:stg_td)
463
464     sep (opt1:opts) core_td stg_td
465       = case (_UNPK_ opt1) of -- the non-"just match a string" options are at the end...
466           ',' : _       -> sep opts core_td stg_td -- it is for the parser
467
468           "-fsimplify"  -> -- gather up SimplifierSwitches specially...
469                            simpl_sep opts defaultSimplSwitches core_td stg_td
470
471           "-ffloat-inwards"  -> CORE_TD(CoreDoFloatInwards)
472           "-ffull-laziness"  -> CORE_TD(CoreDoFullLaziness)
473           "-fliberate-case"  -> CORE_TD(CoreLiberateCase)
474           "-fcse"            -> CORE_TD(CoreCSE)
475           "-fprint-core"     -> CORE_TD(CoreDoPrintCore)
476           "-fstatic-args"    -> CORE_TD(CoreDoStaticArgs)
477           "-fstrictness"     -> CORE_TD(CoreDoStrictness)
478           "-fworker-wrapper" -> CORE_TD(CoreDoWorkerWrapper)
479           "-fspecialise"     -> CORE_TD(CoreDoSpecialising)
480           "-fusagesp"        -> CORE_TD(CoreDoUSPInf)
481           "-fcpr-analyse"    -> CORE_TD(CoreDoCPResult)
482
483           "-fstg-static-args" -> STG_TD(StgDoStaticArgs)
484           "-fupdate-analysis" -> STG_TD(StgDoUpdateAnalysis)
485           "-dstg-stats"       -> STG_TD(D_stg_stats)
486           "-flambda-lift"     -> STG_TD(StgDoLambdaLift)
487           "-fmassage-stg-for-profiling" -> STG_TD(StgDoMassageForProfiling)
488
489           _ -> -- NB: the driver is really supposed to handle bad options
490                sep opts core_td stg_td
491
492     ----------------
493
494     simpl_sep :: [FAST_STRING]            -- cmd-line opts (input)
495               -> [SimplifierSwitch]       -- simplifier-switch accumulator
496               -> [CoreToDo] -> [StgToDo]  -- to_do accumulators
497               -> ([CoreToDo], [StgToDo])  -- result
498
499         -- "simpl_sep" tailcalls "sep" once it's seen one set
500         -- of SimplifierSwitches for a CoreDoSimplify.
501
502 #ifdef DEBUG
503     simpl_sep input@[] simpl_sw core_td stg_td
504       = panic "simpl_sep []"
505 #endif
506
507         -- The SimplifierSwitches should be delimited by "[" and "]".
508
509     simpl_sep (opt1:opts) simpl_sw core_td stg_td
510       = case (_UNPK_ opt1) of
511           "[" -> simpl_sep opts simpl_sw core_td stg_td
512           "]" -> let
513                     this_simpl = CoreDoSimplify (isAmongSimpl simpl_sw)
514                  in
515                  sep opts (this_simpl : core_td) stg_td
516
517           opt -> case matchSimplSw opt of
518                         Just sw -> simpl_sep opts (sw:simpl_sw) core_td stg_td
519                         Nothing -> simpl_sep opts simpl_sw      core_td stg_td
520
521 matchSimplSw opt
522   = firstJust   [ matchSwInt  opt "-fmax-simplifier-iterations"         MaxSimplifierIterations
523                 , matchSwInt  opt "-finline-phase"                      SimplInlinePhase
524                 ]
525
526 matchSwBool :: String -> String -> a -> Maybe a
527 matchSwBool opt str sw | opt == str = Just sw
528                        | otherwise  = Nothing
529
530 matchSwInt :: String -> String -> (Int -> a) -> Maybe a
531 matchSwInt opt str sw = case startsWith str opt of
532                             Just opt_left -> Just (sw (read opt_left))
533                             Nothing       -> Nothing
534 \end{code}
535
536 %************************************************************************
537 %*                                                                      *
538 \subsection{Switch ordering}
539 %*                                                                      *
540 %************************************************************************
541
542 In spite of the @Produce*@ and @SccGroup@ constructors, these things
543 behave just like enumeration types.
544
545 \begin{code}
546 instance Eq SimplifierSwitch where
547     a == b = tagOf_SimplSwitch a _EQ_ tagOf_SimplSwitch b
548
549 instance Ord SimplifierSwitch where
550     a <  b  = tagOf_SimplSwitch a _LT_ tagOf_SimplSwitch b
551     a <= b  = tagOf_SimplSwitch a _LE_ tagOf_SimplSwitch b
552
553
554 tagOf_SimplSwitch (SimplInlinePhase _)          = ILIT(1)
555 tagOf_SimplSwitch (MaxSimplifierIterations _)   = ILIT(2)
556
557 -- If you add anything here, be sure to change lAST_SIMPL_SWITCH_TAG, too!
558
559 lAST_SIMPL_SWITCH_TAG = 2
560 \end{code}
561
562 %************************************************************************
563 %*                                                                      *
564 \subsection{Switch lookup}
565 %*                                                                      *
566 %************************************************************************
567
568 \begin{code}
569 isAmongSimpl :: [SimplifierSwitch] -> SimplifierSwitch -> SwitchResult
570
571 isAmongSimpl on_switches                -- Switches mentioned later occur *earlier*
572                                         -- in the list; defaults right at the end.
573   = let
574         tidied_on_switches = foldl rm_dups [] on_switches
575                 -- The fold*l* ensures that we keep the latest switches;
576                 -- ie the ones that occur earliest in the list.
577
578         sw_tbl :: Array Int SwitchResult
579         sw_tbl = (array (0, lAST_SIMPL_SWITCH_TAG) -- bounds...
580                         all_undefined)
581                  // defined_elems
582
583         all_undefined = [ (i, SwBool False) | i <- [0 .. lAST_SIMPL_SWITCH_TAG ] ]
584
585         defined_elems = map mk_assoc_elem tidied_on_switches
586     in
587     -- (avoid some unboxing, bounds checking, and other horrible things:)
588     case sw_tbl of { Array bounds_who_needs_'em stuff ->
589     \ switch ->
590         case (indexArray# stuff (tagOf_SimplSwitch switch)) of
591 #if __GLASGOW_HASKELL__ < 400
592           Lift v -> v
593 #elif __GLASGOW_HASKELL__ < 403
594           (# _, v #) -> v
595 #else
596           (# v #) -> v
597 #endif
598     }
599   where
600     mk_assoc_elem k@(MaxSimplifierIterations lvl) = (IBOX(tagOf_SimplSwitch k), SwInt lvl)
601     mk_assoc_elem k@(SimplInlinePhase n)          = (IBOX(tagOf_SimplSwitch k), SwInt n)
602     mk_assoc_elem k                               = (IBOX(tagOf_SimplSwitch k), SwBool True) -- I'm here, Mom!
603
604     -- cannot have duplicates if we are going to use the array thing
605     rm_dups switches_so_far switch
606       = if switch `is_elem` switches_so_far
607         then switches_so_far
608         else switch : switches_so_far
609       where
610         sw `is_elem` []     = False
611         sw `is_elem` (s:ss) = (tagOf_SimplSwitch sw) _EQ_ (tagOf_SimplSwitch s)
612                             || sw `is_elem` ss
613 \end{code}
614
615 Default settings for simplifier switches
616
617 \begin{code}
618 defaultSimplSwitches = [MaxSimplifierIterations 1]
619 \end{code}
620
621 %************************************************************************
622 %*                                                                      *
623 \subsection{Misc functions for command-line options}
624 %*                                                                      *
625 %************************************************************************
626
627
628 \begin{code}
629 switchIsOn :: (switch -> SwitchResult) -> switch -> Bool
630
631 switchIsOn lookup_fn switch
632   = case (lookup_fn switch) of
633       SwBool False -> False
634       _            -> True
635
636 intSwitchSet :: (switch -> SwitchResult)
637              -> (Int -> switch)
638              -> Maybe Int
639
640 intSwitchSet lookup_fn switch
641   = case (lookup_fn (switch (panic "intSwitchSet"))) of
642       SwInt int -> Just int
643       _         -> Nothing
644 \end{code}
645
646 \begin{code}
647 startsWith :: String -> String -> Maybe String
648 -- startsWith pfx (pfx++rest) = Just rest
649
650 startsWith []     str = Just str
651 startsWith (c:cs) (s:ss)
652   = if c /= s then Nothing else startsWith cs ss
653 startsWith  _     []  = Nothing
654
655 endsWith  :: String -> String -> Maybe String
656 endsWith cs ss
657   = case (startsWith (reverse cs) (reverse ss)) of
658       Nothing -> Nothing
659       Just rs -> Just (reverse rs)
660 \end{code}