Debian Codegraph @

c2hs/toplevel/Gtk2HsC2Hs.hs

raw symbols SCIP
1 -- C -> Haskell Compiler: main module
2 --
3 -- Author : Manuel M T Chakravarty
4 -- Derived: 12 August 99
5 --
6 -- Version $Revision: 1.6 $ from $Date: 2005/07/03 14:58:16 $
7 --
8 -- Copyright (c) [1999..2004] Manuel M T Chakravarty
9 --
10 -- This file is free software; you can redistribute it and/or modify
11 -- it under the terms of the GNU General Public License as published by
12 -- the Free Software Foundation; either version 2 of the License, or
13 -- (at your option) any later version.
14 --
15 -- This file is distributed in the hope that it will be useful,
16 -- but WITHOUT ANY WARRANTY; without even the implied warranty of
17 -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 -- GNU General Public License for more details.
19 --
20 --- DESCRIPTION ---------------------------------------------------------------
21 --
22 -- This is the main module of the compiler. It sets the version, processes
23 -- the command line arguments, and controls the compilation process.
24 --
25 -- Originally, derived from `Main.hs' of the Nepal Compiler.
26 --
27 --- DOCU ----------------------------------------------------------------------
28 --
29 -- language: Haskell 98
30 --
31 -- Usage:
32 -- ------
33 --
34 -- c2hs [ option... ] header-file binding-file
35 --
36 -- The compiler is supposed to emit a Haskell program that expands all hooks
37 -- in the given binding file.
38 --
39 -- File name suffix:
40 -- -----------------
41 --
42 -- Note: These also depend on suffixes defined in the compiler proper.
43 --
44 -- .h C header file
45 -- .i pre-processed C header file
46 -- .hs Haskell file
47 -- .chs Haskell file with C->Haskell hooks (binding file)
48 -- .chi C->Haskell interface file
49 --
50 -- Options:
51 -- --------
52 --
53 -- -C CPPOPTS
54 -- --cppopts=CPPOPTS
55 -- Pass the additional options CPPOPTS to the C preprocessor.
56 --
57 -- Repeated occurrences accumulate.
58 --
59 -- -c CPP
60 -- --cpp=CPP
61 -- Use the executable CPP to invoke CPP.
62 --
63 -- In the case of repeated occurrences, the last takes effect.
64 --
65 -- -d TYPE
66 -- --dump=TYPE
67 -- Dump intermediate representation:
68 --
69 -- + if TYPE is `trace', trace the compiler phases (to stderr)
70 -- + if TYPE is `genbind', trace binding generation (to stderr)
71 -- + if TYPE is `ctrav', trace C declaration traversal (to stderr)
72 -- + if TYPE is `chs', dump the binding file (insert `.dump' into the
73 -- file name to avoid overwriting the original file)
74 --
75 -- -h, -?
76 -- --help
77 -- Dump brief usage information to stderr.
78 --
79 -- -i DIRS
80 -- --include=DIRS
81 -- Search the colon separated list of directories DIRS when searching
82 -- for .chi files.
83 --
84 -- -k
85 -- --keep
86 -- Keep the intermediate file that contains the pre-processed C header
87 -- (it carries the suffix `.i').
88 --
89 -- -o FILE
90 -- --output=FILE
91 -- Place output in file FILE.
92 --
93 -- If `-o' is not specified, the default is to put the output for
94 -- `source.chs' in `source.hs' in the same directory that contains the
95 -- binding file. If specified, the emitted C header file is put into
96 -- the same directory as the output file. The same holds for
97 -- C->Haskell interface file. All generated files also share the
98 -- basename.
99 --
100 -- -t PATH
101 -- --output-dir=PATH
102 -- Place generated files in the directory PATH.
103 --
104 -- If this option as well as the `-o' option is given, the basename of
105 -- the file specified with `-o' is put in the directory specified with
106 -- `-t'.
107 --
108 -- -v,
109 -- --version
110 -- Print (on standard error output) the version and copyright
111 -- information of the compiler (before doing anything else).
112 --
113 -- -p FILE
114 -- --precomp=FILE
115 -- Use or generate a precompiled header. If a header file is
116 -- given write a condensed version of the header file into
117 -- FILE. If a binding file is given that does not contain any C
118 -- declarations itself, use the condensed information in FILE
119 -- to generate the binding. Using a precompiled header file will
120 -- significantly speed up the translation of a binding module.
121 --
122 -- --old-ffi [=yes|=no]
123 -- Generate hooks using pre-standard FFI libraries. This currently
124 -- affects only call hooks where instead of `Addr' types
125 -- `Ptr <someOtherType>' is used.
126 --
127 -- --lock=NAME
128 -- Wrap each foreign function call in the function NAME. This
129 -- function is usually a function that acquires a lock for
130 -- the memory region that the called function is about to access.
131 -- A wrap function can also be specified within the file in the
132 -- context hook, in which case it overrides the command line function.
133 -- The wrapper function can be omitted on a call-by-call basis by
134 -- using the nolock option in the call hook.
135 --
136 --- TODO ----------------------------------------------------------------------
137 --
138
139 module Gtk2HsC2Hs (c2hsMain)
140 where
141
142 -- standard libraries
143 import Data.List (isPrefixOf)
144 import System.IO (openFile)
145 import System.Process (runProcess, waitForProcess)
146 import Control.Monad (when, unless, mapM)
147 import Data.Maybe (fromJust)
148
149 -- base libraries
150 import System.Console.GetOpt
151 (ArgOrder(..), OptDescr(..), ArgDescr(..), usageInfo, getOpt)
152 import FNameOps (suffix, basename, dirname, stripSuffix, addPath,
153 splitSearchPath)
154 import Errors (interr)
155 import UNames (saveRootNameSupply, restoreRootNameSupply)
156 import Binary (Binary(..), putBinFileWithDict, getBinFileWithDict)
157
158 -- c2hs modules
159 import C2HSState (CST, nop, runC2HS, fatal, fatalsHandledBy, getId,
160 ExitCode(..), stderr, IOMode(..), putStrCIO, hPutStrCIO,
161 hPutStrLnCIO, exitWithCIO, getProgNameCIO,
162 ioeGetErrorString, ioeGetFileName, doesFileExistCIO,
163 removeFileCIO, liftIO,
164 fileFindInCIO, mktempCIO, openFileCIO, hCloseCIO,
165 SwitchBoard(..), Traces(..), setTraces,
166 traceSet, setSwitch, getSwitch, putTraceStr)
167 import C (AttrC, hsuffix, isuffix, loadAttrC)
168 import CHS (CHSModule, skipToLangPragma, hasCPP, loadCHS, dumpCHS, loadAllCHI,
169 hssuffix, chssuffix, dumpCHI)
170 import GenHeader (genHeader)
171 import GenBind (expandHooks)
172 import Version (version, copyright, disclaimer)
173 import C2HSConfig (cpp, cppopts, cppoptsdef, hpaths, tmpdir)
174
175
176 -- wrapper running the compiler
177 -- ============================
178
179 c2hsMain :: [String] -> IO ()
180 c2hsMain = runC2HS (version, copyright, disclaimer) . compile
181
182
183 -- option handling
184 -- ===============
185
186 -- header is output in case of help, before the descriptions of the options;
187 -- errTrailer is output after an error message
188 --
189 header :: String -> String -> String -> String
190 header version copyright disclaimer =
191 version ++ "\n" ++ copyright ++ "\n" ++ disclaimer
192 ++ "\n\nUsage: c2hs [ option... ] header-file binding-file\n"
193
194 trailer, errTrailer :: String
195 trailer = "\n\
196 \The header file must be a C header file matching the given \
197 \binding file.\n\
198 \The dump TYPE can be\n\
199 \ trace -- trace compiler phases\n\
200 \ genbind -- trace binding generation\n\
201 \ ctrav -- trace C declaration traversal\n\
202 \ chs -- dump the binding file (adds `.dump' to the name)\n"
203 errTrailer = "Try the option `--help' on its own for more information.\n"
204
205 -- supported option types
206 --
207 data Flag = CPPOpts String -- additional options for C preprocessor
208 | CPP String -- program name of C preprocessor
209 | Dump DumpType -- dump internal information
210 | Help -- print brief usage information
211 | Keep -- keep the .i file
212 | Include String -- list of directories to search .chi files
213 | Output String -- file where the generated file should go
214 | OutDir String -- directory where generates files should go
215 | PreComp String -- write or read a precompiled header
216 | LockFun String -- wrap each function call in this function
217 | Version -- print version information on stderr
218 | Error String -- error occurred during processing of options
219 deriving Eq
220
221 data DumpType = Trace -- compiler trace
222 | GenBind -- trace `GenBind'
223 | CTrav -- trace `CTrav'
224 | CHS -- dump binding file
225 deriving Eq
226
227 -- option description suitable for `GetOpt'
228 --
229 options :: [OptDescr Flag]
230 options = [
231 Option ['C']
232 ["cppopts"]
233 (ReqArg CPPOpts "CPPOPTS")
234 "pass CPPOPTS to the C preprocessor",
235 Option ['c']
236 ["cpp"]
237 (ReqArg CPP "CPP")
238 "use executable CPP to invoke C preprocessor",
239 Option ['d']
240 ["dump"]
241 (ReqArg dumpArg "TYPE")
242 "dump internal information (for debugging)",
243 Option ['h', '?']
244 ["help"]
245 (NoArg Help)
246 "brief help (the present message)",
247 Option ['i']
248 ["include"]
249 (ReqArg Include "INCLUDE")
250 "include paths for .chi files",
251 Option ['k']
252 ["keep"]
253 (NoArg Keep)
254 "keep pre-processed C header",
255 Option ['o']
256 ["output"]
257 (ReqArg Output "FILE")
258 "output result to FILE (should end in .hs)",
259 Option ['t']
260 ["output-dir"]
261 (ReqArg OutDir "PATH")
262 "place generated files in PATH",
263 Option ['p']
264 ["precomp"]
265 (ReqArg PreComp "FILE")
266 "generate or read precompiled header file FILE",
267 Option ['l']
268 ["lock"]
269 (ReqArg LockFun "NAME")
270 "wrap each foreign call with the function NAME",
271 Option ['v']
272 ["version"]
273 (NoArg Version)
274 "show version information"]
275
276 -- convert argument of `Dump' option
277 --
278 dumpArg :: String -> Flag
279 dumpArg "trace" = Dump Trace
280 dumpArg "genbind" = Dump GenBind
281 dumpArg "ctrav" = Dump CTrav
282 dumpArg "chs" = Dump CHS
283 dumpArg _ = Error "Illegal dump type."
284
285 -- main process (set up base configuration, analyse command line, and execute
286 -- compilation process)
287 --
288 -- * Exceptions are caught and reported
289 --
290 compile :: [String] -> CST s ()
291 compile cmdLine =
292 do
293 setup
294 case getOpt RequireOrder options cmdLine of
295 ([Help] , [] , []) -> doExecute [Help] []
296 ([Version], [] , []) -> doExecute [Version] []
297 (opts , args, [])
298 | properArgs args -> doExecute opts args
299 | otherwise -> raiseErrs [wrongNoOfArgsErr]
300 (_ , _ , errs) -> raiseErrs errs
301 where
302 properArgs [file1, file2] = suffix file1 == hsuffix
303 && suffix file2 == chssuffix
304 properArgs _ = False
305 --
306 doExecute opts args = execute opts args
307 `fatalsHandledBy` failureHandler
308 --
309 wrongNoOfArgsErr =
310 "Supply the header file followed by the binding file.\n\
311 \The header file can be omitted if it is supplied in the binding file.\n\
312 \The binding file can be omitted if the --precomp flag is given.\n"
313 --
314 -- exception handler
315 --
316 failureHandler err =
317 do
318 let msg = ioeGetErrorString err
319 fnMsg = case ioeGetFileName err of
320 Nothing -> ""
321 Just s -> " (file: `" ++ s ++ "')"
322 hPutStrLnCIO stderr (msg ++ fnMsg)
323 exitWithCIO $ ExitFailure 1
324
325 -- set up base configuration
326 --
327 setup :: CST s ()
328 setup = do
329 setCPP cpp
330 addCPPOpts cppopts
331 addHPaths hpaths
332
333 -- output error message
334 --
335 raiseErrs :: [String] -> CST s a
336 raiseErrs errs = do
337 hPutStrCIO stderr (concat errs)
338 hPutStrCIO stderr errTrailer
339 exitWithCIO $ ExitFailure 1
340
341 -- Process tasks
342 -- -------------
343
344 -- execute the compilation task
345 --
346 -- * if `Help' is present, emit the help message and ignore the rest
347 -- * if `Version' is present, do it first (and only once)
348 -- * actual compilation is only invoked if we have one or two extra arguments
349 -- (otherwise, it is just skipped)
350 --
351 execute :: [Flag] -> [FilePath] -> CST s ()
352 execute opts args | Help `elem` opts = help
353 | otherwise =
354 do
355 let vs = filter (== Version) opts
356 opts' = filter (/= Version) opts
357 mapM_ processOpt (atMostOne vs ++ opts')
358
359 let (headerFile, bndFile) = determineFileTypes args
360
361 preCompFile <- getSwitch preCompSB
362
363 unless (preCompFile==Nothing) $
364 preCompileHeader headerFile (fromJust preCompFile)
365 `fatalsHandledBy` ioErrorHandler
366
367 let bndFileWithoutSuffix = stripSuffix bndFile
368 unless (null bndFile) $ do
369 computeOutputName bndFileWithoutSuffix
370 process headerFile preCompFile bndFileWithoutSuffix
371 `fatalsHandledBy` ioErrorHandler
372 where
373 atMostOne = (foldl (\_ x -> [x]) [])
374
375 determineFileTypes [hfile, bfile] = (hfile, bfile)
376 determineFileTypes [file] | suffix file==hsuffix = (file, "")
377 | otherwise = ("", file)
378 determineFileTypes [] = ("", "")
379
380 ioErrorHandler ioerr = do
381 name <- getProgNameCIO
382 putStrCIO $
383 name ++ ": " ++ ioeGetErrorString ioerr ++ "\n"
384 exitWithCIO $ ExitFailure 1
385
386 -- emit help message
387 --
388 help :: CST s ()
389 help = do
390 (version, copyright, disclaimer) <- getId
391 putStrCIO (usageInfo (header version copyright disclaimer) options)
392 putStrCIO trailer
393
394 -- process an option
395 --
396 -- * `Help' cannot occur
397 --
398 processOpt :: Flag -> CST s ()
399 processOpt (CPPOpts cppopt ) = addCPPOpts [cppopt]
400 processOpt (CPP cpp ) = setCPP cpp
401 processOpt (Dump dt ) = setDump dt
402 processOpt (Keep ) = setKeep
403 processOpt (Include dirs ) = setInclude dirs
404 processOpt (Output fname ) = setOutput fname
405 processOpt (OutDir fname ) = setOutDir fname
406 processOpt (PreComp fname ) = setPreComp fname
407 processOpt (LockFun name ) = setLockFun name
408 processOpt Version = do
409 (version, _, _) <- getId
410 putStrCIO (version ++ "\n")
411 processOpt (Error msg ) = abort msg
412
413 -- emit error message and raise an error
414 --
415 abort :: String -> CST s ()
416 abort msg = do
417 hPutStrLnCIO stderr msg
418 hPutStrCIO stderr errTrailer
419 fatal "Error in command line options"
420
421 -- Compute the base name for all generated files (Haskell, C header, and .chi
422 -- file)
423 --
424 -- * The result is available from the `outputSB' switch
425 --
426 computeOutputName :: FilePath -> CST s ()
427 computeOutputName bndFileNoSuffix =
428 do
429 output <- getSwitch outputSB
430 outDir <- getSwitch outDirSB
431 let dir = if null outDir && null output then dirname bndFileNoSuffix
432 else if null outDir then dirname output
433 else outDir
434 let base = if null output then basename bndFileNoSuffix
435 else basename output
436 setSwitch $ \sb -> sb {
437 outputSB = dir `addPath` base,
438 outDirSB = dir
439 }
440
441
442 -- set switches
443 -- ------------
444
445 -- set the options for the C proprocessor
446 --
447 -- * any header search path that is set with `-IDIR' is also added to
448 -- `hpathsSB'
449 --
450 addCPPOpts :: [String] -> CST s ()
451 addCPPOpts opts =
452 do
453 let iopts = [opt | opt <- opts, "-I" `isPrefixOf` opt, "-I-" /= opt]
454 addHPaths . map (drop 2) $ iopts
455 addOpts opts
456 where
457 addOpts opts = setSwitch $
458 \sb -> sb {cppOptsSB = cppOptsSB sb ++ opts}
459
460 -- set the program name of the C proprocessor
461 --
462 setCPP :: FilePath -> CST s ()
463 setCPP fname = setSwitch $ \sb -> sb {cppSB = fname}
464
465 -- add header file search paths
466 --
467 addHPaths :: [FilePath] -> CST s ()
468 addHPaths paths = setSwitch $ \sb -> sb {hpathsSB = paths ++ hpathsSB sb}
469
470 -- set the given dump option
471 --
472 setDump :: DumpType -> CST s ()
473 setDump Trace = setTraces $ \ts -> ts {tracePhasesSW = True}
474 setDump GenBind = setTraces $ \ts -> ts {traceGenBindSW = True}
475 setDump CTrav = setTraces $ \ts -> ts {traceCTravSW = True}
476 setDump CHS = setTraces $ \ts -> ts {dumpCHSSW = True}
477
478 -- set flag to keep the pre-processed header file
479 --
480 setKeep :: CST s ()
481 setKeep = setSwitch $ \sb -> sb {keepSB = True}
482
483 -- set the search directories for .chi files
484 --
485 -- * Several -i flags are accumulated. Later paths have higher priority.
486 --
487 -- * The current directory is always searched last because it is the
488 -- standard value in the compiler state.
489 --
490 setInclude :: String -> CST s ()
491 setInclude str = do
492 let fp = splitSearchPath str
493 setSwitch $ \sb -> sb {chiPathSB = fp ++ (chiPathSB sb)}
494
495 -- set the output file name
496 --
497 setOutput :: FilePath -> CST s ()
498 setOutput fname = do
499 when (suffix fname /= hssuffix) $
500 raiseErrs ["Output file should end in .hs!\n"]
501 setSwitch $ \sb -> sb {outputSB = stripSuffix fname}
502
503 -- set the output directory
504 --
505 setOutDir :: FilePath -> CST s ()
506 setOutDir fname = setSwitch $ \sb -> sb {outDirSB = fname}
507
508 -- set the name of the generated header file
509 --
510 setHeader :: FilePath -> CST s ()
511 setHeader fname = setSwitch $ \sb -> sb {headerSB = fname}
512
513 -- set the file name in which the precompiled header ends up
514 --
515 setPreComp :: FilePath -> CST s ()
516 setPreComp fname = setSwitch $ \sb -> sb { preCompSB = Just fname }
517
518 -- set the name of the wrapper function that acquires a lock
519 --
520 setLockFun :: String -> CST s ()
521 setLockFun name = setSwitch $ \sb -> sb { lockFunSB = Just name }
522
523 -- compilation process
524 -- -------------------
525
526 -- read the binding module, construct a header, run it through CPP, read it,
527 -- and finally generate the Haskell target
528 --
529 -- * the header file name (first argument) may be empty; otherwise, it already
530 -- contains the right suffix
531 --
532 -- * the binding file name has been stripped of the .chs suffix
533 --
534 process :: FilePath -> Maybe FilePath -> FilePath -> CST s ()
535 process headerFile preCompFile bndFileStripped =
536 do
537 -- load the Haskell binding module, any imported module with CHI information is
538 -- only inserted as file name, the content of the CHI modules is inserted below
539 -- using 'loadAllCHI'. This ensures that we don't look for a CHI file that is
540 -- commented out using an #ifdef
541 --
542 (chsMod , warnmsgs) <- loadCHS bndFile
543
544 putStrCIO warnmsgs
545
546 -- check if a CPP language pragma is present and, if so, run CPP on the file
547 -- and re-read it
548 chsMod <- case skipToLangPragma chsMod of
549 Nothing -> loadAllCHI chsMod
550 Just chsMod | not (hasCPP chsMod) -> loadAllCHI chsMod
551 | otherwise -> do
552 outFName <- getSwitch outputSB
553 let outFileBase = if null outFName then basename bndFile else outFName
554 let ppFile = outFileBase ++ "_pp" ++ chssuffix
555 cpp <- getSwitch cppSB
556 cppOpts <- getSwitch cppOptsSB
557 let args = cppOpts ++ [cppoptsdef, headerFile, bndFile]
558 tracePreproc (unwords (cpp:args))
559 exitCode <- liftIO $ do
560 ppHnd <- openFile ppFile WriteMode
561 process <- runProcess cpp args
562 Nothing Nothing Nothing (Just ppHnd) Nothing
563 waitForProcess process
564 case exitCode of
565 ExitFailure _ -> fatal "Error during preprocessing chs file"
566 _ -> nop
567
568 (chsMod , warnmsgs) <- loadCHS ppFile
569
570 keep <- getSwitch keepSB
571 unless keep $
572 removeFileCIO ppFile
573
574 case skipToLangPragma chsMod of Just chsMod -> loadAllCHI chsMod
575
576 traceCHSDump chsMod
577 --
578 -- extract CPP and inline-C embedded in the .chs file (all CPP and
579 -- inline-C fragments are removed from the .chs tree and conditionals are
580 -- replaced by structured conditionals)
581 --
582 (header, strippedCHSMod, warnmsgs) <- genHeader chsMod
583 putStrCIO warnmsgs
584
585 pcFileExists <- maybe (return False) doesFileExistCIO preCompFile
586
587 cheader <- if null header && pcFileExists then do
588 -- there are no cpp directives in the .chs file, use the precompiled header
589 --
590 traceReadPrecomp (fromJust preCompFile)
591 WithNameSupply cheader <- liftIO $ getBinFileWithDict (fromJust preCompFile)
592 return cheader
593
594 else do
595 --
596 -- create new header file, make it #include `headerFile', and emit
597 -- CPP and inline-C of .chs file into the new header
598 --
599 outFName <- getSwitch outputSB
600 let newHeaderFile = outFName ++ hsuffix
601 let preprocFile = basename newHeaderFile ++ isuffix
602 newHeader <- openFileCIO newHeaderFile WriteMode
603 unless (null headerFile) $
604 hPutStrLnCIO newHeader $ "#include \"" ++ headerFile ++ "\""
605 mapM (hPutStrCIO newHeader) header
606 hCloseCIO newHeader
607 setHeader newHeaderFile
608 --
609 -- run C preprocessor over the header
610 --
611 cpp <- getSwitch cppSB
612 cppOpts <- getSwitch cppOptsSB
613 let args = cppOpts ++ [newHeaderFile]
614 tracePreproc (unwords (cpp:args))
615 exitCode <- liftIO $ do
616 preprocHnd <- openFile preprocFile WriteMode
617 process <- runProcess cpp args
618 Nothing Nothing Nothing (Just preprocHnd) Nothing
619 waitForProcess process
620 case exitCode of
621 ExitFailure _ -> fatal "Error during preprocessing custom header file"
622 _ -> nop
623 --
624 -- load and analyse the C header file
625 --
626 (cheader, warnmsgs) <- loadAttrC preprocFile
627 putStrCIO warnmsgs
628 --
629 -- remove the custom header and the pre-processed header
630 --
631 keep <- getSwitch keepSB
632 unless keep $
633 removeFileCIO preprocFile
634
635 return cheader
636
637 --
638 -- expand binding hooks into plain Haskell
639 --
640 (hsMod, chi, warnmsgs) <- expandHooks cheader strippedCHSMod
641 putStrCIO warnmsgs
642 --
643 -- output the result
644 --
645 outFName <- getSwitch outputSB
646 let hsFile = if null outFName then basename bndFile else outFName
647 dumpCHS hsFile hsMod True
648 dumpCHI hsFile chi -- different suffix will be appended
649
650 where
651 bndFile = bndFileStripped ++ chssuffix
652 traceReadPrecomp fName = putTraceStr tracePhasesSW $
653 "Reading precompiled header file " ++ fName ++ "...\n"
654 tracePreproc cmd = putTraceStr tracePhasesSW $
655 "Invoking cpp as `" ++ cmd ++ "'...\n"
656 traceCHSDump mod = do
657 flag <- traceSet dumpCHSSW
658 when flag $
659 (do
660 putStrCIO ("...dumping CHS to `" ++ chsName
661 ++ "'...\n")
662 dumpCHS chsName mod False)
663
664 chsName = basename bndFile ++ ".dump"
665
666 preCompileHeader :: FilePath -> FilePath -> CST s ()
667 preCompileHeader headerFile preCompFile =
668 do
669 let preprocFile = basename headerFile ++ isuffix
670
671 pcFileExists <- doesFileExistCIO preCompFile
672 unless pcFileExists $ do
673
674 hpaths <- getSwitch hpathsSB
675 realHeaderFile <- headerFile `fileFindInCIO` hpaths
676
677 --
678 -- run C preprocessor over the header
679 --
680 cpp <- getSwitch cppSB
681 cppOpts <- getSwitch cppOptsSB
682 let args = cppOpts ++ [realHeaderFile]
683 tracePreproc (unwords (cpp:args))
684 exitCode <- liftIO $ do
685 preprocHnd <- openFile preprocFile WriteMode
686 process <- runProcess cpp args
687 Nothing Nothing Nothing (Just preprocHnd) Nothing
688 waitForProcess process
689 case exitCode of
690 ExitFailure _ -> fatal "Error during preprocessing"
691 _ -> nop
692
693 --
694 -- load and analyse the C header file
695 --
696 (cheader, warnmsgs) <- loadAttrC preprocFile
697 putStrCIO warnmsgs
698
699 --
700 -- save the attributed C to disk
701 --
702 liftIO $ putBinFileWithDict preCompFile (WithNameSupply cheader)
703
704 --
705 -- remove the pre-processed header
706 --
707 keep <- getSwitch keepSB
708 unless keep $
709 removeFileCIO preprocFile
710
711 return ()
712 where
713 tracePreproc cmd = putTraceStr tracePhasesSW $
714 "Invoking cpp as `" ++ cmd ++ "'...\n"
715
716
717 -- dummy type so we can save and restore the name supply
718 data WithNameSupply a = WithNameSupply a
719
720 instance Binary a => Binary (WithNameSupply a) where
721 put_ bh (WithNameSupply x) = do
722 put_ bh x
723 nameSupply <- saveRootNameSupply
724 put_ bh nameSupply
725 get bh = do
726 x <- get bh
727 nameSupply <- get bh
728 restoreRootNameSupply nameSupply
729 return (WithNameSupply x)