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.Types as P
19import Language.PureScript.Kinds as P
20import Language.PureScript.Declarations as P
21import Language.PureScript.Names as P
22import Language.PureScript.Parser as P
23import Language.PureScript.CodeGen as P
24import Language.PureScript.CodeGen.Common as P
25import Language.PureScript.TypeChecker as P
26import Language.PureScript.Pretty as P
27import Language.PureScript.Sugar as P
28import Language.PureScript.Options as P
29import Language.PureScript.ModuleDependencies as P
30import Language.PureScript.Environment as P
31import Language.PureScript.Errors as P
32import Language.PureScript.DeadCodeElimination as P
34import qualified Language.PureScript.Constants as C
36import Data.List (find, sortBy, groupBy, intercalate)
38import Data.Function (on)
39import Data.Generics (mkQ, everything)
40import Data.Maybe (fromJust, fromMaybe)
41import Control.Monad.Error
42import Control.Monad.State.Lazy
43import Control.Arrow ((&&&))
44import Control.Applicative ((<$>))
45import qualified Data.Map as M
46import qualified Data.Set as S
47import System.FilePath (pathSeparator)
50-- Compile a collection of modules
52-- The compilation pipeline proceeds as follows:
54-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
56-- * Perform a set of desugaring passes.
58-- * Type check, and elaborate values to include type annotations and type class dictionaries.
60-- * Regroup values to take into account new value dependencies introduced by elaboration.
62-- * Eliminate dead code.
64-- * Generate Javascript, and perform optimization passes.
66-- * Pretty-print the generated Javascript
68compile :: Options -> [Module] -> Either String (String, String, Environment)
69compile = compile' initEnvironment
71compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
72compile' env opts ms = do
73 (sorted, _) <- sortModules $ if optionsNoPrelude opts then ms else (map importPrelude ms)
74 desugared <- stringifyErrorStack True $ desugar sorted
75 (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
76 regrouped <- stringifyErrorStack True $ 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 = JSVariableIntroduction (fromJust (optionsBrowserNamespace opts)) (Just (JSObjectLiteral []))
82 : concatMap (\m -> moduleToJs Globals opts m env') modulesToCodeGen
83 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
84 js' <- generateMain env' opts js
85 return (prettyPrintJS js', exts, env')
87 mainModuleIdent = moduleNameFromString <$> optionsMain opts
89typeCheckModule :: Maybe ModuleName -> Module -> Check Module
90typeCheckModule mainModuleName (Module mn decls exps) = do
91 modify (\s -> s { checkCurrentModule = Just mn })
92 decls' <- typeCheckAll mainModuleName mn decls
93 mapM_ checkTypesAreExported exps'
94 return $ Module mn decls' exps
97 exps' = fromMaybe (error "exports should have been elaborated") exps
99 -- Check that all the type constructors defined in the current module that appear in member types
100 -- have also been exported from the module
101 checkTypesAreExported :: DeclarationRef -> Check ()
102 checkTypesAreExported (ValueRef name) = do
103 ty <- lookupVariable mn (Qualified (Just mn) name)
104 case find isTconHidden (findTcons ty) of
105 Just hiddenType -> throwError . strMsg $
106 "Error in module '" ++ show mn ++ "':\n\
107 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
109 checkTypesAreExported _ = return ()
111 -- Find the type constructors exported from the current module used in a type
112 findTcons :: Type -> [ProperName]
113 findTcons = everything (++) (mkQ [] go)
115 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
118 -- Checks whether a type constructor is not being exported from the current module
119 isTconHidden :: ProperName -> Bool
120 isTconHidden tyName = all go exps'
122 go (TypeRef tyName' _) = tyName' /= tyName
126generateMain :: Environment -> Options -> [JS] -> Either String [JS]
127generateMain env opts js =
128 case moduleNameFromString <$> optionsMain opts of
130 when ((mmi, Ident C.main) `M.notMember` names env) $
131 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
132 return $ js ++ [JSApp (JSAccessor C.main (JSVar (moduleNameToJs mmi))) []]
136-- A type class which collects the IO actions we need to be able to run in "make" mode
138class MonadMake m where
140 -- Get a file timestamp
142 getTimestamp :: FilePath -> m (Maybe UTCTime)
145 -- Read a file as a string
147 readTextFile :: FilePath -> m String
152 writeTextFile :: FilePath -> String -> m ()
157 liftError :: Either String a -> m a
160 -- Respond to a progress update
162 progress :: String -> m ()
165-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
167-- If timestamps have not changed, the externs file can be used to provide the module's types without
168-- having to typecheck the module again.
170make :: (Functor m, Monad m, MonadMake m) => FilePath -> Options -> [(FilePath, Module)] -> m Environment
171make outputDir opts ms = do
172 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
174 (sorted, graph) <- liftError $ sortModules $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
176 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
177 let filePath = runModuleName moduleName'
179 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
180 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
181 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
183 jsTimestamp <- getTimestamp jsFile
184 externsTimestamp <- getTimestamp externsFile
185 inputTimestamp <- getTimestamp inputFile
187 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
188 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
189 _ -> S.insert moduleName' s) S.empty sorted
191 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
193 desugared <- liftError $ stringifyErrorStack True $ zip (map fst marked) <$> desugar (map snd marked)
195 go initEnvironment desugared
198 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m Environment
199 go env [] = return env
200 go env ((False, m) : ms') = do
201 (_, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
204 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
205 let filePath = runModuleName moduleName'
206 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
207 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
209 progress $ "Compiling " ++ runModuleName moduleName'
211 (Module _ elaborated _, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
213 regrouped <- liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
215 let mod' = Module moduleName' regrouped exps
216 js = prettyPrintJS $ moduleToJs CommonJS opts mod' env'
217 exts = moduleToPs mod' env'
219 writeTextFile jsFile js
220 writeTextFile externsFile exts
224 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
225 rebuildIfNecessary _ _ [] = return []
226 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
227 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
228 toRebuild' = toRebuild `S.union` S.fromList deps
229 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
230 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
231 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
232 externs <- readTextFile externsFile
233 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
234 case externsModules of
235 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
236 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
238reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
239reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
241 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
242 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
245-- Add an import declaration for the Prelude to a module if it does not already explicitly import
248importPrelude :: Module -> Module
249importPrelude m@(Module mn decls exps) =
250 if isPreludeImport `any` decls || mn == prelude then m
251 else Module mn (preludeImport : decls) exps
253 prelude = ModuleName [ProperName C.prelude]
254 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
255 isPreludeImport (PositionedDeclaration _ d) = isPreludeImport d
256 isPreludeImport _ = False
257 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