Configure.hs 42.9 KB
Newer Older
1
2
-----------------------------------------------------------------------------
-- |
ijones's avatar
ijones committed
3
-- Module      :  Distribution.Simple.Configure
4
-- Copyright   :  Isaac Jones 2003-2005
5
--
Duncan Coutts's avatar
Duncan Coutts committed
6
-- Maintainer  :  cabal-devel@haskell.org
ijones's avatar
ijones committed
7
-- Portability :  portable
8
--
Duncan Coutts's avatar
Duncan Coutts committed
9
10
11
12
13
14
15
16
17
18
19
20
21
-- This deals with the /configure/ phase. It provides the 'configure' action
-- which is given the package description and configure flags. It then tries
-- to: configure the compiler; resolves any conditionals in the package
-- description; resolve the package dependencies; check if all the extensions
-- used by this package are supported by the compiler; check that all the build
-- tools are available (including version checks if appropriate); checks for
-- any required @pkg-config@ packages (updating the 'BuildInfo' with the
-- results)
-- 
-- Then based on all this it saves the info in the 'LocalBuildInfo' and writes
-- it out to the @dist\/setup-config@ file. It also displays various details to
-- the user, the amount of information displayed depending on the verbosity
-- level.
22

ijones's avatar
ijones committed
23
{- All rights reserved.
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
50
51
52

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. -}

ijones's avatar
ijones committed
53
54
module Distribution.Simple.Configure (configure,
                                      writePersistBuildConfig,
ijones's avatar
ijones committed
55
                                      getPersistBuildConfig,
56
                                      checkPersistBuildConfig,
57
                                      maybeGetPersistBuildConfig,
58
--                                      getConfiguredPkgDescr,
ijones's avatar
ijones committed
59
                                      localBuildInfoFile,
60
                                      getInstalledPackages,
61
                                      configDependency,
62
                                      configCompiler, configCompilerAux,
63
                                      ccLdOptionsBuildInfo,
jpbernardy's avatar
jpbernardy committed
64
                                      tryGetConfigStateFile,
65
                                      checkForeignDeps,
ijones's avatar
ijones committed
66
                                     )
ijones's avatar
ijones committed
67
    where
68

69
import Distribution.Simple.Compiler
70
    ( CompilerFlavor(..), Compiler(compilerId), compilerFlavor, compilerVersion
71
    , showCompilerId, unsupportedExtensions, PackageDB(..), PackageDBStack )
72
import Distribution.Package
73
    ( PackageName(PackageName), PackageId, PackageIdentifier(PackageIdentifier)
74
75
    , packageName, packageVersion, Package(..)
    , Dependency(Dependency), simplifyDependency )
76
import Distribution.InstalledPackageInfo
77
    ( InstalledPackageInfo, emptyInstalledPackageInfo )
78
79
import qualified Distribution.InstalledPackageInfo as Installed
    ( InstalledPackageInfo_(..) )
80
81
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.PackageIndex (PackageIndex)
82
import Distribution.PackageDescription as PD
83
    ( PackageDescription(..), GenericPackageDescription(..)
84
    , Library(..), hasLibs, Executable(..), BuildInfo(..)
85
86
    , HookedBuildInfo, updatePackageDescription, allBuildInfo
    , FlagName(..) )
87
import Distribution.PackageDescription.Configuration
88
    ( finalizePackageDescription )
89
import Distribution.PackageDescription.Check
90
91
    ( PackageCheck(..)
    , checkPackage, checkConfiguredPackage, checkPackageFiles )
92
import Distribution.Simple.Program
93
    ( Program(..), ProgramLocation(..), ConfiguredProgram(..)
Duncan Coutts's avatar
Duncan Coutts committed
94
    , ProgramConfiguration, defaultProgramConfiguration
95
    , configureAllKnownPrograms, knownPrograms, lookupKnownProgram
96
    , userSpecifyArgss, userSpecifyPaths
97
98
    , lookupProgram, requireProgram, requireProgramVersion
    , pkgConfigProgram, gccProgram, rawSystemProgramStdoutConf )
99
import Distribution.Simple.Setup
100
    ( ConfigFlags(..), CopyDest(..), fromFlag, fromFlagOrDefault, flagToMaybe )
101
import Distribution.Simple.InstallDirs
102
    ( InstallDirs(..), defaultInstallDirs, combineInstallDirs )
103
import Distribution.Simple.LocalBuildInfo
104
    ( LocalBuildInfo(..), ComponentLocalBuildInfo(..)
105
    , absoluteInstallDirs, prefixRelativeInstallDirs, isInternalPackage )
106
import Distribution.Simple.Utils
107
    ( die, warn, info, setupMessage, createDirectoryIfMissingVerbose
108
    , intercalate, comparing, cabalVersion, cabalBootstrapping
109
110
    , withFileContents, writeFileAtomic 
    , withTempFile )
111
112
113
import Distribution.Simple.Register
    ( removeInstalledConfig )
import Distribution.System
114
    ( OS(..), buildOS, buildArch )
115
import Distribution.Version
116
117
    ( Version(..), anyVersion, orLaterVersion, withinRange
    , isSpecificVersion, isAnyVersion
118
    , LowerBound(..), asVersionIntervals, simplifyVersionRange )
119
import Distribution.Verbosity
120
    ( Verbosity, lessVerbose )
121

122
123
import qualified Distribution.Simple.GHC  as GHC
import qualified Distribution.Simple.JHC  as JHC
David Himmelstrup's avatar
David Himmelstrup committed
124
import qualified Distribution.Simple.LHC  as LHC
125
126
127
import qualified Distribution.Simple.NHC  as NHC
import qualified Distribution.Simple.Hugs as Hugs

128
import Control.Monad
129
    ( when, unless, foldM, filterM )
130
import Data.List
131
    ( nub, partition, isPrefixOf, maximumBy, inits )
132
import Data.Maybe
133
    ( fromMaybe, isNothing )
134
135
import Data.Monoid
    ( Monoid(..) )
136
import System.Directory
137
    ( doesFileExist, getModificationTime, createDirectoryIfMissing, getTemporaryDirectory )
138
139
140
import System.Exit
    ( ExitCode(..), exitWith )
import System.FilePath
141
    ( (</>), isAbsolute )
142
import qualified System.Info
143
    ( compilerName, compilerVersion )
144
import System.IO
145
    ( hPutStrLn, stderr, hClose )
146
import Distribution.Text
147
    ( Text(disp), display, simpleParse )
148
149
import Text.PrettyPrint.HughesPJ
    ( comma, punctuate, render, nest, sep )
150
import Distribution.Compat.Exception ( catchExit, catchIO )
151

152
import Prelude hiding (catch)
153

154
155
tryGetConfigStateFile :: (Read a) => FilePath -> IO (Either String a)
tryGetConfigStateFile filename = do
156
157
158
  exists <- doesFileExist filename
  if not exists
    then return (Left missing)
159
160
    else withFileContents filename $ \str ->
      case lines str of
161
        [headder, rest] -> case checkHeader headder of
162
          Just msg -> return (Left msg)
163
          Nothing  -> case reads rest of
164
165
166
            [(bi,_)] -> return (Right bi)
            _        -> return (Left cantParse)
        _            -> return (Left cantParse)
167
168
169
  where
    checkHeader :: String -> Maybe String
    checkHeader header = case parseHeader header of
170
      Just (cabalId, compId)
171
172
        | cabalId
       == currentCabalId -> Nothing
173
        | otherwise      -> Just (badVersion cabalId compId)
174
175
176
177
178
      Nothing            -> Just cantParse

    missing   = "Run the 'configure' command first."
    cantParse = "Saved package config file seems to be corrupt. "
             ++ "Try re-running the 'configure' command."
179
    badVersion cabalId compId
180
181
              = "You need to re-run the 'configure' command. "
             ++ "The version of Cabal being used has changed (was "
182
183
             ++ display cabalId ++ ", now "
             ++ display currentCabalId ++ ")."
184
185
186
             ++ badcompiler compId
    badcompiler compId | compId == currentCompilerId = ""
                       | otherwise
187
              = " Additionally the compiler is different (was "
188
             ++ display compId ++ ", now "
189
             ++ display currentCompilerId
190
             ++ ") which is probably the cause of the problem."
191

192
-- internal function
193
194
195
tryGetPersistBuildConfig :: FilePath -> IO (Either String LocalBuildInfo)
tryGetPersistBuildConfig distPref
    = tryGetConfigStateFile (localBuildInfoFile distPref)
196

197
198
199
-- |Read the 'localBuildInfoFile'.  Error if it doesn't exist.  Also
-- fail if the file containing LocalBuildInfo is older than the .cabal
-- file, indicating that a re-configure is required.
200
201
202
getPersistBuildConfig :: FilePath -> IO LocalBuildInfo
getPersistBuildConfig distPref = do
  lbi <- tryGetPersistBuildConfig distPref
203
204
  either die return lbi

ijones's avatar
ijones committed
205
-- |Try to read the 'localBuildInfoFile'.
206
207
208
maybeGetPersistBuildConfig :: FilePath -> IO (Maybe LocalBuildInfo)
maybeGetPersistBuildConfig distPref = do
  lbi <- tryGetPersistBuildConfig distPref
209
  return $ either (const Nothing) Just lbi
ijones's avatar
ijones committed
210

ijones's avatar
ijones committed
211
212
-- |After running configure, output the 'LocalBuildInfo' to the
-- 'localBuildInfoFile'.
213
214
writePersistBuildConfig :: FilePath -> LocalBuildInfo -> IO ()
writePersistBuildConfig distPref lbi = do
Ross Paterson's avatar
Ross Paterson committed
215
  createDirectoryIfMissing False distPref
216
217
  writeFileAtomic (localBuildInfoFile distPref)
                  (showHeader pkgid ++ '\n' : show lbi)
218
219
220
221
222
  where
    pkgid   = packageId (localPkgDescr lbi)

showHeader :: PackageIdentifier -> String
showHeader pkgid =
223
224
225
     "Saved package config for " ++ display pkgid
  ++ " written by " ++ display currentCabalId
  ++      " using " ++ display currentCompilerId
226
227
228
  where

currentCabalId :: PackageIdentifier
Duncan Coutts's avatar
Duncan Coutts committed
229
currentCabalId = PackageIdentifier (PackageName "Cabal") currentVersion
230
231
232
233
  where currentVersion | cabalBootstrapping = Version [0] []
                       | otherwise          = cabalVersion

currentCompilerId :: PackageIdentifier
Duncan Coutts's avatar
Duncan Coutts committed
234
currentCompilerId = PackageIdentifier (PackageName System.Info.compilerName)
235
236
                                      System.Info.compilerVersion

237
parseHeader :: String -> Maybe (PackageIdentifier, PackageIdentifier)
238
239
240
parseHeader header = case words header of
  ["Saved", "package", "config", "for", pkgid,
   "written", "by", cabalid, "using", compilerid]
241
242
243
    -> case (simpleParse pkgid :: Maybe PackageIdentifier,
             simpleParse cabalid,
             simpleParse compilerid) of
244
245
246
247
248
        (Just _,
         Just cabalid',
         Just compilerid') -> Just (cabalid', compilerid')
        _                  -> Nothing
  _                        -> Nothing
249

250
251
-- |Check that localBuildInfoFile is up-to-date with respect to the
-- .cabal file.
252
253
checkPersistBuildConfig :: FilePath -> FilePath -> IO ()
checkPersistBuildConfig distPref pkg_descr_file = do
254
  t0 <- getModificationTime pkg_descr_file
255
  t1 <- getModificationTime $ localBuildInfoFile distPref
256
257
258
  when (t0 > t1) $
    die (pkg_descr_file ++ " has been changed, please re-configure.")

Ross Paterson's avatar
Ross Paterson committed
259
-- |@dist\/setup-config@
260
261
localBuildInfoFile :: FilePath -> FilePath
localBuildInfoFile distPref = distPref </> "setup-config"
ijones's avatar
ijones committed
262

263
-- -----------------------------------------------------------------------------
ijones's avatar
ijones committed
264
265
-- * Configuration
-- -----------------------------------------------------------------------------
266

267
268
-- |Perform the \"@.\/setup configure@\" action.
-- Returns the @.setup-config@ file.
269
configure :: ( Either GenericPackageDescription PackageDescription
270
             , HookedBuildInfo)
271
          -> ConfigFlags -> IO LocalBuildInfo
Duncan Coutts's avatar
Duncan Coutts committed
272
configure (e_pkg_descr, pbi) cfg
273
274
  = do  let distPref = fromFlag (configDistPref cfg)
            verbosity = fromFlag (configVerbosity cfg)
Duncan Coutts's avatar
Duncan Coutts committed
275
            pkg_descr0 = either packageDescription id e_pkg_descr
276

Duncan Coutts's avatar
Duncan Coutts committed
277
        setupMessage verbosity "Configuring" (packageId pkg_descr0)
278

279
        createDirectoryIfMissingVerbose (lessVerbose verbosity) True distPref
280

281
282
283
        let programsConfig = userSpecifyArgss (configProgramArgs cfg)
                           . userSpecifyPaths (configProgramPaths cfg)
                           $ configPrograms cfg
284
            userInstall = fromFlag (configUserInstall cfg)
285
286
            packageDbs = implicitPackageDbStack userInstall
                           (flagToMaybe $ configPackageDB cfg)
287

288
289
        -- detect compiler
        (comp, programsConfig') <- configCompiler
290
291
292
          (flagToMaybe $ configHcFlavor cfg)
          (flagToMaybe $ configHcPath cfg) (flagToMaybe $ configHcPkg cfg)
          programsConfig (lessVerbose verbosity)
293
294
        let version = compilerVersion comp
            flavor  = compilerFlavor comp
295

296
        -- Create a PackageIndex that makes *any libraries that might be*
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
        -- defined internally to this package look like installed packages, in
        -- case an executable should refer to any of them as dependencies.
        --
        -- It must be *any libraries that might be* defined rather than the
        -- actual definitions, because these depend on conditionals in the .cabal
        -- file, and we haven't resolved them yet.  finalizePackageDescription
        -- does the resolution of conditionals, and it takes internalPackageSet
        -- as part of its input.
        --
        -- Currently a package can define no more than one library (which has
        -- the same name as the package) but we could extend this later.
        -- If we later allowed private internal libraries, then here we would
        -- need to pre-scan the conditional data to make a list of all private
        -- libraries that could possibly be defined by the .cabal file.
        let internalPackageSet = PackageIndex.fromList [ emptyInstalledPackageInfo {
                  Installed.package = package pkg_descr0
              } ]
        maybeInstalledPackageSet <- getInstalledPackages (lessVerbose verbosity) comp
315
                                      packageDbs programsConfig'
316
317
318
        -- The merge of the internal and installed packages
        let maybePackageSet = (`PackageIndex.merge` internalPackageSet)
                                                    `fmap` maybeInstalledPackageSet
319

Duncan Coutts's avatar
Duncan Coutts committed
320
        (pkg_descr0', flags) <- case e_pkg_descr of
321
322
            Left ppd ->
                case finalizePackageDescription
323
                       (configConfigurationsFlags cfg)
324
                       maybePackageSet
325
                       Distribution.System.buildOS
326
                       Distribution.System.buildArch
327
                       (compilerId comp)
328
                       (configConstraints cfg)
329
330
                       ppd
                of Right r -> return r
331
                   Left missing ->
332
                       die $ "At least the following dependencies are missing:\n"
333
334
335
336
                         ++ (render . nest 4 . sep . punctuate comma)
                            [ disp (Dependency name range')
                            | Dependency name range <- missing
                            , let range' = simplifyVersionRange range ]
337
            Right pd -> return (pd,[])
338

339
340
341
        -- add extra include/lib dirs as specified in cfg
        -- we do it here so that those get checked too
        let pkg_descr = addExtraIncludeLibDirs pkg_descr0'
342

343
        when (not (null flags)) $
344
345
346
          info verbosity $ "Flags chosen: "
                        ++ intercalate ", " [ name ++ "=" ++ display value
                                            | (FlagName name, value) <- flags ]
347

348
        checkPackageProblems verbosity
Duncan Coutts's avatar
Duncan Coutts committed
349
          (either Just (\_->Nothing) e_pkg_descr) --TODO: make the Either go away
350
          (updatePackageDescription pbi pkg_descr)
351

352
353
        let installedPackageSet = fromMaybe bogusPackageSet maybeInstalledPackageSet
            packageSet          = fromMaybe bogusPackageSet maybePackageSet
354
355
356
357
358
359
360
            -- FIXME: For Hugs, nhc98 and other compilers we do not know what
            -- packages are already installed, so we just make some up, pretend
            -- that they do exist and just hope for the best. We make them up
            -- based on what other package the package we're currently building
            -- happens to depend on. See 'inventBogusPackageId' below.
            -- Let's hope they really are installed... :-)
            bogusDependencies = map inventBogusPackageId (buildDepends pkg_descr)
361
            bogusPackageSet = PackageIndex.fromList
362
              [ emptyInstalledPackageInfo {
363
                  Installed.package = bogusPackageId
364
365
366
                  -- note that these bogus packages have no other dependencies
                }
              | bogusPackageId <- bogusDependencies ]
367
368
369
370
        allPkgDeps <- case flavor of
          GHC -> mapM (configDependency verbosity internalPackageSet installedPackageSet) (buildDepends pkg_descr)
          JHC -> mapM (configDependency verbosity internalPackageSet installedPackageSet) (buildDepends pkg_descr)
          LHC -> mapM (configDependency verbosity internalPackageSet installedPackageSet) (buildDepends pkg_descr)
371
          _   -> return bogusDependencies
Simon Marlow's avatar
Simon Marlow committed
372

373
374
        let (internalPkgDeps, externalPkgDeps) = partition (isInternalPackage pkg_descr) allPkgDeps

375
        when (not (null internalPkgDeps) && not (newPackageDepsBehaviour pkg_descr)) $
376
377
            die $ "The field 'build-depends: "
               ++ intercalate ", " (map (display . packageName) internalPkgDeps)
378
               ++ "' refers to a library which is defined within the same "
379
380
               ++ "package. To use this feature the package must specify at "
               ++ "least 'cabal-version: >= 1.8'."
381

382
        packageDependsIndex <-
383
          case PackageIndex.dependencyClosure packageSet externalPkgDeps of
384
385
386
            Left packageDependsIndex -> return packageDependsIndex
            Right broken ->
              die $ "The following installed packages are broken because other"
387
388
                 ++ " packages they depend on are missing. These broken "
                 ++ "packages must be rebuilt before they can be used.\n"
389
                 ++ unlines [ "package "
390
                           ++ display (packageId pkg)
391
                           ++ " is broken due to missing package "
392
                           ++ intercalate ", " (map display deps)
393
394
                            | (pkg, deps) <- broken ]

395
        let pseudoTopPkg = emptyInstalledPackageInfo {
396
                Installed.package = packageId pkg_descr,
397
                Installed.depends = allPkgDeps
398
              }
399
400
        case PackageIndex.dependencyInconsistencies
           . PackageIndex.insert pseudoTopPkg
401
           $ packageDependsIndex of
402
403
404
          [] -> return ()
          inconsistencies ->
            warn verbosity $
405
                 "This package indirectly depends on multiple versions of the same "
406
              ++ "package. This is highly likely to cause a compile failure.\n"
407
408
              ++ unlines [ "package " ++ display pkg ++ " requires "
                        ++ display (PackageIdentifier name ver)
409
410
                         | (name, uses) <- inconsistencies
                         , (pkg, ver) <- uses ]
Simon Marlow's avatar
Simon Marlow committed
411

412
        removeInstalledConfig distPref
Simon Marlow's avatar
Simon Marlow committed
413

414
415
416
        -- installation directories
        defaultDirs <- defaultInstallDirs flavor userInstall (hasLibs pkg_descr)
        let installDirs = combineInstallDirs fromFlagOrDefault
417
                            defaultDirs (configInstallDirs cfg)
418

419
        -- check extensions
420
        let extlist = nub $ concatMap extensions (allBuildInfo pkg_descr)
421
        let exts = unsupportedExtensions comp extlist
422
        unless (null exts) $ warn verbosity $ -- Just warn, FIXME: Should this be an error?
423
            display flavor ++ " does not support the following extensions: " ++
424
            intercalate ", " (map display exts)
425

426
        let requiredBuildTools = concatMap buildTools (allBuildInfo pkg_descr)
427
428
        programsConfig'' <-
              configureAllKnownPrograms (lessVerbose verbosity) programsConfig'
429
          >>= configureRequiredPrograms verbosity requiredBuildTools
430

431
432
        (pkg_descr', programsConfig''') <- configurePkgconfigPackages verbosity
                                            pkg_descr programsConfig''
433

434
435
436
437
438
439
        split_objs <-
           if not (fromFlag $ configSplitObjs cfg)
                then return False
                else case flavor of
                            GHC | version >= Version [6,5] [] -> return True
                            _ -> do warn verbosity
Ian Lynagh's avatar
Ian Lynagh committed
440
                                         ("this compiler does not support " ++
441
442
443
                                          "--enable-split-objs; ignoring")
                                    return False

444
        -- The allPkgDeps contains all the package deps for the whole package
445
446
447
448
449
450
451
452
453
        -- but we need to select the subset for this specific component.
        -- we just take the subset for the package names this component
        -- needs. Note, this only works because we cannot yet depend on two
        -- versions of the same package.
        let configLib lib = configComponent (libBuildInfo lib)
            configExe exe = (exeName exe, configComponent(buildInfo exe))
            configComponent bi = ComponentLocalBuildInfo {
              componentPackageDeps =
                if newPackageDepsBehaviour pkg_descr'
454
455
                  then selectDependencies bi allPkgDeps
                  else allPkgDeps
456
457
458
459
460
461
462
            }
            selectDependencies :: BuildInfo -> [PackageId] -> [PackageId]
            selectDependencies bi pkgs =
                [ pkg | pkg <- pkgs, packageName pkg `elem` names ]
              where
                names = [ name | Dependency name _ <- targetBuildDepends bi ]

463
464
465
466
467
        let lbi = LocalBuildInfo{
                    installDirTemplates = installDirs,
                    compiler            = comp,
                    buildDir            = distPref </> "build",
                    scratchDir          = fromFlagOrDefault
468
469
                                            (distPref </> "scratch")
                                            (configScratchDir cfg),
470
471
                    libraryConfig       = configLib `fmap` library pkg_descr',
                    executableConfigs   = configExe `fmap` executables pkg_descr',
472
                    installedPkgs       = packageDependsIndex,
473
                    pkgDescrFile        = Nothing,
474
475
476
477
478
479
480
481
482
                    localPkgDescr       = pkg_descr',
                    withPrograms        = programsConfig''',
                    withVanillaLib      = fromFlag $ configVanillaLib cfg,
                    withProfLib         = fromFlag $ configProfLib cfg,
                    withSharedLib       = fromFlag $ configSharedLib cfg,
                    withProfExe         = fromFlag $ configProfExe cfg,
                    withOptimization    = fromFlag $ configOptimization cfg,
                    withGHCiLib         = fromFlag $ configGHCiLib cfg,
                    splitObjs           = split_objs,
483
                    stripExes           = fromFlag $ configStripExes cfg,
484
                    withPackageDB       = packageDbs,
485
486
                    progPrefix          = fromFlag $ configProgPrefix cfg,
                    progSuffix          = fromFlag $ configProgSuffix cfg
Duncan Coutts's avatar
Duncan Coutts committed
487
                  }
ijones's avatar
ijones committed
488

489
490
        let dirs = absoluteInstallDirs (packageId pkg_descr) lbi NoCopyDest
            relative = prefixRelativeInstallDirs (packageId pkg_descr) lbi
491

492
493
494
        unless (isAbsolute (prefix dirs)) $ die $
            "expected an absolute directory name for --prefix: " ++ prefix dirs

495
496
        info verbosity $ "Using " ++ display currentCabalId
                      ++ " compiled by " ++ display currentCompilerId
497
498
        info verbosity $ "Using compiler: " ++ showCompilerId comp
        info verbosity $ "Using install prefix: " ++ prefix dirs
499

500
501
        let dirinfo name dir isPrefixRelative =
              info verbosity $ name ++ " installed in: " ++ dir ++ relNote
502
503
504
505
506
              where relNote = case buildOS of
                      Windows | not (hasLibs pkg_descr)
                             && isNothing isPrefixRelative
                             -> "  (fixed location)"
                      _      -> ""
507

508
509
510
511
512
513
514
        dirinfo "Binaries"         (bindir dirs)     (bindir relative)
        dirinfo "Libraries"        (libdir dirs)     (libdir relative)
        dirinfo "Private binaries" (libexecdir dirs) (libexecdir relative)
        dirinfo "Data files"       (datadir dirs)    (datadir relative)
        dirinfo "Documentation"    (docdir dirs)     (docdir relative)

        sequence_ [ reportProgram verbosity prog configuredProg
515
                  | (prog, configuredProg) <- knownPrograms programsConfig''' ]
516

517
        return lbi
518

519
520
521
    where
      addExtraIncludeLibDirs pkg_descr =
          let extraBi = mempty { extraLibDirs = configExtraLibDirs cfg
Malcolm.Wallace's avatar
Malcolm.Wallace committed
522
                               , PD.includeDirs = configExtraIncludeDirs cfg}
523
524
525
526
              modifyLib l        = l{ libBuildInfo = libBuildInfo l `mappend` extraBi }
              modifyExecutable e = e{ buildInfo    = buildInfo e    `mappend` extraBi}
          in pkg_descr{ library     = modifyLib        `fmap` library pkg_descr
                      , executables = modifyExecutable  `map` executables pkg_descr}
527
528


529
530
531
-- -----------------------------------------------------------------------------
-- Configuring package dependencies

ijones's avatar
ijones committed
532
533
-- |Converts build dependencies to a versioned dependency.  only sets
-- version information for exact versioned dependencies.
534
inventBogusPackageId :: Dependency -> PackageIdentifier
Duncan Coutts's avatar
Duncan Coutts committed
535
536
537
538
539
inventBogusPackageId (Dependency s vr) = case isSpecificVersion vr of
  -- if they specify the exact version, use that:
  Just v -> PackageIdentifier s v
  -- otherwise, just set it to empty
  Nothing -> PackageIdentifier s (Version [] [])
ijones's avatar
ijones committed
540

541
542
543
544
545
reportProgram :: Verbosity -> Program -> Maybe ConfiguredProgram -> IO ()
reportProgram verbosity prog Nothing
    = info verbosity $ "No " ++ programName prog ++ " found"
reportProgram verbosity prog (Just configuredProg)
    = info verbosity $ "Using " ++ programName prog ++ version ++ location
546
547
548
549
550
    where location = case programLocation configuredProg of
            FoundOnSystem p -> " found on system at: " ++ p
            UserSpecified p -> " given by user at: " ++ p
          version = case programVersion configuredProg of
            Nothing -> ""
551
            Just v  -> " version " ++ display v
ijones's avatar
ijones committed
552

553
554
hackageUrl :: String
hackageUrl = "http://hackage.haskell.org/cgi-bin/hackage-scripts/package/"
555

ijones's avatar
ijones committed
556
-- | Test for a package dependency and record the version we have installed.
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
configDependency :: Verbosity
                 -> PackageIndex InstalledPackageInfo  -- ^ Internally defined packages
                 -> PackageIndex InstalledPackageInfo  -- ^ Installed packages
                 -> Dependency
                 -> IO PackageIdentifier
configDependency verbosity internalIndex installedIndex dep@(Dependency pkgname _) =
  -- If the dependency specification matches anything in the internal package
  -- index, then we prefer that match to anything in the second.
  -- For example:
  --
  -- Name: MyLibrary
  -- Version: 0.1
  -- Library
  --     ..
  -- Executable my-exec
  --     build-depends: MyLibrary
  --
  -- We want "build-depends: MyLibrary" always to match the internal library
  -- even if there is a newer installed library "MyLibrary-0.2".
  -- However, "build-depends: MyLibrary >= 0.2" should match the installed one.
  case PackageIndex.lookupDependency internalIndex dep
                       `inPreferenceTo`
                   PackageIndex.lookupDependency installedIndex dep of
580
        [] -> die $ "cannot satisfy dependency "
581
                      ++ display (simplifyDependency dep) ++ "\n"
Duncan Coutts's avatar
Duncan Coutts committed
582
                      ++ "Perhaps you need to download and install it from\n"
Duncan Coutts's avatar
Duncan Coutts committed
583
                      ++ hackageUrl ++ display pkgname ++ "?"
584
        pkgs -> do let pkgid = maximumBy (comparing packageVersion) (map packageId pkgs)
585
586
                   info verbosity $ "Dependency "
                                 ++ display (simplifyDependency dep)
587
                                ++ ": using " ++ display pkgid
588
                   return pkgid
589
590
591
592
593
594
  where
    -- If there are any matches in the first set, return them, otherwise return
    -- the second set.
    inPreferenceTo :: [a] -> [a] -> [a]
    inPreferenceTo [] second = second
    inPreferenceTo first _   = first
ijones's avatar
ijones committed
595

596
597
getInstalledPackages :: Verbosity -> Compiler
                     -> PackageDBStack -> ProgramConfiguration
598
                     -> IO (Maybe (PackageIndex InstalledPackageInfo))
599
getInstalledPackages verbosity comp packageDBs progconf = do
600
  info verbosity "Reading installed packages..."
601
  case compilerFlavor comp of
602
603
604
    GHC -> Just `fmap` GHC.getInstalledPackages verbosity packageDBs progconf
    JHC -> Just `fmap` JHC.getInstalledPackages verbosity packageDBs progconf
    LHC -> Just `fmap` LHC.getInstalledPackages verbosity packageDBs progconf
605
    _   -> return Nothing
ekarttun's avatar
ekarttun committed
606

607
608
609
610
611
-- | Currently the user interface specifies the package dbs to use with just a
-- single valued option, a 'PackageDB'. However internally we represent the
-- stack of 'PackageDB's explictly as a list. This function converts encodes
-- the package db stack implicit in a single packagedb.
--
612
613
614
615
616
617
618
619
implicitPackageDbStack :: Bool -> Maybe PackageDB -> PackageDBStack
implicitPackageDbStack userInstall maybePackageDB
  | userInstall = GlobalPackageDB : UserPackageDB : extra
  | otherwise   = GlobalPackageDB : extra
  where
    extra = case maybePackageDB of
      Just (SpecificPackageDB db) -> [SpecificPackageDB db]
      _                           -> []
620

621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
newPackageDepsBehaviourMinVersion :: Version
newPackageDepsBehaviourMinVersion = Version { versionBranch = [1,7,1], versionTags = [] }

-- In older cabal versions, there was only one set of package dependencies for
-- the whole package. In this version, we can have separate dependencies per
-- target, but we only enable this behaviour if the minimum cabal version
-- specified is >= a certain minimum. Otherwise, for compatibility we use the
-- old behaviour.
newPackageDepsBehaviour :: PackageDescription -> Bool
newPackageDepsBehaviour pkg_descr =
   minVersionRequired >= newPackageDepsBehaviourMinVersion
  where
    minVersionRequired =
      case asVersionIntervals (descCabalVersion pkg_descr) of
        []                      -> Version [0] []
        ((LowerBound v _, _):_) -> v

638
639
640
641
642
643
644
645
-- -----------------------------------------------------------------------------
-- Configuring program dependencies

configureRequiredPrograms :: Verbosity -> [Dependency] -> ProgramConfiguration -> IO ProgramConfiguration
configureRequiredPrograms verbosity deps conf =
  foldM (configureRequiredProgram verbosity) conf deps

configureRequiredProgram :: Verbosity -> ProgramConfiguration -> Dependency -> IO ProgramConfiguration
Duncan Coutts's avatar
Duncan Coutts committed
646
configureRequiredProgram verbosity conf (Dependency (PackageName progName) verRange) =
647
  case lookupKnownProgram progName conf of
Duncan Coutts's avatar
Duncan Coutts committed
648
    Nothing -> die ("Unknown build tool " ++ progName)
649
650
651
652
653
654
655
656
657
658
    Just prog
      -- requireProgramVersion always requires the program have a version
      -- but if the user says "build-depends: foo" ie no version constraint
      -- then we should not fail if we cannot discover the program version.
      | verRange == anyVersion -> do
          (_, conf') <- requireProgram verbosity prog conf
          return conf'
      | otherwise -> do
          (_, _, conf') <- requireProgramVersion verbosity prog verRange conf
          return conf'
659

660
661
662
663
664
665
666
667
668
-- -----------------------------------------------------------------------------
-- Configuring pkg-config package dependencies

configurePkgconfigPackages :: Verbosity -> PackageDescription
                           -> ProgramConfiguration
                           -> IO (PackageDescription, ProgramConfiguration)
configurePkgconfigPackages verbosity pkg_descr conf
  | null allpkgs = return (pkg_descr, conf)
  | otherwise    = do
669
670
671
    (_, _, conf') <- requireProgramVersion
                       (lessVerbose verbosity) pkgConfigProgram
                       (orLaterVersion $ Version [0,9,0] []) conf
672
673
674
675
676
    mapM_ requirePkg allpkgs
    lib'  <- updateLibrary (library pkg_descr)
    exes' <- mapM updateExecutable (executables pkg_descr)
    let pkg_descr' = pkg_descr { library = lib', executables = exes' }
    return (pkg_descr', conf')
677
678

  where
679
680
681
682
    allpkgs = concatMap pkgconfigDepends (allBuildInfo pkg_descr)
    pkgconfig = rawSystemProgramStdoutConf (lessVerbose verbosity)
                  pkgConfigProgram conf

Duncan Coutts's avatar
Duncan Coutts committed
683
    requirePkg dep@(Dependency (PackageName pkg) range) = do
684
      version <- pkgconfig ["--modversion", pkg]
685
686
                 `catchIO`   (\_ -> die notFound)
                 `catchExit` (\_ -> die notFound)
687
      case simpleParse version of
688
689
        Nothing -> die "parsing output of pkg-config --modversion failed"
        Just v | not (withinRange v range) -> die (badVersion v)
690
               | otherwise                 -> info verbosity (depSatisfied v)
691
      where
692
693
694
695
        notFound     = "The pkg-config package " ++ pkg ++ versionRequirement
                    ++ " is required but it could not be found."
        badVersion v = "The pkg-config package " ++ pkg ++ versionRequirement
                    ++ " is required but the version installed on the"
696
                    ++ " system is version " ++ display v
Duncan Coutts's avatar
Duncan Coutts committed
697
        depSatisfied v = "Dependency " ++ display dep
698
                      ++ ": using version " ++ display v
699
700

        versionRequirement
Duncan Coutts's avatar
Duncan Coutts committed
701
702
          | isAnyVersion range = ""
          | otherwise          = " version " ++ display range
703
704
705

    updateLibrary Nothing    = return Nothing
    updateLibrary (Just lib) = do
706
      bi <- pkgconfigBuildInfo (pkgconfigDepends (libBuildInfo lib))
707
      return $ Just lib { libBuildInfo = libBuildInfo lib `mappend` bi }
708
709

    updateExecutable exe = do
710
      bi <- pkgconfigBuildInfo (pkgconfigDepends (buildInfo exe))
711
      return exe { buildInfo = buildInfo exe `mappend` bi }
712
713

    pkgconfigBuildInfo :: [Dependency] -> IO BuildInfo
714
715
716
    pkgconfigBuildInfo []      = return mempty
    pkgconfigBuildInfo pkgdeps = do
      let pkgs = nub [ display pkg | Dependency pkg _ <- pkgdeps ]
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
      ccflags <- pkgconfig ("--cflags" : pkgs)
      ldflags <- pkgconfig ("--libs"   : pkgs)
      return (ccLdOptionsBuildInfo (words ccflags) (words ldflags))

-- | Makes a 'BuildInfo' from C compiler and linker flags.
--
-- This can be used with the output from configuration programs like pkg-config
-- and similar package-specific programs like mysql-config, freealut-config etc.
-- For example:
--
-- > ccflags <- rawSystemProgramStdoutConf verbosity prog conf ["--cflags"]
-- > ldflags <- rawSystemProgramStdoutConf verbosity prog conf ["--libs"]
-- > return (ccldOptionsBuildInfo (words ccflags) (words ldflags))
--
ccLdOptionsBuildInfo :: [String] -> [String] -> BuildInfo
ccLdOptionsBuildInfo cflags ldflags =
  let (includeDirs',  cflags')   = partition ("-I" `isPrefixOf`) cflags
      (extraLibs',    ldflags')  = partition ("-l" `isPrefixOf`) ldflags
      (extraLibDirs', ldflags'') = partition ("-L" `isPrefixOf`) ldflags'
736
  in mempty {
737
738
739
740
741
       PD.includeDirs  = map (drop 2) includeDirs',
       PD.extraLibs    = map (drop 2) extraLibs',
       PD.extraLibDirs = map (drop 2) extraLibDirs',
       PD.ccOptions    = cflags',
       PD.ldOptions    = ldflags''
742
     }
743

744
745
746
-- -----------------------------------------------------------------------------
-- Determining the compiler details

747
configCompilerAux :: ConfigFlags -> IO (Compiler, ProgramConfiguration)
748
749
750
configCompilerAux cfg = configCompiler (flagToMaybe $ configHcFlavor cfg)
                                       (flagToMaybe $ configHcPath cfg)
                                       (flagToMaybe $ configHcPkg cfg)
751
                                       programsConfig
752
                                       (fromFlag (configVerbosity cfg))
753
754
755
756
  where
    programsConfig = userSpecifyArgss (configProgramArgs cfg)
                   . userSpecifyPaths (configProgramPaths cfg)
                   $ defaultProgramConfiguration
757

758
configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
759
760
761
762
763
764
765
               -> ProgramConfiguration -> Verbosity
               -> IO (Compiler, ProgramConfiguration)
configCompiler Nothing _ _ _ _ = die "Unknown compiler"
configCompiler (Just hcFlavor) hcPath hcPkg conf verbosity = do
  case hcFlavor of
      GHC  -> GHC.configure  verbosity hcPath hcPkg conf
      JHC  -> JHC.configure  verbosity hcPath hcPkg conf
David Himmelstrup's avatar
David Himmelstrup committed
766
767
      LHC  -> do (_,ghcConf) <- GHC.configure  verbosity Nothing hcPkg conf
                 LHC.configure  verbosity hcPath Nothing ghcConf
768
769
      Hugs -> Hugs.configure verbosity hcPath hcPkg conf
      NHC  -> NHC.configure  verbosity hcPath hcPkg conf
770
      _    -> die "Unknown compiler"
ekarttun's avatar
ekarttun committed
771

772

773
774
checkForeignDeps :: PackageDescription -> LocalBuildInfo -> Verbosity -> IO ()
checkForeignDeps pkg lbi verbosity = do
775
  ifBuildsWith allHeaders (commonCcArgs ++ makeLdArgs allLibs) -- I'm feeling lucky
776
777
           (return ())
           (do missingLibs <- findMissingLibs
778
               missingHdr  <- findOffendingHdr
779
               explainErrors missingHdr missingLibs)
780
      where
781
782
783
784
785
786
787
788
        allHeaders = collectField PD.includes
        allLibs    = collectField PD.extraLibs

        ifBuildsWith headers args success failure = do
            ok <- builds (makeProgram headers) args
            if ok then success else failure

        -- NOTE: if some package-local header has errors,
789
790
        -- we will report that this header is missing.
        -- Maybe additional tests for local headers are needed
791
792
793
794
795
796
797
798
799
800
        -- for better diagnostics
        findOffendingHdr =
            ifBuildsWith allHeaders cppArgs
                         (return Nothing)
                         (go . tail . inits $ allHeaders)
            where
              go [] = return Nothing       -- cannot happen
              go (hdrs:hdrsInits) = do
                    ifBuildsWith hdrs cppArgs
                                 (go hdrsInits)
801
                                 (return . Just . last $ hdrs)
802

803
              cppArgs = "-c":commonCcArgs -- don't try to link
804
805
806
807

        findMissingLibs = ifBuildsWith [] (makeLdArgs allLibs)
                                       (return [])
                                       (filterM (fmap not . libExists) allLibs)
808

809
810
        libExists lib = builds (makeProgram []) (makeLdArgs [lib])

811
812
813
814
        commonCcArgs  = programArgs gccProg
                     ++ hcDefines (compiler lbi)
                     ++ [ "-I" ++ dir | dir <- collectField PD.includeDirs ]
                     ++ ["-I."]
815
816
                     ++ collectField PD.cppOptions
                     ++ collectField PD.ccOptions
817
818
819
820
821
822
823
                     ++ [ "-I" ++ dir
                        | dep <- deps
                        , dir <- Installed.includeDirs dep ]
                     ++ [ opt
                        | dep <- deps
                        , opt <- Installed.ccOptions dep ]

824
        commonLdArgs  = [ "-L" ++ dir | dir <- collectField PD.extraLibDirs ]
825
                     ++ collectField PD.ldOptions
826
                     --TODO: do we also need dependent packages' ld options?
827
828
829
830
831
        makeLdArgs libs = [ "-l"++lib | lib <- libs ] ++ commonLdArgs

        makeProgram hdrs = unlines $
                           [ "#include \""  ++ hdr ++ "\"" | hdr <- hdrs ] ++
                           ["int main(int argc, char** argv) { return 0; }"]
832
833
834

        collectField f = concatMap f allBi
        allBi = allBuildInfo pkg
835
836
        Just gccProg = lookupProgram  gccProgram (withPrograms lbi)
        deps = PackageIndex.topologicalOrder (installedPkgs lbi)
837

838
        builds program args = do
839
            tempDir <- getTemporaryDirectory
840
841
842
843
844
            withTempFile tempDir ".c" $ \cName cHnd ->
              withTempFile tempDir "" $ \oNname oHnd -> do
                hPutStrLn cHnd program
                hClose cHnd
                hClose oHnd
845
                rawSystemProgramStdoutConf verbosity
846
                  gccProgram (withPrograms lbi) (cName:"-o":oNname:args)
847
848
849
850
                return True
           `catchIO`   (\_ -> return False)
           `catchExit` (\_ -> return False)

851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
        explainErrors Nothing [] = return ()
        explainErrors hdr libs   = die $ unlines $
             (if plural then "Missing dependencies on foreign libraries:"
                        else "Missing dependency on a foreign library:")
           : case hdr of
               Nothing -> []
               Just h  -> ["* Missing header file: " ++ h ]
          ++ case libs of
               []    -> []
               [lib] -> ["* Missing C library: " ++ lib]
               _     -> ["* Missing C libraries: " ++ intercalate ", " libs]
          ++ [if plural then messagePlural else messageSingular]
          where
            plural = length libs >= 2
            messageSingular =
                 "This problem can usually be solved by installing the system "
              ++ "package that provides this library (you may need the "
              ++ "\"-dev\" version). If the library is already installed "
              ++ "but in a non-standard location then you can use the flags "
              ++ "--extra-include-dirs= and --extra-lib-dirs= to specify "
              ++ "where it is."
            messagePlural =
                 "This problem can usually be solved by installing the system "
              ++ "packages that provide these libraries (you may need the "
              ++ "\"-dev\" versions). If the libraries are already installed "
              ++ "but in a non-standard location then you can use the flags "
              ++ "--extra-include-dirs= and --extra-lib-dirs= to specify "
              ++ "where they are."
879

880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
        --FIXME: share this with the PreProcessor module
        hcDefines :: Compiler -> [String]
        hcDefines comp =
          case compilerFlavor comp of
            GHC  -> ["-D__GLASGOW_HASKELL__=" ++ versionInt version]
            JHC  -> ["-D__JHC__=" ++ versionInt version]
            NHC  -> ["-D__NHC__=" ++ versionInt version]
            Hugs -> ["-D__HUGS__"]
            _    -> []
          where
            version = compilerVersion comp
                      -- TODO: move this into the compiler abstraction
            -- FIXME: this forces GHC's crazy 4.8.2 -> 408 convention on all
            -- the other compilers. Check if that's really what they want.
            versionInt :: Version -> String
            versionInt (Version { versionBranch = [] }) = "1"
            versionInt (Version { versionBranch = [n] }) = show n
            versionInt (Version { versionBranch = n1:n2:_ })
              = -- 6.8.x -> 608
                -- 6.10.x -> 610
                let s1 = show n1
                    s2 = show n2
                    middle = case s2 of
                             _ : _ : _ -> ""
                             _         -> "0"
                in s1 ++ middle ++ s2

907
-- | Output package check warnings and errors. Exit if any errors.
908
909
910
911
912
913
914
915
916
checkPackageProblems :: Verbosity
                     -> Maybe GenericPackageDescription
                     -> PackageDescription
                     -> IO ()
checkPackageProblems verbosity mgpkg pkg = do
  ioChecks      <- checkPackageFiles pkg "."
  let pureChecks = case mgpkg of
                     Just gpkg -> checkPackage gpkg (Just pkg)
                     Nothing   -> checkConfiguredPackage pkg
917
918
919
920
921
922
      errors   = [ e | PackageBuildImpossible e <- pureChecks ++ ioChecks ]
      warnings = [ w | PackageBuildWarning    w <- pureChecks ++ ioChecks ]
  if null errors
    then mapM_ (warn verbosity) warnings
    else do mapM_ (hPutStrLn stderr . ("Error: " ++)) errors
            exitWith (ExitFailure 1)