git.iko.soy/rowtype-yoga/purescript-native
on dc515f3 help sign in
506 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) = 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 ", " (("const boxed& " <>) <$> 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 _ val args) = mconcat <$> sequence
114 [ prettyPrintCpp' val
115 , return $ emit "("
116 , intercalate (emit ", ") <$> forM args prettyPrintCpp'
117 , return $ emit ")"
118 ]
119 match (Function _ (Just name) [] ret@(Block _ [Return _ (Function {})])) = mconcat <$> sequence
120 [ return $ emit "auto "
121 , return $ emit name
122 , return $ emit "() -> boxed "
123 , prettyPrintCpp' ret
124 ]
125 match (Function _ (Just name) [] (Block _ [Return _ ret])) = mconcat <$> sequence
126 [ return $ emit "auto "
127 , return $ emit name
128 , return $ emit "() -> boxed "
129 , return $ emit "{\n"
130 , withIndent $ do
131 indentString <- currentIndent
132 return $ indentString <> emit dispatchOnceBegin
133 , withIndent $ do
134 prettyPrintCpp' ret
135 , return $ emit ";\n"
136 , withIndent $ do
137 indentString <- currentIndent
138 return $ indentString <> emit dispatchOnceEnd
139 , return $ emit "\n}"
140 ]
141 -- match (Function _ (Just name) [] ret) = mconcat <$> sequence
142 match (Function _ (Just name) [] (Block ss sts)) | Return _ ret <- last sts = mconcat <$> sequence
143 [ return $ emit "auto "
144 , return $ emit name
145 , return $ emit "() -> boxed {\n"
146 , withIndent $ do
147 prettyStatements $ init sts
148 , return $ emit "\n"
149 , withIndent $ do
150 indentString <- currentIndent
151 return $ indentString <> emit dispatchOnceBegin
152 , withIndent $ do
153 prettyPrintCpp' ret
154 , return $ emit ";\n"
155 , withIndent $ do
156 indentString <- currentIndent
157 return $ indentString <> emit dispatchOnceEnd
158 , return $ emit "\n}"
159 ]
160 match (Function _ name args ret) = mconcat <$> sequence
161 [ return $ emit $ if name == (Just tcoLoop) then "[&]" else "[=]"
162 , return $ emit "("
163 , return $ emit $ intercalate ", " (("const boxed& " <>) <$> args)
164 , return $ emit ") -> boxed "
165 , prettyPrintCpp' ret
166 ]
167 match (Indexer _ prop@(Var _ name) val) = mconcat <$> sequence
168 [ prettyPrintCpp' val
169 , return $ emit "::"
170 , prettyPrintCpp' prop
171 , return $ emit "()"
172 ]
173 match (Indexer _ (ArrayLiteral _ [name]) val) = mconcat <$> sequence
174 [ prettyPrintCpp' val
175 , return $ emit "."
176 , prettyPrintCpp' name
177 , return $ emit "()"
178 ]
179 match (Indexer _ (NumericLiteral _ (Left index)) val) = mconcat <$> sequence
180 [ prettyPrintCpp' val
181 , return $ emit "["
182 , return . emit . T.pack $ show index
183 , return $ emit "]"
184 ]
185 match (Indexer _ prop val) = mconcat <$> sequence
186 [ prettyPrintCpp' val
187 , return $ emit "["
188 , prettyPrintCpp' prop
189 , return $ emit "]"
190 ]
191 match (InstanceOf _ val ty) = mconcat <$> sequence
192 [ return . emit $ unbox dictType val
193 , return $ emit ".count("
194 , prettyPrintCpp' ty
195 , return $ emit ") == 1"
196 ]
197 match (While _ cond sts) = mconcat <$> sequence
198 [ return $ emit "while ("
199 , prettyPrintCpp' cond
200 , return $ emit ") "
201 , prettyPrintCpp' sts
202 ]
203 match (For _ ident start end sts) = mconcat <$> sequence
204 [ return $ emit $ "for (boxed " <> ident <> " = "
205 , prettyPrintCpp' start
206 , return $ emit $ "; " <> ident <> " < "
207 , prettyPrintCpp' end
208 , return $ emit $ "; " <> ident <> "++) "
209 , prettyPrintCpp' sts
210 ]
211 match (ForIn _ ident obj sts) = mconcat <$> sequence
212 [ return $ emit $ "for (boxed " <> ident <> " in "
213 , prettyPrintCpp' obj
214 , return $ emit ") "
215 , prettyPrintCpp' sts
216 ]
217 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing True)) thens elses) = mconcat <$> sequence
218 [ return $ emit "if ("
219 , return $ emit $ unbox "bool" cond
220 , return $ emit ") "
221 , prettyPrintCpp' thens
222 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
223 ]
224 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing False)) thens elses) = mconcat <$> sequence
225 [ return $ emit "if (!("
226 , return $ emit $ unbox "bool" cond
227 , return $ emit ")) "
228 , prettyPrintCpp' thens
229 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
230 ]
231 match (IfElse _ (Binary _ EqualTo x y@(NumericLiteral _ n)) thens elses) = mconcat <$> sequence
232 [ return $ emit "if ("
233 , return $ emit $ unbox t x
234 , return $ emit $ " == "
235 , prettyPrintCpp' y
236 , return $ emit ") "
237 , prettyPrintCpp' thens
238 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
239 ]
240 where
241 t | Left _ <- n = int
242 | Right _ <- n = float
243 match (IfElse _ (Binary _ EqualTo a b@StringLiteral{}) thens elses) = mconcat <$> sequence
244 [ return $ emit "if ("
245 , return $ emit $ unbox string a
246 , return $ emit $ " == "
247 , prettyPrintCpp' b
248 , return $ emit ") "
249 , prettyPrintCpp' thens
250 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
251 ]
252 match (IfElse _ cond thens elses) = mconcat <$> sequence
253 [ return $ emit "if ("
254 , prettyPrintCpp' cond
255 , return $ emit ") "
256 , prettyPrintCpp' thens
257 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
258 ]
259 match (Return _ value) = mconcat <$> sequence
260 [ return $ emit "return "
261 , prettyPrintCpp' value
262 ]
263 match (ReturnNoResult _) = return $ emit "return nullptr"
264 -- match (Throw _ _) = return mempty
265 match (Throw _ value) = mconcat <$> sequence
266 [ return $ emit "throw "
267 , return $ emit "std::runtime_error(\"PatternMatchFailure: \""
268 , prettyPrintCpp' value
269 , return $ emit ")"
270 ]
271 match (Comment _ com cpp) = mconcat <$> sequence
272 [ return $ emit "\n"
273 , mconcat <$> forM com comment
274 , prettyPrintCpp' cpp
275 ]
276 match _ = mzero
278 comment :: (Emit gen) => Comment -> StateT PrinterState Maybe gen
279 comment (LineComment com) = fmap mconcat $ sequence $
280 [ currentIndent
281 , return $ emit "//" <> emit com <> emit "\n"
282 ]
283 comment (BlockComment com) = fmap mconcat $ sequence $
284 [ currentIndent
285 , return $ emit "/**\n"
286 ] ++
287 map asLine (T.lines com) ++
288 [ currentIndent
289 , return $ emit " */\n"
290 , currentIndent
291 ]
292 where
293 asLine :: (Emit gen) => Text -> StateT PrinterState Maybe gen
294 asLine s = do
295 i <- currentIndent
296 return $ i <> emit " * " <> (emit . removeComments) s <> emit "\n"
298 removeComments :: Text -> Text
299 removeComments t =
300 case T.stripPrefix "*/" t of
301 Just rest -> removeComments rest
302 Nothing -> case T.uncons t of
303 Just (x, xs) -> x `T.cons` removeComments xs
304 Nothing -> ""
306unary' :: (Emit gen) => UnaryOperator -> (AST -> Text) -> Operator PrinterState AST gen
307unary' op mkStr = Wrap match (const)
308 where
309 match :: (Emit gen) => Pattern PrinterState AST (gen, AST)
310 match = mkPattern match'
311 where
312 match' (Unary _ op' val) | op' == op = Just (emit $ mkStr val, val)
313 match' _ = Nothing
315unary :: (Emit gen) => UnaryOperator -> Text -> Operator PrinterState AST gen
316unary op str = unary' op (\v -> str <> "(" <> prettyPrintCpp1 v <> ")")
318negateOperator :: (Emit gen) => Operator PrinterState AST gen
319negateOperator = unary' Negate (\v -> if isNegate v then "- " else "-")
320 where
321 isNegate (Unary _ Negate _) = True
322 isNegate _ = False
324binary :: (Emit gen) => BinaryOperator -> Text -> Operator PrinterState AST gen
325binary op str = AssocL match (\v1 v2 -> v1 <> emit (" " <> str <> " ") <> v2)
326 where
327 match :: Pattern PrinterState AST (AST, AST)
328 match = mkPattern match'
329 where
330 match' (Binary _ op' v1 v2) | op' == op = Just (v1, v2)
331 match' _ = Nothing
333prettyStatements :: (Emit gen) => [AST] -> StateT PrinterState Maybe gen
334prettyStatements sts = do
335 cpps <- forM sts prettyPrintCpp'
336 indentString <- currentIndent
337 return $ intercalate (emit "\n") $ map ((<> emit ";") . (indentString <>)) cpps
339-- | Generate a pretty-printed string representing a collection of Objective-C expressions at the same indentation level
340prettyPrintCppWithSourceMaps :: [AST] -> (Text, [SMap])
341prettyPrintCppWithSourceMaps cpp =
342 let StrPos (_, s, mp) = (fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements) cpp
343 in (s, mp)
345prettyPrintCpp :: [AST] -> Text
346prettyPrintCpp = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyStatements
348-- | Generate an indented, pretty-printed string representing a Objective-C expression
349prettyPrintCpp' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
350prettyPrintCpp' = A.runKleisli $ runPattern matchValue
351 where
352 matchValue :: (Emit gen) => Pattern PrinterState AST gen
353 matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
354 operators :: (Emit gen) => OperatorTable PrinterState AST gen
355 operators =
356 OperatorTable [ [ unary New "box" ]
357 , [ unary Not "!"
358 , unary BitwiseNot "~"
359 , unary Positive "+"
360 , negateOperator ]
361 , [ binary Multiply "*"
362 , binary Divide "/"
363 , binary Modulus "%" ]
364 , [ binary Add "+"
365 , binary Subtract "-" ]
366 , [ binary ShiftLeft "<<"
367 , binary ShiftRight ">>"
368 , binary ZeroFillShiftRight ">>>" ]
369 , [ binary LessThan "<"
370 , binary LessThanOrEqualTo "<="
371 , binary GreaterThan ">"
372 , binary GreaterThanOrEqualTo ">=" ]
373 , [ binary EqualTo "=="
374 , binary NotEqualTo "!=" ]
375 , [ binary BitwiseAnd "&" ]
376 , [ binary BitwiseXor "^" ]
377 , [ binary BitwiseOr "|" ]
378 , [ binary And "&&" ]
379 , [ binary Or "||" ]
380 ]
382prettyPrintCpp1 :: AST -> Text
383prettyPrintCpp1 = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyPrintCpp'
385stringLiteral :: PSString -> Text
386stringLiteral pss | Just s <- decodeString pss =
387 (if T.all isAscii s
388 then ""
389 else ("u8")) <> 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 -> Maybe Text
423renderOp op
424 | op == C.eq = Just " == "
425 | op == C.notEq = Just " != "
426 | op == C.add = Just " + "
427 | op == C.sub = Just " - "
428 | op == C.mul = Just " * "
429 | op == C.div = Just " / "
430 | otherwise = Nothing
432interfaceSource :: Text -> [Ident] -> [Ident] -> Text
433interfaceSource mn exports foreigns =
434 "// Generated by pscpp compiler\n\n" <>
435 "#ifndef " <> mn <> "_H\n" <>
436 "#define " <> mn <> "_H\n\n" <>
437 "#include \"purescript.h\"\n" <>
438 "\n" <>
439 "namespace " <> mn <> " {\n\n" <>
440 "using namespace purescript;\n\n" <>
441 (T.concat $ (\export -> "auto " <> identToCpp export <> "() -> boxed;\n") <$> (exports \\ foreigns)) <>
442 "\n" <>
443 (if null foreigns then "" else ("// Foreign values\n\nauto " <> foreignDict <> "() -> " <> dictType <> "&;\n\n")) <>
444 (T.concat $ (\foreign' -> "inline auto " <>
445 identToCpp foreign' <>
446 "() -> const boxed& { " <>
447 dispatchOnceBegin <>
448 foreignDict <> "().at(\"" <> identToCpp 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()(nullptr);\n\
477 \ return 0;\n\
478 \}\n\n\
479 \"
481dictType :: Text
482dictType = "dict_t"
484arrayType :: Text
485arrayType = "array_t"
487int :: Text
488int = "int"
490float :: Text
491float = "double"
493bool :: Text
494bool = "bool"
496string :: Text
497string = "string"
499foreignDict :: Text
500foreignDict = "_foreign_"
502dispatchOnceBegin :: Text
503dispatchOnceBegin = "static const boxed _value_ = "
505dispatchOnceEnd :: Text
506dispatchOnceEnd = "return _value_;"