git.iko.soy/rowtype-yoga/purescript-native
on 4326d49 help sign in
253 lines 10 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 $ if optionsNoPrelude opts then ms else (map importPrelude ms)
73 desugared <- desugar sorted
74 (elaborated, env') <- runCheck' opts 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 . strMsg $
104 "Error in module '" ++ show mn ++ "':\n\
105 \Exporting declaration '" ++ show name ++ "' requires type '" ++ show hiddenType ++ "' to be exported as well"
106 Nothing -> return ()
107 checkTypesAreExported _ = return ()
109 -- Find the type constructors exported from the current module used in a type
110 findTcons :: Type -> [ProperName]
111 findTcons = everything (++) (mkQ [] go)
112 where
113 go (TypeConstructor (Qualified (Just mn') name)) | mn' == mn = [name]
114 go _ = []
116 -- Checks whether a type constructor is not being exported from the current module
117 isTconHidden :: ProperName -> Bool
118 isTconHidden tyName = all go exps'
119 where
120 go (TypeRef tyName' _) = tyName' /= tyName
121 go _ = True
124generateMain :: Environment -> Options -> [JS] -> Either String [JS]
125generateMain env opts js =
126 case moduleNameFromString <$> optionsMain opts of
127 Just mmi -> do
128 when ((mmi, Ident C.main) `M.notMember` names env) $
129 Left $ show mmi ++ "." ++ C.main ++ " is undefined"
130 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar C._ps))) []]
131 _ -> return js
133-- |
134-- A type class which collects the IO actions we need to be able to run in "make" mode
135--
136class MonadMake m where
137 -- |
138 -- Get a file timestamp
139 --
140 getTimestamp :: FilePath -> m (Maybe UTCTime)
142 -- |
143 -- Read a file as a string
144 --
145 readTextFile :: FilePath -> m String
147 -- |
148 -- Write a text file
149 --
150 writeTextFile :: FilePath -> String -> m ()
152 -- |
153 -- Report an error
154 --
155 liftError :: Either String a -> m a
158-- |
159-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
160--
161-- If timestamps have not changed, the externs file can be used to provide the module's types without
162-- having to typecheck the module again.
163--
164make :: (Functor m, Monad m, MonadMake m) => Options -> [(FilePath, Module)] -> m ()
165make opts ms = do
166 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
168 (sorted, graph) <- liftError $ sortModules $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
170 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
171 let filePath = toFileName moduleName'
173 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
174 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
175 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
177 jsTimestamp <- getTimestamp jsFile
178 externsTimestamp <- getTimestamp externsFile
179 inputTimestamp <- getTimestamp inputFile
181 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
182 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
183 _ -> S.insert moduleName' s) S.empty sorted
185 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
187 desugared <- liftError $ zip (map fst marked) <$> desugar (map snd marked)
189 go initEnvironment desugared
191 where
192 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m ()
193 go _ [] = return ()
194 go env ((False, m) : ms') = do
195 (_, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
197 go env' ms'
198 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
199 let filePath = toFileName moduleName'
200 jsFile = "js" ++ pathSeparator : filePath ++ ".js"
201 externsFile = "externs" ++ pathSeparator : filePath ++ ".externs"
203 (Module _ elaborated _, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
205 regrouped <- liftError . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
207 let mod' = Module moduleName' regrouped exps
208 js = moduleToJs opts mod' env'
209 exts = moduleToPs mod' env'
210 js' = maybe "" (prettyPrintJS . return . wrapExportsContainer opts . return) js
212 writeTextFile jsFile js'
213 writeTextFile externsFile exts
215 go env' ms'
217toFileName :: ModuleName -> FilePath
218toFileName (ModuleName ps) = intercalate [pathSeparator] . map runProperName $ ps
220rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
221rebuildIfNecessary _ _ [] = return []
222rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms) | moduleName' `S.member` toRebuild = do
223 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
224 toRebuild' = toRebuild `S.union` S.fromList deps
225 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms
226rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms) = do
227 let externsFile = "externs" ++ pathSeparator : toFileName moduleName' ++ ".externs"
228 externs <- readTextFile externsFile
229 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
230 case externsModules of
231 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms
232 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
234reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
235reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
236 where
237 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
238 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
240-- |
241-- Add an import declaration for the Prelude to a module if it does not already explicitly import
242-- it.
243--
244importPrelude :: Module -> Module
245importPrelude m@(Module mn decls exps) =
246 if isPreludeImport `any` decls || mn == prelude then m
247 else Module mn (preludeImport : decls) exps
248 where
249 prelude = ModuleName [ProperName C.prelude]
250 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
251 isPreludeImport (PositionedDeclaration _ d) = isPreludeImport d
252 isPreludeImport _ = False
253 preludeImport = ImportDeclaration prelude Nothing Nothing