Commit de88f409 authored by Duncan Coutts's avatar Duncan Coutts
Browse files

Support for C/C++/Obj-C as main

This allows specifying the main-is field as a C file.

This is closely based on patches by Edward Z. Yang, who in turn credits
and earlier set of patches by Irene Knapp. The slight difference in
this version of the patch is that it is adjusted to work with the new
approach where we have separate hs compile; c compile; and link phases.
parent 02f8eef1
......@@ -73,6 +73,7 @@ Library
Distribution.Simple.BuildTarget,
Distribution.Simple.Bench,
Distribution.Simple.Command,
Distribution.Simple.CCompiler,
Distribution.Simple.Compiler,
Distribution.Simple.Configure,
Distribution.Simple.GHC,
......@@ -165,6 +166,7 @@ test-suite package-tests
PackageTests.BenchmarkStanza.Check,
PackageTests.BenchmarkExeV10.Check,
PackageTests.TemplateHaskell.Check,
PackageTests.CMain.Check,
PackageTests.PackageTester
PackageTests.PathsModule.Executable.Check
PackageTests.PathsModule.Library.Check
......
......@@ -79,6 +79,8 @@ import Distribution.System
( OS(..), Arch(..), buildPlatform )
import Distribution.License
( License(..), knownLicenses )
import Distribution.Simple.CCompiler
( filenameCDialect )
import Distribution.Simple.Utils
( cabalVersion, intercalate, parseFileGlob, FileGlob(..), lowercase )
......@@ -252,10 +254,11 @@ checkExecutable exe =
"No 'Main-Is' field found for executable " ++ exeName exe
, check (not (null (modulePath exe))
&& takeExtension (modulePath exe) `notElem` [".hs", ".lhs"]) $
&& (not $ fileExtensionSupportedLanguage $ modulePath exe)) $
PackageBuildImpossible $
"The 'Main-Is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor)."
"The 'main-is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor), "
++ "or it may specify a C/C++/obj-C source file."
, check (not (null moduleDuplicates)) $
PackageBuildWarning $
......@@ -291,7 +294,8 @@ checkTestSuite pkg test =
, check mainIsWrongExt $
PackageBuildImpossible $
"The 'main-is' field must specify a '.hs' or '.lhs' file "
++ "(even if it is generated by a preprocessor)."
++ "(even if it is generated by a preprocessor), "
++ "or it may specify a C/C++/obj-C source file."
-- Test suites might be built as (internal) libraries named after
-- the test suite and thus their names must not clash with the
......@@ -305,7 +309,7 @@ checkTestSuite pkg test =
moduleDuplicates = dups $ testModules test
mainIsWrongExt = case testInterface test of
TestSuiteExeV10 _ f -> takeExtension f `notElem` [".hs", ".lhs"]
TestSuiteExeV10 _ f -> not $ fileExtensionSupportedLanguage f
_ -> False
libNameClash = testName test `elem` [ libName
......@@ -1492,3 +1496,11 @@ commaSep = intercalate ", "
dups :: Ord a => [a] -> [a]
dups xs = [ x | (x:_:_) <- group (sort xs) ]
fileExtensionSupportedLanguage :: FilePath -> Bool
fileExtensionSupportedLanguage path =
isHaskell || isC
where
extension = takeExtension path
isHaskell = extension `elem` [".hs", ".lhs"]
isC = isJust (filenameCDialect extension)
-----------------------------------------------------------------------------
-- |
-- Module : Distribution.Simple.CCompiler
-- Copyright : 2011, Dan Knapp
--
-- Maintainer : cabal-devel@haskell.org
-- Portability : portable
--
-- This simple package provides types and functions for interacting with
-- C compilers. Currently it's just a type enumerating extant C-like
-- languages, which we call dialects.
{-
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above
copyright notice, this list of conditions and the following
disclaimer in the documentation and/or other materials provided
with the distribution.
* Neither the name of Isaac Jones nor the names of other
contributors may be used to endorse or promote products derived
from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -}
module Distribution.Simple.CCompiler (
CDialect(..),
cSourceExtensions,
cDialectFilenameExtension,
filenameCDialect
) where
import Data.Monoid
( Monoid(..) )
import System.FilePath
( takeExtension )
-- | Represents a dialect of C. The Monoid instance expresses backward
-- compatibility, in the sense that 'mappend a b' is the least inclusive
-- dialect which both 'a' and 'b' can be correctly interpreted as.
data CDialect = C
| ObjectiveC
| CPlusPlus
| ObjectiveCPlusPlus
deriving (Show)
instance Monoid CDialect where
mempty = C
mappend C anything = anything
mappend ObjectiveC CPlusPlus = ObjectiveCPlusPlus
mappend CPlusPlus ObjectiveC = ObjectiveCPlusPlus
mappend _ ObjectiveCPlusPlus = ObjectiveCPlusPlus
mappend ObjectiveC _ = ObjectiveC
mappend CPlusPlus _ = CPlusPlus
mappend ObjectiveCPlusPlus _ = ObjectiveCPlusPlus
-- | A list of all file extensions which are recognized as possibly containing
-- some dialect of C code. Note that this list is only for source files,
-- not for header files.
cSourceExtensions :: [String]
cSourceExtensions = ["c", "i", "ii", "m", "mi", "mm", "M", "mii", "cc", "cp",
"cxx", "cpp", "CPP", "c++", "C"]
-- | Takes a dialect of C and whether code is intended to be passed through
-- the preprocessor, and returns a filename extension for containing that
-- code.
cDialectFilenameExtension :: CDialect -> Bool -> String
cDialectFilenameExtension C True = "c"
cDialectFilenameExtension C False = "i"
cDialectFilenameExtension ObjectiveC True = "m"
cDialectFilenameExtension ObjectiveC False = "mi"
cDialectFilenameExtension CPlusPlus True = "cpp"
cDialectFilenameExtension CPlusPlus False = "ii"
cDialectFilenameExtension ObjectiveCPlusPlus True = "mm"
cDialectFilenameExtension ObjectiveCPlusPlus False = "mii"
-- | Infers from a filename's extension the dialect of C which it contains,
-- and whether it is intended to be passed through the preprocessor.
filenameCDialect :: String -> Maybe (CDialect, Bool)
filenameCDialect filename = do
extension <- case takeExtension filename of
'.':ext -> Just ext
_ -> Nothing
case extension of
"c" -> return (C, True)
"i" -> return (C, False)
"ii" -> return (CPlusPlus, False)
"m" -> return (ObjectiveC, True)
"mi" -> return (ObjectiveC, False)
"mm" -> return (ObjectiveCPlusPlus, True)
"M" -> return (ObjectiveCPlusPlus, True)
"mii" -> return (ObjectiveCPlusPlus, False)
"cc" -> return (CPlusPlus, True)
"cp" -> return (CPlusPlus, True)
"cxx" -> return (CPlusPlus, True)
"cpp" -> return (CPlusPlus, True)
"CPP" -> return (CPlusPlus, True)
"c++" -> return (CPlusPlus, True)
"C" -> return (CPlusPlus, True)
_ -> Nothing
......@@ -81,7 +81,7 @@ import qualified Distribution.Simple.GHC.IPI641 as IPI641
import qualified Distribution.Simple.GHC.IPI642 as IPI642
import Distribution.PackageDescription as PD
( PackageDescription(..), BuildInfo(..), Executable(..)
, Library(..), libModules, hcOptions, usedExtensions, allExtensions )
, Library(..), libModules, exeModules, hcOptions, usedExtensions, allExtensions )
import Distribution.InstalledPackageInfo
( InstalledPackageInfo )
import qualified Distribution.InstalledPackageInfo as InstalledPackageInfo
......@@ -827,11 +827,15 @@ buildExe verbosity _pkg_descr lbi
srcMainFile <- findFile (exeDir : hsSourceDirs exeBi) modPath
let cObjs = map (`replaceExtension` objExtension) (cSources exeBi)
baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
let isHaskellMain = elem (takeExtension srcMainFile) [".hs", ".lhs"]
cSrcs = cSources exeBi ++ [srcMainFile | not isHaskellMain]
cObjs = map (`replaceExtension` objExtension) cSrcs
baseOpts = (componentGhcOptions verbosity lbi exeBi clbi exeDir)
`mappend` mempty {
ghcOptMode = toFlag GhcModeMake,
ghcOptInputFiles = [srcMainFile]
ghcOptInputFiles = [ srcMainFile | isHaskellMain],
ghcOptInputModules = [ m | not isHaskellMain
, m <- exeModules exe]
}
staticOpts = baseOpts `mappend` mempty {
ghcOptDynamic = toFlag False
......@@ -858,7 +862,8 @@ buildExe verbosity _pkg_descr lbi
ghcOptLinkLibs = extraLibs exeBi,
ghcOptLinkLibPath = extraLibDirs exeBi,
ghcOptLinkFrameworks = PD.frameworks exeBi,
ghcOptInputFiles = [exeDir </> x | x <- cObjs]
ghcOptInputFiles = [exeDir </> x | x <- cObjs],
ghcOptExtra = ["-no-hs-main" | not isHaskellMain ]
}
-- For building exe's for profiling that use TH we actually
......@@ -874,7 +879,7 @@ buildExe verbosity _pkg_descr lbi
runGhcProg compileOpts { ghcOptNoLink = toFlag True }
-- build any C sources
unless (null (cSources exeBi)) $ do
unless (null cSrcs) $ do
info verbosity "Building C Sources..."
sequence_
[ do let opts = (componentCcGhcOptions verbosity lbi exeBi clbi
......@@ -885,9 +890,10 @@ buildExe verbosity _pkg_descr lbi
odir = fromFlag (ghcOptObjDir opts)
createDirectoryIfMissingVerbose verbosity True odir
runGhcProg opts
| filename <- cSources exeBi]
| filename <- cSrcs ]
-- link:
info verbosity "Linking..."
runGhcProg linkOpts { ghcOptOutputFile = toFlag (targetDir </> exeNameReal) }
......
......@@ -71,6 +71,8 @@ import Distribution.PackageDescription as PD
import qualified Distribution.InstalledPackageInfo as Installed
( InstalledPackageInfo_(..) )
import qualified Distribution.Simple.PackageIndex as PackageIndex
import Distribution.Simple.CCompiler
( cSourceExtensions )
import Distribution.Simple.Compiler
( CompilerFlavor(..), Compiler(..), compilerFlavor, compilerVersion )
import Distribution.Simple.LocalBuildInfo
......@@ -219,9 +221,11 @@ preprocessComponent pd comp lbi isSrcDist verbosity handlers = case comp of
BenchmarkUnsupported tt -> die $ "No support for preprocessing benchmark "
++ "type " ++ display tt
where
builtinSuffixes
builtinHaskellSuffixes
| NHC == compilerFlavor (compiler lbi) = ["hs", "lhs", "gc"]
| otherwise = ["hs", "lhs"]
builtinCSuffixes = cSourceExtensions
builtinSuffixes = builtinHaskellSuffixes ++ builtinCSuffixes
localHandlers bi = [(ext, h bi lbi) | (ext, h) <- handlers]
pre dirs dir lhndlrs fp =
preprocessFile dirs dir isSrcDist fp verbosity builtinSuffixes lhndlrs
......
......@@ -33,6 +33,7 @@ import PackageTests.PathsModule.Executable.Check
import PackageTests.PathsModule.Library.Check
import PackageTests.PreProcess.Check
import PackageTests.TemplateHaskell.Check
import PackageTests.CMain.Check
import PackageTests.TestOptions.Check
import PackageTests.TestStanza.Check
import PackageTests.TestSuiteExeV10.Check
......@@ -90,6 +91,8 @@ tests version =
PackageTests.BuildDeps.InternalLibrary3.Check.suite
, hunit "BuildDeps/InternalLibrary4"
PackageTests.BuildDeps.InternalLibrary4.Check.suite
, hunit "PackageTests/CMain"
PackageTests.CMain.Check.checkBuild
]
else [])
......
{-# LANGUAGE ForeignFunctionInterface #-}
module Bar where
bar :: IO ()
bar = return ()
foreign export ccall bar :: IO ()
module PackageTests.CMain.Check
( checkBuild
) where
import Distribution.Simple.Hpc
import Distribution.Version
import Test.HUnit
import System.Directory
import System.FilePath
import PackageTests.PackageTester
dir :: FilePath
dir = "PackageTests" </> "CMain"
checkBuild :: Test
checkBuild = TestCase $ do
let spec = PackageSpec dir []
buildResult <- cabal_build spec
assertBuildSucceeded buildResult
import Distribution.Simple
main = defaultMain
#include <stdio.h>
#include "HsFFI.h"
#ifdef __GLASGOW_HASKELL__
#include "Bar_stub.h"
#endif
int main(int argc, char **argv) {
hs_init(&argc, &argv);
bar();
printf("Hello world!");
return 0;
}
name: my
version: 0.1
license: BSD3
cabal-version: >= 1.9.2
build-type: Simple
executable foo
main-is: foo.c
other-modules: Bar
build-depends: base
......@@ -99,7 +99,7 @@ doCabalBuild spec = do
configResult <- doCabalConfigure spec
if successful configResult
then do
res <- cabal spec ["build"]
res <- cabal spec ["build", "-v"]
return $ recordRun res BuildSuccess configResult
else
return configResult
......
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment