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