git.iko.soy/rowtype-yoga/purescript-native
on beaef52 help sign in
255 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.Errors as P
32import Language.PureScript.DeadCodeElimination as P
34import qualified Language.PureScript.Constants as C
36import Data.List (find, sortBy, groupBy, intercalate)
37import Data.Time.Clock
38import Data.Function (on)
39import Data.Maybe (fromJust, fromMaybe)
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 <- stringifyErrorStack True $ desugar sorted
74 (elaborated, env') <- runCheck' opts env $ forM desugared $ typeCheckModule mainModuleIdent
75 regrouped <- stringifyErrorStack True $ 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 = concatMap (\m -> moduleToJs Globals opts m env') modulesToCodeGen
81 let exts = intercalate "\n" . map (`moduleToPs` env') $ modulesToCodeGen
82 js' <- generateMain env' opts js
83 return (prettyPrintJS 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 = everythingOnTypes (++) 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 (fromJust (optionsBrowserNamespace opts))))) []]
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
157 -- |
158 -- Respond to a progress update
159 --
160 progress :: String -> m ()
162-- |
163-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
164--
165-- If timestamps have not changed, the externs file can be used to provide the module's types without
166-- having to typecheck the module again.
167--
168make :: (Functor m, Monad m, MonadMake m) => FilePath -> Options -> [(FilePath, Module)] -> m Environment
169make outputDir opts ms = do
170 let filePathMap = M.fromList (map (\(fp, Module mn _ _) -> (mn, fp)) ms)
172 (sorted, graph) <- liftError $ sortModules $ if optionsNoPrelude opts then map snd ms else (map (importPrelude . snd) ms)
174 toRebuild <- foldM (\s (Module moduleName' _ _) -> do
175 let filePath = runModuleName moduleName'
177 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
178 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
179 inputFile = fromMaybe (error "Input file is undefined in make") $ M.lookup moduleName' filePathMap
181 jsTimestamp <- getTimestamp jsFile
182 externsTimestamp <- getTimestamp externsFile
183 inputTimestamp <- getTimestamp inputFile
185 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
186 (Just t1, Just t2, Just t3) | t1 < min t2 t3 -> s
187 _ -> S.insert moduleName' s) S.empty sorted
189 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
191 desugared <- liftError $ stringifyErrorStack True $ zip (map fst marked) <$> desugar (map snd marked)
193 go initEnvironment desugared
195 where
196 go :: (Functor m, Monad m, MonadMake m) => Environment -> [(Bool, Module)] -> m Environment
197 go env [] = return env
198 go env ((False, m) : ms') = do
199 (_, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
201 go env' ms'
202 go env ((True, m@(Module moduleName' _ exps)) : ms') = do
203 let filePath = runModuleName moduleName'
204 jsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "index.js"
205 externsFile = outputDir ++ pathSeparator : filePath ++ pathSeparator : "externs.purs"
207 progress $ "Compiling " ++ runModuleName moduleName'
209 (Module _ elaborated _, env') <- liftError . runCheck' opts env $ typeCheckModule Nothing m
211 regrouped <- liftError . stringifyErrorStack True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
213 let mod' = Module moduleName' regrouped exps
214 js = prettyPrintJS $ moduleToJs CommonJS opts mod' env'
215 exts = moduleToPs mod' env'
217 writeTextFile jsFile js
218 writeTextFile externsFile exts
220 go env' ms'
222 rebuildIfNecessary :: (Functor m, Monad m, MonadMake m) => M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
223 rebuildIfNecessary _ _ [] = return []
224 rebuildIfNecessary graph toRebuild (m@(Module moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
225 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
226 toRebuild' = toRebuild `S.union` S.fromList deps
227 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
228 rebuildIfNecessary graph toRebuild (Module moduleName' _ _ : ms') = do
229 let externsFile = outputDir ++ pathSeparator : runModuleName moduleName' ++ pathSeparator : "externs.purs"
230 externs <- readTextFile externsFile
231 externsModules <- liftError . either (Left . show) Right $ P.runIndentParser externsFile P.parseModules externs
232 case externsModules of
233 [m'@(Module moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
234 _ -> liftError . Left $ "Externs file " ++ externsFile ++ " was invalid"
236reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
237reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
238 where
239 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
240 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
242-- |
243-- Add an import declaration for the Prelude to a module if it does not already explicitly import
244-- it.
245--
246importPrelude :: Module -> Module
247importPrelude m@(Module mn decls exps) =
248 if isPreludeImport `any` decls || mn == prelude then m
249 else Module mn (preludeImport : decls) exps
250 where
251 prelude = ModuleName [ProperName C.prelude]
252 isPreludeImport (ImportDeclaration (ModuleName [ProperName mn']) _ _) | mn' == C.prelude = True
253 isPreludeImport (PositionedDeclaration _ d) = isPreludeImport d
254 isPreludeImport _ = False
255 preludeImport = ImportDeclaration prelude Nothing Nothing