1-----------------------------------------------------------------------------
3-- Module : Language.PureScript
4-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
12-- The main compiler module
14-----------------------------------------------------------------------------
16{-# LANGUAGE DataKinds #-}
17{-# LANGUAGE FlexibleContexts #-}
18{-# LANGUAGE RecordWildCards #-}
19{-# LANGUAGE ScopedTypeVariables #-}
21module Language.PureScript
34import Data.Function (on)
35import Data.List (sortBy, groupBy, intercalate)
36import Data.Maybe (fromMaybe)
38import Data.Version (Version)
39import qualified Data.Map as M
40import qualified Data.Set as S
42import Control.Applicative
43import Control.Arrow ((&&&))
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
75-- Compile a collection of modules
77-- The compilation pipeline proceeds as follows:
79-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
81-- * Perform a set of desugaring passes.
83-- * Type check, and elaborate values to include type annotations and type class dictionaries.
85-- * Regroup values to take into account new value dependencies introduced by elaboration.
87-- * Eliminate dead code.
89-- * Generate Javascript, and perform optimization passes.
91-- * Pretty-print the generated Javascript
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)
100 noPrelude <- asks optionsNoPrelude
101 unless noPrelude (checkPreludeIsDefined ms)
102 additional <- asks optionsAdditional
103 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
104 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
106 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
107 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
108 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
109 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
110 entryPoints = moduleNameFromString `map` entryPointModules additional
111 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
112 renamed = renameInModules elim
113 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
114 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
115 exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
116 return (modulesToCodeGen, env', nextVar, exts)
119-- Compile a collection of modules to JavaScript and externs files
121compileJS :: forall m. (Functor m, Applicative m, MonadError P.MultipleErrors m, MonadWriter P.MultipleErrors m, MonadReader (P.Options P.Compile) m)
122 => [P.Module] -> M.Map P.ModuleName (FilePath, P.ForeignJS) -> [String] -> m (String, String, Environment)
123compileJS ms foreigns prefix = do
124 (modulesToCodeGen, env, nextVar, exts) <- compile ms
125 js <- concat <$> evalSupplyT nextVar (P.parU modulesToCodeGen codegenModule)
126 js' <- generateMain env js
127 let pjs = unlines $ map ("// " ++) prefix ++ [P.prettyPrintJS js']
128 return (pjs, exts, env)
132 codegenModule :: (Functor n, Applicative n, MonadError P.MultipleErrors n, MonadWriter P.MultipleErrors n, MonadReader (P.Options P.Compile) n, MonadSupply n)
133 => CoreFn.Module CoreFn.Ann -> n [J.JS]
135 let requiresForeign = not $ null (CoreFn.moduleForeign m)
136 mn = CoreFn.moduleName m
137 in case mn `M.lookup` foreigns of
139 | not requiresForeign -> do
140 tell $ P.errorMessage $ P.UnnecessaryFFIModule mn path
141 J.moduleToJs m Nothing
142 | otherwise -> J.moduleToJs m $ Just $
143 J.JSApp (J.JSFunction Nothing [] $
144 J.JSBlock [ J.JSVariableIntroduction "exports" (Just $ J.JSObjectLiteral [])
146 , J.JSReturn (J.JSVar "exports")
148 Nothing | requiresForeign -> throwError . P.errorMessage $ P.MissingFFIModule mn
149 | otherwise -> J.moduleToJs m Nothing
151 generateMain :: P.Environment -> [J.JS] -> m [J.JS]
152 generateMain env js = do
153 mainName <- asks P.optionsMain
154 additional <- asks P.optionsAdditional
155 case P.moduleNameFromString <$> mainName of
157 when ((mmi, P.Ident C.main) `M.notMember` P.names env) $
158 throwError . P.errorMessage $ P.NameIsUndefined (P.Ident C.main)
159 return $ js ++ [J.mainCall mmi (P.browserNamespace additional)]
163-- Actions that require implementations when running in "make" mode.
165data MakeActions m = MakeActions {
167 -- Get the timestamp for the input file(s) for a module. If there are multiple
168 -- files (.purs and foreign files, for example) the timestamp should be for
169 -- the most recently modified file.
171 getInputTimestamp :: ModuleName -> m (Either RebuildPolicy (Maybe UTCTime))
173 -- Get the timestamp for the output files for a module. This should be the
174 -- timestamp for the oldest modified file, or Nothing if any of the required
175 -- output files are missing.
177 , getOutputTimestamp :: ModuleName -> m (Maybe UTCTime)
179 -- Read the externs file for a module as a string and also return the actual
180 -- path for the file.
181 , readExterns :: ModuleName -> m (FilePath, String)
183 -- Run the code generator for the module and write any required output files.
185 , codegen :: CoreFn.Module CoreFn.Ann -> Environment -> SupplyVar -> Externs -> m ()
187 -- Respond to a progress update.
189 , progress :: String -> m ()
193-- Generated code for an externs file.
198-- A value to be used in the Supply monad.
200type SupplyVar = Integer
203-- Determines when to rebuild a module
206 -- | Never rebuild this module
208 -- | Always rebuild this module
209 | RebuildAlways deriving (Show, Eq, Ord)
212-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
214-- If timestamps have not changed, the externs file can be used to provide the module's types without
215-- having to typecheck the module again.
217make :: forall m. (Functor m, Applicative m, Monad m, MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m)
219 -> [(Either RebuildPolicy FilePath, Module)]
221make MakeActions{..} ms = do
222 noPrelude <- asks optionsNoPrelude
223 unless noPrelude (checkPreludeIsDefined (map snd ms))
224 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
226 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
227 inputTimestamp <- getInputTimestamp moduleName'
228 outputTimestamp <- getOutputTimestamp moduleName'
229 return $ case (inputTimestamp, outputTimestamp) of
230 (Right (Just t1), Just t2) | t1 < t2 -> s
231 (Left RebuildNever, Just _) -> s
232 _ -> S.insert moduleName' s) S.empty sorted
234 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
235 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
236 evalSupplyT nextVar $ go initEnvironment desugared
239 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
240 go env [] = return env
241 go env ((False, m) : ms') = do
242 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
244 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
245 lift $ progress $ "Compiling " ++ runModuleName moduleName'
246 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
247 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
248 let mod' = Module coms moduleName' regrouped exps
249 corefn = CoreFn.moduleToCoreFn env' mod'
250 [renamed] = renameInModules [corefn]
251 exts = moduleToPs mod' env'
253 lift $ codegen renamed env' nextVar exts
256 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
257 rebuildIfNecessary _ _ [] = return []
258 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
259 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
260 toRebuild' = toRebuild `S.union` S.fromList deps
261 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
262 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
263 (path, externs) <- readExterns moduleName'
264 externsModules <- fmap (map snd) . alterErrors $ P.parseModulesFromFiles id [(path, externs)]
265 case externsModules of
266 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
267 _ -> throwError . errorMessage . InvalidExternsFile $ path
269 alterErrors = flip catchError $ \(MultipleErrors errs) ->
270 throwError . MultipleErrors $ flip map errs $ \e -> case e of
271 SimpleErrorWrapper (ErrorParsingModule err) -> SimpleErrorWrapper (ErrorParsingExterns err)
274checkPreludeIsDefined :: (MonadWriter MultipleErrors m) => [Module] -> m ()
275checkPreludeIsDefined ms = do
276 let mns = map getModuleName ms
277 unless (preludeModuleName `elem` mns) $
278 tell (errorMessage PreludeNotPresent)
280reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
281reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
283 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
284 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
287-- Add an import declaration for a module if it does not already explicitly import it.
289addDefaultImport :: ModuleName -> Module -> Module
290addDefaultImport toImport m@(Module coms mn decls exps) =
291 if isExistingImport `any` decls || mn == toImport then m
292 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
294 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
295 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
296 isExistingImport _ = False
298importPrim :: Module -> Module
299importPrim = addDefaultImport (ModuleName [ProperName C.prim])
301preludeModuleName :: ModuleName
302preludeModuleName = ModuleName [ProperName C.prelude]
304importPrelude :: Module -> Module
305importPrelude = addDefaultImport preludeModuleName
308version = Paths.version
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list