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

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

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

150
import Prelude hiding (catch)
151

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

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

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

195
196
197
-- |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.
198
199
200
getPersistBuildConfig :: FilePath -> IO LocalBuildInfo
getPersistBuildConfig distPref = do
  lbi <- tryGetPersistBuildConfig distPref
201
202
  either die return lbi

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

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

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

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

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

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

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

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

261
-- -----------------------------------------------------------------------------
ijones's avatar
ijones committed
262
263
-- * Configuration
-- -----------------------------------------------------------------------------
264

265
266
-- |Perform the \"@.\/setup configure@\" action.
-- Returns the @.setup-config@ file.
267
configure :: ( Either GenericPackageDescription PackageDescription
268
             , HookedBuildInfo)
269
          -> ConfigFlags -> IO LocalBuildInfo
270
configure (pkg_descr0, pbi) cfg
271
272
  = do  let distPref = fromFlag (configDistPref cfg)
            verbosity = fromFlag (configVerbosity cfg)
273

274
        setupMessage verbosity "Configuring"
275
                     (packageId (either packageDescription id pkg_descr0))
276

277
        createDirectoryIfMissingVerbose (lessVerbose verbosity) True distPref
278

279
280
281
        let programsConfig = userSpecifyArgss (configProgramArgs cfg)
                           . userSpecifyPaths (configProgramPaths cfg)
                           $ configPrograms cfg
282
            userInstall = fromFlag (configUserInstall cfg)
283
284
285
286
            defaultPackageDB | userInstall = UserPackageDB
                             | otherwise   = GlobalPackageDB
            packageDb   = fromFlagOrDefault defaultPackageDB
                                            (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
        maybePackageSet <- getInstalledPackages (lessVerbose verbosity) comp
297
                               (implicitPackageDbStack packageDb) programsConfig'
298

299
        (pkg_descr0', flags) <- case pkg_descr0 of
300
301
            Left ppd ->
                case finalizePackageDescription
302
                       (configConfigurationsFlags cfg)
303
                       maybePackageSet
304
                       Distribution.System.buildOS
305
                       Distribution.System.buildArch
306
                       (compilerId comp)
307
                       (configConstraints cfg)
308
309
                       ppd
                of Right r -> return r
310
                   Left missing ->
311
                       die $ "At least the following dependencies are missing:\n"
312
                         ++ (render . nest 4 . sep . punctuate comma $
313
                             map disp missing)
314
            Right pd -> return (pd,[])
315

316
317
318
        -- 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'
319

320
        when (not (null flags)) $
321
322
323
          info verbosity $ "Flags chosen: "
                        ++ intercalate ", " [ name ++ "=" ++ display value
                                            | (FlagName name, value) <- flags ]
324

325
326
327
        checkPackageProblems verbosity
          (either Just (\_->Nothing) pkg_descr0) --TODO: make the Either go away
          (updatePackageDescription pbi pkg_descr)
328

329
        let packageSet = fromMaybe bogusPackageSet maybePackageSet
330
331
332
333
334
335
336
            -- 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)
337
            bogusPackageSet = PackageIndex.fromList
338
              [ emptyInstalledPackageInfo {
339
                  Installed.package = bogusPackageId
340
341
342
                  -- note that these bogus packages have no other dependencies
                }
              | bogusPackageId <- bogusDependencies ]
343
        dep_pkgs <- case flavor of
344
345
          GHC -> mapM (configDependency verbosity packageSet) (buildDepends pkg_descr)
          JHC -> mapM (configDependency verbosity packageSet) (buildDepends pkg_descr)
David Himmelstrup's avatar
David Himmelstrup committed
346
          LHC -> mapM (configDependency verbosity packageSet) (buildDepends pkg_descr)
347
          _   -> return bogusDependencies
Simon Marlow's avatar
Simon Marlow committed
348

349
        packageDependsIndex <-
350
          case PackageIndex.dependencyClosure packageSet dep_pkgs of
351
352
353
            Left packageDependsIndex -> return packageDependsIndex
            Right broken ->
              die $ "The following installed packages are broken because other"
354
355
                 ++ " packages they depend on are missing. These broken "
                 ++ "packages must be rebuilt before they can be used.\n"
356
                 ++ unlines [ "package "
357
                           ++ display (packageId pkg)
358
                           ++ " is broken due to missing package "
359
                           ++ intercalate ", " (map display deps)
360
361
                            | (pkg, deps) <- broken ]

362
        let pseudoTopPkg = emptyInstalledPackageInfo {
363
364
                Installed.package = packageId pkg_descr,
                Installed.depends = dep_pkgs
365
              }
366
367
        case PackageIndex.dependencyInconsistencies
           . PackageIndex.insert pseudoTopPkg
368
           $ packageDependsIndex of
369
370
371
          [] -> return ()
          inconsistencies ->
            warn verbosity $
372
                 "This package indirectly depends on multiple versions of the same "
373
              ++ "package. This is highly likely to cause a compile failure.\n"
374
375
              ++ unlines [ "package " ++ display pkg ++ " requires "
                        ++ display (PackageIdentifier name ver)
376
377
                         | (name, uses) <- inconsistencies
                         , (pkg, ver) <- uses ]
Simon Marlow's avatar
Simon Marlow committed
378

379
        removeInstalledConfig distPref
Simon Marlow's avatar
Simon Marlow committed
380

381
382
383
        -- installation directories
        defaultDirs <- defaultInstallDirs flavor userInstall (hasLibs pkg_descr)
        let installDirs = combineInstallDirs fromFlagOrDefault
384
                            defaultDirs (configInstallDirs cfg)
385

386
        -- check extensions
387
        let extlist = nub $ concatMap extensions (allBuildInfo pkg_descr)
388
        let exts = unsupportedExtensions comp extlist
389
        unless (null exts) $ warn verbosity $ -- Just warn, FIXME: Should this be an error?
390
            display flavor ++ " does not support the following extensions: " ++
391
            intercalate ", " (map display exts)
392

393
        let requiredBuildTools = concatMap buildTools (allBuildInfo pkg_descr)
394
395
        programsConfig'' <-
              configureAllKnownPrograms (lessVerbose verbosity) programsConfig'
396
          >>= configureRequiredPrograms verbosity requiredBuildTools
397

398
399
        (pkg_descr', programsConfig''') <- configurePkgconfigPackages verbosity
                                            pkg_descr programsConfig''
400

401
402
403
404
405
406
        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
407
                                         ("this compiler does not support " ++
408
409
410
411
412
413
414
415
                                          "--enable-split-objs; ignoring")
                                    return False

        let lbi = LocalBuildInfo{
                    installDirTemplates = installDirs,
                    compiler            = comp,
                    buildDir            = distPref </> "build",
                    scratchDir          = fromFlagOrDefault
416
417
                                            (distPref </> "scratch")
                                            (configScratchDir cfg),
418
                    packageDeps         = dep_pkgs,
419
420
421
422
                    libraryConfig       = (\_ -> ComponentLocalBuildInfo dep_pkgs)
                                              `fmap` library pkg_descr',
                    executableConfigs   = (\exe -> (exeName exe, ComponentLocalBuildInfo dep_pkgs))
                                              `fmap` executables pkg_descr',
423
                    installedPkgs       = packageDependsIndex,
424
                    pkgDescrFile        = Nothing,
425
426
427
428
429
430
431
432
433
                    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,
434
                    stripExes           = fromFlag $ configStripExes cfg,
435
                    withPackageDB       = packageDb,
436
437
                    progPrefix          = fromFlag $ configProgPrefix cfg,
                    progSuffix          = fromFlag $ configProgSuffix cfg
Duncan Coutts's avatar
Duncan Coutts committed
438
                  }
ijones's avatar
ijones committed
439

440
441
        let dirs = absoluteInstallDirs (packageId pkg_descr) lbi NoCopyDest
            relative = prefixRelativeInstallDirs (packageId pkg_descr) lbi
442

443
444
445
        unless (isAbsolute (prefix dirs)) $ die $
            "expected an absolute directory name for --prefix: " ++ prefix dirs

446
447
        info verbosity $ "Using " ++ display currentCabalId
                      ++ " compiled by " ++ display currentCompilerId
448
449
        info verbosity $ "Using compiler: " ++ showCompilerId comp
        info verbosity $ "Using install prefix: " ++ prefix dirs
450

451
452
        let dirinfo name dir isPrefixRelative =
              info verbosity $ name ++ " installed in: " ++ dir ++ relNote
453
454
455
456
457
              where relNote = case buildOS of
                      Windows | not (hasLibs pkg_descr)
                             && isNothing isPrefixRelative
                             -> "  (fixed location)"
                      _      -> ""
458

459
460
461
462
463
464
465
        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
466
                  | (prog, configuredProg) <- knownPrograms programsConfig''' ]
467

468
        return lbi
469

470
471
472
    where
      addExtraIncludeLibDirs pkg_descr =
          let extraBi = mempty { extraLibDirs = configExtraLibDirs cfg
Malcolm.Wallace's avatar
Malcolm.Wallace committed
473
                               , PD.includeDirs = configExtraIncludeDirs cfg}
474
475
476
477
              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}
478
479
480
-- -----------------------------------------------------------------------------
-- Configuring package dependencies

ijones's avatar
ijones committed
481
482
-- |Converts build dependencies to a versioned dependency.  only sets
-- version information for exact versioned dependencies.
483
inventBogusPackageId :: Dependency -> PackageIdentifier
Duncan Coutts's avatar
Duncan Coutts committed
484
485
486
487
488
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
489

490
491
492
493
494
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
495
496
497
498
499
    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 -> ""
500
            Just v  -> " version " ++ display v
ijones's avatar
ijones committed
501

502
503
hackageUrl :: String
hackageUrl = "http://hackage.haskell.org/cgi-bin/hackage-scripts/package/"
504

ijones's avatar
ijones committed
505
-- | Test for a package dependency and record the version we have installed.
506
configDependency :: Verbosity -> PackageIndex InstalledPackageInfo -> Dependency -> IO PackageIdentifier
Duncan Coutts's avatar
Duncan Coutts committed
507
configDependency verbosity index dep@(Dependency pkgname _) =
508
  case PackageIndex.lookupDependency index dep of
509
        [] -> die $ "cannot satisfy dependency "
Duncan Coutts's avatar
Duncan Coutts committed
510
                      ++ display dep ++ "\n"
Duncan Coutts's avatar
Duncan Coutts committed
511
                      ++ "Perhaps you need to download and install it from\n"
Duncan Coutts's avatar
Duncan Coutts committed
512
                      ++ hackageUrl ++ display pkgname ++ "?"
513
        pkgs -> do let pkgid = maximumBy (comparing packageVersion) (map packageId pkgs)
Duncan Coutts's avatar
Duncan Coutts committed
514
                   info verbosity $ "Dependency " ++ display dep
515
                                ++ ": using " ++ display pkgid
516
                   return pkgid
ijones's avatar
ijones committed
517

518
519
getInstalledPackages :: Verbosity -> Compiler
                     -> PackageDBStack -> ProgramConfiguration
520
                     -> IO (Maybe (PackageIndex InstalledPackageInfo))
521
getInstalledPackages verbosity comp packageDBs progconf = do
522
  info verbosity "Reading installed packages..."
523
  case compilerFlavor comp of
524
525
526
    GHC -> Just `fmap` GHC.getInstalledPackages verbosity packageDBs progconf
    JHC -> Just `fmap` JHC.getInstalledPackages verbosity packageDBs progconf
    LHC -> Just `fmap` LHC.getInstalledPackages verbosity packageDBs progconf
527
    _   -> return Nothing
ekarttun's avatar
ekarttun committed
528

529
530
531
532
533
534
535
536
537
538
539
-- | 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.
--
implicitPackageDbStack :: PackageDB -> PackageDBStack
implicitPackageDbStack packageDB = case packageDB of
  GlobalPackageDB     -> [GlobalPackageDB]
  UserPackageDB       -> [GlobalPackageDB, UserPackageDB]
  SpecificPackageDB p -> [GlobalPackageDB, SpecificPackageDB p]

540
541
542
543
544
545
546
547
-- -----------------------------------------------------------------------------
-- 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
548
configureRequiredProgram verbosity conf (Dependency (PackageName progName) verRange) =
549
  case lookupKnownProgram progName conf of
Duncan Coutts's avatar
Duncan Coutts committed
550
    Nothing -> die ("Unknown build tool " ++ progName)
551
552
    Just prog -> snd `fmap` requireProgram verbosity prog verRange conf

553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
-- -----------------------------------------------------------------------------
-- 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
    (_, conf') <- requireProgram (lessVerbose verbosity) pkgConfigProgram
                    (orLaterVersion $ Version [0,9,0] []) conf
    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')
569
570

  where
571
572
573
574
    allpkgs = concatMap pkgconfigDepends (allBuildInfo pkg_descr)
    pkgconfig = rawSystemProgramStdoutConf (lessVerbose verbosity)
                  pkgConfigProgram conf

Duncan Coutts's avatar
Duncan Coutts committed
575
    requirePkg dep@(Dependency (PackageName pkg) range) = do
576
      version <- pkgconfig ["--modversion", pkg]
577
578
                 `catchIO`   (\_ -> die notFound)
                 `catchExit` (\_ -> die notFound)
579
      case simpleParse version of
580
581
        Nothing -> die "parsing output of pkg-config --modversion failed"
        Just v | not (withinRange v range) -> die (badVersion v)
582
               | otherwise                 -> info verbosity (depSatisfied v)
583
      where
584
585
586
587
        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"
588
                    ++ " system is version " ++ display v
Duncan Coutts's avatar
Duncan Coutts committed
589
        depSatisfied v = "Dependency " ++ display dep
590
                      ++ ": using version " ++ display v
591
592

        versionRequirement
Duncan Coutts's avatar
Duncan Coutts committed
593
594
          | isAnyVersion range = ""
          | otherwise          = " version " ++ display range
595
596
597

    updateLibrary Nothing    = return Nothing
    updateLibrary (Just lib) = do
598
      bi <- pkgconfigBuildInfo (pkgconfigDepends (libBuildInfo lib))
599
      return $ Just lib { libBuildInfo = libBuildInfo lib `mappend` bi }
600
601

    updateExecutable exe = do
602
      bi <- pkgconfigBuildInfo (pkgconfigDepends (buildInfo exe))
603
      return exe { buildInfo = buildInfo exe `mappend` bi }
604
605

    pkgconfigBuildInfo :: [Dependency] -> IO BuildInfo
606
607
608
    pkgconfigBuildInfo []      = return mempty
    pkgconfigBuildInfo pkgdeps = do
      let pkgs = nub [ display pkg | Dependency pkg _ <- pkgdeps ]
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
      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'
628
  in mempty {
629
630
631
632
633
       PD.includeDirs  = map (drop 2) includeDirs',
       PD.extraLibs    = map (drop 2) extraLibs',
       PD.extraLibDirs = map (drop 2) extraLibDirs',
       PD.ccOptions    = cflags',
       PD.ldOptions    = ldflags''
634
     }
635

636
637
638
-- -----------------------------------------------------------------------------
-- Determining the compiler details

639
configCompilerAux :: ConfigFlags -> IO (Compiler, ProgramConfiguration)
640
641
642
configCompilerAux cfg = configCompiler (flagToMaybe $ configHcFlavor cfg)
                                       (flagToMaybe $ configHcPath cfg)
                                       (flagToMaybe $ configHcPkg cfg)
643
                                       programsConfig
644
                                       (fromFlag (configVerbosity cfg))
645
646
647
648
  where
    programsConfig = userSpecifyArgss (configProgramArgs cfg)
                   . userSpecifyPaths (configProgramPaths cfg)
                   $ defaultProgramConfiguration
649

650
configCompiler :: Maybe CompilerFlavor -> Maybe FilePath -> Maybe FilePath
651
652
653
654
655
656
657
               -> 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
658
659
      LHC  -> do (_,ghcConf) <- GHC.configure  verbosity Nothing hcPkg conf
                 LHC.configure  verbosity hcPath Nothing ghcConf
660
661
      Hugs -> Hugs.configure verbosity hcPath hcPkg conf
      NHC  -> NHC.configure  verbosity hcPath hcPkg conf
662
      _    -> die "Unknown compiler"
ekarttun's avatar
ekarttun committed
663

664

665
666
checkForeignDeps :: PackageDescription -> LocalBuildInfo -> Verbosity -> IO ()
checkForeignDeps pkg lbi verbosity = do
667
  ifBuildsWith allHeaders (commonCcArgs ++ makeLdArgs allLibs) -- I'm feeling lucky
668
669
           (return ())
           (do missingLibs <- findMissingLibs
670
               missingHdr  <- findOffendingHdr
671
               explainErrors missingHdr missingLibs)
672
      where
673
674
675
676
677
678
679
680
        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,
681
682
        -- we will report that this header is missing.
        -- Maybe additional tests for local headers are needed
683
684
685
686
687
688
689
690
691
692
        -- 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)
693
                                 (return . Just . last $ hdrs)
694

695
              cppArgs = "-c":commonCcArgs -- don't try to link
696
697
698
699

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

701
702
        libExists lib = builds (makeProgram []) (makeLdArgs [lib])

703
704
705
706
        commonCcArgs  = programArgs gccProg
                     ++ hcDefines (compiler lbi)
                     ++ [ "-I" ++ dir | dir <- collectField PD.includeDirs ]
                     ++ ["-I."]
707
708
                     ++ collectField PD.cppOptions
                     ++ collectField PD.ccOptions
709
710
711
712
713
714
715
                     ++ [ "-I" ++ dir
                        | dep <- deps
                        , dir <- Installed.includeDirs dep ]
                     ++ [ opt
                        | dep <- deps
                        , opt <- Installed.ccOptions dep ]

716
        commonLdArgs  = [ "-L" ++ dir | dir <- collectField PD.extraLibDirs ]
717
                     ++ collectField PD.ldOptions
718
                     --TODO: do we also need dependent packages' ld options?
719
720
721
722
723
        makeLdArgs libs = [ "-l"++lib | lib <- libs ] ++ commonLdArgs

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

        collectField f = concatMap f allBi
        allBi = allBuildInfo pkg
727
728
        Just gccProg = lookupProgram  gccProgram (withPrograms lbi)
        deps = PackageIndex.topologicalOrder (installedPkgs lbi)
729

730
        builds program args = do
731
            tempDir <- getTemporaryDirectory
732
733
734
735
736
            withTempFile tempDir ".c" $ \cName cHnd ->
              withTempFile tempDir "" $ \oNname oHnd -> do
                hPutStrLn cHnd program
                hClose cHnd
                hClose oHnd
737
                rawSystemProgramStdoutConf verbosity
738
                  gccProgram (withPrograms lbi) (cName:"-o":oNname:args)
739
740
741
742
                return True
           `catchIO`   (\_ -> return False)
           `catchExit` (\_ -> return False)

743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
        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."
771

772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
        --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

799
-- | Output package check warnings and errors. Exit if any errors.
800
801
802
803
804
805
806
807
808
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
809
810
811
812
813
814
      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)