UHC.hs 12.5 KB
Newer Older
Andres Loeh's avatar
Andres Loeh committed
1
2
3
4
5
6
7
8
9
10
-----------------------------------------------------------------------------
-- |
-- Module      :  Distribution.Simple.UHC
-- Copyright   :  Andres Loeh 2009
--
-- Maintainer  :  cabal-devel@haskell.org
-- Portability :  portable
--
-- This module contains most of the UHC-specific code for configuring, building
-- and installing packages.
11
12
13
14
--
-- Thanks to the authors of the other implementation-specific files, in
-- particular to Isaac Jones, Duncan Coutts and Henning Thielemann, for
-- inspiration on how to design this module.
Andres Loeh's avatar
Andres Loeh committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49

{-
Copyright (c) 2009, Andres Loeh
Copyright (c) 2003-2005, Isaac Jones
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

    * Redistributions of source code must retain the above copyright
      notice, this list of conditions and the following disclaimer.

    * Redistributions in binary form must reproduce the above
      copyright notice, this list of conditions and the following
      disclaimer in the documentation and/or other materials provided
      with the distribution.

    * Neither the name of Isaac Jones nor the names of other
      contributors may be used to endorse or promote products derived
      from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}

module Distribution.Simple.UHC (
50
    configure, getInstalledPackages,
51
    buildLib, buildExe, installLib, registerPackage
Andres Loeh's avatar
Andres Loeh committed
52
53
  ) where

54
import Control.Monad
Andres Loeh's avatar
Andres Loeh committed
55
import Data.List
56
import qualified Data.Map as M ( empty )
57
58
import Distribution.Compat.ReadP
import Distribution.InstalledPackageInfo
Andres Loeh's avatar
Andres Loeh committed
59
60
61
62
63
import Distribution.Package
import Distribution.PackageDescription
import Distribution.Simple.BuildPaths
import Distribution.Simple.Compiler as C
import Distribution.Simple.LocalBuildInfo
64
import Distribution.Simple.PackageIndex
Andres Loeh's avatar
Andres Loeh committed
65
import Distribution.Simple.Program
66
import Distribution.Simple.Utils
Andres Loeh's avatar
Andres Loeh committed
67
68
69
70
import Distribution.Text
import Distribution.Verbosity
import Distribution.Version
import Language.Haskell.Extension
71
import System.Directory
Andres Loeh's avatar
Andres Loeh committed
72
import System.FilePath
73
import Distribution.System ( Platform )
Andres Loeh's avatar
Andres Loeh committed
74
75
76
77
78

-- -----------------------------------------------------------------------------
-- Configuring

configure :: Verbosity -> Maybe FilePath -> Maybe FilePath
79
          -> ProgramConfiguration -> IO (Compiler, Maybe Platform, ProgramConfiguration)
Andres Loeh's avatar
Andres Loeh committed
80
81
82
83
84
85
86
87
configure verbosity hcPath _hcPkgPath conf = do

  (_uhcProg, uhcVersion, conf') <-
    requireProgramVersion verbosity uhcProgram
    (orLaterVersion (Version [1,0,2] []))
    (userMaybeSpecifyPath "uhc" hcPath conf)

  let comp = Compiler {
88
89
               compilerId         =  CompilerId UHC uhcVersion,
               compilerLanguages  =  uhcLanguages,
90
91
               compilerExtensions =  uhcLanguageExtensions,
               compilerProperties =  M.empty
Andres Loeh's avatar
Andres Loeh committed
92
             }
93
94
      compPlatform = Nothing
  return (comp, compPlatform, conf')
Andres Loeh's avatar
Andres Loeh committed
95

96
97
98
uhcLanguages :: [(Language, C.Flag)]
uhcLanguages = [(Haskell98, "")]

Andres Loeh's avatar
Andres Loeh committed
99
-- | The flags for the supported extensions.
100
uhcLanguageExtensions :: [(Extension, C.Flag)]
101
uhcLanguageExtensions =
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
    let doFlag (f, (enable, disable)) = [(EnableExtension  f, enable),
                                         (DisableExtension f, disable)]
        alwaysOn = ("", ""{- wrong -})
    in concatMap doFlag
    [(CPP,                          ("--cpp", ""{- wrong -})),
     (PolymorphicComponents,        alwaysOn),
     (ExistentialQuantification,    alwaysOn),
     (ForeignFunctionInterface,     alwaysOn),
     (UndecidableInstances,         alwaysOn),
     (MultiParamTypeClasses,        alwaysOn),
     (Rank2Types,                   alwaysOn),
     (PatternSignatures,            alwaysOn),
     (EmptyDataDecls,               alwaysOn),
     (ImplicitPrelude,              ("", "--no-prelude"{- wrong -})),
     (TypeOperators,                alwaysOn),
     (OverlappingInstances,         alwaysOn),
     (FlexibleInstances,            alwaysOn)]
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155

getInstalledPackages :: Verbosity -> Compiler -> PackageDBStack -> ProgramConfiguration
                     -> IO PackageIndex
getInstalledPackages verbosity comp packagedbs conf = do
  let compilerid = compilerId comp
  systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram conf ["--meta-pkgdir-system"]
  userPkgDir   <- getUserPackageDir
  let pkgDirs    = nub (concatMap (packageDbPaths userPkgDir systemPkgDir) packagedbs)
  -- putStrLn $ "pkgdirs: " ++ show pkgDirs
  -- call to "lines" necessary, because pkgdir contains an extra newline at the end
  pkgs <- liftM (map addBuiltinVersions . concat) .
          mapM (\ d -> getDirectoryContents d >>= filterM (isPkgDir (display compilerid) d)) .
          concatMap lines $ pkgDirs
  -- putStrLn $ "pkgs: " ++ show pkgs
  let iPkgs =
        map mkInstalledPackageInfo $
        concatMap parsePackage $
        pkgs
  -- putStrLn $ "installed pkgs: " ++ show iPkgs
  return (fromList iPkgs)

getUserPackageDir :: IO FilePath
getUserPackageDir =
  do
    homeDir <- getHomeDirectory
    return $ homeDir </> ".cabal" </> "lib"  -- TODO: determine in some other way

packageDbPaths :: FilePath -> FilePath -> PackageDB -> [FilePath]
packageDbPaths user system db =
  case db of
    GlobalPackageDB         ->  [ system ]
    UserPackageDB           ->  [ user ]
    SpecificPackageDB path  ->  [ path ]

-- | Hack to add version numbers to UHC-builtin packages. This should sooner or
-- later be fixed on the UHC side.
addBuiltinVersions :: String -> String
156
157
{-
addBuiltinVersions "uhcbase"  = "uhcbase-1.0"
158
159
addBuiltinVersions "base"  = "base-3.0"
addBuiltinVersions "array" = "array-0.2"
160
-}
161
162
163
164
165
166
167
168
169
170
addBuiltinVersions xs      = xs

-- | Name of the installed package config file.
installedPkgConfig :: String
installedPkgConfig = "installed-pkg-config"

-- | Check if a certain dir contains a valid package. Currently, we are
-- looking only for the presence of an installed package configuration.
-- TODO: Actually make use of the information provided in the file.
isPkgDir :: String -> String -> String -> IO Bool
171
isPkgDir _ _   ('.' : _)  = return False  -- ignore files starting with a .
172
173
174
175
176
177
isPkgDir c dir xs         = do
                              let candidate = dir </> uhcPackageDir xs c
                              -- putStrLn $ "trying: " ++ candidate
                              doesFileExist (candidate </> installedPkgConfig)

parsePackage :: String -> [PackageId]
178
parsePackage x = map fst (filter (\ (_,y) -> null y) (readP_to_S parse x))
179
180
181
182
183
184

-- | Create a trivial package info from a directory name.
mkInstalledPackageInfo :: PackageId -> InstalledPackageInfo
mkInstalledPackageInfo p = emptyInstalledPackageInfo
  { installedPackageId = InstalledPackageId (display p),
    sourcePackageId    = p }
Andres Loeh's avatar
Andres Loeh committed
185
186
187
188
189
190
191
192
193


-- -----------------------------------------------------------------------------
-- Building

buildLib :: Verbosity -> PackageDescription -> LocalBuildInfo
                      -> Library            -> ComponentLocalBuildInfo -> IO ()
buildLib verbosity pkg_descr lbi lib clbi = do

194
195
  systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram (withPrograms lbi) ["--meta-pkgdir-system"]
  userPkgDir   <- getUserPackageDir
Andres Loeh's avatar
Andres Loeh committed
196
197
198
199
  let runUhcProg = rawSystemProgramConf verbosity uhcProgram (withPrograms lbi)
  let uhcArgs =    -- set package name
                   ["--pkg-build=" ++ display (packageId pkg_descr)]
                   -- common flags lib/exe
200
201
                ++ constructUHCCmdLine userPkgDir systemPkgDir
                                       lbi (libBuildInfo lib) clbi
Andres Loeh's avatar
Andres Loeh committed
202
203
204
205
206
207
208
209
210
211
212
                                       (buildDir lbi) verbosity
                   -- source files
                   -- suboptimal: UHC does not understand module names, so
                   -- we replace periods by path separators
                ++ map (map (\ c -> if c == '.' then pathSeparator else c))
                       (map display (libModules lib))

  runUhcProg uhcArgs
  
  return ()

213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
buildExe :: Verbosity -> PackageDescription -> LocalBuildInfo
                      -> Executable         -> ComponentLocalBuildInfo -> IO ()
buildExe verbosity _pkg_descr lbi exe clbi = do
  systemPkgDir <- rawSystemProgramStdoutConf verbosity uhcProgram (withPrograms lbi) ["--meta-pkgdir-system"]
  userPkgDir   <- getUserPackageDir
  let runUhcProg = rawSystemProgramConf verbosity uhcProgram (withPrograms lbi)
  let uhcArgs =    -- common flags lib/exe
                   constructUHCCmdLine userPkgDir systemPkgDir
                                       lbi (buildInfo exe) clbi
                                       (buildDir lbi) verbosity
                   -- output file
                ++ ["--output", buildDir lbi </> exeName exe]
                   -- main source module
                ++ [modulePath exe]
  runUhcProg uhcArgs

229
230
constructUHCCmdLine :: FilePath -> FilePath
                    -> LocalBuildInfo -> BuildInfo -> ComponentLocalBuildInfo
Andres Loeh's avatar
Andres Loeh committed
231
                    -> FilePath -> Verbosity -> [String]
232
constructUHCCmdLine user system lbi bi clbi odir verbosity =
Andres Loeh's avatar
Andres Loeh committed
233
234
235
236
     -- verbosity
     (if      verbosity >= deafening then ["-v4"]
      else if verbosity >= normal    then []
      else                                ["-v0"])
237
  ++ hcOptions UHC bi
238
     -- flags for language extensions
239
  ++ languageToFlags   (compiler lbi) (defaultLanguage bi)
240
  ++ extensionsToFlags (compiler lbi) (usedExtensions bi)
Andres Loeh's avatar
Andres Loeh committed
241
242
     -- packages
  ++ ["--hide-all-packages"]
243
  ++ uhcPackageDbOptions user system (withPackageDB lbi)
244
  ++ ["--package=uhcbase"]
Andres Loeh's avatar
Andres Loeh committed
245
246
247
248
249
  ++ ["--package=" ++ display (pkgName pkgid) | (_, pkgid) <- componentPackageDeps clbi ]
     -- search paths
  ++ ["-i" ++ odir]
  ++ ["-i" ++ l | l <- nub (hsSourceDirs bi)]
  ++ ["-i" ++ autogenModulesDir lbi]
Nick Smallbone's avatar
Nick Smallbone committed
250
251
     -- cpp options
  ++ ["--optP=" ++ opt | opt <- cppOptions bi]
Andres Loeh's avatar
Andres Loeh committed
252
253
254
255
256
257
258
     -- output path
  ++ ["--odir=" ++ odir]
     -- optimization
  ++ (case withOptimization lbi of
        NoOptimisation       ->  ["-O0"]
        NormalOptimisation   ->  ["-O1"]
        MaximumOptimisation  ->  ["-O2"])
259
260
261
262
263
264
265
266

uhcPackageDbOptions :: FilePath -> FilePath -> PackageDBStack -> [String]
uhcPackageDbOptions user system db = map (\ x -> "--pkg-searchpath=" ++ x)
                                         (concatMap (packageDbPaths user system) db)

-- -----------------------------------------------------------------------------
-- Installation

267
installLib :: Verbosity -> LocalBuildInfo
268
           -> FilePath -> FilePath -> FilePath
269
           -> PackageDescription -> Library -> IO ()
270
installLib verbosity _lbi targetDir _dynlibTargetDir builtDir pkg _library = do
271
272
    -- putStrLn $ "dest:  " ++ targetDir
    -- putStrLn $ "built: " ++ builtDir
273
    installDirectoryContents verbosity (builtDir </> display (packageId pkg)) targetDir
274
275

-- currently hardcoded UHC code generator and variant to use
276
uhcTarget, uhcTargetVariant :: String
277
278
279
280
uhcTarget        = "bc"
uhcTargetVariant = "plain"

-- root directory for a package in UHC
281
282
uhcPackageDir    :: String -> String -> FilePath
uhcPackageSubDir ::           String -> FilePath
283
uhcPackageDir    pkgid compilerid = pkgid </> uhcPackageSubDir compilerid
284
uhcPackageSubDir       compilerid = compilerid </> uhcTarget </> uhcTargetVariant
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306

-- -----------------------------------------------------------------------------
-- Registering

registerPackage
  :: Verbosity
  -> InstalledPackageInfo
  -> PackageDescription
  -> LocalBuildInfo
  -> Bool
  -> PackageDBStack
  -> IO ()
registerPackage verbosity installedPkgInfo pkg lbi inplace _packageDbs = do
    let installDirs = absoluteInstallDirs pkg lbi NoCopyDest
        pkgdir  | inplace   = buildDir lbi       </> uhcPackageDir    (display pkgid) (display compilerid)
                | otherwise = libdir installDirs </> uhcPackageSubDir                 (display compilerid)
    createDirectoryIfMissingVerbose verbosity True pkgdir
    writeUTF8File (pkgdir </> installedPkgConfig)
                  (showInstalledPackageInfo installedPkgInfo)
  where
    pkgid      = packageId pkg
    compilerid = compilerId (compiler lbi)