git.iko.soy/rowtype-yoga/purescript-native
on e34cc85 help sign in
400 lines 20 kB history raw
1-- | This module generates code in the core imperative representation from
2-- elaborated PureScript code.
3module CodeGen.Cpp
4 ( module AST
5 , module Common
6 , moduleToCpp
7 ) where
9import Prelude.Compat
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
45-- module.
46moduleToCpp
47 :: forall m
48 -- . (Monad m, MonadReader Options m, MonadSupply m, MonadError MultipleErrors m)
49 . (Monad m, MonadSupply m)
50 => Module Ann
51 -> Maybe AST
52 -> m (Text, [Text], [AST], Text, Text)
53moduleToCpp (Module _ coms mn _ imps _ foreigns decls) _ =
54 do
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)
69 where
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
88 where
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'
96 go acc _ [] = acc
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
103 else newName
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
118 in map f binds
119 where
120 goExpr :: Expr a -> Expr a
121 goExpr (Var ann q) = Var ann (renameQual q)
122 goExpr e = e
123 goBinder :: Binder a -> Binder a
124 goBinder (ConstructorBinder ann q1 q2 bs) = ConstructorBinder ann (renameQual q1) (renameQual q2) bs
125 goBinder b = b
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
130 renameQual q = q
132 -- |
133 -- Generate code in the simplified intermediate representation for a declaration
134 --
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')
138 where
139 dt' = if dt == LetDecl then RecLetDecl else dt
141 -- | Generate code in the simplified intermediate representation for a single non-recursive
142 -- declaration.
143 --
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
149 if withoutComment
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
157 pure $
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
162 -- prettyPrintCpp1 $
163 -- AST.VariableIntroduction Nothing retainedName (Just unretained)
164 in
165 case cpp of
166 AST.Function _ name args (AST.Block Nothing cpps) ->
167 AST.Assignment Nothing
168 (retained)
169 (AST.Function Nothing
170 name
171 args
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.
180 var :: Ident -> AST
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
201 obj <- valueToCpp o
202 updates <- mapM (sndM valueToCpp) ps
203 obj' <- freshName
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
212 UnusedIdent -> []
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
218 case f of
219 Var (_, _, _, Just IsNewtype) _ -> return (head args')
220 _ -> flip (foldl (\fn a -> AST.App Nothing fn [a])) args' <$> valueToCpp f
221 where
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)
228 -- else varToCpp qi
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
234 -- else varToCpp qi
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.VariableIntroduction Nothing (identToCpp v) (Just (AST.Var Nothing "box<fn_t>()"))) <$> recurs
244 -- recurDsWeak = (\v -> AST.VariableIntroduction Nothing ("__unsafe_unretained " <> identToCpp v <> unretainedSuffix) Nothing) <$> recurs
245 ds' <- concat <$> mapM (bindToCpp LetDecl) ds
246 ret <- valueToCpp val
247 return $
248 AST.App Nothing
249 (AST.Function Nothing
250 Nothing
251 []
252 (AST.Block Nothing (recurDs ++ ds' ++ [AST.Return Nothing ret])))
253 []
254 where
255 isRec :: Bind Ann -> Bool
256 isRec (Rec _) = True
257 isRec _ = False
258 valueToCpp (Constructor (_, _, _, Just IsNewtype) _ (ProperName ctor) _) = error "IsNewtype"
259 valueToCpp (Constructor _ _ (ProperName ctor) fields) =
260 let body = AST.ObjectLiteral Nothing $ (mkString ctor, AST.BooleanLiteral Nothing True) :
261 ((\field -> (mkString (identToCpp field), var field)) `map` fields)
262 fn = foldr (\f inner -> AST.Function Nothing Nothing [identToCpp f] (AST.Block Nothing [AST.Return Nothing inner])) body fields
263 in return fn
266 iife :: Text -> [AST] -> AST
267 iife v exprs = AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing $ exprs ++ [AST.Return Nothing $ AST.Var Nothing v])) []
269 literalToValueCpp :: SourceSpan -> Literal (Expr Ann) -> m AST
270 literalToValueCpp ss (NumericLiteral (Left i)) = return $ AST.NumericLiteral (Just ss) (Left i)
271 literalToValueCpp ss (NumericLiteral (Right n)) = return $ AST.NumericLiteral (Just ss) (Right n)
272 literalToValueCpp ss (StringLiteral s) = return $ AST.StringLiteral (Just ss) s
273 literalToValueCpp ss (CharLiteral c) = return $ AST.StringLiteral (Just ss) (fromString [c])
274 literalToValueCpp ss (BooleanLiteral b) = return $ AST.BooleanLiteral (Just ss) b
275 literalToValueCpp ss (ArrayLiteral xs) = AST.ArrayLiteral (Just ss) <$> mapM valueToCpp xs
276 literalToValueCpp ss (ObjectLiteral ps) = AST.ObjectLiteral (Just ss) <$> mapM (sndM valueToCpp) ps
278 -- | Generate code in the simplified intermediate representation for a reference to a
279 -- variable.
280 varToCpp :: Qualified Ident -> AST
281 varToCpp (Qualified Nothing ident) = var ident
282 varToCpp qual = qualifiedToCpp id qual
284 -- | Generate code in the simplified intermediate representation for a reference to a
285 -- variable that may have a qualified name.
286 qualifiedToCpp :: (a -> Ident) -> Qualified a -> AST
287 qualifiedToCpp f (Qualified (Just (ModuleName [ProperName mn'])) a) | mn' == C.prim = AST.Var Nothing . runIdent $ f a
288 qualifiedToCpp f (Qualified (Just mn') a) = AST.Indexer Nothing (AST.Var Nothing . identToCpp $ f a) (AST.Var Nothing (moduleNameToCpp mn'))
289 qualifiedToCpp f (Qualified _ a) = AST.Var Nothing $ identToCpp (f a)
291 -- foreignIdent :: Ident -> AST
292 -- foreignIdent ident = accessorString (mkString $ runIdent ident) (AST.Var Nothing "$foreign")
294 -- | Generate code in the simplified intermediate representation for pattern match binders
295 -- and guards.
296 bindersToCpp :: SourceSpan -> [CaseAlternative Ann] -> [AST] -> m AST
297 bindersToCpp ss binders vals = do
298 valNames <- replicateM (length vals) freshName
299 let assignments = zipWith (AST.VariableIntroduction Nothing) valNames (map Just vals)
300 cpps <- forM binders $ \(CaseAlternative bs result) -> do
301 ret <- guardsToCpp result
302 go valNames ret bs
303 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (assignments ++ concat cpps ++ [AST.Throw Nothing (AST.StringLiteral Nothing $ mkString failedPatternMessage)])))
304 []
305 where
306 go :: [Text] -> [AST] -> [Binder Ann] -> m [AST]
307 go _ done [] = return done
308 go (v:vs) done' (b:bs) = do
309 done'' <- go vs done' bs
310 binderToCpp v done'' b
311 go _ _ _ = internalError "Invalid arguments to bindersToCpp"
313 failedPatternMessage :: Text
314 failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss <> ": "
316 guardsToCpp :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
317 guardsToCpp (Left gs) = traverse genGuard gs where
318 genGuard (cond, val) = do
319 cond' <- valueToCpp cond
320 val' <- valueToCpp val
321 return
322 (AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo cond' (AST.BooleanLiteral Nothing True))
323 (AST.Block Nothing [AST.Return Nothing val']) Nothing)
325 guardsToCpp (Right v) = return . AST.Return Nothing <$> valueToCpp v
327 -- | Generate code in the simplified intermediate representation for a pattern match
328 -- binder.
329 binderToCpp :: Text -> [AST] -> Binder Ann -> m [AST]
330 binderToCpp _ done NullBinder{} = return done
331 binderToCpp varName done (LiteralBinder _ l) =
332 literalToBinderCpp varName done l
333 binderToCpp varName done (VarBinder _ ident) =
334 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : done)
335 binderToCpp varName done (ConstructorBinder (_, _, _, Just IsNewtype) _ _ [b]) =
336 binderToCpp varName done b
337 binderToCpp varName done (ConstructorBinder (_, _, _, Just (IsConstructor ctorType fields)) _ (Qualified _ (ProperName ctor)) bs) = do
338 cpp <- go (zip fields bs) done
339 return $ case ctorType of
340 ProductType -> cpp
341 SumType ->
342 [AST.IfElse Nothing (AST.InstanceOf Nothing (AST.Var Nothing varName) (AST.StringLiteral Nothing (mkString ctor)))
343 (AST.Block Nothing cpp)
344 Nothing]
345 where
346 go :: [(Ident, Binder Ann)] -> [AST] -> m [AST]
347 go [] done' = return done'
348 go ((field, binder) : remain) done' = do
349 argVar <- freshName
350 done'' <- go remain done'
351 cpp <- binderToCpp argVar done'' binder
352 return (AST.VariableIntroduction Nothing argVar (Just $ accessorString (mkString $ identToCpp field) $ AST.Var Nothing varName) : cpp)
354 binderToCpp _ _ ConstructorBinder{} =
355 internalError "binderToCpp: Invalid ConstructorBinder in binderToCpp"
356 binderToCpp varName done (NamedBinder _ ident binder) = do
357 cpp <- binderToCpp varName done binder
358 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : cpp)
360 literalToBinderCpp :: Text -> [AST] -> Literal (Binder Ann) -> m [AST]
361 literalToBinderCpp varName done (NumericLiteral num) =
362 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.NumericLiteral Nothing num)) (AST.Block Nothing done) Nothing]
363 literalToBinderCpp varName done (CharLiteral c) =
364 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing (fromString [c]))) (AST.Block Nothing done) Nothing]
365 literalToBinderCpp varName done (StringLiteral str) =
366 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing str)) (AST.Block Nothing done) Nothing]
367 literalToBinderCpp varName done (BooleanLiteral True) =
368 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing True)) (AST.Block Nothing done) Nothing]
369 literalToBinderCpp varName done (BooleanLiteral False) =
370 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing False)) (AST.Block Nothing done) Nothing]
371 -- return [AST.IfElse Nothing (AST.Unary Nothing AST.Not (AST.Var Nothing varName)) (AST.Block Nothing done) Nothing]
372 literalToBinderCpp varName done (ObjectLiteral bs) = go done bs
373 where
374 go :: [AST] -> [(PSString, Binder Ann)] -> m [AST]
375 go done' [] = return done'
376 go done' ((prop, binder):bs') = do
377 propVar <- freshName
378 done'' <- go done' bs'
379 cpp <- binderToCpp propVar done'' binder
380 return (AST.VariableIntroduction Nothing propVar (Just (accessorString prop (AST.Var Nothing varName))) : cpp)
381 literalToBinderCpp varName done (ArrayLiteral bs) = do
382 cpp <- go done 0 bs
383 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo
384 (arrayLength $ AST.Var Nothing varName)
385 (AST.NumericLiteral Nothing (Left (fromIntegral $ length bs))))
386 (AST.Block Nothing cpp) Nothing]
387 where
388 go :: [AST] -> Integer -> [Binder Ann] -> m [AST]
389 go done' _ [] = return done'
390 go done' index (binder:bs') = do
391 elVar <- freshName
392 done'' <- go done' (index + 1) bs'
393 cpp <- binderToCpp elVar done'' binder
394 return (AST.VariableIntroduction Nothing elVar (Just (AST.Indexer Nothing (AST.NumericLiteral Nothing (Left index)) (AST.Var Nothing varName))) : cpp)
396emptyAnn :: Ann
397emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
399arrayLength :: AST -> AST
400arrayLength a = AST.App Nothing (AST.Var Nothing arrayLengthFn) [a]