git.iko.soy/rowtype-yoga/purescript-native
on 32cb3b4 help sign in
262 lines 10 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 , RebuildPolicy(..)
26 , MakeActions(..)
27 , SupplyVar()
28 , Externs()
29 , make
30 , version
31 ) where
33import Data.Function (on)
34import Data.List (sortBy, groupBy, intercalate)
35import Data.Maybe (fromMaybe)
36import Data.Time.Clock
37import Data.Version (Version)
38import qualified Data.Map as M
39import qualified Data.Set as S
41import Control.Applicative
42import Control.Arrow ((&&&))
43import Control.Monad
44import Control.Monad.Error.Class (MonadError(..))
45import Control.Monad.Reader
46import Control.Monad.Writer
47import Control.Monad.Supply.Class (fresh)
49import Language.PureScript.AST as P
50import Language.PureScript.Comments as P
51import Language.PureScript.CodeGen.Externs (moduleToPs)
52import Language.PureScript.DeadCodeElimination as P
53import Language.PureScript.Environment as P
54import Language.PureScript.Errors as P
55import Language.PureScript.Kinds as P
56import Language.PureScript.Linter as P
57import Language.PureScript.ModuleDependencies as P
58import Language.PureScript.Names as P
59import Language.PureScript.Options as P
60import Language.PureScript.Parser as P
61import Language.PureScript.Pretty as P
62import Language.PureScript.Renamer as P
63import Language.PureScript.Sugar as P
64import Control.Monad.Supply as P
65import Language.PureScript.TypeChecker as P
66import Language.PureScript.Types as P
67import qualified Language.PureScript.CoreFn as CoreFn
68import qualified Language.PureScript.Constants as C
70import qualified Paths_purescript as Paths
72-- |
73-- Compile a collection of modules
74--
75-- The compilation pipeline proceeds as follows:
76--
77-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
78--
79-- * Perform a set of desugaring passes.
80--
81-- * Type check, and elaborate values to include type annotations and type class dictionaries.
82--
83-- * Regroup values to take into account new value dependencies introduced by elaboration.
84--
85-- * Eliminate dead code.
86--
87-- * Generate Javascript, and perform optimization passes.
88--
89-- * Pretty-print the generated Javascript
90--
91compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
92 => [Module] -> m ([CoreFn.Module CoreFn.Ann], Environment, SupplyVar, Externs)
93compile = compile' initEnvironment
95compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
96 => Environment -> [Module] -> m ([CoreFn.Module CoreFn.Ann], Environment, SupplyVar, Externs)
97compile' env ms = do
98 noPrelude <- asks optionsNoPrelude
99 unless noPrelude (checkPreludeIsDefined ms)
100 additional <- asks optionsAdditional
101 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
102 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude 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-- Actions that require implementations when running in "make" mode.
118--
119data MakeActions m = MakeActions {
120 -- |
121 -- Get the timestamp for the input file(s) for a module. If there are multiple
122 -- files (.purs and foreign files, for example) the timestamp should be for
123 -- the most recently modified file.
124 --
125 getInputTimestamp :: ModuleName -> m (Either RebuildPolicy (Maybe UTCTime))
126 -- |
127 -- Get the timestamp for the output files for a module. This should be the
128 -- timestamp for the oldest modified file, or Nothing if any of the required
129 -- output files are missing.
130 --
131 , getOutputTimestamp :: ModuleName -> m (Maybe UTCTime)
132 -- |
133 -- Read the externs file for a module as a string and also return the actual
134 -- path for the file.
135 , readExterns :: ModuleName -> m (FilePath, String)
136 -- |
137 -- Run the code generator for the module and write any required output files.
138 --
139 , codegen :: CoreFn.Module CoreFn.Ann -> Environment -> SupplyVar -> Externs -> m ()
140 -- |
141 -- Respond to a progress update.
142 --
143 , progress :: String -> m ()
144 }
146-- |
147-- Generated code for an externs file.
148--
149type Externs = String
151-- |
152-- A value to be used in the Supply monad.
153--
154type SupplyVar = Integer
156-- |
157-- Determines when to rebuild a module
158--
159data RebuildPolicy
160 -- | Never rebuild this module
161 = RebuildNever
162 -- | Always rebuild this module
163 | RebuildAlways deriving (Show, Eq, Ord)
165-- |
166-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
167--
168-- If timestamps have not changed, the externs file can be used to provide the module's types without
169-- having to typecheck the module again.
170--
171make :: forall m. (Functor m, Applicative m, Monad m, MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
172 => MakeActions m
173 -> [(Either RebuildPolicy FilePath, Module)]
174 -> m Environment
175make MakeActions{..} ms = do
176 noPrelude <- asks optionsNoPrelude
177 unless noPrelude (checkPreludeIsDefined (map snd ms))
178 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
179 mapM_ lint sorted
180 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
181 inputTimestamp <- getInputTimestamp moduleName'
182 outputTimestamp <- getOutputTimestamp moduleName'
183 return $ case (inputTimestamp, outputTimestamp) of
184 (Right (Just t1), Just t2) | t1 < t2 -> s
185 (Left RebuildNever, Just _) -> s
186 _ -> S.insert moduleName' s) S.empty sorted
188 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
189 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
190 evalSupplyT nextVar $ go initEnvironment desugared
191 where
193 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
194 go env [] = return env
195 go env ((False, m) : ms') = do
196 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
197 go env' ms'
198 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
199 lift $ progress $ "Compiling " ++ runModuleName moduleName'
200 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
201 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
202 let mod' = Module coms moduleName' regrouped exps
203 corefn = CoreFn.moduleToCoreFn env' mod'
204 [renamed] = renameInModules [corefn]
205 exts = moduleToPs mod' env'
206 nextVar <- fresh
207 lift $ codegen renamed env' nextVar exts
208 go env' ms'
210 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
211 rebuildIfNecessary _ _ [] = return []
212 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
213 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
214 toRebuild' = toRebuild `S.union` S.fromList deps
215 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
216 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
217 (path, externs) <- readExterns moduleName'
218 externsModules <- fmap (map snd) . alterErrors $ P.parseModulesFromFiles id [(path, externs)]
219 case externsModules of
220 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
221 _ -> throwError . errorMessage . InvalidExternsFile $ path
222 where
223 alterErrors = flip catchError $ \(MultipleErrors errs) ->
224 throwError . MultipleErrors $ flip map errs $ \e -> case e of
225 SimpleErrorWrapper (ErrorParsingModule err) -> SimpleErrorWrapper (ErrorParsingExterns err)
226 _ -> e
228checkPreludeIsDefined :: (MonadWriter MultipleErrors m) => [Module] -> m ()
229checkPreludeIsDefined ms = do
230 let mns = map getModuleName ms
231 unless (preludeModuleName `elem` mns) $
232 tell (errorMessage PreludeNotPresent)
234reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
235reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
236 where
237 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
238 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
240-- |
241-- Add an import declaration for a module if it does not already explicitly import it.
242--
243addDefaultImport :: ModuleName -> Module -> Module
244addDefaultImport toImport m@(Module coms mn decls exps) =
245 if isExistingImport `any` decls || mn == toImport then m
246 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
247 where
248 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
249 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
250 isExistingImport _ = False
252importPrim :: Module -> Module
253importPrim = addDefaultImport (ModuleName [ProperName C.prim])
255preludeModuleName :: ModuleName
256preludeModuleName = ModuleName [ProperName C.prelude]
258importPrelude :: Module -> Module
259importPrelude = addDefaultImport preludeModuleName
261version :: Version
262version = Paths.version