1-- | This module generates code in the core imperative representation from
2-- elaborated PureScript code.
10import Protolude (ordNub)
12import Control.Arrow ((&&&))
13import Control.Monad (forM, liftM, replicateM, void)
14import Control.Monad.Supply.Class
16import Data.List ((\\), delete, intersect)
17import qualified Data.Foldable as F
18import qualified Data.Map as M
19import Data.Maybe (fromMaybe, isNothing, mapMaybe)
20import Data.Monoid ((<>))
21import Data.String (fromString)
22import Data.Text (Text)
23import qualified Data.Text as T
25import Language.PureScript.AST.SourcePos
26import Language.PureScript.CoreImp.AST (AST)
27import qualified Language.PureScript.CoreImp.AST as AST
28import Language.PureScript.CoreFn
29import Language.PureScript.Crash
30import Language.PureScript.Names
31import Language.PureScript.Options
32import Language.PureScript.PSString (PSString, mkString)
33import Language.PureScript.Traversals (sndM)
34import qualified Language.PureScript.Constants as C
36import System.FilePath.Posix ((</>))
38import CodeGen.Cpp.Common as Common
39import CodeGen.Cpp.Optimizer
40import CodeGen.Cpp.Printer
42data DeclType = ModuleDecl | LetDecl | RecLetDecl deriving (Eq)
44-- | Generate code in the simplified intermediate representation for all declarations in a
48 -- . (Monad m, MonadReader Options m, MonadSupply m, MonadError MultipleErrors m)
49 . (Monad m, MonadSupply m)
52 -> m (Text, [Text], [AST], Text, Text)
53moduleToCpp (Module _ coms mn _ imps _ foreigns decls) _ =
55 let usedNames = concatMap getNames decls
56 let mnLookup = renameImports usedNames imps
57 cppImports <- traverse (importToCpp mnLookup) . (\\ (mn : C.primModules)) . (\\ [mn]) $ ordNub $ map snd imps
58 interfaceImport <- importToCpp (renameImports [] [(emptyAnn, mn)]) mn
59 let decls' = renameModules mnLookup decls
60 cppDecls <- mapM (bindToCpp ModuleDecl) decls'
61 optimized <- traverse (traverse (optimize modName')) cppDecls
62 let optimized' = concat optimized
63 values = annotValue <$> optimized'
64 foreigns' = identToCpp <$> foreigns
65 interface = interfaceSource modName values foreigns
66 implHeader = implHeaderSource modName cppImports interfaceImport
67 implFooter = implFooterSource modName foreigns
68 return $ (interface, foreigns', optimized', implHeader, implFooter)
70 modName = moduleNameToCpp mn
71 modName' = AST.Var Nothing modName
73 annotValue :: AST -> (Text, Bool)
74 annotValue (AST.Function _ (Just name) [] (AST.Block _ [AST.Return _ ret]))
75 | isLiteral ret = (name, True)
76 annotValue (AST.Function _ (Just name) [] _) = (name, False)
77 annotValue _ = error "Unexpected top-level value form"
79 -- | Extracts all declaration names from a binding group.
80 getNames :: Bind Ann -> [Ident]
81 getNames (NonRec _ ident _) = [ident]
82 getNames (Rec vals) = map (snd . fst) vals
84 -- | Creates alternative names for each module to ensure they don't collide
85 -- with declaration names.
86 renameImports :: [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
87 renameImports = go M.empty
89 go :: M.Map ModuleName (Ann, ModuleName) -> [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
90 go acc used ((ann, mn') : mns') =
91 let mni = Ident $ runModuleName mn'
92 in if mn' /= mn && mni `elem` used
93 then let newName = freshModuleName 1 mn' used
94 in go (M.insert mn' (ann, newName) acc) (Ident (runModuleName newName) : used) mns'
95 else go (M.insert mn' (ann, mn') acc) used mns'
98 freshModuleName :: Integer -> ModuleName -> [Ident] -> ModuleName
99 freshModuleName i mn'@(ModuleName pns) used =
100 let newName = ModuleName $ init pns ++ [ProperName $ runProperName (last pns) <> "_" <> T.pack (show i)]
101 in if Ident (runModuleName newName) `elem` used
102 then freshModuleName (i + 1) mn' used
105 -- | Generates C++ code for a module import, binding the required module
106 -- to the alternative
107 importToCpp :: M.Map ModuleName (Ann, ModuleName) -> ModuleName -> m Text
108 importToCpp mnLookup mn' = do
109 let ((_, _, _, _), mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
110 mname = moduleNameToCpp mnSafe
111 pure $ "#include \"" <> mname <> "/" <> mname <> ".h\"\n"
113 -- | Replaces the `ModuleName`s in the AST so that the generated code refers to
114 -- the collision-avoiding renamed module imports.
115 renameModules :: M.Map ModuleName (Ann, ModuleName) -> [Bind Ann] -> [Bind Ann]
116 renameModules mnLookup binds =
117 let (f, _, _) = everywhereOnValues id goExpr goBinder
120 goExpr :: Expr a -> Expr a
121 goExpr (Var ann q) = Var ann (renameQual q)
123 goBinder :: Binder a -> Binder a
124 goBinder (ConstructorBinder ann q1 q2 bs) = ConstructorBinder ann (renameQual q1) (renameQual q2) bs
126 renameQual :: Qualified a -> Qualified a
127 renameQual (Qualified (Just mn') a) =
128 let (_,mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
129 in Qualified (Just mnSafe) a
133 -- Generate code in the simplified intermediate representation for a declaration
135 bindToCpp :: DeclType -> Bind Ann -> m [AST]
136 bindToCpp dt (NonRec ann ident val) = return <$> nonRecToCpp dt ann ident val
137 bindToCpp dt (Rec vals) = forM vals (uncurry . uncurry $ nonRecToCpp dt')
139 dt' = if dt == LetDecl then RecLetDecl else dt
141 -- | Generate code in the simplified intermediate representation for a single non-recursive
144 -- The main purpose of this function is to handle code generation for comments.
145 nonRecToCpp :: DeclType -> Ann -> Ident -> Expr Ann -> m AST
146 nonRecToCpp dt a i e@(extractAnn -> (_, com, _, _)) | not (null com) = do
147 -- withoutComment <- asks optionsNoComments
148 let withoutComment = False
150 then nonRecToCpp dt a i (modifyAnn removeComments e)
151 else AST.Comment Nothing com <$> nonRecToCpp dt a i (modifyAnn removeComments e)
152 nonRecToCpp ModuleDecl (ss, _, _, _) ident val = do
153 cpp <- valueToCpp val
154 pure $ AST.Function Nothing (Just $ identToCpp ident) [] (AST.Block Nothing [AST.Return Nothing cpp])
155 nonRecToCpp RecLetDecl (ss, _, _, _) ident val = do
156 cpp <- valueToCpp val
158 let retainedName = identToCpp ident
159 retained = AST.Var Nothing $ retainedName
160 -- unretained = AST.Var Nothing $ retainedName <> unretainedSuffix
161 -- alias = AST.Var Nothing . -- Note: prevents optimizer from eliminating this
163 -- AST.VariableIntroduction Nothing retainedName (Just unretained)
166 AST.Function _ name args (AST.Block Nothing cpps) ->
167 AST.Assignment Nothing
169 (AST.Function Nothing
172 (AST.Block Nothing cpps))
173 _ -> AST.Assignment Nothing retained cpp
174 nonRecToCpp _ (ss, _, _, _) ident val = do
175 cpp <- valueToCpp val
176 pure $ AST.VariableIntroduction Nothing (identToCpp ident) (Just cpp)
178 -- | Generate code in the simplified intermediate representation for a variable based on a
179 -- PureScript identifier.
181 var = AST.Var Nothing . identToCpp
183 -- | Generate code in the simplified intermediate representation for an accessor based on
184 -- a PureScript identifier. If the name is not valid in C++ (symbol based, reserved name) an
185 -- indexer is returned.
186 accessor :: Ident -> AST -> AST
187 accessor (Ident prop) = accessorString $ mkString prop
188 accessor (GenIdent _ _) = internalError "GenIdent in accessor"
189 accessor UnusedIdent = internalError "UnusedIdent in accessor"
191 accessorString :: PSString -> AST -> AST
192 accessorString prop = AST.Indexer Nothing (AST.StringLiteral Nothing prop)
194 -- | Generate code in the simplified intermediate representation for a value or expression.
196 valueToCpp :: Expr Ann -> m AST
197 valueToCpp (Literal (pos, _, _, _) l) = literalToValueCpp pos l
198 valueToCpp (Accessor _ prop val) =
199 accessorString prop <$> valueToCpp val
200 valueToCpp (ObjectUpdate _ o ps) = do
202 updates <- mapM (sndM valueToCpp) ps
204 let objVar = AST.Var Nothing obj'
205 copy = AST.VariableIntroduction Nothing obj' (Just $ AST.App Nothing (AST.Var Nothing (unbox dictType)) [obj])
206 assign (k, v) = AST.Assignment Nothing (accessorString k objVar) v
207 sts = copy : (assign <$> updates) ++ [AST.Return Nothing objVar]
208 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing sts)) []
209 valueToCpp (Abs _ arg val) = do
210 ret <- valueToCpp val
211 let cppArg = case arg of
213 _ -> [identToCpp arg]
214 return $ AST.Function Nothing Nothing cppArg (AST.Block Nothing [AST.Return Nothing ret])
215 valueToCpp e@App{} = do
216 let (f, args) = unApp e []
217 args' <- mapM valueToCpp args
219 Var (_, _, _, Just IsNewtype) _ -> return (head args')
220 _ -> flip (foldl (\fn a -> AST.App Nothing fn [a])) args' <$> valueToCpp f
222 unApp :: Expr Ann -> [Expr Ann] -> (Expr Ann, [Expr Ann])
223 unApp (App _ val arg) args = unApp val (arg : args)
224 unApp other args = (other, args)
225 -- valueToCpp (Var (_, _, _, Just IsForeign) qi@(Qualified (Just mn') ident)) =
226 -- return $ if mn' == mn
227 -- then AST.Var Nothing (moduleNameToCpp mn' <> "::" <> identToCpp ident)
229 -- valueToCpp (Var (_, _, _, Just IsForeign) (Qualified (Just mn') ident)) =
230 -- return $ AST.Var Nothing (moduleNameToCpp mn' <> "::" <> identToCpp ident)
231 -- valueToCpp (Var (_, _, _, Just IsForeign) qi@(Qualified (Just mn') ident)) =
232 -- return $ if mn' == mn
233 -- then foreignIdent ident
235 -- valueToCpp (Var (_, _, _, Just IsForeign) ident) =
236 -- internalError $ "Encountered an unqualified reference to a foreign ident " ++ T.unpack (showQualified showIdent ident)
237 valueToCpp (Var _ ident) = return $ varToCpp ident
238 valueToCpp (Case (ss, _, _, _) values binders) = do
239 vals <- mapM valueToCpp values
240 bindersToCpp ss binders vals
241 valueToCpp (Let _ ds val) = do
242 let recurs = concatMap getNames $ filter isRec ds
243 recurDs = (\v -> AST.Var Nothing $ "boxed_r " <> identToCpp v) <$> recurs
244 ds' <- concat <$> mapM (bindToCpp LetDecl) ds
245 ret <- valueToCpp val
248 (AST.Function Nothing
251 (AST.Block Nothing (recurDs ++ ds' ++ [AST.Return Nothing ret])))
254 isRec :: Bind Ann -> Bool
257 valueToCpp (Constructor (_, _, _, Just IsNewtype) _ (ProperName ctor) _) = error "IsNewtype"
258 valueToCpp (Constructor _ _ (ProperName ctor) fields) =
259 let body = AST.ObjectLiteral Nothing $ (mkString ctor, AST.BooleanLiteral Nothing True) :
260 ((\field -> (mkString (identToCpp field), var field)) `map` fields)
261 fn = foldr (\f inner -> AST.Function Nothing Nothing [identToCpp f] (AST.Block Nothing [AST.Return Nothing inner])) body fields
265 iife :: Text -> [AST] -> AST
266 iife v exprs = AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing $ exprs ++ [AST.Return Nothing $ AST.Var Nothing v])) []
268 literalToValueCpp :: SourceSpan -> Literal (Expr Ann) -> m AST
269 literalToValueCpp ss (NumericLiteral (Left i)) = return $ AST.NumericLiteral (Just ss) (Left i)
270 literalToValueCpp ss (NumericLiteral (Right n)) = return $ AST.NumericLiteral (Just ss) (Right n)
271 literalToValueCpp ss (StringLiteral s) = return $ AST.StringLiteral (Just ss) s
272 literalToValueCpp ss (CharLiteral c) = return $ AST.StringLiteral (Just ss) (fromString [c])
273 literalToValueCpp ss (BooleanLiteral b) = return $ AST.BooleanLiteral (Just ss) b
274 literalToValueCpp ss (ArrayLiteral xs) = AST.ArrayLiteral (Just ss) <$> mapM valueToCpp xs
275 literalToValueCpp ss (ObjectLiteral ps) = AST.ObjectLiteral (Just ss) <$> mapM (sndM valueToCpp) ps
277 -- | Generate code in the simplified intermediate representation for a reference to a
279 varToCpp :: Qualified Ident -> AST
280 varToCpp (Qualified Nothing ident) = var ident
281 varToCpp qual = qualifiedToCpp id qual
283 -- | Generate code in the simplified intermediate representation for a reference to a
284 -- variable that may have a qualified name.
285 qualifiedToCpp :: (a -> Ident) -> Qualified a -> AST
286 qualifiedToCpp f (Qualified (Just (ModuleName [ProperName mn'])) a) | mn' == C.prim = AST.Var Nothing . runIdent $ f a
287 qualifiedToCpp f (Qualified (Just mn') a) = AST.Indexer Nothing (AST.Var Nothing . identToCpp $ f a) (AST.Var Nothing (moduleNameToCpp mn'))
288 qualifiedToCpp f (Qualified _ a) = AST.Var Nothing $ identToCpp (f a)
290 -- foreignIdent :: Ident -> AST
291 -- foreignIdent ident = accessorString (mkString $ runIdent ident) (AST.Var Nothing "$foreign")
293 -- | Generate code in the simplified intermediate representation for pattern match binders
295 bindersToCpp :: SourceSpan -> [CaseAlternative Ann] -> [AST] -> m AST
296 bindersToCpp ss binders vals = do
297 valNames <- replicateM (length vals) freshName
298 let assignments = zipWith (AST.VariableIntroduction Nothing) valNames (map Just vals)
299 cpps <- forM binders $ \(CaseAlternative bs result) -> do
300 ret <- guardsToCpp result
302 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (assignments ++ concat cpps ++ [AST.Throw Nothing (AST.StringLiteral Nothing $ mkString failedPatternMessage)])))
305 go :: [Text] -> [AST] -> [Binder Ann] -> m [AST]
306 go _ done [] = return done
307 go (v:vs) done' (b:bs) = do
308 done'' <- go vs done' bs
309 binderToCpp v done'' b
310 go _ _ _ = internalError "Invalid arguments to bindersToCpp"
312 failedPatternMessage :: Text
313 failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss <> ": "
315 guardsToCpp :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
316 guardsToCpp (Left gs) = traverse genGuard gs where
317 genGuard (cond, val) = do
318 cond' <- valueToCpp cond
319 val' <- valueToCpp val
321 (AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo cond' (AST.BooleanLiteral Nothing True))
322 (AST.Block Nothing [AST.Return Nothing val']) Nothing)
324 guardsToCpp (Right v) = return . AST.Return Nothing <$> valueToCpp v
326 -- | Generate code in the simplified intermediate representation for a pattern match
328 binderToCpp :: Text -> [AST] -> Binder Ann -> m [AST]
329 binderToCpp _ done NullBinder{} = return done
330 binderToCpp varName done (LiteralBinder _ l) =
331 literalToBinderCpp varName done l
332 binderToCpp varName done (VarBinder _ ident) =
333 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : done)
334 binderToCpp varName done (ConstructorBinder (_, _, _, Just IsNewtype) _ _ [b]) =
335 binderToCpp varName done b
336 binderToCpp varName done (ConstructorBinder (_, _, _, Just (IsConstructor ctorType fields)) _ (Qualified _ (ProperName ctor)) bs) = do
337 cpp <- go (zip fields bs) done
338 return $ case ctorType of
341 [AST.IfElse Nothing (AST.InstanceOf Nothing (AST.Var Nothing varName) (AST.StringLiteral Nothing (mkString ctor)))
342 (AST.Block Nothing cpp)
345 go :: [(Ident, Binder Ann)] -> [AST] -> m [AST]
346 go [] done' = return done'
347 go ((field, binder) : remain) done' = do
349 done'' <- go remain done'
350 cpp <- binderToCpp argVar done'' binder
351 return (AST.VariableIntroduction Nothing argVar (Just $ accessorString (mkString $ identToCpp field) $ AST.Var Nothing varName) : cpp)
353 binderToCpp _ _ ConstructorBinder{} =
354 internalError "binderToCpp: Invalid ConstructorBinder in binderToCpp"
355 binderToCpp varName done (NamedBinder _ ident binder) = do
356 cpp <- binderToCpp varName done binder
357 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : cpp)
359 literalToBinderCpp :: Text -> [AST] -> Literal (Binder Ann) -> m [AST]
360 literalToBinderCpp varName done (NumericLiteral num) =
361 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.NumericLiteral Nothing num)) (AST.Block Nothing done) Nothing]
362 literalToBinderCpp varName done (CharLiteral c) =
363 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing (fromString [c]))) (AST.Block Nothing done) Nothing]
364 literalToBinderCpp varName done (StringLiteral str) =
365 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing str)) (AST.Block Nothing done) Nothing]
366 literalToBinderCpp varName done (BooleanLiteral True) =
367 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing True)) (AST.Block Nothing done) Nothing]
368 literalToBinderCpp varName done (BooleanLiteral False) =
369 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing False)) (AST.Block Nothing done) Nothing]
370 -- return [AST.IfElse Nothing (AST.Unary Nothing AST.Not (AST.Var Nothing varName)) (AST.Block Nothing done) Nothing]
371 literalToBinderCpp varName done (ObjectLiteral bs) = go done bs
373 go :: [AST] -> [(PSString, Binder Ann)] -> m [AST]
374 go done' [] = return done'
375 go done' ((prop, binder):bs') = do
377 done'' <- go done' bs'
378 cpp <- binderToCpp propVar done'' binder
379 return (AST.VariableIntroduction Nothing propVar (Just (accessorString prop (AST.Var Nothing varName))) : cpp)
380 literalToBinderCpp varName done (ArrayLiteral bs) = do
382 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo
383 (arrayLength $ AST.Var Nothing varName)
384 (AST.NumericLiteral Nothing (Left (fromIntegral $ length bs))))
385 (AST.Block Nothing cpp) Nothing]
387 go :: [AST] -> Integer -> [Binder Ann] -> m [AST]
388 go done' _ [] = return done'
389 go done' index (binder:bs') = do
391 done'' <- go done' (index + 1) bs'
392 cpp <- binderToCpp elVar done'' binder
393 return (AST.VariableIntroduction Nothing elVar (Just (AST.Indexer Nothing (AST.NumericLiteral Nothing (Left index)) (AST.Var Nothing varName))) : cpp)
396emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
398arrayLength :: AST -> AST
399arrayLength a = AST.App Nothing (AST.Var Nothing arrayLengthFn) [a]
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