git.iko.soy/rowtype-yoga/purescript-native
on a316590 help sign in
263 lines 11 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript
4-- Copyright : (c) Phil Freeman 2013
5-- License : MIT
6--
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
9-- Portability :
10--
11-- |
12-- The main compiler module
13--
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
33import Language.PureScript.Supply as P
34import Language.PureScript.Renamer as P
36import qualified Language.PureScript.Constants as C
38import Data.List (find, sortBy, groupBy, intercalate)
39import Data.Time.Clock
40import Data.Function (on)
41import Data.Maybe (fromJust, fromMaybe)
42import Control.Monad.Error
43import Control.Monad.State.Lazy
44import Control.Arrow ((&&&))
45import Control.Applicative
46import qualified Data.Map as M
47import qualified Data.Set as S
48import System.FilePath (pathSeparator)
50-- |
51-- Compile a collection of modules
52--
53-- The compilation pipeline proceeds as follows:
54--
55-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
56--
57-- * Perform a set of desugaring passes.
58--
59-- * Type check, and elaborate values to include type annotations and type class dictionaries.
60--
61-- * Regroup values to take into account new value dependencies introduced by elaboration.
62--
63-- * Eliminate dead code.
64--
65-- * Generate Javascript, and perform optimization passes.
66--
67-- * Pretty-print the generated Javascript
68--
69compile :: Options -> [Module] -> Either String (String, String, Environment)
70compile = compile' initEnvironment
72compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
73compile' env opts ms = do
74 (sorted, _) <- sortModules $ map importPrim $ if optionsNoPrelude opts then ms else (map importPrelude ms)
75 (desugared, nextVar) <- stringifyErrorStack True $ runSupplyT 0 $ desugar sorted
76 (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
77 regrouped <- stringifyErrorStack True $ createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
78 let entryPoints = moduleNameFromString `map` optionsModules opts
79 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
80 let renamed = renameInModules elim
81 let codeGenModules = moduleNameFromString `map` optionsCodeGenModules opts
82 let modulesToCodeGen = if null codeGenModules then renamed else filter (\(Module mn _ _) -> mn `elem` codeGenModules) renamed
83 let js = evalSupply nextVar $ concat <$> mapM (\m -> moduleToJs Globals opts m env') modulesToCodeGen
84 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
85 js' <- generateMain env' opts js
86 return (prettyPrintJS js', exts, env')
87 where
88 mainModuleIdent = moduleNameFromString <$> optionsMain opts
90typeCheckModule :: Maybe ModuleName -> Module -> Check Module
91typeCheckModule mainModuleName (Module mn decls exps) = do
92 modify (\s -> s { checkCurrentModule = Just mn })
93 decls' <- typeCheckAll mainModuleName mn decls
94 mapM_ checkTypesAreExported exps'
95 return $ Module mn decls' exps
96 where
98 exps' = fromMaybe (error "exports should have been elaborated") exps
100 -- Check that all the type constructors defined in the current module that appear in member types
101 -- have also been exported from the module
102 checkTypesAreExported :: DeclarationRef -> Check ()
103 checkTypesAreExported (ValueRef name) = do
104 ty <- lookupVariable mn (Qualified (Just mn) name)
105 case find isTconHidden (findTcons ty) of
106 Just hiddenType -> throwError . strMsg $
107 "Error in module '" ++ show mn ++ "':\n\
108 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
109 Nothing -> return ()
110 checkTypesAreExported _ = return ()
112 -- Find the type constructors exported from the current module used in a type
113 findTcons :: Type -> [ProperName]
114 findTcons = everythingOnTypes (++) go
115 where
116 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
117 go _ = []
119 -- Checks whether a type constructor is not being exported from the current module
120 isTconHidden :: ProperName -> Bool
121 isTconHidden tyName = all go exps'
122 where
123 go (TypeRef tyName' _) = tyName' /= tyName
124 go _ = True
127generateMain :: Environment -> Options -> [JS] -> Either String [JS]
128generateMain env opts js =
129 case moduleNameFromString <$> optionsMain opts of
130 Just mmi -> do
131 when ((mmi, Ident C.main) `M.notMember` names env) $
132 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
133 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (fromJust (optionsBrowserNamespace opts))))) []]
134 _ -> return js
136-- |
137-- A type class which collects the IO actions we need to be able to run in "make" mode
138--
139class MonadMake m where
140 -- |
141 -- Get a file timestamp
142 --
143 getTimestamp :: FilePath -> m (Maybe UTCTime)
145 -- |
146 -- Read a file as a string
147 --
148 readTextFile :: FilePath -> m String
150 -- |
151 -- Write a text file
152 --
153 writeTextFile :: FilePath -> String -> m ()
155 -- |
156 -- Report an error
157 --
158 liftError :: Either String a -> m a
160 -- |
161 -- Respond to a progress update
162 --
163 progress :: String -> m ()
165-- |
166-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
167--
168-- If timestamps have not changed, the externs file can be used to provide the module's types without
169-- having to typecheck the module again.
170--
171make :: (Functor m, Applicative m, Monad m, MonadMake m) => FilePath -> Options -> [(FilePath, Module)] -> m Environment
172make outputDir opts ms = do
173 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
175 (sorted, graph) <- liftError $ sortModules $ map importPrim $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
177 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
178 let filePath = runModuleName moduleName'
180 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
181 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
182 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
184 jsTimestamp <- getTimestamp jsFile
185 externsTimestamp <- getTimestamp externsFile
186 inputTimestamp <- getTimestamp inputFile
188 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
189 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
190 _ -> S.insert moduleName' s) S.empty sorted
192 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
194 (desugared, nextVar) <- liftError $ stringifyErrorStack True $ runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
196 evalSupplyT nextVar (go initEnvironment desugared)
198 where
199 go :: (Functor m, Applicative m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> SupplyT m Environment
200 go env [] = return env
201 go env ((False, m) : ms') = do
202 (_, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
204 go env' ms'
205 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
206 let filePath = runModuleName moduleName'
207 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
208 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
210 lift . progress $ "Compiling " ++ runModuleName moduleName'
212 (Module _ elaborated _, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
214 regrouped <- lift . liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
216 let mod' = Module moduleName' regrouped exps
217 let [renamed] = renameInModules [mod']
219 js <- prettyPrintJS <$> moduleToJs CommonJS opts renamed env'
220 let exts = moduleToPs renamed env'
222 lift $ writeTextFile jsFile js
223 lift $ writeTextFile externsFile exts
225 go env' ms'
227 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
228 rebuildIfNecessary _ _ [] = return []
229 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
230 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
231 toRebuild' = toRebuild `S.union` S.fromList deps
232 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
233 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
234 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
235 externs <- readTextFile externsFile
236 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
237 case externsModules of
238 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
239 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
241reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
242reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
243 where
244 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
245 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
247-- |
248-- Add an import declaration for a module if it does not already explicitly import it.
249--
250addDefaultImport :: ModuleName -> Module -> Module
251addDefaultImport toImport m@(Module mn decls exps) =
252 if isExistingImport `any` decls || mn == toImport then m
253 else Module mn (ImportDeclaration toImport Nothing Nothing : decls) exps
254 where
255 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
256 isExistingImport (PositionedDeclaration _ d) = isExistingImport d
257 isExistingImport _ = False
259importPrim :: Module -> Module
260importPrim = addDefaultImport (ModuleName [ProperName C.prim])
262importPrelude :: Module -> Module
263importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])