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 QuasiQuotes #-}
18{-# LANGUAGE TemplateHaskell #-}
19{-# LANGUAGE FlexibleContexts #-}
20{-# LANGUAGE ScopedTypeVariables #-}
22module Language.PureScript
32import Data.Function (on)
33import Data.List (sortBy, groupBy, intercalate)
34import Data.Maybe (fromMaybe)
36import Data.Version (Version)
37import qualified Data.Traversable as T (traverse)
38import qualified Data.Map as M
39import qualified Data.Set as S
41import Control.Applicative
42import Control.Arrow ((&&&))
43import Control.Monad.Except
44import Control.Monad.Reader
45import Control.Monad.Writer
47import System.FilePath ((</>))
49import Language.PureScript.AST as P
50import Language.PureScript.Comments as P
51import Language.PureScript.CodeGen as P
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
73-- Compile a collection of modules
75-- The compilation pipeline proceeds as follows:
77-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
79-- * Perform a set of desugaring passes.
81-- * Type check, and elaborate values to include type annotations and type class dictionaries.
83-- * Regroup values to take into account new value dependencies introduced by elaboration.
85-- * Eliminate dead code.
87-- * Generate Javascript, and perform optimization passes.
89-- * Pretty-print the generated Javascript
91compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
92 => [Module] -> [String] -> m (String, String, Environment)
93compile = compile' initEnvironment
95compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
96 => Environment -> [Module] -> [String] -> m (String, String, Environment)
97compile' env ms prefix = do
98 noPrelude <- asks optionsNoPrelude
99 additional <- asks optionsAdditional
100 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
101 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
103 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
104 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
105 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
106 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
107 entryPoints = moduleNameFromString `map` entryPointModules additional
108 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
109 renamed = renameInModules elim
110 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
111 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
112 js <- concat <$> (evalSupplyT nextVar $ T.traverse moduleToJs modulesToCodeGen)
113 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
114 js' <- generateMain env' js
115 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
116 return (pjs, exts, env')
118generateMain :: (MonadError MultipleErrors m, MonadReader (Options Compile) m) => Environment -> [JS] -> m [JS]
119generateMain env js = do
120 main <- asks optionsMain
121 additional <- asks optionsAdditional
122 case moduleNameFromString <$> main of
124 when ((mmi, Ident C.main) `M.notMember` names env) $
125 throwError . errorMessage $ NameIsUndefined (Ident C.main)
126 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace additional)))) []]
130-- A type class which collects the IO actions we need to be able to run in "make" mode
132class (MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => MonadMake m where
134 -- Get a file timestamp
136 getTimestamp :: FilePath -> m (Maybe UTCTime)
139 -- Read a file as a string
141 readTextFile :: FilePath -> m String
146 writeTextFile :: FilePath -> String -> m ()
149 -- Respond to a progress update
151 progress :: String -> m ()
154-- Determines when to rebuild a module
157 -- | Never rebuild this module
159 -- | Always rebuild this module
160 | RebuildAlways deriving (Show, Eq, Ord)
162-- Traverse (Either e) instance (base 4.7)
163traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
164traverseEither _ (Left x) = pure (Left x)
165traverseEither f (Right y) = Right <$> f y
168-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
170-- If timestamps have not changed, the externs file can be used to provide the module's types without
171-- having to typecheck the module again.
173make :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
174 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
175make outputDir ms prefix = do
176 noPrelude <- asks optionsNoPrelude
177 let filePathMap = M.fromList (map (\(fp, Module _ mn _ _) -> (mn, fp)) ms)
179 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
183 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
184 let filePath = runModuleName moduleName'
186 jsFile = outputDir </> filePath </> "index.js"
187 externsFile = outputDir </> filePath </> "externs.purs"
188 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
190 jsTimestamp <- getTimestamp jsFile
191 externsTimestamp <- getTimestamp externsFile
192 inputTimestamp <- traverseEither getTimestamp inputFile
194 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
195 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
196 (Left RebuildNever, Just _, Just _) -> s
197 _ -> S.insert moduleName' s) S.empty sorted
199 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
201 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
203 evalSupplyT nextVar $ go initEnvironment desugared
206 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
207 go env [] = return env
208 go env ((False, m) : ms') = do
209 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
212 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
213 let filePath = runModuleName moduleName'
214 jsFile = outputDir </> filePath </> "index.js"
215 externsFile = outputDir </> filePath </> "externs.purs"
217 lift . progress $ "Compiling " ++ runModuleName moduleName'
219 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
221 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
223 let mod' = Module coms moduleName' regrouped exps
224 corefn = CoreFn.moduleToCoreFn env' mod'
225 [renamed] = renameInModules [corefn]
227 pjs <- prettyPrintJS <$> moduleToJs renamed
228 let js = unlines $ map ("// " ++) prefix ++ [pjs]
229 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
231 lift $ writeTextFile jsFile js
232 lift $ writeTextFile externsFile exts
236 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
237 rebuildIfNecessary _ _ [] = return []
238 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
239 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
240 toRebuild' = toRebuild `S.union` S.fromList deps
241 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
242 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
243 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
244 externs <- readTextFile externsFile
245 externsModules <- fmap (map snd) . either (throwError . errorMessage . ErrorParsingExterns) return $ P.parseModulesFromFiles id [(externsFile, externs)]
246 case externsModules of
247 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
248 _ -> throwError . errorMessage . InvalidExternsFile $ externsFile
250reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
251reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
253 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
254 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
257-- Add an import declaration for a module if it does not already explicitly import it.
259addDefaultImport :: ModuleName -> Module -> Module
260addDefaultImport toImport m@(Module coms mn decls exps) =
261 if isExistingImport `any` decls || mn == toImport then m
262 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
264 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
265 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
266 isExistingImport _ = False
268importPrim :: Module -> Module
269importPrim = addDefaultImport (ModuleName [ProperName C.prim])
271importPrelude :: Module -> Module
272importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
275version = 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