git.iko.soy/rowtype-yoga/purescript-native
on 2021aa0 help sign in
292 lines 12 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript
4-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
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-----------------------------------------------------------------------------
16{-# LANGUAGE DataKinds #-}
17{-# LANGUAGE FlexibleContexts #-}
18{-# LANGUAGE RecordWildCards #-}
19{-# LANGUAGE ScopedTypeVariables #-}
21module Language.PureScript
22 ( module P
23 , compile
24 , compile'
25 , compileJS
26 , RebuildPolicy(..)
27 , MakeActions(..)
28 , SupplyVar()
29 , Externs()
30 , make
31 , version
32 ) where
34import Data.Function (on)
35import Data.List (sortBy, groupBy, intercalate)
36import Data.Maybe (fromMaybe)
37import Data.Time.Clock
38import Data.Version (Version)
39import qualified Data.Map as M
40import qualified Data.Set as S
42import Control.Applicative
43import Control.Arrow ((&&&))
44import Control.Monad
45import Control.Monad.Error.Class (MonadError(..))
46import Control.Monad.Reader
47import Control.Monad.Writer
48import Control.Monad.Supply.Class (MonadSupply, fresh)
50import Language.PureScript.AST as P
51import Language.PureScript.Comments as P
52import Language.PureScript.CodeGen.Externs (moduleToPs)
53import Language.PureScript.DeadCodeElimination as P
54import Language.PureScript.Environment as P
55import Language.PureScript.Errors as P
56import Language.PureScript.Kinds as P
57import Language.PureScript.Linter as P
58import Language.PureScript.ModuleDependencies as P
59import Language.PureScript.Names as P
60import Language.PureScript.Options as P
61import Language.PureScript.Parser as P
62import Language.PureScript.Pretty as P
63import Language.PureScript.Renamer as P
64import Language.PureScript.Sugar as P
65import Control.Monad.Supply as P
66import Language.PureScript.TypeChecker as P
67import Language.PureScript.Types as P
68import qualified Language.PureScript.CoreFn as CoreFn
69import qualified Language.PureScript.Constants as C
70import qualified Language.PureScript.CodeGen.JS as J
72import qualified Paths_purescript as Paths
74-- |
75-- Compile a collection of modules
76--
77-- The compilation pipeline proceeds as follows:
78--
79-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
80--
81-- * Perform a set of desugaring passes.
82--
83-- * Type check, and elaborate values to include type annotations and type class dictionaries.
84--
85-- * Regroup values to take into account new value dependencies introduced by elaboration.
86--
87-- * Eliminate dead code.
88--
89-- * Generate Javascript, and perform optimization passes.
90--
91-- * Pretty-print the generated Javascript
92--
93compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
94 => [Module] -> m ([CoreFn.Module CoreFn.Ann], Environment, SupplyVar, Externs)
95compile = compile' initEnvironment
97compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
98 => Environment -> [Module] -> m ([CoreFn.Module CoreFn.Ann], Environment, SupplyVar, Externs)
99compile' env ms = do
100 additional <- asks optionsAdditional
101 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
102 (sorted, _) <- sortModules $ map importPrim ms
103 mapM_ lint sorted
104 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
105 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
106 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
107 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
108 entryPoints = moduleNameFromString `map` entryPointModules additional
109 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
110 renamed = renameInModules elim
111 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
112 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
113 exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
114 return (modulesToCodeGen, env', nextVar, exts)
116-- |
117-- Compile a collection of modules to JavaScript and externs files
118--
119compileJS :: forall m. (Functor m, Applicative m, MonadError P.MultipleErrors m, MonadWriter P.MultipleErrors m, MonadReader (P.Options P.Compile) m)
120 => [P.Module] -> M.Map P.ModuleName (FilePath, P.ForeignJS) -> [String] -> m (String, String, Environment)
121compileJS ms foreigns prefix = do
122 (modulesToCodeGen, env, nextVar, exts) <- compile ms
123 js <- concat <$> evalSupplyT nextVar (P.parU modulesToCodeGen codegenModule)
124 js' <- generateMain env js
125 let pjs = unlines $ map ("// " ++) prefix ++ [P.prettyPrintJS js']
126 return (pjs, exts, env)
128 where
130 codegenModule :: (Functor n, Applicative n, MonadError P.MultipleErrors n, MonadWriter P.MultipleErrors n, MonadReader (P.Options P.Compile) n, MonadSupply n)
131 => CoreFn.Module CoreFn.Ann -> n [J.JS]
132 codegenModule m =
133 let requiresForeign = not $ null (CoreFn.moduleForeign m)
134 mn = CoreFn.moduleName m
135 in case mn `M.lookup` foreigns of
136 Just (path, js)
137 | not requiresForeign -> do
138 tell $ P.errorMessage $ P.UnnecessaryFFIModule mn path
139 J.moduleToJs m Nothing
140 | otherwise -> J.moduleToJs m $ Just $
141 J.JSApp (J.JSFunction Nothing [] $
142 J.JSBlock [ J.JSVariableIntroduction "exports" (Just $ J.JSObjectLiteral [])
143 , J.JSRaw js
144 , J.JSReturn (J.JSVar "exports")
145 ]) []
146 Nothing | requiresForeign -> throwError . P.errorMessage $ P.MissingFFIModule mn
147 | otherwise -> J.moduleToJs m Nothing
149 generateMain :: P.Environment -> [J.JS] -> m [J.JS]
150 generateMain env js = do
151 mainName <- asks P.optionsMain
152 additional <- asks P.optionsAdditional
153 case P.moduleNameFromString <$> mainName of
154 Just mmi -> do
155 when ((mmi, P.Ident C.main) `M.notMember` P.names env) $
156 throwError . P.errorMessage $ P.NameIsUndefined (P.Ident C.main)
157 return $ js ++ [J.mainCall mmi (P.browserNamespace additional)]
158 _ -> return js
160-- |
161-- Actions that require implementations when running in "make" mode.
162--
163data MakeActions m = MakeActions {
164 -- |
165 -- Get the timestamp for the input file(s) for a module. If there are multiple
166 -- files (.purs and foreign files, for example) the timestamp should be for
167 -- the most recently modified file.
168 --
169 getInputTimestamp :: ModuleName -> m (Either RebuildPolicy (Maybe UTCTime))
170 -- |
171 -- Get the timestamp for the output files for a module. This should be the
172 -- timestamp for the oldest modified file, or Nothing if any of the required
173 -- output files are missing.
174 --
175 , getOutputTimestamp :: ModuleName -> m (Maybe UTCTime)
176 -- |
177 -- Read the externs file for a module as a string and also return the actual
178 -- path for the file.
179 , readExterns :: ModuleName -> m (FilePath, String)
180 -- |
181 -- Run the code generator for the module and write any required output files.
182 --
183 , codegen :: CoreFn.Module CoreFn.Ann -> Environment -> SupplyVar -> Externs -> m ()
184 -- |
185 -- Respond to a progress update.
186 --
187 , progress :: String -> m ()
188 }
190-- |
191-- Generated code for an externs file.
192--
193type Externs = String
195-- |
196-- A value to be used in the Supply monad.
197--
198type SupplyVar = Integer
200-- |
201-- Determines when to rebuild a module
202--
203data RebuildPolicy
204 -- | Never rebuild this module
205 = RebuildNever
206 -- | Always rebuild this module
207 | RebuildAlways deriving (Show, Eq, Ord)
209-- |
210-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
211--
212-- If timestamps have not changed, the externs file can be used to provide the module's types without
213-- having to typecheck the module again.
214--
215make :: forall m. (Functor m, Applicative m, Monad m, MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
216 => MakeActions m
217 -> [(Either RebuildPolicy FilePath, Module)]
218 -> m Environment
219make MakeActions{..} ms = do
220 (sorted, graph) <- sortModules $ map (importPrim . snd) ms
221 mapM_ lint sorted
222 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
223 inputTimestamp <- getInputTimestamp moduleName'
224 outputTimestamp <- getOutputTimestamp moduleName'
225 return $ case (inputTimestamp, outputTimestamp) of
226 (Right (Just t1), Just t2) | t1 < t2 -> s
227 (Left RebuildNever, Just _) -> s
228 _ -> S.insert moduleName' s) S.empty sorted
230 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
231 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
232 evalSupplyT nextVar $ go initEnvironment desugared
233 where
235 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
236 go env [] = return env
237 go env ((False, m) : ms') = do
238 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
239 go env' ms'
240 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
241 lift $ progress $ "Compiling " ++ runModuleName moduleName'
242 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
243 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
244 let mod' = Module coms moduleName' regrouped exps
245 corefn = CoreFn.moduleToCoreFn env' mod'
246 [renamed] = renameInModules [corefn]
247 exts = moduleToPs mod' env'
248 nextVar <- fresh
249 lift $ codegen renamed env' nextVar exts
250 go env' ms'
252 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
253 rebuildIfNecessary _ _ [] = return []
254 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
255 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
256 toRebuild' = toRebuild `S.union` S.fromList deps
257 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
258 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
259 (path, externs) <- readExterns moduleName'
260 externsModules <- fmap (map snd) . alterErrors $ P.parseModulesFromFiles id [(path, externs)]
261 case externsModules of
262 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
263 _ -> throwError . errorMessage . InvalidExternsFile $ path
264 where
265 alterErrors = flip catchError $ \(MultipleErrors errs) ->
266 throwError . MultipleErrors $ flip map errs $ \e -> case e of
267 SimpleErrorWrapper (ErrorParsingModule err) -> SimpleErrorWrapper (ErrorParsingExterns err)
268 _ -> e
270reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
271reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
272 where
273 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
274 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
276-- |
277-- Add an import declaration for a module if it does not already explicitly import it.
278--
279addDefaultImport :: ModuleName -> Module -> Module
280addDefaultImport toImport m@(Module coms mn decls exps) =
281 if isExistingImport `any` decls || mn == toImport then m
282 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
283 where
284 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
285 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
286 isExistingImport _ = False
288importPrim :: Module -> Module
289importPrim = addDefaultImport (ModuleName [ProperName C.prim])
291version :: Version
292version = Paths.version