1-----------------------------------------------------------------------------
3-- Module : Language.PureScript
4-- Copyright : (c) 2013-14 Phil Freeman, (c) 2014 Gary Burgess, and other contributors
7-- Maintainer : Phil Freeman <paf31@cantab.net>
8-- Stability : experimental
12-- The main compiler module
14-----------------------------------------------------------------------------
16{-# LANGUAGE DataKinds #-}
17{-# LANGUAGE QuasiQuotes #-}
18{-# LANGUAGE TemplateHaskell #-}
19{-# LANGUAGE FlexibleContexts #-}
20{-# LANGUAGE ScopedTypeVariables #-}
22module Language.PureScript
33import Data.FileEmbed (embedFile)
34import Data.Function (on)
35import Data.List (sortBy, groupBy, intercalate)
36import Data.Maybe (fromMaybe)
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.Except
47import Control.Monad.Reader
48import Control.Monad.Writer
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.Linter as P
60import Language.PureScript.ModuleDependencies as P
61import Language.PureScript.Names as P
62import Language.PureScript.Options as P
63import Language.PureScript.Parser as P
64import Language.PureScript.Pretty as P
65import Language.PureScript.Renamer as P
66import Language.PureScript.Sugar as P
67import Control.Monad.Supply as P
68import Language.PureScript.TypeChecker as P
69import Language.PureScript.Types as P
70import qualified Language.PureScript.CoreFn as CoreFn
71import qualified Language.PureScript.Constants as C
73import qualified Paths_purescript as Paths
76-- Compile a collection of modules
78-- The compilation pipeline proceeds as follows:
80-- * Sort the modules based on module dependencies, checking for cyclic dependencies.
82-- * Perform a set of desugaring passes.
84-- * Type check, and elaborate values to include type annotations and type class dictionaries.
86-- * Regroup values to take into account new value dependencies introduced by elaboration.
88-- * Eliminate dead code.
90-- * Generate Javascript, and perform optimization passes.
92-- * Pretty-print the generated Javascript
94compile :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
95 => [Module] -> [String] -> m (String, String, Environment)
96compile = compile' initEnvironment
98compile' :: (Functor m, Applicative m, MonadError MultipleErrors m, MonadWriter MultipleErrors m, MonadReader (Options Compile) m)
99 => Environment -> [Module] -> [String] -> m (String, String, Environment)
100compile' env ms prefix = do
101 noPrelude <- asks optionsNoPrelude
102 additional <- asks optionsAdditional
103 mainModuleIdent <- asks (fmap moduleNameFromString . optionsMain)
104 (sorted, _) <- sortModules $ map importPrim $ if noPrelude then ms else map importPrelude ms
106 (desugared, nextVar) <- runSupplyT 0 $ desugar sorted
107 (elaborated, env') <- runCheck' env $ forM desugared $ typeCheckModule mainModuleIdent
108 regrouped <- createBindingGroupsModule . collapseBindingGroupsModule $ elaborated
109 let corefn = map (CoreFn.moduleToCoreFn env') regrouped
110 entryPoints = moduleNameFromString `map` entryPointModules additional
111 elim = if null entryPoints then corefn else eliminateDeadCode entryPoints corefn
112 renamed = renameInModules elim
113 codeGenModuleNames = moduleNameFromString `map` codeGenModules additional
114 modulesToCodeGen = if null codeGenModuleNames then renamed else filter (\(CoreFn.Module _ mn _ _ _ _) -> mn `elem` codeGenModuleNames) renamed
115 js <- concat <$> (evalSupplyT nextVar $ T.traverse moduleToJs modulesToCodeGen)
116 let exts = intercalate "\n" . map (`moduleToPs` env') $ regrouped
117 js' <- generateMain env' js
118 let pjs = unlines $ map ("// " ++) prefix ++ [prettyPrintJS js']
119 return (pjs, exts, env')
121generateMain :: (MonadError MultipleErrors m, MonadReader (Options Compile) m) => Environment -> [JS] -> m [JS]
122generateMain env js = do
123 main <- asks optionsMain
124 additional <- asks optionsAdditional
125 case moduleNameFromString <$> main of
127 when ((mmi, Ident C.main) `M.notMember` names env) $
128 throwError . errorMessage $ NameIsUndefined (Ident C.main)
129 return $ js ++ [JSApp (JSAccessor C.main (JSAccessor (moduleNameToJs mmi) (JSVar (browserNamespace additional)))) []]
133-- A type class which collects the IO actions we need to be able to run in "make" mode
135class (MonadReader (P.Options P.Make) m, MonadError MultipleErrors m, MonadWriter MultipleErrors m) => MonadMake m where
137 -- Get a file timestamp
139 getTimestamp :: FilePath -> m (Maybe UTCTime)
142 -- Read a file as a string
144 readTextFile :: FilePath -> m String
149 writeTextFile :: FilePath -> String -> m ()
152 -- Respond to a progress update
154 progress :: String -> m ()
157-- Determines when to rebuild a module
160 -- | Never rebuild this module
162 -- | Always rebuild this module
163 | RebuildAlways deriving (Show, Eq, Ord)
165-- Traverse (Either e) instance (base 4.7)
166traverseEither :: Applicative f => (a -> f b) -> Either e a -> f (Either e b)
167traverseEither _ (Left x) = pure (Left x)
168traverseEither f (Right y) = Right <$> f y
171-- Compiles in "make" mode, compiling each module separately to a js files and an externs file
173-- If timestamps have not changed, the externs file can be used to provide the module's types without
174-- having to typecheck the module again.
176make :: forall m. (Functor m, Applicative m, Monad m, MonadMake m)
177 => FilePath -> [(Either RebuildPolicy FilePath, Module)] -> [String] -> m Environment
178make outputDir ms prefix = do
179 noPrelude <- asks optionsNoPrelude
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
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
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
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
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
253reverseDependencies :: ModuleGraph -> M.Map ModuleName [ModuleName]
254reverseDependencies g = combine [ (dep, mn) | (mn, deps) <- g, dep <- deps ]
256 combine :: (Ord a) => [(a, b)] -> M.Map a [b]
257 combine = M.fromList . map ((fst . head) &&& map snd) . groupBy ((==) `on` fst) . sortBy (compare `on` fst)
260-- Add an import declaration for a module if it does not already explicitly import it.
262addDefaultImport :: ModuleName -> Module -> Module
263addDefaultImport toImport m@(Module coms mn decls exps) =
264 if isExistingImport `any` decls || mn == toImport then m
265 else Module coms mn (ImportDeclaration toImport Implicit Nothing : decls) exps
267 isExistingImport (ImportDeclaration mn' _ _) | mn' == toImport = True
268 isExistingImport (PositionedDeclaration _ _ d) = isExistingImport d
269 isExistingImport _ = False
271importPrim :: Module -> Module
272importPrim = addDefaultImport (ModuleName [ProperName C.prim])
274importPrelude :: Module -> Module
275importPrelude = addDefaultImport (ModuleName [ProperName C.prelude])
278prelude = BU.toString $(embedFile "prelude/prelude.purs")
281version = Paths.version
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list