1-- | Pretty printer for the AST
2module CodeGen.Cpp.Printer
5 , prettyPrintCppWithSourceMaps
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'
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'
55 -- match (ObjectLiteral _ []) = return $ emit "std::initializer_list<std::pair<const string, boxed>>{}"
56 match (ObjectLiteral _ ps) = mconcat <$> sequence
57 [ return . emit $ dictType <> "{\n"
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
69 objectPropertyToString :: (Emit gen) => PSString -> gen
70 objectPropertyToString s = emit $ stringLiteral s <> ", "
71 match (Block _ sts) = mconcat <$> sequence
73 , withIndent $ prettyStatements sts
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
83 match (Assignment _ target@(Var _ var) value@(Function _ Nothing args body)) = mconcat <$> sequence
84 [ prettyPrintCpp' target
86 , return $ emit "[=, &"
87 , prettyPrintCpp' target
90 , return $ emit $ intercalate ", " (("const boxed& " <>) <$> args)
91 , return $ emit ") -> boxed "
92 , prettyPrintCpp' body
94 match (Assignment _ target value) = mconcat <$> sequence
95 [ prettyPrintCpp' target
97 , prettyPrintCpp' value
99 match (App _ val []) = mconcat <$> sequence
100 [ prettyPrintCpp' val
103 match (App ss (App _ (App _ (Indexer _ (Var _ fn) (Var _ fnMod)) [Indexer _ (Var _ dict) (Var _ dictMod)]) [x]) [y])
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
111 , return $ emit $ unbox t y
113 match (App _ val args) = mconcat <$> sequence
114 [ prettyPrintCpp' val
116 , intercalate (emit ", ") <$> forM args prettyPrintCpp'
119 match (Function _ (Just name) [] ret@(Block _ [Return _ (Function {})])) = mconcat <$> sequence
120 [ return $ emit "auto "
122 , return $ emit "() -> boxed "
123 , prettyPrintCpp' ret
125 match (Function _ (Just name) [] (Block _ [Return _ ret])) = mconcat <$> sequence
126 [ return $ emit "auto "
128 , return $ emit "() -> boxed "
129 , return $ emit "{\n"
131 indentString <- currentIndent
132 return $ indentString <> emit dispatchOnceBegin
135 , return $ emit ";\n"
137 indentString <- currentIndent
138 return $ indentString <> emit dispatchOnceEnd
139 , return $ emit "\n}"
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 "
145 , return $ emit "() -> boxed {\n"
147 prettyStatements $ init sts
150 indentString <- currentIndent
151 return $ indentString <> emit dispatchOnceBegin
154 , return $ emit ";\n"
156 indentString <- currentIndent
157 return $ indentString <> emit dispatchOnceEnd
158 , return $ emit "\n}"
160 match (Function _ name args ret) = mconcat <$> sequence
161 [ return $ emit $ if name == (Just tcoLoop) then "[&]" else "[=]"
163 , return $ emit $ intercalate ", " (("const boxed& " <>) <$> args)
164 , return $ emit ") -> boxed "
165 , prettyPrintCpp' ret
167 match (Indexer _ prop@(Var _ name) val) = mconcat <$> sequence
168 [ prettyPrintCpp' val
170 , prettyPrintCpp' prop
173 match (Indexer _ (ArrayLiteral _ [name]) val) = mconcat <$> sequence
174 [ prettyPrintCpp' val
176 , prettyPrintCpp' name
179 match (Indexer _ (NumericLiteral _ (Left index)) val) = mconcat <$> sequence
180 [ prettyPrintCpp' val
182 , return . emit . T.pack $ show index
185 match (Indexer _ prop val) = mconcat <$> sequence
186 [ prettyPrintCpp' val
188 , prettyPrintCpp' prop
191 match (InstanceOf _ val ty) = mconcat <$> sequence
192 [ return . emit $ unbox dictType val
193 , return $ emit ".count("
195 , return $ emit ") == 1"
197 match (While _ cond sts) = mconcat <$> sequence
198 [ return $ emit "while ("
199 , prettyPrintCpp' cond
201 , prettyPrintCpp' sts
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
211 match (ForIn _ ident obj sts) = mconcat <$> sequence
212 [ return $ emit $ "for (boxed " <> ident <> " in "
213 , prettyPrintCpp' obj
215 , prettyPrintCpp' sts
217 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing True)) thens elses) = mconcat <$> sequence
218 [ return $ emit "if ("
219 , return $ emit $ unbox "bool" cond
221 , prettyPrintCpp' thens
222 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
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
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 $ " == "
237 , prettyPrintCpp' thens
238 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
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 $ " == "
249 , prettyPrintCpp' thens
250 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
252 match (IfElse _ cond thens elses) = mconcat <$> sequence
253 [ return $ emit "if ("
254 , prettyPrintCpp' cond
256 , prettyPrintCpp' thens
257 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
259 match (Return _ value) = mconcat <$> sequence
260 [ return $ emit "return "
261 , prettyPrintCpp' value
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
271 match (Comment _ com cpp) = mconcat <$> sequence
273 , mconcat <$> forM com comment
274 , prettyPrintCpp' cpp
278 comment :: (Emit gen) => Comment -> StateT PrinterState Maybe gen
279 comment (LineComment com) = fmap mconcat $ sequence $
281 , return $ emit "//" <> emit com <> emit "\n"
283 comment (BlockComment com) = fmap mconcat $ sequence $
285 , return $ emit "/**\n"
287 map asLine (T.lines com) ++
289 , return $ emit " */\n"
293 asLine :: (Emit gen) => Text -> StateT PrinterState Maybe gen
296 return $ i <> emit " * " <> (emit . removeComments) s <> emit "\n"
298 removeComments :: Text -> Text
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
306unary' :: (Emit gen) => UnaryOperator -> (AST -> Text) -> Operator PrinterState AST gen
307unary' op mkStr = Wrap match (const)
309 match :: (Emit gen) => Pattern PrinterState AST (gen, AST)
310 match = mkPattern match'
312 match' (Unary _ op' val) | op' == op = Just (emit $ mkStr val, val)
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 "-")
321 isNegate (Unary _ Negate _) = True
324binary :: (Emit gen) => BinaryOperator -> Text -> Operator PrinterState AST gen
325binary op str = AssocL match (\v1 v2 -> v1 <> emit (" " <> str <> " ") <> v2)
327 match :: Pattern PrinterState AST (AST, AST)
328 match = mkPattern match'
330 match' (Binary _ op' v1 v2) | op' == op = Just (v1, v2)
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
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
352 matchValue :: (Emit gen) => Pattern PrinterState AST gen
353 matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
354 operators :: (Emit gen) => OperatorTable PrinterState AST gen
356 OperatorTable [ [ unary New "box" ]
358 , unary BitwiseNot "~"
361 , [ binary Multiply "*"
363 , binary Modulus "%" ]
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 "&&" ]
382prettyPrintCpp1 :: AST -> Text
383prettyPrintCpp1 = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyPrintCpp'
385stringLiteral :: PSString -> Text
386stringLiteral pss | Just s <- decodeString pss =
389 else ("u8")) <> stringLiteral' s
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
413 t == C.semiringInt ||
416 | t == C.semiringNumber ||
418 t == C.euclideanRingNumber
420 | otherwise = Nothing
422renderOp :: Text -> Maybe Text
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" <>
439 "namespace " <> mn <> " {\n\n" <>
440 "using namespace purescript;\n\n" <>
441 (T.concat $ (\export -> "auto " <> identToCpp export <> "() -> boxed;\n") <$> (exports \\ foreigns)) <>
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& { " <>
448 foreignDict <> "().at(\"" <> identToCpp foreign' <> "\"); " <>
450 " };\n") <$> foreigns) <>
452 "} // end namespace " <> mn <>
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 =
465 (if null foreigns then "" else ("auto " <> foreignDict <> "() -> " <> dictType <> "& {\n" <>
466 " static " <> dictType <> " _dict_;\n" <>
467 " return _dict_;\n" <>
469 "} // end namespace " <> mn <>
471 if mn == "Main" then mainSource else "\n"
475 \int main(int argc, const char * argv[]) {\n\
476 \ Main::main()(nullptr);\n\
500foreignDict = "_foreign_"
502dispatchOnceBegin :: Text
503dispatchOnceBegin = "static const boxed _value_ = "
505dispatchOnceEnd :: Text
506dispatchOnceEnd = "return _value_;"
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list