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 (find, sortBy, groupBy, intercalate)
43import Data.Function (on)
44import Data.Maybe (listToMaybe, fromMaybe)
45import Control.Monad.Error
46import Control.Monad.State.Lazy
47import Control.Arrow ((&&&))
48import Control.Applicative
49import qualified Data.Map as M
50import qualified Data.Set as S
52import System.FilePath ((</>), pathSeparator)
53import System.Directory (getHomeDirectory, doesFileExist)
56-- Compile a collection of modules
58-- The compilation pipeline proceeds as follows:
60-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
62-- * Perform a set of desugaring passes.
64-- * Type check, and elaborate values to include type annotations and type class dictionaries.
66-- * Regroup values to take into account new value dependencies introduced by elaboration.
68-- * Eliminate dead code.
70-- * Generate Javascript, and perform optimization passes.
72-- * Pretty-print the generated Javascript
74compile :: Options Compile -> [Module] -> [String] -> Either String (String, String, Environment)
75compile = compile' initEnvironment
77compile' :: Environment -> Options Compile -> [Module] -> [String] -> Either String (String, String, Environment)
78compile' env opts ms prefix = do
79 (sorted, _) <- sortModules $ map importPrim $ if optionsNoPrelude opts then ms else (map importPrelude ms)
80 (desugared, nextVar) <- stringifyErrorStack True $ runSupplyT 0 $ desugar sorted
81 (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
82 regrouped <- stringifyErrorStack True $ createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
83 let entryPoints = moduleNameFromString `map` entryPointModules (optionsAdditional opts)
84 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
85 let renamed = renameInModules elim
86 let codeGenModuleNames = moduleNameFromString `map` codeGenModules (optionsAdditional opts)
87 let modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(Module mn _ _) -> mn `elem` codeGenModuleNames) renamed
88 let js = evalSupply nextVar $ concat <$> mapM (\m -> moduleToJs opts m env') modulesToCodeGen
89 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
90 js' <- generateMain env' opts js
91 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
92 return (pjs, exts, env')
94 mainModuleIdent = moduleNameFromString <$> optionsMain opts
96typeCheckModule :: Maybe ModuleName -> Module -> Check Module
97typeCheckModule mainModuleName (Module mn decls exps) = do
98 modify (\s -> s { checkCurrentModule = Just mn })
99 decls' <- typeCheckAll mainModuleName mn exps decls
100 mapM_ checkTypesAreExported exps'
101 return $ Module mn decls' exps
104 exps' = fromMaybe (error "exports should have been elaborated") exps
106 -- Check that all the type constructors defined in the current module that appear in member types
107 -- have also been exported from the module
108 checkTypesAreExported :: DeclarationRef -> Check ()
109 checkTypesAreExported (ValueRef name) = do
110 ty <- lookupVariable mn (Qualified (Just mn) name)
111 case find isTconHidden (findTcons ty) of
112 Just hiddenType -> throwError . strMsg $
113 "Error in module '" ++ show mn ++ "':\n\
114 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
116 checkTypesAreExported _ = return ()
118 -- Find the type constructors exported from the current module used in a type
119 findTcons :: Type -> [ProperName]
120 findTcons = everythingOnTypes (++) go
122 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
125 -- Checks whether a type constructor is not being exported from the current module
126 isTconHidden :: ProperName -> Bool
127 isTconHidden tyName = all go exps'
129 go (TypeRef tyName' _) = tyName' /= tyName
133generateMain :: Environment -> Options Compile -> [JS] -> Either String [JS]
134generateMain env opts js =
135 case moduleNameFromString <$> optionsMain opts of
137 when ((mmi, Ident C.main) `M.notMember` names env) $
138 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
139 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace (optionsAdditional opts))))) []]
143-- A type class which collects the IO actions we need to be able to run in "make" mode
145class MonadMake m where
147 -- Get a file timestamp
149 getTimestamp :: FilePath -> m (Maybe UTCTime)
152 -- Read a file as a string
154 readTextFile :: FilePath -> m String
159 writeTextFile :: FilePath -> String -> m ()
164 liftError :: Either String a -> m a
167 -- Respond to a progress update
169 progress :: String -> m ()
172-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
174-- If timestamps have not changed, the externs file can be used to provide the module's types without
175-- having to typecheck the module again.
177make :: (Functor m, Applicative m, Monad m, MonadMake m) => FilePath -> Options Make -> [(FilePath, Module)] -> [String] -> m Environment
178make outputDir opts ms prefix = do
179 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
181 (sorted, graph) <- liftError $ sortModules $ map importPrim $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
183 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
184 let filePath = runModuleName moduleName'
186 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
187 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
188 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
190 jsTimestamp <- getTimestamp jsFile
191 externsTimestamp <- getTimestamp externsFile
192 inputTimestamp <- getTimestamp inputFile
194 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
195 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
196 _ -> S.insert moduleName' s) S.empty sorted
198 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
200 (desugared, nextVar) <- liftError $ stringifyErrorStack True $ runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
202 evalSupplyT nextVar (go initEnvironment desugared)
205 go :: (Functor m, Applicative m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> SupplyT m Environment
206 go env [] = return env
207 go env ((False, m) : ms') = do
208 (_, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
211 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
212 let filePath = runModuleName moduleName'
213 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
214 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
216 lift . progress $ "Compiling " ++ runModuleName moduleName'
218 (Module _ elaborated _, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
220 regrouped <- lift . liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
222 let mod' = Module moduleName' regrouped exps
223 let [renamed] = renameInModules [mod']
225 pjs <- prettyPrintJS <$> moduleToJs opts renamed env'
226 let js = unlines $ map ("// " ++) prefix ++ [pjs]
227 let exts = unlines $ map ("-- " ++ ) prefix ++ [moduleToPs renamed env']
229 lift $ writeTextFile jsFile js
230 lift $ writeTextFile externsFile exts
234 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
235 rebuildIfNecessary _ _ [] = return []
236 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
237 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
238 toRebuild' = toRebuild `S.union` S.fromList deps
239 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
240 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
241 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
242 externs <- readTextFile externsFile
243 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
244 case externsModules of
245 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
246 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
248reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
249reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
251 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
252 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
255-- Add an import declaration for a module if it does not already explicitly import it.
257addDefaultImport :: ModuleName -> Module -> Module
258addDefaultImport toImport m@(Module mn decls exps) =
259 if isExistingImport `any` decls || mn == toImport then m
260 else Module mn (ImportDeclaration toImport Unqualified Nothing : decls) exps
262 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
263 isExistingImport (PositionedDeclaration _ d) = isExistingImport d
264 isExistingImport _ = False
266importPrim :: Module -> Module
267importPrim = addDefaultImport (ModuleName [ProperName C.prim])
269importPrelude :: Module -> Module
270importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
272preludeFilename :: IO FilePath
273preludeFilename = fromMaybe missingPrelude . listToMaybe <$> do
274 fs <- sequence [homePrelude, cabalPrelude]
275 filterM doesFileExist fs
277 missingPrelude :: FilePath
278 missingPrelude = error "No Prelude found in user home or cabal path."
280 homePrelude :: IO FilePath
282 homeDir <- getHomeDirectory
283 return $ homeDir </> ".purescript" </> "prelude" </> "prelude.purs"
285 cabalPrelude :: IO FilePath
286 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