git.iko.soy/rowtype-yoga/purescript-native
on fb12693 help sign in
287 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 unless noPrelude (checkPreludeIsDefined ms)
101 additional <- asks optionsAdditional
102 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
103 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
104 mapM_ lint sorted
105 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
106 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
107 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
108 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
109 entryPoints = moduleNameFromString `map` entryPointModules additional
110 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
111 renamed = renameInModules elim
112 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
113 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
114 js <- concat <$> (evalSupplyT nextVar $ T.traverse moduleToJs modulesToCodeGen)
115 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
116 js' <- generateMain env' js
117 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
118 return (pjs, exts, env')
120generateMain :: (MonadError MultipleErrors m, MonadReader (Options Compile) m) => Environment -> [JS] -> m [JS]
121generateMain env js = do
122 main <- asks optionsMain
123 additional <- asks optionsAdditional
124 case moduleNameFromString <$> main of
125 Just mmi -> do
126 when ((mmi, Ident C.main) `M.notMember` names env) $
127 throwError . errorMessage $ NameIsUndefined (Ident C.main)
128 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace additional)))) []]
129 _ -> return js
131-- |
132-- A type class which collects the IO actions we need to be able to run in "make" mode
133--
134class (MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => MonadMake m where
135 -- |
136 -- Get a file timestamp
137 --
138 getTimestamp :: FilePath -> m (Maybe UTCTime)
140 -- |
141 -- Read a file as a string
142 --
143 readTextFile :: FilePath -> m String
145 -- |
146 -- Write a text file
147 --
148 writeTextFile :: FilePath -> String -> m ()
150 -- |
151 -- Respond to a progress update
152 --
153 progress :: String -> m ()
155-- |
156-- Determines when to rebuild a module
157--
158data RebuildPolicy
159 -- | Never rebuild this module
160 = RebuildNever
161 -- | Always rebuild this module
162 | RebuildAlways deriving (Show, Eq, Ord)
164-- Traverse (Either e) instance (base 4.7)
165traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
166traverseEither _ (Left x) = pure (Left x)
167traverseEither f (Right y) = Right <$> f y
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 :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
176 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
177make outputDir ms prefix = do
178 noPrelude <- asks optionsNoPrelude
179 unless noPrelude (checkPreludeIsDefined (map snd ms))
180 let filePathMap = M.fromList (map (\(fp, Module _ mn _ _) -> (mn, fp)) ms)
182 (sorted, graph) <- sortModules $ map importPrim $ if noPrelude then map snd ms else map (importPrelude . snd) ms
184 mapM_ lint sorted
186 toRebuild <- foldM (\s (Module _ moduleName' _ _) -> do
187 let filePath = runModuleName moduleName'
189 jsFile = outputDir </> filePath </> "index.js"
190 externsFile = outputDir </> filePath </> "externs.purs"
191 inputFile = fromMaybe (error "Module has no filename in 'make'") $ M.lookup moduleName' filePathMap
193 jsTimestamp <- getTimestamp jsFile
194 externsTimestamp <- getTimestamp externsFile
195 inputTimestamp <- traverseEither getTimestamp inputFile
197 return $ case (inputTimestamp, jsTimestamp, externsTimestamp) of
198 (Right (Just t1), Just t2, Just t3) | t1 < min t2 t3 -> s
199 (Left RebuildNever, Just _, Just _) -> s
200 _ -> S.insert moduleName' s) S.empty sorted
202 marked <- rebuildIfNecessary (reverseDependencies graph) toRebuild sorted
204 (desugared, nextVar) <- runSupplyT 0 $ zip (map fst marked) <$> desugar (map snd marked)
206 evalSupplyT nextVar $ go initEnvironment desugared
208 where
209 go :: Environment -> [(Bool, Module)] -> SupplyT m Environment
210 go env [] = return env
211 go env ((False, m) : ms') = do
212 (_, env') <- lift . runCheck' env $ typeCheckModule Nothing m
214 go env' ms'
215 go env ((True, m@(Module coms moduleName' _ exps)) : ms') = do
216 let filePath = runModuleName moduleName'
217 jsFile = outputDir </> filePath </> "index.js"
218 externsFile = outputDir </> filePath </> "externs.purs"
220 lift . progress $ "Compiling " ++ runModuleName moduleName'
222 (Module _ _ elaborated _, env') <- lift . runCheck' env $ typeCheckModule Nothing m
224 regrouped <- createBindingGroups moduleName' . collapseBindingGroups $ elaborated
226 let mod' = Module coms moduleName' regrouped exps
227 corefn = CoreFn.moduleToCoreFn env' mod'
228 [renamed] = renameInModules [corefn]
230 pjs <- prettyPrintJS <$> moduleToJs renamed
231 let js = unlines $ map ("// " ++) prefix ++ [pjs]
232 let exts = unlines $ map ("-- " ++) prefix ++ [moduleToPs mod' env']
234 lift $ writeTextFile jsFile js
235 lift $ writeTextFile externsFile exts
237 go env' ms'
239 rebuildIfNecessary :: M.Map ModuleName [ModuleName] -> S.Set ModuleName -> [Module] -> m [(Bool, Module)]
240 rebuildIfNecessary _ _ [] = return []
241 rebuildIfNecessary graph toRebuild (m@(Module _ moduleName' _ _) : ms') | moduleName' `S.member` toRebuild = do
242 let deps = fromMaybe [] $ moduleName' `M.lookup` graph
243 toRebuild' = toRebuild `S.union` S.fromList deps
244 (:) (True, m) <$> rebuildIfNecessary graph toRebuild' ms'
245 rebuildIfNecessary graph toRebuild (Module _ moduleName' _ _ : ms') = do
246 let externsFile = outputDir </> runModuleName moduleName' </> "externs.purs"
247 externs <- readTextFile externsFile
248 externsModules <- fmap (map snd) . either (throwError . errorMessage . ErrorParsingExterns) return $ P.parseModulesFromFiles id [(externsFile, externs)]
249 case externsModules of
250 [m'@(Module _ moduleName'' _ _)] | moduleName'' == moduleName' -> (:) (False, m') <$> rebuildIfNecessary graph toRebuild ms'
251 _ -> throwError . errorMessage . InvalidExternsFile $ externsFile
253checkPreludeIsDefined :: (MonadWriter MultipleErrors m) => [Module] -> m ()
254checkPreludeIsDefined ms = do
255 let mns = map getModuleName ms
256 unless (preludeModuleName `elem` mns) $
257 tell (errorMessage PreludeNotPresent)
259reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
260reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
261 where
262 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
263 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
265-- |
266-- Add an import declaration for a module if it does not already explicitly import it.
267--
268addDefaultImport :: ModuleName -> Module -> Module
269addDefaultImport toImport m@(Module coms mn decls exps) =
270 if isExistingImport `any` decls || mn == toImport then m
271 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
272 where
273 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
274 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
275 isExistingImport _ = False
277importPrim :: Module -> Module
278importPrim = addDefaultImport (ModuleName [ProperName C.prim])
280preludeModuleName :: ModuleName
281preludeModuleName = ModuleName [ProperName C.prelude]
283importPrelude :: Module -> Module
284importPrelude = addDefaultImport preludeModuleName
286version :: Version
287version = Paths.version