1 {-# OPTIONS -cpp -fffi #-}
2 #if __GLASGOW_HASKELL__ < 603
7 -----------------------------------------------------------------------------
9 -- (c) The University of Glasgow, 2004
11 -- runghc program, for invoking from a #! line in a script. For example:
15 -- > main = putStrLn "hello!"
17 -- runghc accepts one flag:
19 -- -f <path> specify the path
21 -- -----------------------------------------------------------------------------
23 module Main (main) where
25 import System.Environment
30 import System.Directory ( removeFile )
31 import Control.Exception ( bracket )
32 import System.Directory ( findExecutable, getTemporaryDirectory )
33 import System.Cmd ( rawSystem )
38 case getGhcLoc args of
39 (Just ghc, args') -> doIt ghc args'
40 (Nothing, args') -> do
41 mb_ghc <- findExecutable "ghc"
43 Nothing -> dieProg ("cannot find ghc")
44 Just ghc -> doIt ghc args'
46 getGhcLoc :: [String] -> (Maybe FilePath, [String])
47 getGhcLoc ("-f" : ghc : args) = (Just ghc, args)
48 getGhcLoc (('-' : 'f' : ghc) : args) = (Just ghc, args)
49 -- If you need the first GHC flag to be a -f flag then you can pass --
51 getGhcLoc ("--" : args) = (Nothing, args)
52 getGhcLoc args = (Nothing, args)
54 doIt :: String -> [String] -> IO ()
56 let (ghc_args, rest) = getGhcArgs args
59 -- behave like typical perl, python, ruby interpreters:
61 tmpdir <- getTemporaryDirectory
63 (openTempFile tmpdir "runghcXXXX.hs")
64 (\(filename,_) -> removeFile filename)
66 getContents >>= hPutStr h
68 doIt ghc (ghc_args ++ [filename])
69 filename : prog_args -> do
70 let c1 = ":set prog " ++ show filename
71 c2 = ":main " ++ show prog_args
72 res <- rawSystem ghc (["-ignore-dot-ghci"] ++ ghc_args ++
73 [ "-e", c1, "-e", c2, filename])
76 getGhcArgs :: [String] -> ([String], [String])
78 = let (ghcArgs, otherArgs) = case break pastArgs args of
79 (xs, "--":ys) -> (xs, ys)
81 in (map unescape ghcArgs, otherArgs)
82 where unescape ('-':'-':'g':'h':'c':'-':'a':'r':'g':'=':arg) = arg
85 pastArgs :: String -> Bool
86 -- You can use -- to mark the end of the flags, in case you need to use
87 -- a file called -foo.hs for some reason. You almost certainly shouldn't,
90 pastArgs ('-':_) = False
93 dieProg :: String -> IO a
96 hPutStrLn stderr (p ++ ": " ++ msg)
97 exitWith (ExitFailure 1)
100 -- usage = "syntax: runghc [-f GHC-PATH | --] [GHC-ARGS] [--] FILE ARG..."