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