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 ScopedTypeVariables #-}
20module Language.PureScript
30import Data.Function (on)
31import Data.List (sortBy, groupBy, intercalate)
32import Data.Maybe (fromMaybe)
34import Data.Version (Version)
35import qualified Data.Map as M
36import qualified Data.Set as S
38import Control.Applicative
39import Control.Arrow ((&&&))
41import Control.Monad.Error.Class (MonadError(..))
42import Control.Monad.Reader
43import Control.Monad.Writer
45import System.FilePath ((</>))
47import Language.PureScript.AST as P
48import Language.PureScript.Comments as P
49import Language.PureScript.CodeGen
50import Language.PureScript.DeadCodeElimination as P
51import Language.PureScript.Environment as P
52import Language.PureScript.Errors as P
53import Language.PureScript.Kinds as P
54import Language.PureScript.Linter as P
55import Language.PureScript.ModuleDependencies as P
56import Language.PureScript.Names as P
57import Language.PureScript.Options as P
58import Language.PureScript.Parser as P
59import Language.PureScript.Pretty as P
60import Language.PureScript.Renamer as P
61import Language.PureScript.Sugar as P
62import Control.Monad.Supply as P
63import Language.PureScript.TypeChecker as P
64import Language.PureScript.Types as P
65import qualified Language.PureScript.CoreFn as CoreFn
66import qualified Language.PureScript.Constants as C
68import qualified Paths_purescript as Paths
71-- Compile a collection of modules
73-- The compilation pipeline proceeds as follows:
75-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
77-- * Perform a set of desugaring passes.
79-- * Type check, and elaborate values to include type annotations and type class dictionaries.
81-- * Regroup values to take into account new value dependencies introduced by elaboration.
83-- * Eliminate dead code.
85-- * Generate Javascript, and perform optimization passes.
87-- * Pretty-print the generated Javascript
89compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
90 => [Module] -> m ([CoreFn.Module CoreFn.Ann], String, Environment, Integer)
91compile = compile' initEnvironment
93compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
94 => Environment -> [Module] -> m ([CoreFn.Module CoreFn.Ann], String, Environment, Integer)
96 noPrelude <- asks optionsNoPrelude
97 unless noPrelude (checkPreludeIsDefined ms)
98 additional <- asks optionsAdditional
99 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
100 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
102 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
103 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
104 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
105 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
106 entryPoints = moduleNameFromString `map` entryPointModules additional
107 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
108 renamed = renameInModules elim
109 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
110 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
111 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
112 return (modulesToCodeGen, exts, env', nextVar)
115-- A type class which collects the IO actions we need to be able to run in "make" mode
117class (MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => MonadMake m where
119 -- Get a file timestamp
121 getTimestamp :: FilePath -> m (Maybe UTCTime)
124 -- Read a file as a string
126 readTextFile :: FilePath -> m String
131 writeTextFile :: FilePath -> String -> m ()
134 -- Respond to a progress update
136 progress :: String -> m ()
139-- Determines when to rebuild a module
142 -- | Never rebuild this module
144 -- | Always rebuild this module
145 | RebuildAlways deriving (Show, Eq, Ord)
147-- Traverse (Either e) instance (base 4.7)
148traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
149traverseEither _ (Left x) = pure (Left x)
150traverseEither f (Right y) = Right <$> f y
153-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
155-- If timestamps have not changed, the externs file can be used to provide the module's types without
156-- having to typecheck the module again.
158make :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
159 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
160make outputDir ms prefix = do
161 noPrelude <- asks optionsNoPrelude
162 unless noPrelude (checkPreludeIsDefined (map snd ms))
163 let filePathMap = M.fromList (map (\(fp, Module _ mn _ _) -> (mn, fp)) ms)
165 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
169 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
170 let filePath = runModuleName moduleName'
172 jsFile = outputDir </> filePath </> "index.js"
173 externsFile = outputDir </> filePath </> "externs.purs"
174 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
176 jsTimestamp <- getTimestamp jsFile
177 externsTimestamp <- getTimestamp externsFile
178 inputTimestamp <- traverseEither getTimestamp inputFile
180 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
181 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
182 (Left RebuildNever, Just _, Just _) -> s
183 _ -> S.insert moduleName' s) S.empty sorted
185 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
187 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
189 evalSupplyT nextVar $ go initEnvironment desugared
192 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
193 go env [] = return env
194 go env ((False, m) : ms') = do
195 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
198 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
199 let filePath = runModuleName moduleName'
200 jsFile = outputDir </> filePath </> "index.js"
201 externsFile = outputDir </> filePath </> "externs.purs"
203 lift . progress $ "Compiling " ++ runModuleName moduleName'
205 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
207 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
209 let mod' = Module coms moduleName' regrouped exps
210 corefn = CoreFn.moduleToCoreFn env' mod'
211 [renamed] = renameInModules [corefn]
213 pjs <- prettyPrintJS <$> moduleToJs renamed Nothing
214 let js = unlines $ map ("// " ++) prefix ++ [pjs]
215 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
217 lift $ writeTextFile jsFile js
218 lift $ writeTextFile externsFile exts
222 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
223 rebuildIfNecessary _ _ [] = return []
224 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
225 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
226 toRebuild' = toRebuild `S.union` S.fromList deps
227 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
228 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
229 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
230 externs <- readTextFile externsFile
231 externsModules <- fmap (map snd) . either (throwError . errorMessage . ErrorParsingExterns) return $ P.parseModulesFromFiles id [(externsFile, externs)]
232 case externsModules of
233 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
234 _ -> throwError . errorMessage . InvalidExternsFile $ externsFile
236checkPreludeIsDefined :: (MonadWriter MultipleErrors m) => [Module] -> m ()
237checkPreludeIsDefined ms = do
238 let mns = map getModuleName ms
239 unless (preludeModuleName `elem` mns) $
240 tell (errorMessage PreludeNotPresent)
242reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
243reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
245 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
246 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
249-- Add an import declaration for a module if it does not already explicitly import it.
251addDefaultImport :: ModuleName -> Module -> Module
252addDefaultImport toImport m@(Module coms mn decls exps) =
253 if isExistingImport `any` decls || mn == toImport then m
254 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
256 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
257 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
258 isExistingImport _ = False
260importPrim :: Module -> Module
261importPrim = addDefaultImport (ModuleName [ProperName C.prim])
263preludeModuleName :: ModuleName
264preludeModuleName = ModuleName [ProperName C.prelude]
266importPrelude :: Module -> Module
267importPrelude = addDefaultImport preludeModuleName
270version = 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