on de232b6 help sign in
elk/compiler/Compiler.hs
216 lines 8.5 kB history raw
1{-# LANGUAGE DeriveDataTypeable #-}
2module Main where
4import Control.Monad
5import qualified Data.Map as Map
6import qualified Data.List as List
7import qualified Data.Binary as Binary
8import Data.Version (showVersion)
9import System.Console.CmdArgs hiding (program)
10import System.Directory
11import System.Exit
12import System.FilePath
13import System.IO
14import GHC.Conc
16import qualified Text.Blaze.Html.Renderer.Pretty as Pretty
17import qualified Text.Blaze.Html.Renderer.String as Normal
18import qualified Text.Jasmine as JS
19import qualified Data.ByteString.Lazy.Char8 as BS
20import qualified Data.ByteString.Lazy as L
22import qualified Metadata.Prelude as Prelude
23import qualified Transform.Canonicalize as Canonical
24import SourceSyntax.Module
25import Parse.Module (getModuleName)
26import Initialize (buildFromSource, getSortedDependencies)
27import Generate.JavaScript (jsModule)
28import Generate.Html (createHtml, JSStyle(..), JSSource(..))
29import Paths_Elm
31import SourceSyntax.PrettyPrint (pretty, variable)
32import Text.PrettyPrint as P
33import qualified Type.Type as Type
34import qualified Type.Alias as Alias
36data Flags =
37 Flags { make :: Bool
38 , files :: [FilePath]
39 , runtime :: Maybe FilePath
40 , only_js :: Bool
41 , print_types :: Bool
42 , print_program :: Bool
43 , scripts :: [FilePath]
44 , no_prelude :: Bool
45 , minify :: Bool
46 , cache_dir :: FilePath
47 , build_dir :: FilePath
48 }
49 deriving (Data,Typeable,Show,Eq)
51flags = Flags
52 { make = False
53 &= help "automatically compile dependencies."
54 , files = def &= args &= typ "FILES"
55 , runtime = Nothing &= typFile
56 &= help "Specify a custom location for Elm's runtime system."
57 , only_js = False
58 &= help "Compile only to JavaScript."
59 , print_types = False
60 &= help "Print out infered types of top-level definitions."
61 , print_program = False
62 &= help "Print out an internal representation of a program."
63 , scripts = [] &= typFile
64 &= help "Load JavaScript files in generated HTML. Files will be included in the given order."
65 , no_prelude = False
66 &= help "Do not import Prelude by default, used only when compiling standard libraries."
67 , minify = False
68 &= help "Minify generated JavaScript and HTML"
69 , cache_dir = "cache" &= typFile
70 &= help "Directory for files cached to make builds faster. Defaults to cache/ directory."
71 , build_dir = "build" &= typFile
72 &= help "Directory for generated HTML and JS files. Defaults to build/ directory."
73 } &= help "Compile Elm programs to HTML, CSS, and JavaScript."
74 &= summary ("The Elm Compiler " ++ showVersion version ++ ", (c) Evan Czaplicki")
76main :: IO ()
77main = do setNumCapabilities =<< getNumProcessors
78 compileArgs =<< cmdArgs flags
80compileArgs :: Flags -> IO ()
81compileArgs flags =
82 case files flags of
83 [] -> putStrLn "Usage: elm [OPTIONS] [FILES]\nFor more help: elm --help"
84 fs -> mapM_ (build flags) fs
87buildPath :: Flags -> FilePath -> String -> FilePath
88buildPath flags filePath ext = build_dir flags </> replaceExtension filePath ext
90cachePath :: Flags -> FilePath -> String -> FilePath
91cachePath flags filePath ext = cache_dir flags </> replaceExtension filePath ext
93elmo :: Flags -> FilePath -> FilePath
94elmo flags filePath = cachePath flags filePath "elmo"
96elmi :: Flags -> FilePath -> FilePath
97elmi flags filePath = cachePath flags filePath "elmi"
100buildFile :: Flags -> Int -> Int -> Interfaces -> FilePath -> IO (String,ModuleInterface)
101buildFile flags moduleNum numModules interfaces filePath =
102 do compiled <- alreadyCompiled
103 case compiled of
104 False -> compile
105 True -> do
106 handle <- openBinaryFile (elmi flags filePath) ReadMode
107 bits <- L.hGetContents handle
108 let info :: (String, ModuleInterface)
109 info = Binary.decode bits
110 L.length bits `seq` hClose handle
111 return info
112 where
113 alreadyCompiled :: IO Bool
114 alreadyCompiled = do
115 existsi <- doesFileExist (elmi flags filePath)
116 existso <- doesFileExist (elmo flags filePath)
117 if not existsi || not existso
118 then return False
119 else do tsrc <- getModificationTime filePath
120 tint <- getModificationTime (elmo flags filePath)
121 return (tsrc < tint)
123 number :: String
124 number = "[" ++ show moduleNum ++ " of " ++ show numModules ++ "]"
126 compile :: IO (String,ModuleInterface)
127 compile = do
128 source <- readFile filePath
129 let name = case getModuleName source of
130 Just n -> n
131 Nothing -> "Main"
132 putStrLn $ concat [ number, " Compiling ", name
133 , replicate (max 1 (20 - length name)) ' '
134 , "( " ++ filePath ++ " )" ]
136 createDirectoryIfMissing True (cache_dir flags)
137 createDirectoryIfMissing True (build_dir flags)
138 metaModule <-
139 case buildFromSource (no_prelude flags) interfaces source of
140 Left errors -> do
141 mapM print (List.intersperse (P.text " ") errors)
142 exitFailure
143 Right modul -> do
144 case print_program flags of
145 False -> return ()
146 True -> print . pretty $ program modul
147 return modul
149 if print_types flags then printTypes interfaces metaModule else return ()
150 let interface = Canonical.interface name $ ModuleInterface {
151 iTypes = types metaModule,
152 iAdts = datatypes metaModule,
153 iAliases = aliases metaModule,
154 iFixities = fixities metaModule
155 }
156 createDirectoryIfMissing True . dropFileName $ elmi flags filePath
157 handle <- openBinaryFile (elmi flags filePath) WriteMode
158 L.hPut handle (Binary.encode (name,interface))
159 hClose handle
160 writeFile (elmo flags filePath) (jsModule metaModule)
161 return (name,interface)
163printTypes interfaces metaModule = do
164 putStrLn ""
165 let rules = Alias.rules interfaces metaModule
166 forM_ (Map.toList $ types metaModule) $ \(n,t) -> do
167 print $ variable n <+> P.text ":" <+> pretty (Alias.realias rules t)
168 putStrLn ""
170getRuntime :: Flags -> IO FilePath
171getRuntime flags =
172 case runtime flags of
173 Just fp -> return fp
174 Nothing -> getDataFileName "elm-runtime.js"
176build :: Flags -> FilePath -> IO ()
177build flags rootFile = do
178 let noPrelude = no_prelude flags
179 files <- if make flags then getSortedDependencies noPrelude rootFile else return [rootFile]
180 let ifaces = if noPrelude then Map.empty else Prelude.interfaces
181 (moduleName, interfaces) <- buildFiles flags (length files) ifaces "" files
182 js <- foldM appendToOutput BS.empty files
184 (extension, code) <- case only_js flags of
185 True -> do
186 putStr "Generating JavaScript ... "
187 return ("js", genJs js)
188 False -> do
189 putStr "Generating HTML ... "
190 rtsPath <- getRuntime flags
191 return ("html", BS.pack . genHtml $
192 createHtml rtsPath (takeBaseName rootFile) (sources js) moduleName "")
194 let targetFile = buildPath flags rootFile extension
195 createDirectoryIfMissing True (takeDirectory targetFile)
196 BS.writeFile targetFile code
197 putStrLn "Done"
199 where
200 appendToOutput :: BS.ByteString -> FilePath -> IO BS.ByteString
201 appendToOutput js filePath =
202 do src <- BS.readFile (elmo flags filePath)
203 return (BS.append src js)
205 genHtml = if minify flags then Normal.renderHtml else Pretty.renderHtml
206 genJs = if minify flags then JS.minify else id
207 sources js = map Link (scripts flags) ++
208 [ Source (if minify flags then Minified else Readable) js ]
211buildFiles :: Flags -> Int -> Interfaces -> String -> [FilePath] -> IO (String, Interfaces)
212buildFiles _ _ interfaces moduleName [] = return (moduleName, interfaces)
213buildFiles flags numModules interfaces _ (filePath:rest) = do
214 (name,interface) <- buildFile flags (numModules - length rest) numModules interfaces filePath
215 let interfaces' = Map.insert name interface interfaces
216 buildFiles flags numModules interfaces' name rest