git.iko.soy/rowtype-yoga/purescript-native
on 363b03c help sign in
259 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
35import qualified Language.PureScript.Constants as C
37import Data.List (find, sortBy, groupBy, intercalate)
38import Data.Time.Clock
39import Data.Function (on)
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)
49-- |
50-- Compile a collection of modules
51--
52-- The compilation pipeline proceeds as follows:
53--
54-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
55--
56-- * Perform a set of desugaring passes.
57--
58-- * Type check, and elaborate values to include type annotations and type class dictionaries.
59--
60-- * Regroup values to take into account new value dependencies introduced by elaboration.
61--
62-- * Eliminate dead code.
63--
64-- * Generate Javascript, and perform optimization passes.
65--
66-- * Pretty-print the generated Javascript
67--
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 $ map importPrim $ if optionsNoPrelude opts then ms else (map importPrelude ms)
74 (desugared, nextVar) <- stringifyErrorStack True $ runSupplyT 0 $ 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 = evalSupply nextVar $ concat <$> mapM (\m -> moduleToJs Globals opts m env') modulesToCodeGen
82 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
83 js' <- generateMain env' opts js
84 return (prettyPrintJS js', exts, env')
85 where
86 mainModuleIdent = moduleNameFromString <$> optionsMain opts
88typeCheckModule :: Maybe ModuleName -> Module -> Check Module
89typeCheckModule mainModuleName (Module mn decls exps) = do
90 modify (\s -> s { checkCurrentModule = Just mn })
91 decls' <- typeCheckAll mainModuleName mn decls
92 mapM_ checkTypesAreExported exps'
93 return $ Module mn decls' exps
94 where
96 exps' = fromMaybe (error "exports should have been elaborated") exps
98 -- Check that all the type constructors defined in the current module that appear in member types
99 -- have also been exported from the module
100 checkTypesAreExported :: DeclarationRef -> Check ()
101 checkTypesAreExported (ValueRef name) = do
102 ty <- lookupVariable mn (Qualified (Just mn) name)
103 case find isTconHidden (findTcons ty) of
104 Just hiddenType -> throwError . strMsg $
105 "Error in module '" ++ show mn ++ "':\n\
106 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
107 Nothing -> return ()
108 checkTypesAreExported _ = return ()
110 -- Find the type constructors exported from the current module used in a type
111 findTcons :: Type -> [ProperName]
112 findTcons = everythingOnTypes (++) go
113 where
114 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
115 go _ = []
117 -- Checks whether a type constructor is not being exported from the current module
118 isTconHidden :: ProperName -> Bool
119 isTconHidden tyName = all go exps'
120 where
121 go (TypeRef tyName' _) = tyName' /= tyName
122 go _ = True
125generateMain :: Environment -> Options -> [JS] -> Either String [JS]
126generateMain env opts js =
127 case moduleNameFromString <$> optionsMain opts of
128 Just mmi -> do
129 when ((mmi, Ident C.main) `M.notMember` names env) $
130 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
131 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (fromJust (optionsBrowserNamespace opts))))) []]
132 _ -> return js
134-- |
135-- A type class which collects the IO actions we need to be able to run in "make" mode
136--
137class MonadMake m where
138 -- |
139 -- Get a file timestamp
140 --
141 getTimestamp :: FilePath -> m (Maybe UTCTime)
143 -- |
144 -- Read a file as a string
145 --
146 readTextFile :: FilePath -> m String
148 -- |
149 -- Write a text file
150 --
151 writeTextFile :: FilePath -> String -> m ()
153 -- |
154 -- Report an error
155 --
156 liftError :: Either String a -> m a
158 -- |
159 -- Respond to a progress update
160 --
161 progress :: String -> m ()
163-- |
164-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
165--
166-- If timestamps have not changed, the externs file can be used to provide the module's types without
167-- having to typecheck the module again.
168--
169make :: (Functor m, Applicative m, Monad m, MonadMake m) => FilePath -> Options -> [(FilePath, Module)] -> m Environment
170make outputDir opts ms = do
171 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
173 (sorted, graph) <- liftError $ sortModules $ map importPrim $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
175 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
176 let filePath = runModuleName moduleName'
178 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
179 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
180 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
182 jsTimestamp <- getTimestamp jsFile
183 externsTimestamp <- getTimestamp externsFile
184 inputTimestamp <- getTimestamp inputFile
186 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
187 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
188 _ -> S.insert moduleName' s) S.empty sorted
190 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
192 (desugared, nextVar) <- liftError $ stringifyErrorStack True $ runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
194 evalSupplyT nextVar (go initEnvironment desugared)
196 where
197 go :: (Functor m, Applicative m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> SupplyT m Environment
198 go env [] = return env
199 go env ((False, m) : ms') = do
200 (_, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
202 go env' ms'
203 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
204 let filePath = runModuleName moduleName'
205 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
206 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
208 lift . progress $ "Compiling " ++ runModuleName moduleName'
210 (Module _ elaborated _, env') <- lift . liftError . runCheck' opts env $ typeCheckModule Nothing m
212 regrouped <- lift . liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
214 let mod' = Module moduleName' regrouped exps
215 js <- prettyPrintJS <$> moduleToJs CommonJS opts mod' env'
216 let exts = moduleToPs mod' env'
218 lift $ writeTextFile jsFile js
219 lift $ writeTextFile externsFile exts
221 go env' ms'
223 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
224 rebuildIfNecessary _ _ [] = return []
225 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
226 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
227 toRebuild' = toRebuild `S.union` S.fromList deps
228 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
229 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
230 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
231 externs <- readTextFile externsFile
232 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
233 case externsModules of
234 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
235 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
237reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
238reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
239 where
240 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
241 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
243-- |
244-- Add an import declaration for a module if it does not already explicitly import it.
245--
246addDefaultImport :: ModuleName -> Module -> Module
247addDefaultImport toImport m@(Module mn decls exps) =
248 if isExistingImport `any` decls || mn == toImport then m
249 else Module mn (ImportDeclaration toImport Nothing Nothing : decls) exps
250 where
251 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
252 isExistingImport (PositionedDeclaration _ d) = isExistingImport d
253 isExistingImport _ = False
255importPrim :: Module -> Module
256importPrim = addDefaultImport (ModuleName [ProperName C.prim])
258importPrelude :: Module -> Module
259importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])