aboutsummaryrefslogtreecommitdiff
path: root/bootstrap/src/Build.hs
blob: 724a1c6bbbafc52e98f89a5c4aab5a907e798a7f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
{-# LANGUAGE MultiWayIf #-}
module Build
  ( CompilerSettings(..)
  , buildLibrary
  , buildProgram
  , buildWithScript
  )
where

import           BuildModel                     ( AvailableModule(..)
                                                , CompileTimeInfo(..)
                                                , RawSource(..)
                                                , Source(..)
                                                , constructCompileTimeInfo
                                                , getAllObjectFiles
                                                , getAvailableModules
                                                , getSourceFileName
                                                , processRawSource
                                                )
import           Data.List                      ( intercalate
                                                , isSuffixOf
                                                )
import           Data.List.Utils                ( replace )
import           Development.Shake              ( FilePattern
                                                , Change(ChangeModtimeAndDigest)
                                                , cmd
                                                , getDirectoryFilesIO
                                                , liftIO
                                                , need
                                                , progressSimple
                                                , shake
                                                , shakeChange
                                                , shakeColor
                                                , shakeFiles
                                                , shakeOptions
                                                , shakeProgress
                                                , shakeThreads
                                                , want
                                                , (<//>)
                                                , (%>)
                                                , (&?>)
                                                )
import           Development.Shake.FilePath     ( exe
                                                , splitDirectories
                                                , (</>)
                                                , (<.>)
                                                )
import           System.Environment             ( setEnv )
import           System.FilePath                ( takeBaseName )
import           System.Process                 ( system )
import           System.Directory               ( createDirectoryIfMissing
                                                , makeAbsolute
                                                , withCurrentDirectory
                                                )

data CompilerSettings = CompilerSettings {
      compilerSettingsCompiler :: FilePath
    , compilerSettingsFlags :: [String]
    , compilerSettingsModuleFlag :: String
    , compilerSettingsIncludeFlag :: String
}

buildProgram
  :: FilePath
  -> [FilePath]
  -> [FilePattern]
  -> FilePath
  -> CompilerSettings
  -> String
  -> FilePath
  -> [FilePath]
  -> IO ()
buildProgram programDirectory' libraryDirectories sourceExtensions buildDirectory' (CompilerSettings { compilerSettingsCompiler = compiler, compilerSettingsFlags = flags, compilerSettingsModuleFlag = moduleFlag, compilerSettingsIncludeFlag = includeFlag }) programName programSource archives
  = do
    libraryModules <- findAvailableModules libraryDirectories
    let programDirectory = foldl1 (</>) (splitDirectories programDirectory')
    let buildDirectory   = foldl1 (</>) (splitDirectories buildDirectory')
    let includeFlags     = (includeFlag ++ buildDirectory) : map (includeFlag ++) libraryDirectories
    sourceFiles <- getDirectoriesFiles [programDirectory] sourceExtensions
    rawSources  <- mapM sourceFileToRawSource sourceFiles
    let sources' = map processRawSource rawSources
    let isThisProgramOrNotProgram p@(Program{}) =
          programSourceFileName p == programDirectory </> programSource
        isThisProgramOrNotProgram _ = True
    let sources          = filter isThisProgramOrNotProgram sources'
    let availableModules = (getAvailableModules sources buildDirectory) ++ libraryModules
    let compileTimeInfo = map
          (\s -> constructCompileTimeInfo s availableModules buildDirectory)
          sources
    let objectFiles = getAllObjectFiles buildDirectory sources
    shake shakeOptions { shakeFiles    = buildDirectory
                       , shakeChange   = ChangeModtimeAndDigest
                       , shakeColor    = True
                       , shakeThreads  = 0
                       , shakeProgress = progressSimple
                       }
      $ do
          let infoToRule cti =
                let obj                = compileTimeInfoObjectFileProduced cti
                    other              = compileTimeInfoOtherFilesProduced cti
                    directDependencies = compileTimeInfoDirectDependencies cti
                    sourceFile         = compileTimeInfoSourceFileName cti
                    fileMatcher f =
                        let realf = foldl1 (</>) (splitDirectories f)
                        in  if realf == obj || realf `elem` other
                              then Just (obj : other)
                              else Nothing
                in  fileMatcher &?> \(objectFile : _) -> do
                      need (sourceFile : directDependencies)
                      cmd compiler
                          ["-c", moduleFlag, buildDirectory]
                          includeFlags
                          flags
                          ["-o", objectFile, sourceFile]
          want [buildDirectory </> programName <.> exe]
          buildDirectory </> programName <.> exe %> \executable -> do
            need objectFiles
            need archives
            cmd compiler objectFiles archives ["-o", executable] flags
          mapM_ infoToRule compileTimeInfo

buildLibrary
  :: FilePath
  -> [FilePattern]
  -> FilePath
  -> CompilerSettings
  -> String
  -> [FilePath]
  -> IO (FilePath)
buildLibrary libraryDirectory sourceExtensions buildDirectory (CompilerSettings { compilerSettingsCompiler = compiler, compilerSettingsFlags = flags, compilerSettingsModuleFlag = moduleFlag, compilerSettingsIncludeFlag = includeFlag }) libraryName otherLibraryDirectories
  = do
    otherModules <- findAvailableModules otherLibraryDirectories
    let includeFlags = (includeFlag ++ buildDirectory) : map (includeFlag ++) otherLibraryDirectories
    sourceFiles <- getDirectoriesFiles [libraryDirectory] sourceExtensions
    rawSources  <- mapM sourceFileToRawSource sourceFiles
    let sources          = map processRawSource rawSources
    let availableModules = (getAvailableModules sources buildDirectory) ++ otherModules
    let compileTimeInfo = map
          (\s -> constructCompileTimeInfo s availableModules buildDirectory)
          sources
    let objectFiles = getAllObjectFiles buildDirectory sources
    let archiveFile = buildDirectory </> "lib" ++ libraryName <.> "a"
    shake shakeOptions { shakeFiles    = buildDirectory
                       , shakeChange   = ChangeModtimeAndDigest
                       , shakeColor    = True
                       , shakeThreads  = 0
                       , shakeProgress = progressSimple
                       }
      $ do
          let infoToRule cti =
                let obj                = compileTimeInfoObjectFileProduced cti
                    other              = compileTimeInfoOtherFilesProduced cti
                    directDependencies = compileTimeInfoDirectDependencies cti
                    sourceFile         = compileTimeInfoSourceFileName cti
                    fileMatcher f =
                        let realf = foldl1 (</>) (splitDirectories f)
                        in  if realf == obj || realf `elem` other
                              then Just (obj : other)
                              else Nothing
                in  fileMatcher &?> \(objectFile : _) -> do
                      need (sourceFile : directDependencies)
                      cmd compiler
                          ["-c", moduleFlag, buildDirectory]
                          includeFlags
                          flags
                          ["-o", objectFile, sourceFile]
          want [archiveFile]
          archiveFile %> \a -> do
            need objectFiles
            cmd "ar" ["rs"] a objectFiles
          mapM_ infoToRule compileTimeInfo
    return archiveFile

buildWithScript
  :: String
  -> FilePath
  -> FilePath
  -> CompilerSettings
  -> String
  -> [FilePath]
  -> IO (FilePath)
buildWithScript script projectDirectory buildDirectory (CompilerSettings { compilerSettingsCompiler = compiler, compilerSettingsFlags = flags, compilerSettingsModuleFlag = moduleFlag, compilerSettingsIncludeFlag = includeFlag }) libraryName otherLibraryDirectories
  = do
    absoluteBuildDirectory <- makeAbsolute buildDirectory
    createDirectoryIfMissing True absoluteBuildDirectory
    absoluteLibraryDirectories <- mapM makeAbsolute otherLibraryDirectories
    setEnv "FC"           compiler
    setEnv "FFLAGS"       (intercalate " " flags)
    setEnv "FINCLUDEFLAG" includeFlag
    setEnv "FMODUELFLAG"  moduleFlag
    setEnv "BUILD_DIR" $ unWindowsPath absoluteBuildDirectory
    setEnv "INCLUDE_DIRS"
           (intercalate " " (map unWindowsPath absoluteLibraryDirectories))
    let archiveFile =
          (unWindowsPath absoluteBuildDirectory)
            ++  "/lib"
            ++  libraryName
            <.> "a"
    withCurrentDirectory
      projectDirectory
      if
        | isMakefile script -> system
          ("make -f " ++ script ++ " " ++ archiveFile)
        | otherwise -> system (script ++ " " ++ archiveFile)
    return archiveFile

-- A little wrapper around getDirectoryFiles so we can get files from multiple directories
getDirectoriesFiles :: [FilePath] -> [FilePattern] -> IO [FilePath]
getDirectoriesFiles dirs exts = getDirectoryFilesIO "" newPatterns
 where
  newPatterns = concatMap appendExts dirs
  appendExts dir = map ((dir <//> "*") ++) exts

sourceFileToRawSource :: FilePath -> IO RawSource
sourceFileToRawSource sourceFile = do
  contents <- readFile sourceFile
  return $ RawSource sourceFile contents

isMakefile :: String -> Bool
isMakefile script | script == "Makefile"      = True
                  | script == "makefile"      = True
                  | ".mk" `isSuffixOf` script = True
                  | otherwise                 = False

unWindowsPath :: String -> String
unWindowsPath = changeSeparators . removeDriveLetter

removeDriveLetter :: String -> String
removeDriveLetter path | ':' `elem` path = (tail . dropWhile (/= ':')) path
                       | otherwise       = path

changeSeparators :: String -> String
changeSeparators = replace "\\" "/"

findAvailableModules :: [FilePath] -> IO [AvailableModule]
findAvailableModules directories = do
    moduleFiles <- getDirectoriesFiles directories ["*.mod"]
    let availableModules = map (\mf -> AvailableModule { availableModuleName = takeBaseName mf, availableModuleFile = mf }) moduleFiles
    return availableModules