git.iko.soy/rowtype-yoga/purescript-native
on 04bc640 help sign in
219 lines 8.7 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript
4-- Copyright : (c) Phil Freeman 2013
5-- License : MIT
6--
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
9-- Portability :
10--
11-- |
12-- The main compiler module
13--
14-----------------------------------------------------------------------------
16module Language.PureScript (module P, compile, compile', MonadMake(..), make) where
18import Language.PureScript.Types as P
19import Language.PureScript.Kinds as P
20import Language.PureScript.Declarations as P
21import Language.PureScript.Names as P
22import Language.PureScript.Parser as P
23import Language.PureScript.CodeGen as P
24import Language.PureScript.CodeGen.Common as P
25import Language.PureScript.TypeChecker as P
26import Language.PureScript.Pretty as P
27import Language.PureScript.Sugar as P
28import Language.PureScript.Options as P
29import Language.PureScript.ModuleDependencies as P
30import Language.PureScript.Environment as P
31import Language.PureScript.DeadCodeElimination as P
33import qualified Language.PureScript.Constants as C
35import Data.List (sortBy, groupBy, intercalate)
36import Data.Time.Clock
37import Data.Function (on)
38import Data.Maybe (fromMaybe, mapMaybe)
39import Control.Monad.State.Lazy
40import Control.Arrow ((&&&))
41import Control.Applicative ((<$>), (<*>), pure)
42import qualified Data.Map as M
43import qualified Data.Set as S
44import System.FilePath (pathSeparator)
46-- |
47-- Compile a collection of modules
48--
49-- The compilation pipeline proceeds as follows:
50--
51-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
52--
53-- * Perform a set of desugaring passes.
54--
55-- * Type check, and elaborate values to include type annotations and type class dictionaries.
56--
57-- * Regroup values to take into account new value dependencies introduced by elaboration.
58--
59-- * Eliminate dead code.
60--
61-- * Generate Javascript, and perform optimization passes.
62--
63-- * Pretty-print the generated Javascript
64--
65compile :: Options -> [Module] -> Either String (String, String, Environment)
66compile = compile' initEnvironment
68compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
69compile' env opts ms = do
70 (sorted, _) <- sortModules (map importPrelude ms)
71 desugared <- desugar sorted
72 (elaborated, env') <- runCheck' env $ forM desugared $ \(Module moduleName' decls exps) -> do
73 modify (\s -> s { checkCurrentModule = Just moduleName' })
74 Module moduleName' <$> typeCheckAll mainModuleIdent moduleName' decls <*> pure exps
75 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
76 let entryPoints = moduleNameFromString `map` optionsModules opts
77 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
78 let codeGenModules = moduleNameFromString `map` optionsCodeGenModules opts
79 let modulesToCodeGen = if null codeGenModules then elim else filter (\(Module mn _ _) -> mn `elem` codeGenModules) elim
80 let js = mapMaybe (flip (moduleToJs opts) env') modulesToCodeGen
81 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
82 js' <- generateMain env' opts js
83 return (prettyPrintJS [wrapExportsContainer opts js'], exts, env')
84 where
85 mainModuleIdent = moduleNameFromString <$> optionsMain opts
87generateMain :: Environment -> Options -> [JS] -> Either String [JS]
88generateMain env opts js =
89 case moduleNameFromString <$> optionsMain opts of
90 Just mmi -> do
91 when ((mmi, Ident C.main) `M.notMember` names env) $
92 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
93 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
94 _ -> return js
96-- |
97-- A type class which collects the IO actions we need to be able to run in "make" mode
98--
99class MonadMake m where
100 -- |
101 -- Get a file timestamp
102 --
103 getTimestamp :: FilePath -> m (Maybe UTCTime)
105 -- |
106 -- Read a file as a string
107 --
108 readTextFile :: FilePath -> m String
110 -- |
111 -- Write a text file
112 --
113 writeTextFile :: FilePath -> String -> m ()
115 -- |
116 -- Report an error
117 --
118 liftError :: Either String a -> m a
121-- |
122-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
123--
124-- If timestamps have not changed, the externs file can be used to provide the module's types without
125-- having to typecheck the module again.
126--
127make :: (Functor m, Monad m, MonadMake m) => Options -> [(FilePath, Module)] -> m ()
128make opts ms = do
129 let filePathMap = M.fromList (map (\(fp, (Module mn _ _)) -> (mn, fp)) ms)
131 (sorted, graph) <- liftError $ sortModules (map (importPrelude . snd) ms)
133 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
134 let filePath = toFileName moduleName'
136 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
137 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
138 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
140 jsTimestamp <- getTimestamp jsFile
141 externsTimestamp <- getTimestamp externsFile
142 inputTimestamp <- getTimestamp inputFile
144 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
145 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
146 _ -> S.insert moduleName' s) S.empty sorted
148 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
150 desugared <- liftError $ zip (map fst marked) <$> desugar (map snd marked)
152 go initEnvironment desugared
154 where
155 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m ()
156 go _ [] = return ()
157 go env ((False, Module moduleName' typings _) : ms') = do
158 (_, env') <- liftError . runCheck' env $ do
159 modify (\s -> s { checkCurrentModule = Just moduleName' })
160 typeCheckAll Nothing moduleName' typings
162 go env' ms'
163 go env ((True, Module moduleName' decls exps) : ms') = do
164 let filePath = toFileName moduleName'
165 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
166 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
168 (elaborated, env') <- liftError . runCheck' env $ do
169 modify (\s -> s { checkCurrentModule = Just moduleName' })
170 typeCheckAll Nothing moduleName' decls
172 regrouped <- liftError . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
174 let mod' = Module moduleName' regrouped exps
175 js = moduleToJs opts mod' env'
176 exts = moduleToPs mod' env'
177 js' = maybe "" (prettyPrintJS . return . wrapExportsContainer opts . return) js
179 writeTextFile jsFile js'
180 writeTextFile externsFile exts
182 go env' ms'
184toFileName :: ModuleName -> FilePath
185toFileName (ModuleName ps) = intercalate [pathSeparator] . map runProperName $ ps
187rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
188rebuildIfNecessary _ _ [] = return []
189rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms) | moduleName' `S.member` toRebuild = do
190 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
191 toRebuild' = toRebuild `S.union` S.fromList deps
192 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms
193rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms) = do
194 let externsFile = "externs" ++ pathSeparator : toFileName moduleName' ++ ".externs"
195 externs <- readTextFile externsFile
196 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
197 case externsModules of
198 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms
199 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
201reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
202reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
203 where
204 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
205 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
207-- |
208-- Add an import declaration for the Prelude to a module if it does not already explicitly import
209-- it.
210--
211importPrelude :: Module -> Module
212importPrelude m@(Module mn decls exps) =
213 if isPreludeImport `any` decls || mn == prelude then m
214 else Module mn (preludeImport : decls) exps
215 where
216 prelude = ModuleName [ProperName C.prelude]
217 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
218 isPreludeImport _ = False
219 preludeImport = ImportDeclaration prelude Nothing Nothing