1 {-# LANGUAGE CPP, ForeignFunctionInterface #-}
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:
14 -- #!/usr/bin/env /usr/bin/runghc
15 -- > main = putStrLn "hello!"
17 -- runghc accepts one flag:
19 -- -f <path> specify the path
21 -- -----------------------------------------------------------------------------
23 module Main (main) where
25 import Control.Exception
29 import System.Directory
30 import System.Environment
32 import System.FilePath
38 case getGhcLoc args of
39 (Just ghc, args') -> doIt ghc args'
40 (Nothing, args') -> do
43 Nothing -> dieProg ("cannot find ghc")
45 let ghc = takeDirectory (normalise path) </> "ghc"
48 getGhcLoc :: [String] -> (Maybe FilePath, [String])
49 getGhcLoc args = case args of
50 "-f" : ghc : args' -> f ghc args'
51 ('-' : 'f' : ghc) : args' -> f ghc args'
52 -- If you need the first GHC flag to be a -f flag then
53 -- you can pass -- first
54 "--" : args -> (Nothing, args)
55 args -> (Nothing, args)
56 where f ghc args' = -- If there is another -f flag later on then
57 -- that overrules the one that we've already
59 case getGhcLoc args' of
60 (Nothing, _) -> (Just ghc, args')
63 doIt :: String -> [String] -> IO ()
65 let (ghc_args, rest) = getGhcArgs args
68 -- behave like typical perl, python, ruby interpreters:
70 tmpdir <- getTemporaryDirectory
72 (openTempFile tmpdir "runghcXXXX.hs")
73 (\(filename,_) -> removeFile filename)
75 getContents >>= hPutStr h
77 doIt ghc (ghc_args ++ [filename])
78 filename : prog_args -> do
79 let xflag = if takeExtension filename == ".lhs"
82 c1 = ":set prog " ++ show filename
83 c2 = ":main " ++ show prog_args
84 res <- rawSystem ghc (["-ignore-dot-ghci"] ++
87 [ "-e", c1, "-e", c2, filename])
90 getGhcArgs :: [String] -> ([String], [String])
92 = let (ghcArgs, otherArgs) = case break pastArgs args of
93 (xs, "--":ys) -> (xs, ys)
95 in (map unescape ghcArgs, otherArgs)
96 where unescape ('-':'-':'g':'h':'c':'-':'a':'r':'g':'=':arg) = arg
99 pastArgs :: String -> Bool
100 -- You can use -- to mark the end of the flags, in case you need to use
101 -- a file called -foo.hs for some reason. You almost certainly shouldn't,
104 pastArgs ('-':_) = False
107 dieProg :: String -> IO a
110 hPutStrLn stderr (p ++ ": " ++ msg)
111 exitWith (ExitFailure 1)
114 -- usage = "syntax: runghc [-f GHC-PATH | --] [GHC-ARGS] [--] FILE ARG..."
116 getExecPath :: IO (Maybe String)
117 #if defined(mingw32_HOST_OS)
119 allocaArray len $ \buf -> do
120 ret <- getModuleFileName nullPtr buf len
121 if ret == 0 then return Nothing
122 else liftM Just $ peekCString buf
123 where len = 2048 -- Plenty, PATH_MAX is 512 under Win32.
125 foreign import stdcall unsafe "GetModuleFileNameA"
126 getModuleFileName :: Ptr () -> CString -> Int -> IO Int32
128 getExecPath = return Nothing