git.iko.soy/rowtype-yoga/purescript-native
on 130e8ae help sign in
251 lines 9.9 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.DeadCodeElimination as P
33import qualified Language.PureScript.Constants as C
35import Data.List (find, sortBy, groupBy, intercalate)
36import Data.Time.Clock
37import Data.Function (on)
38import Data.Generics (mkQ, everything)
39import Data.Maybe (fromMaybe, mapMaybe)
40import Control.Monad.Error
41import Control.Monad.State.Lazy
42import Control.Arrow ((&&&))
43import Control.Applicative ((<$>))
44import qualified Data.Map as M
45import qualified Data.Set as S
46import System.FilePath (pathSeparator)
48-- |
49-- Compile a collection of modules
50--
51-- The compilation pipeline proceeds as follows:
52--
53-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
54--
55-- * Perform a set of desugaring passes.
56--
57-- * Type check, and elaborate values to include type annotations and type class dictionaries.
58--
59-- * Regroup values to take into account new value dependencies introduced by elaboration.
60--
61-- * Eliminate dead code.
62--
63-- * Generate Javascript, and perform optimization passes.
64--
65-- * Pretty-print the generated Javascript
66--
67compile :: Options -> [Module] -> Either String (String, String, Environment)
68compile = compile' initEnvironment
70compile' :: Environment -> Options -> [Module] -> Either String (String, String, Environment)
71compile' env opts ms = do
72 (sorted, _) <- sortModules (map importPrelude ms)
73 desugared <- desugar sorted
74 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
75 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
76 let entryPoints = moduleNameFromString `map` optionsModules opts
77 let elim = if null entryPoints then regrouped else eliminateDeadCode entryPoints regrouped
78 let codeGenModules = moduleNameFromString `map` optionsCodeGenModules opts
79 let modulesToCodeGen = if null codeGenModules then elim else filter (\(Module mn _ _) -> mn `elem` codeGenModules) elim
80 let js = mapMaybe (flip (moduleToJs opts) env') modulesToCodeGen
81 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
82 js' <- generateMain env' opts js
83 return (prettyPrintJS [wrapExportsContainer opts js'], exts, env')
84 where
85 mainModuleIdent = moduleNameFromString <$> optionsMain opts
87typeCheckModule :: Maybe ModuleName -> Module -> Check Module
88typeCheckModule mainModuleName (Module mn decls exps) = do
89 modify (\s -> s { checkCurrentModule = Just mn })
90 decls' <- typeCheckAll mainModuleName mn decls
91 mapM_ checkTypesAreExported exps'
92 return $ Module mn decls' exps
93 where
95 exps' = fromMaybe (error "exports should have been elaborated") exps
97 -- Check that all the type constructors defined in the current module that appear in member types
98 -- have also been exported from the module
99 checkTypesAreExported :: DeclarationRef -> Check ()
100 checkTypesAreExported (ValueRef name) = do
101 ty <- lookupVariable mn (Qualified (Just mn) name)
102 case find isTconHidden (findTcons ty) of
103 Just hiddenType -> throwError $ "Error in module '" ++ show mn ++ "':\n\
104 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
105 Nothing -> return ()
106 checkTypesAreExported _ = return ()
108 -- Find the type constructors exported from the current module used in a type
109 findTcons :: Type -> [ProperName]
110 findTcons = everything (++) (mkQ [] go)
111 where
112 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
113 go _ = []
115 -- Checks whether a type constructor is not being exported from the current module
116 isTconHidden :: ProperName -> Bool
117 isTconHidden tyName = all go exps'
118 where
119 go (TypeRef tyName' _) = tyName' /= tyName
120 go _ = True
123generateMain :: Environment -> Options -> [JS] -> Either String [JS]
124generateMain env opts js =
125 case moduleNameFromString <$> optionsMain opts of
126 Just mmi -> do
127 when ((mmi, Ident C.main) `M.notMember` names env) $
128 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
129 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
130 _ -> return js
132-- |
133-- A type class which collects the IO actions we need to be able to run in "make" mode
134--
135class MonadMake m where
136 -- |
137 -- Get a file timestamp
138 --
139 getTimestamp :: FilePath -> m (Maybe UTCTime)
141 -- |
142 -- Read a file as a string
143 --
144 readTextFile :: FilePath -> m String
146 -- |
147 -- Write a text file
148 --
149 writeTextFile :: FilePath -> String -> m ()
151 -- |
152 -- Report an error
153 --
154 liftError :: Either String a -> m a
157-- |
158-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
159--
160-- If timestamps have not changed, the externs file can be used to provide the module's types without
161-- having to typecheck the module again.
162--
163make :: (Functor m, Monad m, MonadMake m) => Options -> [(FilePath, Module)] -> m ()
164make opts ms = do
165 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
167 (sorted, graph) <- liftError $ sortModules (map (importPrelude . snd) ms)
169 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
170 let filePath = toFileName moduleName'
172 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
173 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
174 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
176 jsTimestamp <- getTimestamp jsFile
177 externsTimestamp <- getTimestamp externsFile
178 inputTimestamp <- getTimestamp inputFile
180 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
181 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
182 _ -> S.insert moduleName' s) S.empty sorted
184 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
186 desugared <- liftError $ zip (map fst marked) <$> desugar (map snd marked)
188 go initEnvironment desugared
190 where
191 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m ()
192 go _ [] = return ()
193 go env ((False, m) : ms') = do
194 (_, env') <- liftError . runCheck' env $ typeCheckModule Nothing m
196 go env' ms'
197 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
198 let filePath = toFileName moduleName'
199 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
200 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
202 (Module _ elaborated _, env') <- liftError . runCheck' env $ typeCheckModule Nothing m
204 regrouped <- liftError . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
206 let mod' = Module moduleName' regrouped exps
207 js = moduleToJs opts mod' env'
208 exts = moduleToPs mod' env'
209 js' = maybe "" (prettyPrintJS . return . wrapExportsContainer opts . return) js
211 writeTextFile jsFile js'
212 writeTextFile externsFile exts
214 go env' ms'
216toFileName :: ModuleName -> FilePath
217toFileName (ModuleName ps) = intercalate [pathSeparator] . map runProperName $ ps
219rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
220rebuildIfNecessary _ _ [] = return []
221rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms) | moduleName' `S.member` toRebuild = do
222 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
223 toRebuild' = toRebuild `S.union` S.fromList deps
224 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms
225rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms) = do
226 let externsFile = "externs" ++ pathSeparator : toFileName moduleName' ++ ".externs"
227 externs <- readTextFile externsFile
228 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
229 case externsModules of
230 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms
231 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
233reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
234reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
235 where
236 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
237 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
239-- |
240-- Add an import declaration for the Prelude to a module if it does not already explicitly import
241-- it.
242--
243importPrelude :: Module -> Module
244importPrelude m@(Module mn decls exps) =
245 if isPreludeImport `any` decls || mn == prelude then m
246 else Module mn (preludeImport : decls) exps
247 where
248 prelude = ModuleName [ProperName C.prelude]
249 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
250 isPreludeImport _ = False
251 preludeImport = ImportDeclaration prelude Nothing Nothing