------------------------------------------------------------------------------- |-- Module : Distribution.Simple.NHC-- Copyright : Isaac Jones 2003-2006-- Duncan Coutts 2009---- Maintainer : cabal-devel@haskell.org-- Portability : portable---- This module contains most of the NHC-specific code for configuring, building-- and installing packages.{- Copyright (c) 2003-2005, Isaac Jones
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}moduleDistribution.Simple.NHC(configure,getInstalledPackages,buildLib,buildExe,installLib,installExe,)whereimportDistribution.Package(PackageName,PackageIdentifier(..),InstalledPackageId(..),packageId,packageName)importDistribution.InstalledPackageInfo(InstalledPackageInfo,InstalledPackageInfo_(InstalledPackageInfo,installedPackageId,sourcePackageId),emptyInstalledPackageInfo,parseInstalledPackageInfo)importDistribution.PackageDescription(PackageDescription(..),BuildInfo(..),Library(..),Executable(..),hcOptions,usedExtensions)importDistribution.ModuleName(ModuleName)importqualifiedDistribution.ModuleNameasModuleNameimportDistribution.Simple.LocalBuildInfo(LocalBuildInfo(..),ComponentLocalBuildInfo(..))importDistribution.Simple.BuildPaths(mkLibName,objExtension,exeExtension)importDistribution.Simple.Compiler(CompilerFlavor(..),CompilerId(..),Compiler(..),Flag,languageToFlags,extensionsToFlags,PackageDB(..),PackageDBStack)importqualifiedDistribution.Simple.PackageIndexasPackageIndeximportDistribution.Simple.PackageIndex(PackageIndex)importLanguage.Haskell.Extension(Language(Haskell98),Extension(..))importDistribution.Simple.Program(ProgramConfiguration,userMaybeSpecifyPath,programPath,requireProgram,requireProgramVersion,lookupProgram,nhcProgram,hmakeProgram,ldProgram,arProgram,rawSystemProgramConf)importDistribution.Simple.Utils(die,info,findFileWithExtension,findModuleFiles,installOrdinaryFile,installExecutableFile,installOrdinaryFiles,createDirectoryIfMissingVerbose,withUTF8FileContents)importDistribution.Version(Version(..),orLaterVersion)importDistribution.VerbosityimportDistribution.Text(display,simpleParse)importDistribution.ParseUtils(ParseResult(..))importSystem.FilePath((</>),(<.>),normalise,takeDirectory,dropExtension)importSystem.Directory(doesFileExist,doesDirectoryExist,getDirectoryContents,removeFile,getHomeDirectory)importData.Char(toLower)importData.List(nub)importData.Maybe(catMaybes)importData.Monoid(Monoid(..))importControl.Monad(when,unless)importDistribution.Compat.Exception-- ------------------------------------------------------------------------------- Configuringconfigure::Verbosity->MaybeFilePath->MaybeFilePath->ProgramConfiguration->IO(Compiler,ProgramConfiguration)configureverbosityhcPath_hcPkgPathconf=do(_nhcProg,nhcVersion,conf')<-requireProgramVersionverbositynhcProgram(orLaterVersion(Version[1,20][]))(userMaybeSpecifyPath"nhc98"hcPathconf)(_hmakeProg,_hmakeVersion,conf'')<-requireProgramVersionverbosityhmakeProgram(orLaterVersion(Version[3,13][]))conf'(_ldProg,conf''')<-requireProgramverbosityldProgramconf''(_arProg,conf'''')<-requireProgramverbosityarProgramconf'''--TODO: put this stuff in a monad so we can say just:-- requireProgram hmakeProgram (orLaterVersion (Version [3,13] []))-- requireProgram ldProgram anyVersion-- requireProgram ldPrograrProgramam anyVersion-- unless (null (cSources bi)) $ requireProgram ccProgram anyVersionletcomp=Compiler{compilerId=CompilerIdNHCnhcVersion,compilerLanguages=nhcLanguages,compilerExtensions=nhcLanguageExtensions}return(comp,conf'''')nhcLanguages::[(Language,Flag)]nhcLanguages=[(Haskell98,"-98")]-- | The flags for the supported extensionsnhcLanguageExtensions::[(Extension,Flag)]nhcLanguageExtensions=-- NHC doesn't enforce the monomorphism restriction at all.-- TODO: pattern guards in 1.20[(NoMonomorphismRestriction,""),(ForeignFunctionInterface,""),(ExistentialQuantification,""),(EmptyDataDecls,""),(NamedFieldPuns,"-puns"),(CPP,"-cpp")]getInstalledPackages::Verbosity->PackageDBStack->ProgramConfiguration->IOPackageIndexgetInstalledPackagesverbositypackagedbsconf=dohomedir<-getHomeDirectory(nhcProg,_)<-requireProgramverbositynhcProgramconfletbindir=takeDirectory(programPathnhcProg)incdir=takeDirectorybindir</>"include"</>"nhc98"dbdirs=nub(concatMap(packageDbPathshomedirincdir)packagedbs)indexes<-mapMgetIndividualDBPackagesdbdirsreturn$!mconcatindexeswheregetIndividualDBPackages::FilePath->IOPackageIndexgetIndividualDBPackagesdbdir=dopkgdirs<-getPackageDbDirsdbdirpkgs<-sequence[getInstalledPackagepkgnamepkgdir|(pkgname,pkgdir)<-pkgdirs]letpkgs'=mapsetInstalledPackageId(catMaybespkgs)return(PackageIndex.fromListpkgs')packageDbPaths::FilePath->FilePath->PackageDB->[FilePath]packageDbPaths_homeincdirdb=casedbofGlobalPackageDB->[incdir</>"packages"]UserPackageDB->[]--TODO any standard per-user db?SpecificPackageDBpath->[path]getPackageDbDirs::FilePath->IO[(PackageName,FilePath)]getPackageDbDirsdbdir=dodbexists<-doesDirectoryExistdbdirifnotdbexiststhenreturn[]elsedoentries<-getDirectoryContentsdbdirpkgdirs<-sequence[dopkgdirExists<-doesDirectoryExistpkgdirreturn(pkgname,pkgdir,pkgdirExists)|(entry,Justpkgname)<-[(entry,simpleParseentry)|entry<-entries],letpkgdir=dbdir</>entry]return[(pkgname,pkgdir)|(pkgname,pkgdir,True)<-pkgdirs]getInstalledPackage::PackageName->FilePath->IO(MaybeInstalledPackageInfo)getInstalledPackagepkgnamepkgdir=doletpkgconfFile=pkgdir</>"package.conf"pkgconfExists<-doesFileExistpkgconfFileletcabalFile=pkgdir<.>"cabal"cabalExists<-doesFileExistcabalFilecase()of_|pkgconfExists->getFullInstalledPackageInfopkgnamepkgconfFile|cabalExists->getPhonyInstalledPackageInfopkgnamecabalFile|otherwise->returnNothinggetFullInstalledPackageInfo::PackageName->FilePath->IO(MaybeInstalledPackageInfo)getFullInstalledPackageInfopkgnamepkgconfFile=withUTF8FileContentspkgconfFile$\contents->caseparseInstalledPackageInfocontentsofParseOk_pkginfo|packageNamepkginfo==pkgname->return(Justpkginfo)_->returnNothing-- | This is a backup option for existing versions of nhc98 which do not supply-- proper installed package info files for the bundled libs. Instead we look-- for the .cabal file and extract the package version from that.-- We don't know any other details for such packages, in particular we pretend-- that they have no dependencies.--getPhonyInstalledPackageInfo::PackageName->FilePath->IO(MaybeInstalledPackageInfo)getPhonyInstalledPackageInfopkgnamepathsModule=docontent<-readFilepathsModulecaseextractVersioncontentofNothing->returnNothingJustversion->return(Justpkginfo)wherepkgid=PackageIdentifierpkgnameversionpkginfo=emptyInstalledPackageInfo{sourcePackageId=pkgid}where-- search through the .cabal file, looking for a line like:---- > version: 2.0--extractVersion::String->MaybeVersionextractVersioncontent=casecatMaybes(mapextractVersionLine(linescontent))of[version]->Justversion_->NothingextractVersionLine::String->MaybeVersionextractVersionLineline=casewordslineof[versionTag,":",versionStr]|maptoLowerversionTag=="version"->simpleParseversionStr[versionTag,versionStr]|maptoLowerversionTag=="version:"->simpleParseversionStr_->Nothing-- Older installed package info files did not have the installedPackageId-- field, so if it is missing then we fill it as the source package ID.setInstalledPackageId::InstalledPackageInfo->InstalledPackageInfosetInstalledPackageIdpkginfo@InstalledPackageInfo{installedPackageId=InstalledPackageId"",sourcePackageId=pkgid}=pkginfo{--TODO use a proper named function for the conversion-- from source package id to installed package idinstalledPackageId=InstalledPackageId(displaypkgid)}setInstalledPackageIdpkginfo=pkginfo-- ------------------------------------------------------------------------------- Building-- |FIX: For now, the target must contain a main module. Not used-- ATM. Re-add later.buildLib::Verbosity->PackageDescription->LocalBuildInfo->Library->ComponentLocalBuildInfo->IO()buildLibverbositypkg_descrlbilibclbi=doletconf=withProgramslbiJustnhcProg=lookupProgramnhcProgramconfletbi=libBuildInfolibmodules=exposedModuleslib++otherModulesbi-- Unsupported extensions have already been checked by configurelanguageFlags=languageToFlags(compilerlbi)(defaultLanguagebi)++extensionsToFlags(compilerlbi)(usedExtensionsbi)inFiles<-getModulePathslbibimoduleslettargetDir=buildDirlbisrcDirs=nub(maptakeDirectoryinFiles)destDirs=map(targetDir</>)srcDirsmapM_(createDirectoryIfMissingVerboseverbosityTrue)destDirsrawSystemProgramConfverbosityhmakeProgramconf$["-hc="++programPathnhcProg]++nhcVerbosityOptionsverbosity++["-d",targetDir,"-hidir",targetDir]++maybe[](hcOptionsNHC.libBuildInfo)(librarypkg_descr)++languageFlags++concat[["-package",display(packageNamepkgid)]|(_,pkgid)<-componentPackageDepsclbi]++inFiles{-
-- build any C sources
unless (null (cSources bi)) $ do
info verbosity "Building C Sources..."
let commonCcArgs = (if verbosity >= deafening then ["-v"] else [])
++ ["-I" ++ dir | dir <- includeDirs bi]
++ [opt | opt <- ccOptions bi]
++ (if withOptimization lbi then ["-O2"] else [])
flip mapM_ (cSources bi) $ \cfile -> do
let ofile = targetDir </> cfile `replaceExtension` objExtension
createDirectoryIfMissingVerbose verbosity True (takeDirectory ofile)
rawSystemProgramConf verbosity hmakeProgram conf
(commonCcArgs ++ ["-c", cfile, "-o", ofile])
-}-- link:infoverbosity"Linking..."let--cObjs = [ targetDir </> cFile `replaceExtension` objExtension-- | cFile <- cSources bi ]libFilePath=targetDir</>mkLibName(packageIdpkg_descr)hObjs=[targetDir</>ModuleName.toFilePathm<.>objExtension|m<-modules]unless(nullhObjs{-&& null cObjs-})$do-- first remove library if it existsremoveFilelibFilePath`catchIO`\_->return()letarVerbosity|verbosity>=deafening="v"|verbosity>=normal=""|otherwise="c"rawSystemProgramConfverbosityarProgram(withProgramslbi)$["q"++arVerbosity,libFilePath]++hObjs-- ++ cObjs-- | Building an executable for NHC.buildExe::Verbosity->PackageDescription->LocalBuildInfo->Executable->ComponentLocalBuildInfo->IO()buildExeverbositypkg_descrlbiexeclbi=doletconf=withProgramslbiJustnhcProg=lookupProgramnhcProgramconfwhen(dropExtension(modulePathexe)/=exeNameexe)$die$"hmake does not support exe names that do not match the name of "++"the 'main-is' file. You will have to rename your executable to "++show(dropExtension(modulePathexe))letbi=buildInfoexemodules=otherModulesbi-- Unsupported extensions have already been checked by configurelanguageFlags=languageToFlags(compilerlbi)(defaultLanguagebi)++extensionsToFlags(compilerlbi)(usedExtensionsbi)inFiles<-getModulePathslbibimoduleslettargetDir=buildDirlbi</>exeNameexeexeDir=targetDir</>(exeNameexe++"-tmp")srcDirs=nub(maptakeDirectory(modulePathexe:inFiles))destDirs=map(exeDir</>)srcDirsmapM_(createDirectoryIfMissingVerboseverbosityTrue)destDirsrawSystemProgramConfverbosityhmakeProgramconf$["-hc="++programPathnhcProg]++nhcVerbosityOptionsverbosity++["-d",targetDir,"-hidir",targetDir]++maybe[](hcOptionsNHC.libBuildInfo)(librarypkg_descr)++languageFlags++concat[["-package",display(packageNamepkgid)]|(_,pkgid)<-componentPackageDepsclbi]++inFiles++[exeNameexe]nhcVerbosityOptions::Verbosity->[String]nhcVerbosityOptionsverbosity|verbosity>=deafening=["-v"]|verbosity>=normal=[]|otherwise=["-q"]--TODO: where to put this? it's duplicated in .Simple toogetModulePaths::LocalBuildInfo->BuildInfo->[ModuleName]->IO[FilePath]getModulePathslbibimodules=sequence[findFileWithExtension["hs","lhs"](buildDirlbi:hsSourceDirsbi)(ModuleName.toFilePathmodule_)>>=maybe(notFoundmodule_)(return.normalise)|module_<-modules]wherenotFoundmodule_=die$"can't find source for module "++displaymodule_-- ------------------------------------------------------------------------------- Installing-- |Install executables for NHC.installExe::Verbosity-- ^verbosity->FilePath-- ^install location->FilePath-- ^Build location->(FilePath,FilePath)-- ^Executable (prefix,suffix)->Executable->IO()installExeverbosityprefbuildPref(progprefix,progsuffix)exe=docreateDirectoryIfMissingVerboseverbosityTrueprefletexeBaseName=exeNameexeexeFileName=exeBaseName<.>exeExtensionfixedExeFileName=(progprefix++exeBaseName++progsuffix)<.>exeExtensioninstallExecutableFileverbosity(buildPref</>exeBaseName</>exeFileName)(pref</>fixedExeFileName)-- |Install for nhc98: .hi and .a filesinstallLib::Verbosity-- ^verbosity->FilePath-- ^install location->FilePath-- ^Build location->PackageIdentifier->Library->IO()installLibverbosityprefbuildPrefpkgidlib=doletbi=libBuildInfolibmodules=exposedModuleslib++otherModulesbifindModuleFiles[buildPref]["hi"]modules>>=installOrdinaryFilesverbosityprefletlibName=mkLibNamepkgidinstallOrdinaryFileverbosity(buildPref</>libName)(pref</>libName)