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