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