git.iko.soy/rowtype-yoga/purescript-native
on 080f35f help sign in
397 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)
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 Objective-C 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 exports 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) cppDecls
62 let interface = interfaceSource modName exports foreigns
63 foreigns' = identToCpp <$> foreigns
64 implHeader = implHeaderSource modName cppImports interfaceImport
65 implFooter = implFooterSource modName foreigns
66 return $ (interface, foreigns', concat optimized, implHeader, implFooter)
67 where
68 modName = moduleNameToCpp mn
70 -- | Extracts all declaration names from a binding group.
71 getNames :: Bind Ann -> [Ident]
72 getNames (NonRec _ ident _) = [ident]
73 getNames (Rec vals) = map (snd . fst) vals
75 -- | Creates alternative names for each module to ensure they don't collide
76 -- with declaration names.
77 renameImports :: [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
78 renameImports = go M.empty
79 where
80 go :: M.Map ModuleName (Ann, ModuleName) -> [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
81 go acc used ((ann, mn') : mns') =
82 let mni = Ident $ runModuleName mn'
83 in if mn' /= mn && mni `elem` used
84 then let newName = freshModuleName 1 mn' used
85 in go (M.insert mn' (ann, newName) acc) (Ident (runModuleName newName) : used) mns'
86 else go (M.insert mn' (ann, mn') acc) used mns'
87 go acc _ [] = acc
89 freshModuleName :: Integer -> ModuleName -> [Ident] -> ModuleName
90 freshModuleName i mn'@(ModuleName pns) used =
91 let newName = ModuleName $ init pns ++ [ProperName $ runProperName (last pns) <> "_" <> T.pack (show i)]
92 in if Ident (runModuleName newName) `elem` used
93 then freshModuleName (i + 1) mn' used
94 else newName
96 -- | Generates Objective-C code for a module import, binding the required module
97 -- to the alternative
98 importToCpp :: M.Map ModuleName (Ann, ModuleName) -> ModuleName -> m Text
99 importToCpp mnLookup mn' = do
100 let ((_, _, _, _), mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
101 mname = moduleNameToCpp mnSafe
102 pure $ "#include \"" <> mname <> "/" <> mname <> ".h\"\n"
104 -- | Replaces the `ModuleName`s in the AST so that the generated code refers to
105 -- the collision-avoiding renamed module imports.
106 renameModules :: M.Map ModuleName (Ann, ModuleName) -> [Bind Ann] -> [Bind Ann]
107 renameModules mnLookup binds =
108 let (f, _, _) = everywhereOnValues id goExpr goBinder
109 in map f binds
110 where
111 goExpr :: Expr a -> Expr a
112 goExpr (Var ann q) = Var ann (renameQual q)
113 goExpr e = e
114 goBinder :: Binder a -> Binder a
115 goBinder (ConstructorBinder ann q1 q2 bs) = ConstructorBinder ann (renameQual q1) (renameQual q2) bs
116 goBinder b = b
117 renameQual :: Qualified a -> Qualified a
118 renameQual (Qualified (Just mn') a) =
119 let (_,mnSafe) = fromMaybe (internalError "Missing value in mnLookup") $ M.lookup mn' mnLookup
120 in Qualified (Just mnSafe) a
121 renameQual q = q
123 -- |
124 -- Generate code in the simplified Objective-C intermediate representation for a declaration
125 --
126 bindToCpp :: DeclType -> Bind Ann -> m [AST]
127 bindToCpp dt (NonRec ann ident val) = return <$> nonRecToCpp dt ann ident val
128 bindToCpp dt (Rec vals) = forM vals (uncurry . uncurry $ nonRecToCpp dt')
129 where
130 dt' = if dt == LetDecl then RecLetDecl else dt
132 -- | Generate code in the simplified Objective-C intermediate representation for a single non-recursive
133 -- declaration.
134 --
135 -- The main purpose of this function is to handle code generation for comments.
136 nonRecToCpp :: DeclType -> Ann -> Ident -> Expr Ann -> m AST
137 nonRecToCpp dt a i e@(extractAnn -> (_, com, _, _)) | not (null com) = do
138 -- withoutComment <- asks optionsNoComments
139 let withoutComment = False
140 if withoutComment
141 then nonRecToCpp dt a i (modifyAnn removeComments e)
142 else AST.Comment Nothing com <$> nonRecToCpp dt a i (modifyAnn removeComments e)
143 nonRecToCpp ModuleDecl (ss, _, _, _) ident val = do
144 cpp <- valueToCpp val
145 pure $ AST.Function Nothing (Just $ identToCpp ident) [] (AST.Block Nothing [AST.Return Nothing cpp])
146 nonRecToCpp RecLetDecl (ss, _, _, _) ident val = do
147 cpp <- valueToCpp val
148 pure $
149 let retainedName = identToCpp ident
150 retained = AST.Var Nothing $ retainedName
151 -- unretained = AST.Var Nothing $ retainedName <> unretainedSuffix
152 -- alias = AST.Var Nothing . -- Note: prevents optimizer from eliminating this
153 -- prettyPrintCpp1 $
154 -- AST.VariableIntroduction Nothing retainedName (Just unretained)
155 in
156 case cpp of
157 AST.Function _ name args (AST.Block Nothing cpps) ->
158 AST.Assignment Nothing
159 (retained)
160 (AST.Function Nothing
161 name
162 args
163 (AST.Block Nothing cpps))
164 _ -> AST.Assignment Nothing retained cpp
165 nonRecToCpp _ (ss, _, _, _) ident val = do
166 cpp <- valueToCpp val
167 pure $ AST.VariableIntroduction Nothing (identToCpp ident) (Just cpp)
169 -- | Generate code in the simplified Objective-C intermediate representation for a variable based on a
170 -- PureScript identifier.
171 var :: Ident -> AST
172 var = AST.Var Nothing . identToCpp
174 -- | Generate code in the simplified Objective-C intermediate representation for an accessor based on
175 -- a PureScript identifier. If the name is not valid in Objective-C (symbol based, reserved name) an
176 -- indexer is returned.
177 accessor :: Ident -> AST -> AST
178 accessor (Ident prop) = accessorString $ mkString prop
179 accessor (GenIdent _ _) = internalError "GenIdent in accessor"
180 accessor UnusedIdent = internalError "UnusedIdent in accessor"
182 accessorString :: PSString -> AST -> AST
183 accessorString prop = AST.Indexer Nothing (AST.StringLiteral Nothing prop)
185 -- | Generate code in the simplified Objective-C intermediate representation for a value or expression.
187 valueToCpp :: Expr Ann -> m AST
188 valueToCpp (Literal (pos, _, _, _) l) = literalToValueCpp pos l
189 valueToCpp (Accessor _ prop val) =
190 accessorString prop <$> valueToCpp val
191 valueToCpp (ObjectUpdate _ o ps) = do
192 obj <- valueToCpp o
193 updates <- mapM (sndM valueToCpp) ps
194 obj' <- freshName
195 let objVar = AST.Var Nothing obj'
196 copy = AST.VariableIntroduction Nothing obj' (Just $ makeCopy obj)
197 assign (k, v) = AST.Assignment Nothing (accessorString k objVar) v
198 sts = copy : (assign <$> updates) ++ [AST.Return Nothing $ makeCopy objVar]
199 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing sts)) []
200 valueToCpp (Abs _ arg val) = do
201 ret <- valueToCpp val
202 let cppArg = case arg of
203 UnusedIdent -> []
204 _ -> [identToCpp arg]
205 return $ AST.Function Nothing Nothing cppArg (AST.Block Nothing [AST.Return Nothing ret])
206 valueToCpp e@App{} = do
207 let (f, args) = unApp e []
208 args' <- mapM valueToCpp args
209 case f of
210 Var (_, _, _, Just IsNewtype) _ -> return (head args')
211 _ -> flip (foldl (\fn a -> AST.App Nothing fn [a])) args' <$> valueToCpp f
212 where
213 unApp :: Expr Ann -> [Expr Ann] -> (Expr Ann, [Expr Ann])
214 unApp (App _ val arg) args = unApp val (arg : args)
215 unApp other args = (other, args)
216 -- valueToCpp (Var (_, _, _, Just IsForeign) qi@(Qualified (Just mn') ident)) =
217 -- return $ if mn' == mn
218 -- then AST.Var Nothing (moduleNameToCpp mn' <> "::" <> identToCpp ident)
219 -- else varToCpp qi
220 -- valueToCpp (Var (_, _, _, Just IsForeign) (Qualified (Just mn') ident)) =
221 -- return $ AST.Var Nothing (moduleNameToCpp mn' <> "::" <> identToCpp ident)
222 -- valueToCpp (Var (_, _, _, Just IsForeign) qi@(Qualified (Just mn') ident)) =
223 -- return $ if mn' == mn
224 -- then foreignIdent ident
225 -- else varToCpp qi
226 -- valueToCpp (Var (_, _, _, Just IsForeign) ident) =
227 -- internalError $ "Encountered an unqualified reference to a foreign ident " ++ T.unpack (showQualified showIdent ident)
228 valueToCpp (Var _ ident) = return $ varToCpp ident
229 valueToCpp (Case (ss, _, _, _) values binders) = do
230 vals <- mapM valueToCpp values
231 bindersToCpp ss binders vals
232 valueToCpp (Let _ ds val) = do
233 let recurs = concatMap getNames $ filter isRec ds
234 recurDs = (\v -> AST.VariableIntroduction Nothing (identToCpp v) (Just (AST.Var Nothing "box<fn_t>()"))) <$> recurs
235 -- recurDsWeak = (\v -> AST.VariableIntroduction Nothing ("__unsafe_unretained " <> identToCpp v <> unretainedSuffix) Nothing) <$> recurs
236 ds' <- concat <$> mapM (bindToCpp LetDecl) ds
237 ret <- valueToCpp val
238 return $
239 AST.App Nothing
240 (AST.Function Nothing
241 Nothing
242 []
243 (AST.Block Nothing (recurDs ++ ds' ++ [AST.Return Nothing ret])))
244 []
245 where
246 isRec :: Bind Ann -> Bool
247 isRec (Rec _) = True
248 isRec _ = False
249 valueToCpp (Constructor (_, _, _, Just IsNewtype) _ (ProperName ctor) _) = error "IsNewtype"
250 valueToCpp (Constructor _ _ (ProperName ctor) fields) =
251 let body = AST.ObjectLiteral Nothing $ (mkString ctor, AST.BooleanLiteral Nothing True) :
252 ((\field -> (mkString (identToCpp field), var field)) `map` fields)
253 fn = foldr (\f inner -> AST.Function Nothing Nothing [identToCpp f] (AST.Block Nothing [AST.Return Nothing inner])) body fields
254 in return fn
257 iife :: Text -> [AST] -> AST
258 iife v exprs = AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing $ exprs ++ [AST.Return Nothing $ AST.Var Nothing v])) []
260 literalToValueCpp :: SourceSpan -> Literal (Expr Ann) -> m AST
261 literalToValueCpp ss (NumericLiteral (Left i)) = return $ AST.NumericLiteral (Just ss) (Left i)
262 literalToValueCpp ss (NumericLiteral (Right n)) = return $ AST.NumericLiteral (Just ss) (Right n)
263 literalToValueCpp ss (StringLiteral s) = return $ AST.StringLiteral (Just ss) s
264 literalToValueCpp ss (CharLiteral c) = return $ AST.StringLiteral (Just ss) (fromString [c])
265 literalToValueCpp ss (BooleanLiteral b) = return $ AST.BooleanLiteral (Just ss) b
266 literalToValueCpp ss (ArrayLiteral xs) = AST.ArrayLiteral (Just ss) <$> mapM valueToCpp xs
267 literalToValueCpp ss (ObjectLiteral ps) = AST.ObjectLiteral (Just ss) <$> mapM (sndM valueToCpp) ps
269 -- | Generate code in the simplified Objective-C intermediate representation for a reference to a
270 -- variable.
271 varToCpp :: Qualified Ident -> AST
272 varToCpp (Qualified Nothing ident) = var ident
273 varToCpp qual = qualifiedToCpp id qual
275 -- | Generate code in the simplified Objective-C intermediate representation for a reference to a
276 -- variable that may have a qualified name.
277 qualifiedToCpp :: (a -> Ident) -> Qualified a -> AST
278 qualifiedToCpp f (Qualified (Just (ModuleName [ProperName mn'])) a) | mn' == C.prim = AST.Var Nothing . runIdent $ f a
279 qualifiedToCpp f (Qualified (Just mn') a) = AST.Indexer Nothing (AST.Var Nothing . identToCpp $ f a) (AST.Var Nothing (moduleNameToCpp mn'))
280 qualifiedToCpp f (Qualified _ a) = AST.Var Nothing $ identToCpp (f a)
282 -- foreignIdent :: Ident -> AST
283 -- foreignIdent ident = accessorString (mkString $ runIdent ident) (AST.Var Nothing "$foreign")
285 -- | Generate code in the simplified Objective-C intermediate representation for pattern match binders
286 -- and guards.
287 bindersToCpp :: SourceSpan -> [CaseAlternative Ann] -> [AST] -> m AST
288 bindersToCpp ss binders vals = do
289 valNames <- replicateM (length vals) freshName
290 let assignments = zipWith (AST.VariableIntroduction Nothing) valNames (map Just vals)
291 cpps <- forM binders $ \(CaseAlternative bs result) -> do
292 ret <- guardsToCpp result
293 go valNames ret bs
294 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (assignments ++ concat cpps ++ [AST.Throw Nothing (AST.StringLiteral Nothing $ mkString failedPatternMessage)])))
295 []
296 where
297 go :: [Text] -> [AST] -> [Binder Ann] -> m [AST]
298 go _ done [] = return done
299 go (v:vs) done' (b:bs) = do
300 done'' <- go vs done' bs
301 binderToCpp v done'' b
302 go _ _ _ = internalError "Invalid arguments to bindersToCpp"
304 failedPatternMessage :: Text
305 failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss <> ": "
307 guardsToCpp :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
308 guardsToCpp (Left gs) = traverse genGuard gs where
309 genGuard (cond, val) = do
310 cond' <- valueToCpp cond
311 val' <- valueToCpp val
312 return
313 (AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo cond' (AST.BooleanLiteral Nothing True))
314 (AST.Block Nothing [AST.Return Nothing val']) Nothing)
316 guardsToCpp (Right v) = return . AST.Return Nothing <$> valueToCpp v
318 -- | Generate code in the simplified Objective-C intermediate representation for a pattern match
319 -- binder.
320 binderToCpp :: Text -> [AST] -> Binder Ann -> m [AST]
321 binderToCpp _ done NullBinder{} = return done
322 binderToCpp varName done (LiteralBinder _ l) =
323 literalToBinderCpp varName done l
324 binderToCpp varName done (VarBinder _ ident) =
325 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : done)
326 binderToCpp varName done (ConstructorBinder (_, _, _, Just IsNewtype) _ _ [b]) =
327 binderToCpp varName done b
328 binderToCpp varName done (ConstructorBinder (_, _, _, Just (IsConstructor ctorType fields)) _ (Qualified _ (ProperName ctor)) bs) = do
329 cpp <- go (zip fields bs) done
330 return $ case ctorType of
331 ProductType -> cpp
332 SumType ->
333 [AST.IfElse Nothing (AST.InstanceOf Nothing (AST.Var Nothing varName) (AST.StringLiteral Nothing (mkString ctor)))
334 (AST.Block Nothing cpp)
335 Nothing]
336 where
337 go :: [(Ident, Binder Ann)] -> [AST] -> m [AST]
338 go [] done' = return done'
339 go ((field, binder) : remain) done' = do
340 argVar <- freshName
341 done'' <- go remain done'
342 cpp <- binderToCpp argVar done'' binder
343 return (AST.VariableIntroduction Nothing argVar (Just $ accessorString (mkString $ identToCpp field) $ AST.Var Nothing varName) : cpp)
345 binderToCpp _ _ ConstructorBinder{} =
346 internalError "binderToCpp: Invalid ConstructorBinder in binderToCpp"
347 binderToCpp varName done (NamedBinder _ ident binder) = do
348 cpp <- binderToCpp varName done binder
349 return (AST.VariableIntroduction Nothing (identToCpp ident) (Just (AST.Var Nothing varName)) : cpp)
351 literalToBinderCpp :: Text -> [AST] -> Literal (Binder Ann) -> m [AST]
352 literalToBinderCpp varName done (NumericLiteral num) =
353 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.NumericLiteral Nothing num)) (AST.Block Nothing done) Nothing]
354 literalToBinderCpp varName done (CharLiteral c) =
355 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing (fromString [c]))) (AST.Block Nothing done) Nothing]
356 literalToBinderCpp varName done (StringLiteral str) =
357 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing str)) (AST.Block Nothing done) Nothing]
358 literalToBinderCpp varName done (BooleanLiteral True) =
359 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing True)) (AST.Block Nothing done) Nothing]
360 literalToBinderCpp varName done (BooleanLiteral False) =
361 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing False)) (AST.Block Nothing done) Nothing]
362 -- return [AST.IfElse Nothing (AST.Unary Nothing AST.Not (AST.Var Nothing varName)) (AST.Block Nothing done) Nothing]
363 literalToBinderCpp varName done (ObjectLiteral bs) = go done bs
364 where
365 go :: [AST] -> [(PSString, Binder Ann)] -> m [AST]
366 go done' [] = return done'
367 go done' ((prop, binder):bs') = do
368 propVar <- freshName
369 done'' <- go done' bs'
370 cpp <- binderToCpp propVar done'' binder
371 return (AST.VariableIntroduction Nothing propVar (Just (accessorString prop (AST.Var Nothing varName))) : cpp)
372 literalToBinderCpp varName done (ArrayLiteral bs) = do
373 cpp <- go done 0 bs
374 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo
375 (arrayLength $ AST.Var Nothing varName)
376 (AST.NumericLiteral Nothing (Left (fromIntegral $ length bs))))
377 (AST.Block Nothing cpp) Nothing]
378 where
379 go :: [AST] -> Integer -> [Binder Ann] -> m [AST]
380 go done' _ [] = return done'
381 go done' index (binder:bs') = do
382 elVar <- freshName
383 done'' <- go done' (index + 1) bs'
384 cpp <- binderToCpp elVar done'' binder
385 return (AST.VariableIntroduction Nothing elVar (Just (AST.Indexer Nothing (AST.NumericLiteral Nothing (Left index)) (AST.Var Nothing varName))) : cpp)
387emptyAnn :: Ann
388emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
390makeCopy :: AST -> AST
391makeCopy obj = AST.App Nothing (AST.Var Nothing "copy<dict_t>") [obj]
393arrayLength :: AST -> AST
394arrayLength array = applyMethod (AST.App Nothing (AST.Var Nothing "unbox<array_t>") [array]) "size"
396applyMethod :: AST -> Text -> AST
397applyMethod obj method = (AST.Indexer Nothing (AST.ArrayLiteral Nothing [AST.Var Nothing method]) obj)