1-----------------------------------------------------------------------------
3-- Module : Language.PureScript
4-- Copyright : (c) Phil Freeman 2013
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
12-- The main compiler module
14-----------------------------------------------------------------------------
16module Language.PureScript (module P, compile, compile', MonadMake(..), make) where
18import Language.PureScript.Values as P
19import Language.PureScript.Types as P
20import Language.PureScript.Kinds as P
21import Language.PureScript.Declarations as P
22import Language.PureScript.Names as P
23import Language.PureScript.Parser as P
24import Language.PureScript.CodeGen as P
25import Language.PureScript.CodeGen.Common as P
26import Language.PureScript.TypeChecker as P
27import Language.PureScript.Pretty as P
28import Language.PureScript.Sugar as P
29import Language.PureScript.Options as P
30import Language.PureScript.ModuleDependencies as P
31import Language.PureScript.Environment as P
32import Language.PureScript.DeadCodeElimination as P
34import qualified Language.PureScript.Constants as C
36import Data.List (sortBy, groupBy, intercalate)
38import Data.Function (on)
39import Data.Maybe (fromMaybe, mapMaybe)
40import Control.Monad.State.Lazy
41import Control.Arrow ((&&&))
42import Control.Applicative ((<$>), (<*>), pure)
43import qualified Data.Map as M
44import qualified Data.Set as S
45import System.FilePath (pathSeparator)
48-- Compile a collection of modules
50-- The compilation pipeline proceeds as follows:
52-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
54-- * Perform a set of desugaring passes.
56-- * Type check, and elaborate values to include type annotations and type class dictionaries.
58-- * Regroup values to take into account new value dependencies introduced by elaboration.
60-- * Eliminate dead code.
62-- * Generate Javascript, and perform optimization passes.
64-- * Pretty-print the generated Javascript
66compile :: Options -> [Module] -> Either String (String, String, Environment)
67compile = compile' initEnvironment
69compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
70compile' env opts ms = do
71 (sorted, _) <- sortModules (map importPrelude ms)
72 desugared <- desugar sorted
73 (elaborated, env') <- runCheck' env $ forM desugared $ \(Module moduleName' decls exps) -> do
74 modify (\s -> s { checkCurrentModule = Just moduleName' })
75 Module moduleName' <$> typeCheckAll mainModuleIdent moduleName' decls <*> pure exps
76 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
77 let entryPoints = moduleNameFromString `map` optionsModules opts
78 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
79 let codeGenModules = moduleNameFromString `map` optionsCodeGenModules opts
80 let modulesToCodeGen = if null codeGenModules then elim else filter (\(Module mn _ _) -> mn `elem` codeGenModules) elim
81 let js = mapMaybe (flip (moduleToJs opts) env') modulesToCodeGen
82 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
83 js' <- generateMain env' opts js
84 return (prettyPrintJS [wrapExportsContainer opts js'], exts, env')
86 mainModuleIdent = moduleNameFromString <$> optionsMain opts
88generateMain :: Environment -> Options -> [JS] -> Either String [JS]
89generateMain env opts js =
90 case moduleNameFromString <$> optionsMain opts of
92 when ((mmi, Ident C.main) `M.notMember` names env) $
93 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
94 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
98-- A type class which collects the IO actions we need to be able to run in "make" mode
100class MonadMake m where
102 -- Get a file timestamp
104 getTimestamp :: FilePath -> m (Maybe UTCTime)
107 -- Read a file as a string
109 readTextFile :: FilePath -> m String
114 writeTextFile :: FilePath -> String -> m ()
119 liftError :: Either String a -> m a
123-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
125-- If timestamps have not changed, the externs file can be used to provide the module's types without
126-- having to typecheck the module again.
128make :: (Functor m, Monad m, MonadMake m) => Options -> [(FilePath, Module)] -> m ()
130 let filePathMap = M.fromList (map (\(fp, (Module mn _ _)) -> (mn, fp)) ms)
132 (sorted, graph) <- liftError $ sortModules (map (importPrelude . snd) ms)
134 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
135 let filePath = toFileName moduleName'
137 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
138 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
139 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
141 jsTimestamp <- getTimestamp jsFile
142 externsTimestamp <- getTimestamp externsFile
143 inputTimestamp <- getTimestamp inputFile
145 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
146 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
147 _ -> S.insert moduleName' s) S.empty sorted
149 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
151 desugared <- liftError $ zip (map fst marked) <$> desugar (map snd marked)
153 go initEnvironment desugared
156 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m ()
158 go env ((False, Module moduleName' typings _) : ms') = do
159 (_, env') <- liftError . runCheck' env $ do
160 modify (\s -> s { checkCurrentModule = Just moduleName' })
161 typeCheckAll Nothing moduleName' typings
164 go env ((True, Module moduleName' decls exps) : ms') = do
165 let filePath = toFileName moduleName'
166 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
167 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
169 (elaborated, env') <- liftError . runCheck' env $ do
170 modify (\s -> s { checkCurrentModule = Just moduleName' })
171 typeCheckAll Nothing moduleName' decls
173 regrouped <- liftError . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
175 let mod' = Module moduleName' regrouped exps
176 js = moduleToJs opts mod' env'
177 exts = moduleToPs mod' env'
178 js' = maybe "" (prettyPrintJS . return . wrapExportsContainer opts . return) js
180 writeTextFile jsFile js'
181 writeTextFile externsFile exts
185toFileName :: ModuleName -> FilePath
186toFileName (ModuleName ps) = intercalate [pathSeparator] . map runProperName $ ps
188rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
189rebuildIfNecessary _ _ [] = return []
190rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms) | moduleName' `S.member` toRebuild = do
191 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
192 toRebuild' = toRebuild `S.union` S.fromList deps
193 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms
194rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms) = do
195 let externsFile = "externs" ++ pathSeparator : toFileName moduleName' ++ ".externs"
196 externs <- readTextFile externsFile
197 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
198 case externsModules of
199 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms
200 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
202reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
203reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
205 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
206 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
209-- Add an import declaration for the Prelude to a module if it does not already explicitly import
212importPrelude :: Module -> Module
213importPrelude m@(Module mn decls exps) =
214 if isPreludeImport `any` decls || mn == prelude then m
215 else Module mn (preludeImport : decls) exps
217 prelude = ModuleName [ProperName C.prelude]
218 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
219 isPreludeImport _ = False
220 preludeImport = ImportDeclaration prelude Nothing Nothing
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