git.iko.soy/rowtype-yoga/purescript-native
on 7296802 help sign in
275 lines 11 kB history raw
1-----------------------------------------------------------------------------
2--
3-- Module : Language.PureScript
4-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
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 #-}
17{-# LANGUAGE QuasiQuotes #-}
18{-# LANGUAGE TemplateHaskell #-}
19{-# LANGUAGE FlexibleContexts #-}
20{-# LANGUAGE ScopedTypeVariables #-}
22module Language.PureScript
23 ( module P
24 , compile
25 , compile'
26 , RebuildPolicy(..)
27 , MonadMake(..)
28 , make
29 , version
30 ) where
32import Data.Function (on)
33import Data.List (sortBy, groupBy, intercalate)
34import Data.Maybe (fromMaybe)
35import Data.Time.Clock
36import Data.Version (Version)
37import qualified Data.Traversable as T (traverse)
38import qualified Data.Map as M
39import qualified Data.Set as S
41import Control.Applicative
42import Control.Arrow ((&&&))
43import Control.Monad.Except
44import Control.Monad.Reader
45import Control.Monad.Writer
47import System.FilePath ((</>))
49import Language.PureScript.AST as P
50import Language.PureScript.Comments as P
51import Language.PureScript.CodeGen as P
52import Language.PureScript.DeadCodeElimination as P
53import Language.PureScript.Environment as P
54import Language.PureScript.Errors as P
55import Language.PureScript.Kinds as P
56import Language.PureScript.Linter as P
57import Language.PureScript.ModuleDependencies as P
58import Language.PureScript.Names as P
59import Language.PureScript.Options as P
60import Language.PureScript.Parser as P
61import Language.PureScript.Pretty as P
62import Language.PureScript.Renamer as P
63import Language.PureScript.Sugar as P
64import Control.Monad.Supply as P
65import Language.PureScript.TypeChecker as P
66import Language.PureScript.Types as P
67import qualified Language.PureScript.CoreFn as CoreFn
68import qualified Language.PureScript.Constants as C
70import qualified Paths_purescript as Paths
72-- |
73-- Compile a collection of modules
74--
75-- The compilation pipeline proceeds as follows:
76--
77-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
78--
79-- * Perform a set of desugaring passes.
80--
81-- * Type check, and elaborate values to include type annotations and type class dictionaries.
82--
83-- * Regroup values to take into account new value dependencies introduced by elaboration.
84--
85-- * Eliminate dead code.
86--
87-- * Generate Javascript, and perform optimization passes.
88--
89-- * Pretty-print the generated Javascript
90--
91compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
92 => [Module] -> [String] -> m (String, String, Environment)
93compile = compile' initEnvironment
95compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
96 => Environment -> [Module] -> [String] -> m (String, String, Environment)
97compile' env ms prefix = do
98 noPrelude <- asks optionsNoPrelude
99 additional <- asks optionsAdditional
100 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
101 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
102 mapM_ lint sorted
103 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
104 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
105 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
106 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
107 entryPoints = moduleNameFromString `map` entryPointModules additional
108 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
109 renamed = renameInModules elim
110 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
111 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
112 js <- concat <$> (evalSupplyT nextVar $ T.traverse moduleToJs modulesToCodeGen)
113 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
114 js' <- generateMain env' js
115 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
116 return (pjs, exts, env')
118generateMain :: (MonadError MultipleErrors m, MonadReader (Options Compile) m) => Environment -> [JS] -> m [JS]
119generateMain env js = do
120 main <- asks optionsMain
121 additional <- asks optionsAdditional
122 case moduleNameFromString <$> main of
123 Just mmi -> do
124 when ((mmi, Ident C.main) `M.notMember` names env) $
125 throwError . errorMessage $ NameIsUndefined (Ident C.main)
126 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace additional)))) []]
127 _ -> return js
129-- |
130-- A type class which collects the IO actions we need to be able to run in "make" mode
131--
132class (MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => MonadMake m where
133 -- |
134 -- Get a file timestamp
135 --
136 getTimestamp :: FilePath -> m (Maybe UTCTime)
138 -- |
139 -- Read a file as a string
140 --
141 readTextFile :: FilePath -> m String
143 -- |
144 -- Write a text file
145 --
146 writeTextFile :: FilePath -> String -> m ()
148 -- |
149 -- Respond to a progress update
150 --
151 progress :: String -> m ()
153-- |
154-- Determines when to rebuild a module
155--
156data RebuildPolicy
157 -- | Never rebuild this module
158 = RebuildNever
159 -- | Always rebuild this module
160 | RebuildAlways deriving (Show, Eq, Ord)
162-- Traverse (Either e) instance (base 4.7)
163traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
164traverseEither _ (Left x) = pure (Left x)
165traverseEither f (Right y) = Right <$> f y
167-- |
168-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
169--
170-- If timestamps have not changed, the externs file can be used to provide the module's types without
171-- having to typecheck the module again.
172--
173make :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
174 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
175make outputDir ms prefix = do
176 noPrelude <- asks optionsNoPrelude
177 let filePathMap = M.fromList (map (\(fp, Module _ mn _ _) -> (mn, fp)) ms)
179 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
181 mapM_ lint sorted
183 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
184 let filePath = runModuleName moduleName'
186 jsFile = outputDir </> filePath </> "index.js"
187 externsFile = outputDir </> filePath </> "externs.purs"
188 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
190 jsTimestamp <- getTimestamp jsFile
191 externsTimestamp <- getTimestamp externsFile
192 inputTimestamp <- traverseEither getTimestamp inputFile
194 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
195 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
196 (Left RebuildNever, Just _, Just _) -> s
197 _ -> S.insert moduleName' s) S.empty sorted
199 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
201 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
203 evalSupplyT nextVar $ go initEnvironment desugared
205 where
206 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
207 go env [] = return env
208 go env ((False, m) : ms') = do
209 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
211 go env' ms'
212 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
213 let filePath = runModuleName moduleName'
214 jsFile = outputDir </> filePath </> "index.js"
215 externsFile = outputDir </> filePath </> "externs.purs"
217 lift . progress $ "Compiling " ++ runModuleName moduleName'
219 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
221 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
223 let mod' = Module coms moduleName' regrouped exps
224 corefn = CoreFn.moduleToCoreFn env' mod'
225 [renamed] = renameInModules [corefn]
227 pjs <- prettyPrintJS <$> moduleToJs renamed
228 let js = unlines $ map ("// " ++) prefix ++ [pjs]
229 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
231 lift $ writeTextFile jsFile js
232 lift $ writeTextFile externsFile exts
234 go env' ms'
236 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
237 rebuildIfNecessary _ _ [] = return []
238 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
239 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
240 toRebuild' = toRebuild `S.union` S.fromList deps
241 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
242 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
243 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
244 externs <- readTextFile externsFile
245 externsModules <- fmap (map snd) . either (throwError . errorMessage . ErrorParsingExterns) return $ P.parseModulesFromFiles id [(externsFile, externs)]
246 case externsModules of
247 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
248 _ -> throwError . errorMessage . InvalidExternsFile $ externsFile
250reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
251reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
252 where
253 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
254 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
256-- |
257-- Add an import declaration for a module if it does not already explicitly import it.
258--
259addDefaultImport :: ModuleName -> Module -> Module
260addDefaultImport toImport m@(Module coms mn decls exps) =
261 if isExistingImport `any` decls || mn == toImport then m
262 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
263 where
264 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
265 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
266 isExistingImport _ = False
268importPrim :: Module -> Module
269importPrim = addDefaultImport (ModuleName [ProperName C.prim])
271importPrelude :: Module -> Module
272importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
274version :: Version
275version = Paths.version