git.iko.soy/rowtype-yoga/purescript-native
on 943a37f help sign in
276 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
44import Control.Monad.Error.Class (MonadError(..))
45import Control.Monad.Reader
46import Control.Monad.Writer
48import System.FilePath ((</>))
50import Language.PureScript.AST as P
51import Language.PureScript.Comments as P
52import Language.PureScript.CodeGen as P
53import Language.PureScript.DeadCodeElimination as P
54import Language.PureScript.Environment as P
55import Language.PureScript.Errors as P
56import Language.PureScript.Kinds as P
57import Language.PureScript.Linter as P
58import Language.PureScript.ModuleDependencies as P
59import Language.PureScript.Names as P
60import Language.PureScript.Options as P
61import Language.PureScript.Parser as P
62import Language.PureScript.Pretty as P
63import Language.PureScript.Renamer as P
64import Language.PureScript.Sugar as P
65import Control.Monad.Supply as P
66import Language.PureScript.TypeChecker as P
67import Language.PureScript.Types as P
68import qualified Language.PureScript.CoreFn as CoreFn
69import qualified Language.PureScript.Constants as C
71import qualified Paths_purescript as Paths
73-- |
74-- Compile a collection of modules
75--
76-- The compilation pipeline proceeds as follows:
77--
78-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
79--
80-- * Perform a set of desugaring passes.
81--
82-- * Type check, and elaborate values to include type annotations and type class dictionaries.
83--
84-- * Regroup values to take into account new value dependencies introduced by elaboration.
85--
86-- * Eliminate dead code.
87--
88-- * Generate Javascript, and perform optimization passes.
89--
90-- * Pretty-print the generated Javascript
91--
92compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
93 => [Module] -> [String] -> m (String, String, Environment)
94compile = compile' initEnvironment
96compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
97 => Environment -> [Module] -> [String] -> m (String, String, Environment)
98compile' env ms prefix = do
99 noPrelude <- asks optionsNoPrelude
100 additional <- asks optionsAdditional
101 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
102 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
103 mapM_ lint sorted
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 entryPoints = moduleNameFromString `map` entryPointModules additional
109 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
110 renamed = renameInModules elim
111 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
112 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, MonadWriter 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 mapM_ lint sorted
184 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
185 let filePath = runModuleName moduleName'
187 jsFile = outputDir </> filePath </> "index.js"
188 externsFile = outputDir </> filePath </> "externs.purs"
189 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
191 jsTimestamp <- getTimestamp jsFile
192 externsTimestamp <- getTimestamp externsFile
193 inputTimestamp <- traverseEither getTimestamp inputFile
195 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
196 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
197 (Left RebuildNever, Just _, Just _) -> s
198 _ -> S.insert moduleName' s) S.empty sorted
200 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
202 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
204 evalSupplyT nextVar $ go initEnvironment desugared
206 where
207 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
208 go env [] = return env
209 go env ((False, m) : ms') = do
210 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
212 go env' ms'
213 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
214 let filePath = runModuleName moduleName'
215 jsFile = outputDir </> filePath </> "index.js"
216 externsFile = outputDir </> filePath </> "externs.purs"
218 lift . progress $ "Compiling " ++ runModuleName moduleName'
220 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
222 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
224 let mod' = Module coms moduleName' regrouped exps
225 corefn = CoreFn.moduleToCoreFn env' mod'
226 [renamed] = renameInModules [corefn]
228 pjs <- prettyPrintJS <$> moduleToJs renamed
229 let js = unlines $ map ("// " ++) prefix ++ [pjs]
230 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
232 lift $ writeTextFile jsFile js
233 lift $ writeTextFile externsFile exts
235 go env' ms'
237 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
238 rebuildIfNecessary _ _ [] = return []
239 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
240 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
241 toRebuild' = toRebuild `S.union` S.fromList deps
242 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
243 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
244 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
245 externs <- readTextFile externsFile
246 externsModules <- fmap (map snd) . either (throwError . errorMessage . ErrorParsingExterns) return $ P.parseModulesFromFiles id [(externsFile, externs)]
247 case externsModules of
248 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
249 _ -> throwError . errorMessage . InvalidExternsFile $ externsFile
251reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
252reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
253 where
254 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
255 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
257-- |
258-- Add an import declaration for a module if it does not already explicitly import it.
259--
260addDefaultImport :: ModuleName -> Module -> Module
261addDefaultImport toImport m@(Module coms mn decls exps) =
262 if isExistingImport `any` decls || mn == toImport then m
263 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
264 where
265 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
266 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
267 isExistingImport _ = False
269importPrim :: Module -> Module
270importPrim = addDefaultImport (ModuleName [ProperName C.prim])
272importPrelude :: Module -> Module
273importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
275version :: Version
276version = Paths.version