Don't generate in-tree directories by ghc-cabal
[hadrian.git] / src / Oracles / ModuleFiles.hs
1 {-# LANGUAGE GeneralizedNewtypeDeriving #-}
2 module Oracles.ModuleFiles (
3 decodeModule, encodeModule, findGenerator, hsSources, hsObjects, moduleFilesOracle
4 ) where
5
6 import qualified Data.HashMap.Strict as Map
7
8 import Base
9 import Context
10 import Expression
11 import Oracles.PackageData
12 import Settings.Path
13
14 newtype ModuleFilesKey = ModuleFilesKey (Stage, Package)
15 deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
16
17 newtype Generator = Generator (Stage, Package, FilePath)
18 deriving (Binary, Eq, Hashable, NFData, Show, Typeable)
19
20 -- | We scan for the following Haskell source extensions when looking for module
21 -- files. Note, we do not list "*.(l)hs-boot" files here, as they can never
22 -- appear by themselves and always have accompanying "*.(l)hs" master files.
23 haskellExtensions :: [String]
24 haskellExtensions = [".hs", ".lhs"]
25
26 -- | Non-Haskell source extensions and corresponding builders.
27 otherExtensions :: [(String, Builder)]
28 otherExtensions = [ (".x" , Alex )
29 , (".y" , Happy )
30 , (".ly" , Happy )
31 , (".hsc", Hsc2Hs) ]
32
33 -- | We match the following file patterns when looking for module files.
34 moduleFilePatterns :: [FilePattern]
35 moduleFilePatterns = map ("*" ++) $ haskellExtensions ++ map fst otherExtensions
36
37 -- | Given a FilePath determine the corresponding builder.
38 determineBuilder :: FilePath -> Maybe Builder
39 determineBuilder file = lookup (takeExtension file) otherExtensions
40
41 -- | Given a module name extract the directory and file name, e.g.:
42 --
43 -- > decodeModule "Data.Functor.Identity" == ("Data/Functor", "Identity")
44 -- > decodeModule "Prelude" == ("", "Prelude")
45 decodeModule :: String -> (FilePath, String)
46 decodeModule modName = (intercalate "/" (init xs), last xs)
47 where
48 xs = words $ replaceEq '.' ' ' modName
49
50 -- | Given the directory and file name find the corresponding module name, e.g.:
51 --
52 -- > encodeModule "Data/Functor" "Identity.hs" == "Data.Functor.Identity"
53 -- > encodeModule "" "Prelude" == "Prelude"
54 -- > uncurry encodeModule (decodeModule name) == name
55 encodeModule :: FilePath -> String -> String
56 encodeModule dir file
57 | dir == "" = takeBaseName file
58 | otherwise = replaceEq '/' '.' dir ++ '.' : takeBaseName file
59
60 -- | Find the generator for a given 'Context' and a source file. For example:
61 -- findGenerator (Context Stage1 compiler vanilla)
62 -- "_build/stage1/compiler/build/Lexer.hs"
63 -- == Just ("compiler/parser/Lexer.x", Alex)
64 -- findGenerator (Context Stage1 base vanilla)
65 -- "_build/stage1/base/build/Prelude.hs"
66 -- == Nothing
67 findGenerator :: Context -> FilePath -> Action (Maybe (FilePath, Builder))
68 findGenerator Context {..} file = do
69 maybeSource <- askOracle $ Generator (stage, package, file)
70 return $ do
71 source <- maybeSource
72 builder <- determineBuilder source
73 return (source, builder)
74
75 -- | Find all Haskell source files for a given 'Context'.
76 hsSources :: Context -> Action [FilePath]
77 hsSources context = do
78 let modFile (m, Nothing ) = generatedFile context m
79 modFile (m, Just file )
80 | takeExtension file `elem` haskellExtensions = file
81 | otherwise = generatedFile context m
82 map modFile <$> contextFiles context
83
84 -- | Find all Haskell object files for a given 'Context'. Note: this is a much
85 -- simpler function compared to 'hsSources', because all object files live in
86 -- the build directory regardless of whether they are generated or not.
87 hsObjects :: Context -> Action [FilePath]
88 hsObjects context = do
89 modules <- pkgDataList $ Modules (buildPath context)
90 -- GHC.Prim module is only for documentation, we do not actually build it.
91 return . map (objectPath context . moduleSource) $ filter (/= "GHC.Prim") modules
92
93 -- | Generated module files live in the 'Context' specific build directory.
94 generatedFile :: Context -> String -> FilePath
95 generatedFile context moduleName = buildPath context -/- moduleSource moduleName
96
97 moduleSource :: String -> FilePath
98 moduleSource moduleName = replaceEq '.' '/' moduleName <.> "hs"
99
100 -- | Module files for a given 'Context'.
101 contextFiles :: Context -> Action [(String, Maybe FilePath)]
102 contextFiles context@Context {..} = do
103 modules <- fmap sort . pkgDataList . Modules $ buildPath context
104 zip modules <$> askOracle (ModuleFilesKey (stage, package))
105
106 -- | This is an important oracle whose role is to find and cache module source
107 -- files. It takes a 'Stage' and a 'Package', looks up corresponding source
108 -- directories @dirs@ and a sorted list of module names @modules@, and for each
109 -- module, e.g. @A.B.C@, returns a 'FilePath' of the form @dir/A/B/C.extension@,
110 -- such that @dir@ belongs to @dirs@, and file @dir/A/B/C.extension@ exists, or
111 -- 'Nothing' if there is no such file. If more than one matching file is found
112 -- an error is raised. For example, for 'Stage1' and 'compiler', @dirs@ will
113 -- contain ["compiler/codeGen", "compiler/parser"], and @modules@ will contain
114 -- ["CodeGen.Platform.ARM", "Config", "Lexer"]; the oracle will produce a list
115 -- containing [Just "compiler/codeGen/CodeGen/Platform/ARM.hs", Nothing,
116 -- Just "compiler/parser/Lexer.x"]. The oracle ignores @.(l)hs-boot@ files.
117 moduleFilesOracle :: Rules ()
118 moduleFilesOracle = void $ do
119 void . addOracle $ \(ModuleFilesKey (stage, package)) -> do
120 let context = vanillaContext stage package
121 path = buildPath context
122 srcDirs <- pkgDataList $ SrcDirs path
123 modules <- fmap sort . pkgDataList $ Modules path
124 let dirs = autogenPath context : map (pkgPath package -/-) srcDirs
125 modDirFiles = groupSort $ map decodeModule modules
126 result <- concatForM dirs $ \dir -> do
127 todo <- filterM (doesDirectoryExist . (dir -/-) . fst) modDirFiles
128 forM todo $ \(mDir, mFiles) -> do
129 let fullDir = unifyPath $ dir -/- mDir
130 files <- getDirectoryFiles fullDir moduleFilePatterns
131 let cmp fe f = compare (dropExtension fe) f
132 found = intersectOrd cmp files mFiles
133 return (map (fullDir -/-) found, mDir)
134 let pairs = sort [ (encodeModule d f, f) | (fs, d) <- result, f <- fs ]
135 multi = [ (m, f1, f2) | (m, f1):(n, f2):_ <- tails pairs, m == n ]
136 unless (null multi) $ do
137 let (m, f1, f2) = head multi
138 error $ "Module " ++ m ++ " has more than one source file: "
139 ++ f1 ++ " and " ++ f2 ++ "."
140 return $ lookupAll modules pairs
141
142 -- Optimisation: we discard Haskell files here, because they are never used
143 -- as generators, and hence would be discarded in 'findGenerator' anyway.
144 generators <- newCache $ \(stage, package) -> do
145 let context = vanillaContext stage package
146 files <- contextFiles context
147 return $ Map.fromList [ (generatedFile context modName, src)
148 | (modName, Just src) <- files
149 , takeExtension src `notElem` haskellExtensions ]
150
151 addOracle $ \(Generator (stage, package, file)) ->
152 Map.lookup file <$> generators (stage, package)