git.iko.soy/rowtype-yoga/purescript-native
on 2eb5852 help sign in
269 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 , prelude
30 ) where
32import Data.FileEmbed (embedFile)
33import Data.Function (on)
34import Data.List (sortBy, groupBy, intercalate)
35import Data.Maybe (fromMaybe)
36import Data.Time.Clock
37import qualified Data.Traversable as T (traverse)
38import qualified Data.ByteString.UTF8 as BU
39import qualified Data.Map as M
40import qualified Data.Set as S
42import Control.Applicative
43import Control.Arrow ((&&&))
44import Control.Monad.Except
45import Control.Monad.Reader
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.ModuleDependencies as P
57import Language.PureScript.Names as P
58import Language.PureScript.Options as P
59import Language.PureScript.Parser as P
60import Language.PureScript.Pretty as P
61import Language.PureScript.Renamer as P
62import Language.PureScript.Sugar as P
63import Control.Monad.Supply as P
64import Language.PureScript.TypeChecker as P
65import Language.PureScript.Types as P
66import qualified Language.PureScript.CoreFn as CoreFn
67import qualified Language.PureScript.Constants as C
69-- |
70-- Compile a collection of modules
71--
72-- The compilation pipeline proceeds as follows:
73--
74-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
75--
76-- * Perform a set of desugaring passes.
77--
78-- * Type check, and elaborate values to include type annotations and type class dictionaries.
79--
80-- * Regroup values to take into account new value dependencies introduced by elaboration.
81--
82-- * Eliminate dead code.
83--
84-- * Generate Javascript, and perform optimization passes.
85--
86-- * Pretty-print the generated Javascript
87--
88compile :: (Functor m, Applicative m, MonadError String m, MonadReader (Options Compile) m)
89 => [Module] -> [String] -> m (String, String, Environment)
90compile = compile' initEnvironment
92compile' :: (Functor m, Applicative m, MonadError String m, MonadReader (Options Compile) m)
93 => Environment -> [Module] -> [String] -> m (String, String, Environment)
94compile' env ms prefix = do
95 noPrelude <- asks optionsNoPrelude
96 additional <- asks optionsAdditional
97 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
98 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
99 (desugared, nextVar) <- interpretMultipleErrors True $ runSupplyT 0 $ desugar sorted
100 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
101 regrouped <- interpretMultipleErrors True $ createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
102 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
103 let entryPoints = moduleNameFromString `map` entryPointModules additional
104 let elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
105 let renamed = renameInModules elim
106 let codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
107 let modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
108 js <- concat <$> (evalSupplyT nextVar $ T.traverse moduleToJs modulesToCodeGen)
109 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
110 js' <- generateMain env' js
111 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
112 return (pjs, exts, env')
114generateMain :: (MonadError String m, MonadReader (Options Compile) m) => Environment -> [JS] -> m [JS]
115generateMain env js = do
116 main <- asks optionsMain
117 additional <- asks optionsAdditional
118 case moduleNameFromString <$> main of
119 Just mmi -> do
120 when ((mmi, Ident C.main) `M.notMember` names env) $
121 throwError $ show mmi ++ "." ++ C.main ++ " is undefined"
122 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace additional)))) []]
123 _ -> return js
125-- |
126-- A type class which collects the IO actions we need to be able to run in "make" mode
127--
128class (MonadReader (P.Options P.Make) m, MonadError String m) => MonadMake m where
129 -- |
130 -- Get a file timestamp
131 --
132 getTimestamp :: FilePath -> m (Maybe UTCTime)
134 -- |
135 -- Read a file as a string
136 --
137 readTextFile :: FilePath -> m String
139 -- |
140 -- Write a text file
141 --
142 writeTextFile :: FilePath -> String -> m ()
144 -- |
145 -- Respond to a progress update
146 --
147 progress :: String -> m ()
149-- |
150-- Determines when to rebuild a module
151--
152data RebuildPolicy
153 -- | Never rebuild this module
154 = RebuildNever
155 -- | Always rebuild this module
156 | RebuildAlways deriving (Show, Eq, Ord)
158-- Traverse (Either e) instance (base 4.7)
159traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
160traverseEither _ (Left x) = pure (Left x)
161traverseEither f (Right y) = Right <$> f y
163-- |
164-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
165--
166-- If timestamps have not changed, the externs file can be used to provide the module's types without
167-- having to typecheck the module again.
168--
169make :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
170 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
171make outputDir ms prefix = do
172 noPrelude <- asks optionsNoPrelude
173 let filePathMap = M.fromList (map (\(fp, Module _ mn _ _) -> (mn, fp)) ms)
175 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
177 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
178 let filePath = runModuleName moduleName'
180 jsFile = outputDir </> filePath </> "index.js"
181 externsFile = outputDir </> filePath </> "externs.purs"
182 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
184 jsTimestamp <- getTimestamp jsFile
185 externsTimestamp <- getTimestamp externsFile
186 inputTimestamp <- traverseEither getTimestamp inputFile
188 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
189 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
190 (Left RebuildNever, Just _, Just _) -> s
191 _ -> S.insert moduleName' s) S.empty sorted
193 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
195 (desugared, nextVar) <- interpretMultipleErrors True $ runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
197 evalSupplyT nextVar $ go initEnvironment desugared
199 where
200 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
201 go env [] = return env
202 go env ((False, m) : ms') = do
203 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
205 go env' ms'
206 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
207 let filePath = runModuleName moduleName'
208 jsFile = outputDir </> filePath </> "index.js"
209 externsFile = outputDir </> filePath </> "externs.purs"
211 lift . progress $ "Compiling " ++ runModuleName moduleName'
213 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
215 regrouped <- interpretMultipleErrors True . createBindingGroups moduleName' . collapseBindingGroups $ elaborated
217 let mod' = Module coms moduleName' regrouped exps
218 let corefn = CoreFn.moduleToCoreFn env' mod'
219 let [renamed] = renameInModules [corefn]
221 pjs <- prettyPrintJS <$> moduleToJs renamed
222 let js = unlines $ map ("// " ++) prefix ++ [pjs]
223 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
225 lift $ writeTextFile jsFile js
226 lift $ writeTextFile externsFile exts
228 go env' ms'
230 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
231 rebuildIfNecessary _ _ [] = return []
232 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
233 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
234 toRebuild' = toRebuild `S.union` S.fromList deps
235 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
236 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
237 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
238 externs <- readTextFile externsFile
239 externsModules <- fmap (map snd) . either (throwError . show) return $ P.parseModulesFromFiles id [(externsFile, externs)]
240 case externsModules of
241 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
242 _ -> throwError $ "Externs file " ++ externsFile ++ " was invalid"
244reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
245reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
246 where
247 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
248 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
250-- |
251-- Add an import declaration for a module if it does not already explicitly import it.
252--
253addDefaultImport :: ModuleName -> Module -> Module
254addDefaultImport toImport m@(Module coms mn decls exps) =
255 if isExistingImport `any` decls || mn == toImport then m
256 else Module coms mn (ImportDeclaration toImport Unqualified Nothing : decls) exps
257 where
258 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
259 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
260 isExistingImport _ = False
262importPrim :: Module -> Module
263importPrim = addDefaultImport (ModuleName [ProperName C.prim])
265importPrelude :: Module -> Module
266importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
268prelude :: String
269prelude = BU.toString $(embedFile "prelude/prelude.purs")