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-----------------------------------------------------------------------------
16{-# LANGUAGE DataKinds #-}
18module Language.PureScript (module P, compile, compile', MonadMake(..), make, preludeFilename) where
20import Language.PureScript.Types as P
21import Language.PureScript.Kinds as P
22import Language.PureScript.Declarations as P
23import Language.PureScript.Names as P
24import Language.PureScript.Parser as P
25import Language.PureScript.CodeGen as P
26import Language.PureScript.CodeGen.Common as P
27import Language.PureScript.TypeChecker as P
28import Language.PureScript.Pretty as P
29import Language.PureScript.Sugar as P
30import Language.PureScript.Options as P
31import Language.PureScript.ModuleDependencies as P
32import Language.PureScript.Environment as P
33import Language.PureScript.Errors as P
34import Language.PureScript.DeadCodeElimination as P
35import Language.PureScript.Supply as P
36import Language.PureScript.Renamer as P
38import qualified Language.PureScript.Constants as C
39import qualified Paths_purescript as Paths
41import Data.List (sortBy, groupBy, intercalate)
43import Data.Function (on)
44import Data.Maybe (listToMaybe, fromMaybe)
45import Control.Monad.Error
46import Control.Arrow ((&&&))
47import Control.Applicative
48import qualified Data.Map as M
49import qualified Data.Set as S
51import System.FilePath ((</>), pathSeparator)
52import System.Directory (getHomeDirectory, doesFileExist)
55-- Compile a collection of modules
57-- The compilation pipeline proceeds as follows:
59-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
61-- * Perform a set of desugaring passes.
63-- * Type check, and elaborate values to include type annotations and type class dictionaries.
65-- * Regroup values to take into account new value dependencies introduced by elaboration.
67-- * Eliminate dead code.
69-- * Generate Javascript, and perform optimization passes.
71-- * Pretty-print the generated Javascript
73compile :: Options Compile -> [Module] -> [String] -> Either String (String, String, Environment)
74compile = compile' initEnvironment
76compile' :: Environment -> Options Compile -> [Module] -> [String] -> Either String (String, String, Environment)
77compile' env opts ms prefix = do
78 (sorted, _) <- sortModules $ map importPrim $ if optionsNoPrelude opts then ms else (map importPrelude ms)
79 (desugared, nextVar) <- stringifyErrorStack True $ runSupplyT 0 $ desugar sorted
80 (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
81 regrouped <- stringifyErrorStack True $ createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
82 let entryPoints = moduleNameFromString `map` entryPointModules (optionsAdditional opts)
83 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
84 let renamed = renameInModules elim
85 let codeGenModuleNames = moduleNameFromString `map` codeGenModules (optionsAdditional opts)
86 let modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(Module mn _ _) -> mn `elem` codeGenModuleNames) renamed
87 let js = evalSupply nextVar $ concat <$> mapM (\m -> moduleToJs opts m env') modulesToCodeGen
88 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
89 js' <- generateMain env' opts js
90 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
91 return (pjs, exts, env')
93 mainModuleIdent = moduleNameFromString <$> optionsMain opts
95generateMain :: Environment -> Options Compile -> [JS] -> Either String [JS]
96generateMain env opts js =
97 case moduleNameFromString <$> optionsMain opts of
99 when ((mmi, Ident C.main) `M.notMember` names env) $
100 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
101 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace (optionsAdditional opts))))) []]
105-- A type class which collects the IO actions we need to be able to run in "make" mode
107class MonadMake m where
109 -- Get a file timestamp
111 getTimestamp :: FilePath -> m (Maybe UTCTime)
114 -- Read a file as a string
116 readTextFile :: FilePath -> m String
121 writeTextFile :: FilePath -> String -> m ()
126 liftError :: Either String a -> m a
129 -- Respond to a progress update
131 progress :: String -> m ()
134-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
136-- If timestamps have not changed, the externs file can be used to provide the module's types without
137-- having to typecheck the module again.
139make :: (Functor m, Applicative m, Monad m, MonadMake m) => FilePath -> Options Make -> [(FilePath, Module)] -> [String] -> m Environment
140make outputDir opts ms prefix = do
141 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
143 (sorted, graph) <- liftError $ sortModules $ map importPrim $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
145 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
146 let filePath = runModuleName moduleName'
148 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
149 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
150 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
152 jsTimestamp <- getTimestamp jsFile
153 externsTimestamp <- getTimestamp externsFile
154 inputTimestamp <- getTimestamp inputFile
156 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
157 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
158 _ -> S.insert moduleName' s) S.empty sorted
160 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
162 (desugared, nextVar) <- liftError $ stringifyErrorStack True $ runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
164 evalSupplyT nextVar (go initEnvironment desugared)
167 go :: (Functor m, Applicative m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> SupplyT m Environment
168 go env [] = return env
169 go env ((False, m) : ms') = do
170 (_, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
173 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
174 let filePath = runModuleName moduleName'
175 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
176 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
178 lift . progress $ "Compiling " ++ runModuleName moduleName'
180 (Module _ elaborated _, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
182 regrouped <- lift . liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
184 let mod' = Module moduleName' regrouped exps
185 let [renamed] = renameInModules [mod']
187 pjs <- prettyPrintJS <$> moduleToJs opts renamed env'
188 let js = unlines $ map ("// " ++) prefix ++ [pjs]
189 let exts = unlines $ map ("-- " ++ ) prefix ++ [moduleToPs renamed env']
191 lift $ writeTextFile jsFile js
192 lift $ writeTextFile externsFile exts
196 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
197 rebuildIfNecessary _ _ [] = return []
198 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
199 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
200 toRebuild' = toRebuild `S.union` S.fromList deps
201 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
202 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
203 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
204 externs <- readTextFile externsFile
205 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
206 case externsModules of
207 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
208 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
210reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
211reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
213 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
214 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
217-- Add an import declaration for a module if it does not already explicitly import it.
219addDefaultImport :: ModuleName -> Module -> Module
220addDefaultImport toImport m@(Module mn decls exps) =
221 if isExistingImport `any` decls || mn == toImport then m
222 else Module mn (ImportDeclaration toImport Unqualified Nothing : decls) exps
224 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
225 isExistingImport (PositionedDeclaration _ d) = isExistingImport d
226 isExistingImport _ = False
228importPrim :: Module -> Module
229importPrim = addDefaultImport (ModuleName [ProperName C.prim])
231importPrelude :: Module -> Module
232importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
234preludeFilename :: IO FilePath
235preludeFilename = fromMaybe missingPrelude . listToMaybe <$> do
236 fs <- sequence [homePrelude, cabalPrelude]
237 filterM doesFileExist fs
239 missingPrelude :: FilePath
240 missingPrelude = error "No Prelude found in user home or cabal path."
242 homePrelude :: IO FilePath
244 homeDir <- getHomeDirectory
245 return $ homeDir </> ".purescript" </> "prelude" </> "prelude.purs"
247 cabalPrelude :: IO FilePath
248 cabalPrelude = Paths.getDataFileName "prelude/prelude.purs"
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