git.iko.soy/rowtype-yoga/purescript-native
on ba2cc5c help sign in
359 lines 17 kB history raw
1-- | This module generates code in the core imperative representation from
2-- elaborated PureScript code.
3module CodeGen.IL
4 ( module AST
5 , module Common
6 , moduleToIL
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, nub)
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.IL.Common as Common
39import CodeGen.IL.Optimizer
40import CodeGen.IL.Printer
42data DeclType = ModuleDecl | LetDecl | RecLetDecl deriving (Eq)
44-- | Generate code in the simplified intermediate representation for all declarations in a
45-- module.
46moduleToIL
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)
53moduleToIL (Module _ coms mn _ imps _ foreigns decls) _ =
54 do
55 let usedNames = concatMap getNames decls
56 let mnLookup = renameImports usedNames imps
57 let decls' = renameModules mnLookup decls
58 ilDecls <- mapM (bindToIL ModuleDecl) decls'
59 optimized <- traverse (traverse (optimize modName')) ilDecls
60 let optimized' = concat optimized
61 values = annotValue <$> optimized'
62 foreigns' = moduleIdentToIL <$> foreigns
63 interface = interfaceSource modName values foreigns
64 imports = nub . concat $ importToIL <$> optimized'
65 implHeader = implHeaderSource modName imports ""
66 implFooter = implFooterSource modName foreigns
67 return $ (interface, foreigns', optimized', implHeader, implFooter)
68 where
69 modName = moduleNameToIL mn
70 modName' = AST.Var Nothing modName
72 annotValue :: AST -> (Text, Bool)
73 annotValue (AST.Function _ (Just name) [] (AST.Block _ [AST.Return _ ret]))
74 | isLiteral ret = (name, True)
75 annotValue (AST.Function _ (Just name) [] _) = (name, False)
76 annotValue _ = error "Unexpected top-level value form"
78 -- | Extracts all declaration names from a binding group.
79 getNames :: Bind Ann -> [Ident]
80 getNames (NonRec _ ident _) = [ident]
81 getNames (Rec vals) = map (snd . fst) vals
83 -- | Creates alternative names for each module to ensure they don't collide
84 -- with declaration names.
85 renameImports :: [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
86 renameImports = go M.empty
87 where
88 go :: M.Map ModuleName (Ann, ModuleName) -> [Ident] -> [(Ann, ModuleName)] -> M.Map ModuleName (Ann, ModuleName)
89 go acc used ((ann, mn') : mns') =
90 let mni = Ident $ runModuleName mn'
91 in if mn' /= mn && mni `elem` used
92 then let newName = freshModuleName 1 mn' used
93 in go (M.insert mn' (ann, newName) acc) (Ident (runModuleName newName) : used) mns'
94 else go (M.insert mn' (ann, mn') acc) used mns'
95 go acc _ [] = acc
97 freshModuleName :: Integer -> ModuleName -> [Ident] -> ModuleName
98 freshModuleName i mn'@(ModuleName pns) used =
99 let newName = ModuleName $ init pns ++ [ProperName $ runProperName (last pns) <> "_" <> T.pack (show i)]
100 in if Ident (runModuleName newName) `elem` used
101 then freshModuleName (i + 1) mn' used
102 else newName
104 -- | Generates IL code for a module import
105 --
106 importToIL :: AST -> [Text]
107 importToIL = AST.everything (++) modRef
108 where
109 modRef (AST.Indexer _ (AST.Var _ _) (AST.Var _ mname))
110 | not $ T.null mname = [mname]
111 modRef _ = []
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 ilExpr goBinder
118 in map f binds
119 where
120 ilExpr :: Expr a -> Expr a
121 ilExpr (Var ann q) = Var ann (renameQual q)
122 ilExpr 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 bindToIL :: DeclType -> Bind Ann -> m [AST]
136 bindToIL dt (NonRec ann ident val) = return <$> nonRecToIL dt ann ident val
137 bindToIL dt (Rec vals) = forM vals (uncurry . uncurry $ nonRecToIL 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 nonRecToIL :: DeclType -> Ann -> Ident -> Expr Ann -> m AST
146 nonRecToIL dt a i e@(extractAnn -> (_, com, _, _)) | not (null com) = do
147 -- withoutComment <- asks optionsNoComments
148 let withoutComment = False
149 if withoutComment
150 then nonRecToIL dt a i (modifyAnn removeComments e)
151 else AST.Comment Nothing com <$> nonRecToIL dt a i (modifyAnn removeComments e)
152 nonRecToIL ModuleDecl (ss, _, _, _) ident val = do
153 il <- valueToIL val
154 pure $ AST.Function Nothing (Just $ moduleIdentToIL ident) [] (AST.Block Nothing [AST.Return Nothing il])
155 nonRecToIL RecLetDecl (ss, _, _, _) ident val = do
156 ilExpr <- valueToIL val
157 pure $ AST.Assignment Nothing (AST.Var Nothing $ identToIL ident) ilExpr
158 nonRecToIL _ (ss, _, _, _) ident val = do
159 il <- valueToIL val
160 pure $ AST.VariableIntroduction Nothing (identToIL ident) (Just il)
162 -- | Generate code in the simplified intermediate representation for a variable based on a
163 -- PureScript identifier.
164 var :: Ident -> AST
165 var = AST.Var Nothing . identToIL
167 accessorString :: PSString -> AST -> AST
168 accessorString prop = AST.Indexer Nothing (AST.StringLiteral Nothing prop)
170 -- | Generate code in the simplified intermediate representation for a value or expression.
172 valueToIL :: Expr Ann -> m AST
173 valueToIL (Literal (pos, _, _, _) l) = literalToValueIL pos l
174 valueToIL (Accessor _ prop val) =
175 accessorString prop <$> valueToIL val
176 valueToIL (ObjectUpdate _ o ps) = do
177 obj <- valueToIL o
178 updates <- mapM (sndM valueToIL) ps
179 obj' <- freshName'
180 let objVar = AST.Var Nothing obj'
181 copy = AST.VariableIntroduction Nothing obj' (Just $ AST.App Nothing (AST.StringLiteral Nothing (mkString dictType)) [obj])
182 assign (k, v) = AST.Assignment Nothing (accessorString k objVar) v
183 sts = copy : (assign <$> updates) ++ [AST.Return Nothing objVar]
184 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing sts)) []
185 valueToIL (Abs _ arg val) = do
186 ret <- valueToIL val
187 let ilArg = case arg of
188 UnusedIdent -> []
189 _ -> [identToIL arg]
190 return $ AST.Function Nothing Nothing ilArg (AST.Block Nothing [AST.Return Nothing ret])
191 valueToIL e@App{} = do
192 let (f, args) = unApp e []
193 args' <- mapM valueToIL args
194 fn <- valueToIL f
195 case f of
196 Var (_, _, _, Just IsNewtype) _ -> return (head args')
197 _ -> flip (foldl (\fn a -> AST.App Nothing fn [a])) args' <$> valueToIL f
198 where
199 unApp :: Expr Ann -> [Expr Ann] -> (Expr Ann, [Expr Ann])
200 unApp (App _ val arg) args = unApp val (arg : args)
201 unApp other args = (other, args)
202 valueToIL (Var _ ident) = return $ varToIL ident
203 valueToIL (Case (ss, _, _, _) values binders) = do
204 vals <- mapM valueToIL values
205 bindersToIL ss binders vals
206 valueToIL (Let _ ds val) = do
207 let recurs = concatMap getNames $ filter isRec ds
208 recurDs = (\v -> AST.VariableIntroduction Nothing (identToIL v) Nothing) <$> recurs
209 ds' <- concat <$> mapM (bindToIL LetDecl) ds
210 ret <- valueToIL val
211 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (recurDs ++ ds' ++ [AST.Return Nothing ret]))) []
212 where
213 isRec :: Bind Ann -> Bool
214 isRec (Rec _) = True
215 isRec _ = False
216 valueToIL (Constructor (_, _, _, Just IsNewtype) _ (ProperName ctor) _) = error "IsNewtype"
217 valueToIL (Constructor _ _ (ProperName ctor) fields) =
218 let body = AST.ObjectLiteral Nothing $ (mkString ctor, AST.BooleanLiteral Nothing True) :
219 ((\field -> (mkString (identToIL field), var field)) `map` fields)
220 fn = foldr (\f inner -> AST.Function Nothing Nothing [identToIL f] (AST.Block Nothing [AST.Return Nothing inner])) body fields
221 in return fn
224 iife :: Text -> [AST] -> AST
225 iife v exprs = AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing $ exprs ++ [AST.Return Nothing $ AST.Var Nothing v])) []
227 literalToValueIL :: SourceSpan -> Literal (Expr Ann) -> m AST
228 literalToValueIL ss (NumericLiteral (Left i)) = return $ AST.NumericLiteral (Just ss) (Left i)
229 literalToValueIL ss (NumericLiteral (Right n)) = return $ AST.NumericLiteral (Just ss) (Right n)
230 literalToValueIL ss (StringLiteral s) = return $ AST.StringLiteral (Just ss) s
231 literalToValueIL ss (CharLiteral c) = return $ AST.StringLiteral (Just ss) (fromString [c])
232 literalToValueIL ss (BooleanLiteral b) = return $ AST.BooleanLiteral (Just ss) b
233 literalToValueIL ss (ArrayLiteral xs) = AST.ArrayLiteral (Just ss) <$> mapM valueToIL xs
234 literalToValueIL ss (ObjectLiteral ps) = AST.ObjectLiteral (Just ss) <$> mapM (sndM valueToIL) ps
236 -- | Generate code in the simplified intermediate representation for a reference to a
237 -- variable.
238 varToIL :: Qualified Ident -> AST
239 varToIL (Qualified Nothing ident) = var ident
240 varToIL qual = qualifiedToIL id qual
242 -- | Generate code in the simplified intermediate representation for a reference to a
243 -- variable that may have a qualified name.
244 qualifiedToIL :: (a -> Ident) -> Qualified a -> AST
245 qualifiedToIL f (Qualified (Just (ModuleName [ProperName mn'])) a) | mn' == C.prim = AST.Var Nothing . moduleIdentToIL $ f a
246 qualifiedToIL f (Qualified (Just mn') a) | mn /= mn' = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing (moduleNameToIL mn'))
247 qualifiedToIL f (Qualified _ a) = AST.Indexer Nothing (AST.Var Nothing . moduleIdentToIL $ f a) (AST.Var Nothing "")
249 -- foreignIdent :: Ident -> AST
250 -- foreignIdent ident = accessorString (mkString $ runIdent ident) (AST.Var Nothing "$foreign")
252 -- | Generate code in the simplified intermediate representation for pattern match binders
253 -- and guards.
254 bindersToIL :: SourceSpan -> [CaseAlternative Ann] -> [AST] -> m AST
255 bindersToIL ss binders vals = do
256 valNames <- replicateM (length vals) freshName'
257 let assignments = zipWith (AST.VariableIntroduction Nothing) valNames (map Just vals)
258 ils <- forM binders $ \(CaseAlternative bs result) -> do
259 ret <- guardsToIL result
260 go valNames ret bs
261 return $ AST.App Nothing (AST.Function Nothing Nothing [] (AST.Block Nothing (assignments ++ concat ils ++ [AST.Throw Nothing (AST.StringLiteral Nothing $ mkString failedPatternMessage)])))
262 []
263 where
264 go :: [Text] -> [AST] -> [Binder Ann] -> m [AST]
265 go _ done [] = return done
266 go (v:vs) done' (b:bs) = do
267 done'' <- go vs done' bs
268 binderToIL v done'' b
269 go _ _ _ = internalError "Invalid arguments to bindersToIL"
271 failedPatternMessage :: Text
272 failedPatternMessage = "Failed pattern match at " <> runModuleName mn <> " " <> displayStartEndPos ss <> ": "
274 guardsToIL :: Either [(Guard Ann, Expr Ann)] (Expr Ann) -> m [AST]
275 guardsToIL (Left gs) = traverse genGuard gs where
276 genGuard (cond, val) = do
277 cond' <- valueToIL cond
278 val' <- valueToIL val
279 return
280 (AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo cond' (AST.BooleanLiteral Nothing True))
281 (AST.Block Nothing [AST.Return Nothing val']) Nothing)
283 guardsToIL (Right v) = return . AST.Return Nothing <$> valueToIL v
285 -- | Generate code in the simplified intermediate representation for a pattern match
286 -- binder.
287 binderToIL :: Text -> [AST] -> Binder Ann -> m [AST]
288 binderToIL _ done NullBinder{} = return done
289 binderToIL varName done (LiteralBinder _ l) =
290 literalToBinderIL varName done l
291 binderToIL varName done (VarBinder _ ident) =
292 return (AST.VariableIntroduction Nothing (identToIL ident) (Just (AST.Var Nothing varName)) : done)
293 binderToIL varName done (ConstructorBinder (_, _, _, Just IsNewtype) _ _ [b]) =
294 binderToIL varName done b
295 binderToIL varName done (ConstructorBinder (_, _, _, Just (IsConstructor ctorType fields)) _ (Qualified _ (ProperName ctor)) bs) = do
296 il <- go (zip fields bs) done
297 return $ case ctorType of
298 ProductType -> il
299 SumType ->
300 [AST.IfElse Nothing (AST.InstanceOf Nothing (AST.Var Nothing varName) (AST.StringLiteral Nothing (mkString ctor)))
301 (AST.Block Nothing il)
302 Nothing]
303 where
304 go :: [(Ident, Binder Ann)] -> [AST] -> m [AST]
305 go [] done' = return done'
306 go ((field, binder) : remain) done' = do
307 argVar <- freshName'
308 done'' <- go remain done'
309 il <- binderToIL argVar done'' binder
310 return (AST.VariableIntroduction Nothing argVar (Just $ accessorString (mkString $ identToIL field) $ AST.Var Nothing varName) : il)
312 binderToIL _ _ ConstructorBinder{} =
313 internalError "binderToIL: Invalid ConstructorBinder in binderToIL"
314 binderToIL varName done (NamedBinder _ ident binder) = do
315 il <- binderToIL varName done binder
316 return (AST.VariableIntroduction Nothing (identToIL ident) (Just (AST.Var Nothing varName)) : il)
318 literalToBinderIL :: Text -> [AST] -> Literal (Binder Ann) -> m [AST]
319 literalToBinderIL varName done (NumericLiteral num) =
320 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.NumericLiteral Nothing num)) (AST.Block Nothing done) Nothing]
321 literalToBinderIL varName done (CharLiteral c) =
322 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing (fromString [c]))) (AST.Block Nothing done) Nothing]
323 literalToBinderIL varName done (StringLiteral str) =
324 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.StringLiteral Nothing str)) (AST.Block Nothing done) Nothing]
325 literalToBinderIL varName done (BooleanLiteral True) =
326 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing True)) (AST.Block Nothing done) Nothing]
327 literalToBinderIL varName done (BooleanLiteral False) =
328 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo (AST.Var Nothing varName) (AST.BooleanLiteral Nothing False)) (AST.Block Nothing done) Nothing]
329 -- return [AST.IfElse Nothing (AST.Unary Nothing AST.Not (AST.Var Nothing varName)) (AST.Block Nothing done) Nothing]
330 literalToBinderIL varName done (ObjectLiteral bs) = go done bs
331 where
332 go :: [AST] -> [(PSString, Binder Ann)] -> m [AST]
333 go done' [] = return done'
334 go done' ((prop, binder):bs') = do
335 propVar <- freshName'
336 done'' <- go done' bs'
337 il <- binderToIL propVar done'' binder
338 return (AST.VariableIntroduction Nothing propVar (Just (accessorString prop (AST.Var Nothing varName))) : il)
339 literalToBinderIL varName done (ArrayLiteral bs) = do
340 il <- go done 0 bs
341 return [AST.IfElse Nothing (AST.Binary Nothing AST.EqualTo
342 (arrayLength $ AST.Var Nothing varName)
343 (AST.NumericLiteral Nothing (Left (fromIntegral $ length bs))))
344 (AST.Block Nothing il) Nothing]
345 where
346 go :: [AST] -> Integer -> [Binder Ann] -> m [AST]
347 go done' _ [] = return done'
348 go done' index (binder:bs') = do
349 elVar <- freshName'
350 done'' <- go done' (index + 1) bs'
351 il <- binderToIL elVar done'' binder
352 return (AST.VariableIntroduction Nothing elVar (Just (AST.Indexer Nothing (AST.NumericLiteral Nothing (Left index)) (AST.Var Nothing varName))) : il)
354emptyAnn :: Ann
355emptyAnn = (SourceSpan "" (SourcePos 0 0) (SourcePos 0 0), [], Nothing, Nothing)
357arrayLength :: AST -> AST
358arrayLength a = AST.App Nothing (AST.Var Nothing arrayLengthFn) [a]
359-- arrayLength a = AST.Var Nothing (arrayLengthFn <> "(" <> prettyPrintIL1 a <> ")")