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