git.iko.soy/rowtype-yoga/purescript-native
on 0301a73 help sign in
496 lines 18 kB history raw
1-- | Pretty printer for the AST
2module CodeGen.Cpp.Printer
3 ( prettyPrintCpp
4 , prettyPrintCpp1
5 , prettyPrintCppWithSourceMaps
6 , interfaceSource
7 , implHeaderSource
8 , implFooterSource
9 ) where
11import Prelude.Compat
13import Control.Arrow ((<+>))
14import Control.Monad (forM, mzero)
15import Control.Monad.State (StateT, evalStateT)
16import Control.PatternArrows
17import Data.Char (isAscii)
18import Data.List ((\\))
19import qualified Control.Arrow as A
21import Data.Maybe (fromMaybe)
22import Data.Monoid ((<>))
23import Data.Text (Text)
24import qualified Data.Text as T
26import Language.PureScript.AST (SourceSpan(..))
27import Language.PureScript.CoreImp.AST
28import Language.PureScript.Comments
29import Language.PureScript.Crash
30import Language.PureScript.Names (Ident, runIdent)
31import Language.PureScript.Pretty.Common
32import Language.PureScript.PSString (PSString, decodeString, mkString)
33import CodeGen.Cpp.Common
35import qualified Language.PureScript.Constants as C
37-- TODO (Christoph): Get rid of T.unpack / pack
39literals :: (Emit gen) => Pattern PrinterState AST gen
40literals = mkPattern' match'
41 where
42 match' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
43 match' cpp = (addMapping' (getSourceSpan cpp) <>) <$> match cpp
45 match :: (Emit gen) => AST -> StateT PrinterState Maybe gen
46 match (NumericLiteral _ n) = return $ emit $ T.pack $ either show show n
47 match (StringLiteral _ s) = return $ emit $ stringLiteral s
48 match (BooleanLiteral _ True) = return $ emit "true"
49 match (BooleanLiteral _ False) = return $ emit "false"
50 match (ArrayLiteral _ xs) = mconcat <$> sequence
51 [ return . emit $ arrayType <> "{"
52 , intercalate (emit ", ") <$> forM xs prettyPrintCpp'
53 , return $ emit "}"
54 ]
55 -- match (ObjectLiteral _ []) = return $ emit "std::initializer_list<std::pair<const string, boxed>>{}"
56 match (ObjectLiteral _ ps) = mconcat <$> sequence
57 [ return . emit $ dictType <> "{\n"
58 , withIndent $ do
59 cpps <- forM ps $ \(key, value) -> do
60 value' <- prettyPrintCpp' value
61 return $ emit "{ " <> objectPropertyToString key <> value' <> emit " }"
62 indentString <- currentIndent
63 return $ intercalate (emit ",\n") $ map (indentString <>) cpps
64 , return $ emit "\n"
65 , currentIndent
66 , return $ emit "}"
67 ]
68 where
69 objectPropertyToString :: (Emit gen) => PSString -> gen
70 objectPropertyToString s = emit $ stringLiteral s <> ", "
71 match (Block _ sts) = mconcat <$> sequence
72 [ return $ emit "{\n"
73 , withIndent $ prettyStatements sts
74 , return $ emit "\n"
75 , currentIndent
76 , return $ emit "}"
77 ]
78 match (Var _ ident) = return $ emit ident
79 match (VariableIntroduction _ ident value) = mconcat <$> sequence
80 [ return $ emit $ "boxed " <> ident
81 , maybe (return mempty) (fmap (emit " = " <>) . prettyPrintCpp') value
82 ]
83 match (Assignment _ target@(Var _ var) value@(Function _ Nothing args body)) = mconcat <$> sequence
84 [ prettyPrintCpp' target
85 , return $ emit " = "
86 , return $ emit "[=, &"
87 , prettyPrintCpp' target
88 , return $ emit "]"
89 , return $ emit "("
90 , return $ emit $ intercalate ", " (renderArg <$> args)
91 , return $ emit ") -> boxed "
92 , prettyPrintCpp' body
93 ]
94 match (Assignment _ target value) = mconcat <$> sequence
95 [ prettyPrintCpp' target
96 , return $ emit " = "
97 , prettyPrintCpp' value
98 ]
99 match (App _ val []) = mconcat <$> sequence
100 [ prettyPrintCpp' val
101 , return $ emit "()"
102 ]
103 match (App ss (App _ (App _ (Indexer _ (Var _ fn) (Var _ fnMod)) [Indexer _ (Var _ dict) (Var _ dictMod)]) [x]) [y])
104 | fnMod == dictMod
105 , dictMod == C.dataEq || dictMod == C.dataSemiring || dictMod == C.dataRing || dictMod == C.dataEuclideanRing
106 , Just op <- renderOp fn
107 , Just t <- unboxType dict
108 = mconcat <$> sequence
109 [ return $ emit $ unbox' t x
110 , return $ emit op
111 , return $ emit $ unbox' t y
112 ]
113 match (App _ (App _ (Indexer _ (Var _ fn) (Var _ fnMod)) [Indexer _ (Var _ dict) (Var _ dictMod)]) [n])
114 | fnMod == dictMod
115 , dictMod == C.dataRing
116 , fn == C.negate
117 , Just t <- unboxType dict
118 = mconcat <$> sequence
119 [ return $ emit "-"
120 , return $ emit $ unbox' t n
121 ]
122 match (App _ val args) = mconcat <$> sequence
123 [ prettyPrintCpp' val
124 , return $ emit "("
125 , intercalate (emit ", ") <$> forM args prettyPrintCpp'
126 , return $ emit ")"
127 ]
128 match (Function _ (Just name) [] ret@(Block _ [Return _ (Function {})])) = mconcat <$> sequence
129 [ return $ emit "auto "
130 , return $ emit name
131 , return $ emit "() -> boxed "
132 , prettyPrintCpp' ret
133 ]
134 match (Function _ (Just name) [] (Block _ [Return _ ret])) = mconcat <$> sequence
135 [ return $ emit "auto "
136 , return $ emit name
137 , return $ emit "() -> boxed "
138 , return $ emit "{\n"
139 , withIndent $ do
140 indentString <- currentIndent
141 return $ indentString <> emit dispatchOnceBegin
142 , withIndent $ do
143 prettyPrintCpp' ret
144 , return $ emit ";\n"
145 , withIndent $ do
146 indentString <- currentIndent
147 return $ indentString <> emit dispatchOnceEnd
148 , return $ emit "\n}"
149 ]
150 -- match (Function _ (Just name) [] ret) = mconcat <$> sequence
151 match (Function _ (Just name) [] (Block ss sts)) | Return _ ret <- last sts = mconcat <$> sequence
152 [ return $ emit "auto "
153 , return $ emit name
154 , return $ emit "() -> boxed {\n"
155 , withIndent $ do
156 prettyStatements $ init sts
157 , return $ emit "\n"
158 , withIndent $ do
159 indentString <- currentIndent
160 return $ indentString <> emit dispatchOnceBegin
161 , withIndent $ do
162 prettyPrintCpp' ret
163 , return $ emit ";\n"
164 , withIndent $ do
165 indentString <- currentIndent
166 return $ indentString <> emit dispatchOnceEnd
167 , return $ emit "\n}"
168 ]
169 match (Function _ name args ret) = mconcat <$> sequence
170 [ return $ emit $ if name == (Just tcoLoop) then "[&]" else "[=]"
171 , return $ emit "("
172 , return $ emit $ intercalate ", " (renderArg <$> args)
173 , return $ emit ") -> boxed "
174 , prettyPrintCpp' ret
175 ]
176 match (Indexer _ prop@(Var _ name) val) = mconcat <$> sequence
177 [ prettyPrintCpp' val
178 , return $ emit "::"
179 , prettyPrintCpp' prop
180 , return $ emit "()"
181 ]
182 match (Indexer _ prop val) = mconcat <$> sequence
183 [ prettyPrintCpp' val
184 , return $ emit "["
185 , prettyPrintCpp' prop
186 , return $ emit "]"
187 ]
188 match (InstanceOf _ val ty) = mconcat <$> sequence
189 [ return . emit $ unbox' dictType val
190 , return $ emit ".contains("
191 , prettyPrintCpp' ty
192 , return $ emit ")"
193 ]
194 match (While _ cond sts) = mconcat <$> sequence
195 [ return $ emit "while ("
196 , prettyPrintCpp' cond
197 , return $ emit ") "
198 , prettyPrintCpp' sts
199 ]
200 match (For _ ident start end sts) = mconcat <$> sequence
201 [ return $ emit $ "for (boxed " <> ident <> " = "
202 , prettyPrintCpp' start
203 , return $ emit $ "; " <> ident <> " < "
204 , prettyPrintCpp' end
205 , return $ emit $ "; " <> ident <> "++) "
206 , prettyPrintCpp' sts
207 ]
208 match (ForIn _ ident obj sts) = mconcat <$> sequence
209 [ return $ emit $ "for (boxed " <> ident <> " in "
210 , prettyPrintCpp' obj
211 , return $ emit ") "
212 , prettyPrintCpp' sts
213 ]
214 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing True)) thens elses) = mconcat <$> sequence
215 [ return $ emit "if ("
216 , return $ emit $ unbox' "bool" cond
217 , return $ emit ") "
218 , prettyPrintCpp' thens
219 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
220 ]
221 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing False)) thens elses) = mconcat <$> sequence
222 [ return $ emit "if (!("
223 , return $ emit $ unbox' "bool" cond
224 , return $ emit ")) "
225 , prettyPrintCpp' thens
226 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
227 ]
228 match (IfElse _ (Binary _ EqualTo x y@(NumericLiteral _ n)) thens elses) = mconcat <$> sequence
229 [ return $ emit "if ("
230 , return $ emit $ unbox' t x
231 , return $ emit $ " == "
232 , prettyPrintCpp' y
233 , return $ emit ") "
234 , prettyPrintCpp' thens
235 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
236 ]
237 where
238 t | Left _ <- n = int
239 | Right _ <- n = float
240 match (IfElse _ (Binary _ EqualTo a b@StringLiteral{}) thens elses) = mconcat <$> sequence
241 [ return $ emit "if ("
242 , return $ emit $ unbox' string a
243 , return $ emit $ " == "
244 , prettyPrintCpp' b
245 , return $ emit ") "
246 , prettyPrintCpp' thens
247 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
248 ]
249 match (IfElse _ cond thens elses) = mconcat <$> sequence
250 [ return $ emit "if ("
251 , prettyPrintCpp' cond
252 , return $ emit ") "
253 , prettyPrintCpp' thens
254 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
255 ]
256 match (Return _ value) = mconcat <$> sequence
257 [ return $ emit "return "
258 , prettyPrintCpp' value
259 ]
260 match (ReturnNoResult _) = return $ emit "return nullptr"
261 -- match (Throw _ _) = return mempty
262 match (Throw _ value) = mconcat <$> sequence
263 [ return $ emit "throw "
264 , return $ emit "std::runtime_error(\"PatternMatchFailure: \""
265 , prettyPrintCpp' value
266 , return $ emit ")"
267 ]
268 match (Comment _ com cpp) = mconcat <$> sequence
269 [ return $ emit "\n"
270 , mconcat <$> forM com comment
271 , prettyPrintCpp' cpp
272 ]
273 match _ = mzero
275 comment :: (Emit gen) => Comment -> StateT PrinterState Maybe gen
276 comment (LineComment com) = fmap mconcat $ sequence $
277 [ currentIndent
278 , return $ emit "//" <> emit com <> emit "\n"
279 ]
280 comment (BlockComment com) = fmap mconcat $ sequence $
281 [ currentIndent
282 , return $ emit "/**\n"
283 ] ++
284 map asLine (T.lines com) ++
285 [ currentIndent
286 , return $ emit " */\n"
287 , currentIndent
288 ]
289 where
290 asLine :: (Emit gen) => Text -> StateT PrinterState Maybe gen
291 asLine s = do
292 i <- currentIndent
293 return $ i <> emit " * " <> (emit . removeComments) s <> emit "\n"
295 removeComments :: Text -> Text
296 removeComments t =
297 case T.stripPrefix "*/" t of
298 Just rest -> removeComments rest
299 Nothing -> case T.uncons t of
300 Just (x, xs) -> x `T.cons` removeComments xs
301 Nothing -> ""
303unary' :: (Emit gen) => UnaryOperator -> (AST -> Text) -> Operator PrinterState AST gen
304unary' op mkStr = Wrap match (const)
305 where
306 match :: (Emit gen) => Pattern PrinterState AST (gen, AST)
307 match = mkPattern match'
308 where
309 match' (Unary _ op' val) | op' == op = Just (emit $ mkStr val, val)
310 match' _ = Nothing
312unary :: (Emit gen) => UnaryOperator -> Text -> Operator PrinterState AST gen
313unary op str = unary' op (\v -> str <> "(" <> prettyPrintCpp1 v <> ")")
315negateOperator :: (Emit gen) => Operator PrinterState AST gen
316negateOperator = unary' Negate (\v -> if isNegate v then "- " else "-")
317 where
318 isNegate (Unary _ Negate _) = True
319 isNegate _ = False
321binary :: (Emit gen) => BinaryOperator -> Text -> Operator PrinterState AST gen
322binary op str = AssocL match (\v1 v2 -> v1 <> emit (" " <> str <> " ") <> v2)
323 where
324 match :: Pattern PrinterState AST (AST, AST)
325 match = mkPattern match'
326 where
327 match' (Binary _ op' v1 v2) | op' == op = Just (v1, v2)
328 match' _ = Nothing
330prettyStatements :: (Emit gen) => [AST] -> StateT PrinterState Maybe gen
331prettyStatements sts = do
332 cpps <- forM sts prettyPrintCpp'
333 indentString <- currentIndent
334 return $ intercalate (emit "\n") $ map ((<> emit ";") . (indentString <>)) cpps
336-- | Generate a pretty-printed string representing a collection of Objective-C expressions at the same indentation level
337prettyPrintCppWithSourceMaps :: [AST] -> (Text, [SMap])
338prettyPrintCppWithSourceMaps cpp =
339 let StrPos (_, s, mp) = (fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements) cpp
340 in (s, mp)
342prettyPrintCpp :: [AST] -> Text
343prettyPrintCpp = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyStatements
345-- | Generate an indented, pretty-printed string representing a Objective-C expression
346prettyPrintCpp' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
347prettyPrintCpp' = A.runKleisli $ runPattern matchValue
348 where
349 matchValue :: (Emit gen) => Pattern PrinterState AST gen
350 matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
351 operators :: (Emit gen) => OperatorTable PrinterState AST gen
352 operators =
353 OperatorTable [ [ unary New "box" ]
354 , [ unary Not "!"
355 , unary BitwiseNot "~"
356 , unary Positive "+"
357 , negateOperator ]
358 , [ binary Multiply "*"
359 , binary Divide "/"
360 , binary Modulus "%" ]
361 , [ binary Add "+"
362 , binary Subtract "-" ]
363 , [ binary ShiftLeft "<<"
364 , binary ShiftRight ">>"
365 , binary ZeroFillShiftRight ">>>" ]
366 , [ binary LessThan "<"
367 , binary LessThanOrEqualTo "<="
368 , binary GreaterThan ">"
369 , binary GreaterThanOrEqualTo ">=" ]
370 , [ binary EqualTo "=="
371 , binary NotEqualTo "!=" ]
372 , [ binary BitwiseAnd "&" ]
373 , [ binary BitwiseXor "^" ]
374 , [ binary BitwiseOr "|" ]
375 , [ binary And "&&" ]
376 , [ binary Or "||" ]
377 ]
379prettyPrintCpp1 :: AST -> Text
380prettyPrintCpp1 = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyPrintCpp'
382stringLiteral :: PSString -> Text
383stringLiteral pss | Just s <- decodeString pss =
384 (if T.all isAscii s
385 then ""
386 else ("u8")) <> stringLiteral' s
387 where
388 stringLiteral' :: Text -> Text
389 stringLiteral' s = "\"" <> T.concatMap encodeChar s <> "\""
390 encodeChar :: Char -> Text
391 encodeChar '\0' = "\\0"
392 encodeChar '\b' = "\\b"
393 encodeChar '\t' = "\\t"
394 encodeChar '\n' = "\\n"
395 encodeChar '\v' = "\\v"
396 encodeChar '\f' = "\\f"
397 encodeChar '\r' = "\\r"
398 encodeChar '"' = "\\\""
399 encodeChar '\\' = "\\\\"
400 encodeChar c = T.singleton $ c
401stringLiteral _ = "\"\\uFFFD\""
403unbox' :: Text -> AST -> Text
404unbox' _ v@(NumericLiteral{}) = prettyPrintCpp1 v
405unbox' _ v@(BooleanLiteral{}) = prettyPrintCpp1 v
406unbox' _ v@(StringLiteral{}) = prettyPrintCpp1 v
407unbox' t v = unbox t <> "(" <> prettyPrintCpp1 v <> ")"
409unboxType :: Text -> Maybe Text
410unboxType t
411 | t == C.eqInt ||
412 t == C.semiringInt ||
413 t == C.ringInt
414 = Just int
415 | t == C.semiringNumber ||
416 t == C.ringNumber ||
417 t == C.euclideanRingNumber
418 = Just float
419 | otherwise = Nothing
421renderOp :: Text -> Maybe Text
422renderOp op
423 | op == C.eq = Just " == "
424 | op == C.notEq = Just " != "
425 | op == C.add = Just " + "
426 | op == C.sub = Just " - "
427 | op == C.mul = Just " * "
428 | op == C.div = Just " / "
429 | otherwise = Nothing
431interfaceSource :: Text -> [Ident] -> [Ident] -> Text
432interfaceSource mn exports foreigns =
433 "// Generated by pscpp compiler\n\n" <>
434 "#ifndef " <> mn <> "_H\n" <>
435 "#define " <> mn <> "_H\n\n" <>
436 "#include \"purescript.h\"\n" <>
437 "\n" <>
438 "namespace " <> mn <> " {\n\n" <>
439 "using namespace purescript;\n\n" <>
440 (T.concat $ (\export -> "auto " <> identToCpp export <> "() -> boxed;\n") <$> (exports \\ foreigns)) <>
441 "\n" <>
442 (if null foreigns then "" else ("// Foreign values\n\nauto " <> foreignDict <> "() -> " <> dictType <> "&;\n\n")) <>
443 (T.concat $ (\foreign' -> "inline auto " <>
444 identToCpp foreign' <>
445 "() -> " <> varDecl <> " { " <>
446 dispatchOnceBegin <>
447 foreignDict <> "()[" <>
448 (stringLiteral . mkString $ runIdent foreign') <> "]; " <>
449 dispatchOnceEnd <>
450 " };\n") <$> foreigns) <>
451 "\n" <>
452 "} // end namespace " <> mn <>
453 "\n\n" <>
454 "#endif // " <> mn <> "_H\n\n"
456implHeaderSource :: Text -> [Text] -> Text -> Text
457implHeaderSource mn imports interfaceImport =
458 T.concat imports <> "\n"<>
459 interfaceImport <> "\n\n" <>
460 "namespace " <> mn <> " {\n\n"
462implFooterSource :: Text -> [Ident] -> Text
463implFooterSource mn foreigns =
464 "\n\n" <>
465 (if null foreigns then "" else ("auto " <> foreignDict <> "() -> " <> dictType <> "& {\n" <>
466 " static " <> dictType <> " $dict$;\n" <>
467 " return $dict$;\n" <>
468 "}\n\n")) <>
469 "} // end namespace " <> mn <>
470 "\n\n" <>
471 if mn == "Main" then mainSource else "\n"
472 where
473 mainSource :: Text
474 mainSource = "\
475 \int main(int argc, const char * argv[]) {\n\
476 \ Main::main()();\n\
477 \ return 0;\n\
478 \}\n\n\
479 \"
481varDecl :: Text
482varDecl = "const boxed&"
484renderArg :: Text -> Text
485renderArg arg
486 | arg == unusedName = varDecl
487 | otherwise = varDecl <> " " <> arg
489foreignDict :: Text
490foreignDict = "foreign"
492dispatchOnceBegin :: Text
493dispatchOnceBegin = "static const boxed $value$ = "
495dispatchOnceEnd :: Text
496dispatchOnceEnd = "return $value$;"