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)
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 "as_array { "
56 , intercalate (emit ", ") <$> forM xs prettyPrintCpp'
59 -- match (ObjectLiteral _ []) = return $ emit "std::initializer_list<std::pair<const string, boxed>>{}"
60 match (ObjectLiteral _ ps) = mconcat <$> sequence
61 [ return $ emit "as_dict {\n"
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
73 objectPropertyToString :: (Emit gen) => PSString -> gen
74 objectPropertyToString s = emit $ stringLiteral s <> ", "
75 match (Block _ sts) = mconcat <$> sequence
77 , withIndent $ prettyStatements sts
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
87 match (Assignment _ target@(Var _ var) value@(Function _ Nothing args body)) = mconcat <$> sequence
88 [ prettyPrintCpp' target
90 , return $ emit "[=, &"
91 , prettyPrintCpp' target
94 , return $ emit $ intercalate ", " (("const boxed& " <>) <$> args)
95 , return $ emit ") -> boxed "
96 , prettyPrintCpp' body
98 match (Assignment _ target value) = mconcat <$> sequence
99 [ prettyPrintCpp' target
100 , return $ emit " = "
101 , prettyPrintCpp' value
103 match (App _ val []) = mconcat <$> sequence
104 [ prettyPrintCpp' val
107 match (App ss (App _ (App _ (Indexer _ (Var _ fn) (Var _ fnMod)) [Indexer _ (Var _ dict) (Var _ dictMod)]) [x]) [y])
109 , 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
116 match (App _ val args) = mconcat <$> sequence
117 [ prettyPrintCpp' val
119 , intercalate (emit ", ") <$> forM args prettyPrintCpp'
122 match (Function _ (Just name) [] ret@(Block _ [Return _ (Function {})])) = mconcat <$> sequence
123 [ return $ emit "auto "
125 , return $ emit "() -> boxed "
126 , prettyPrintCpp' ret
128 match (Function _ (Just name) [] (Block _ [Return _ ret])) = mconcat <$> sequence
129 [ return $ emit "auto "
131 , return $ emit "() -> boxed "
132 , return $ emit "{\n"
134 indentString <- currentIndent
135 return $ indentString <> emit dispatchOnceBegin
138 , return $ emit ";\n"
140 indentString <- currentIndent
141 return $ indentString <> emit dispatchOnceEnd
142 , return $ emit "\n}"
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 "
148 , return $ emit "() -> boxed {\n"
150 prettyStatements $ init sts
153 indentString <- currentIndent
154 return $ indentString <> emit dispatchOnceBegin
157 , return $ emit ";\n"
159 indentString <- currentIndent
160 return $ indentString <> emit dispatchOnceEnd
161 , return $ emit "\n}"
163 match (Function _ name args ret) = mconcat <$> sequence
164 [ return $ emit $ if name == (Just tcoLoop) then "[&]" else "[=]"
166 , return $ emit $ intercalate ", " (("const boxed& " <>) <$> args)
167 , return $ emit ") -> boxed "
168 , prettyPrintCpp' ret
170 match (Indexer _ prop@(Var _ name) val) = mconcat <$> sequence
171 [ prettyPrintCpp' val
173 , prettyPrintCpp' prop
176 match (Indexer _ (ArrayLiteral _ [name]) val) = mconcat <$> sequence
177 [ prettyPrintCpp' val
179 , prettyPrintCpp' name
182 match (Indexer _ (NumericLiteral _ (Left index)) val) = mconcat <$> sequence
183 [ prettyPrintCpp' val
185 , return . emit . T.pack $ show index
188 match (Indexer _ prop val) = mconcat <$> sequence
189 [ prettyPrintCpp' val
191 , prettyPrintCpp' prop
194 match (InstanceOf _ val ty) = mconcat <$> sequence
195 [ return . emit $ unbox dictType val
196 , return $ emit ".count("
198 , return $ emit ") == 1"
200 match (While _ cond sts) = mconcat <$> sequence
201 [ return $ emit "while ("
202 , prettyPrintCpp' cond
204 , prettyPrintCpp' sts
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
214 match (ForIn _ ident obj sts) = mconcat <$> sequence
215 [ return $ emit $ "for (boxed " <> ident <> " in "
216 , prettyPrintCpp' obj
218 , prettyPrintCpp' sts
220 match (IfElse _ (Binary _ EqualTo cond (BooleanLiteral Nothing True)) thens elses) = mconcat <$> sequence
221 [ return $ emit "if ("
222 , return $ emit $ unbox "bool" cond
224 , prettyPrintCpp' thens
225 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
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
234 match (IfElse _ (Binary _ EqualTo x@Var{} y@(NumericLiteral _ n)) thens elses) = mconcat <$> sequence
235 [ return $ emit "if ("
236 , return $ emit $ unbox t x
237 , return $ emit $ " == "
240 , prettyPrintCpp' thens
241 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
244 t | Left _ <- n = int
245 | Right _ <- n = float
247 match (IfElse _ cond thens elses) = mconcat <$> sequence
248 [ return $ emit "if ("
249 , prettyPrintCpp' cond
251 , prettyPrintCpp' thens
252 , maybe (return mempty) (fmap (emit " else " <>) . prettyPrintCpp') elses
254 match (Return _ value) = mconcat <$> sequence
255 [ return $ emit "return "
256 , prettyPrintCpp' value
258 match (ReturnNoResult _) = return $ emit "return nullptr"
259 -- match (Throw _ _) = return mempty
260 match (Throw _ value) = mconcat <$> sequence
261 [ return $ emit "throw "
262 , return $ emit "std::runtime_error(\"PatternMatchFailure: \""
263 , prettyPrintCpp' value
266 match (Comment _ com cpp) = mconcat <$> sequence
268 , mconcat <$> forM com comment
269 , prettyPrintCpp' cpp
273 comment :: (Emit gen) => Comment -> StateT PrinterState Maybe gen
274 comment (LineComment com) = fmap mconcat $ sequence $
276 , return $ emit "//" <> emit com <> emit "\n"
278 comment (BlockComment com) = fmap mconcat $ sequence $
280 , return $ emit "/**\n"
282 map asLine (T.lines com) ++
284 , return $ emit " */\n"
288 asLine :: (Emit gen) => Text -> StateT PrinterState Maybe gen
291 return $ i <> emit " * " <> (emit . removeComments) s <> emit "\n"
293 removeComments :: Text -> Text
295 case T.stripPrefix "*/" t of
296 Just rest -> removeComments rest
297 Nothing -> case T.uncons t of
298 Just (x, xs) -> x `T.cons` removeComments xs
301unary' :: (Emit gen) => UnaryOperator -> (AST -> Text) -> Operator PrinterState AST gen
302unary' op mkStr = Wrap match (const)
304 match :: (Emit gen) => Pattern PrinterState AST (gen, AST)
305 match = mkPattern match'
307 match' (Unary _ op' val) | op' == op = Just (emit $ mkStr val, val)
310unary :: (Emit gen) => UnaryOperator -> Text -> Operator PrinterState AST gen
311unary op str = unary' op (\v -> str <> "(" <> prettyPrintCpp1 v <> ")")
313negateOperator :: (Emit gen) => Operator PrinterState AST gen
314negateOperator = unary' Negate (\v -> if isNegate v then "- " else "-")
316 isNegate (Unary _ Negate _) = True
319binary :: (Emit gen) => BinaryOperator -> Text -> Operator PrinterState AST gen
320binary op str = AssocL match (\v1 v2 -> v1 <> emit (" " <> str <> " ") <> v2)
322 match :: Pattern PrinterState AST (AST, AST)
323 match = mkPattern match'
325 match' (Binary _ op' v1 v2) | op' == op = Just (v1, v2)
328prettyStatements :: (Emit gen) => [AST] -> StateT PrinterState Maybe gen
329prettyStatements sts = do
330 cpps <- forM sts prettyPrintCpp'
331 indentString <- currentIndent
332 return $ intercalate (emit "\n") $ map ((<> emit ";") . (indentString <>)) cpps
334-- | Generate a pretty-printed string representing a collection of Objective-C expressions at the same indentation level
335prettyPrintCppWithSourceMaps :: [AST] -> (Text, [SMap])
336prettyPrintCppWithSourceMaps cpp =
337 let StrPos (_, s, mp) = (fromMaybe (internalError "Incomplete pattern") . flip evalStateT (PrinterState 0) . prettyStatements) cpp
340prettyPrintCpp :: [AST] -> Text
341prettyPrintCpp = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyStatements
343-- | Generate an indented, pretty-printed string representing a Objective-C expression
344prettyPrintCpp' :: (Emit gen) => AST -> StateT PrinterState Maybe gen
345prettyPrintCpp' = A.runKleisli $ runPattern matchValue
347 matchValue :: (Emit gen) => Pattern PrinterState AST gen
348 matchValue = buildPrettyPrinter operators (literals <+> fmap parensPos matchValue)
349 operators :: (Emit gen) => OperatorTable PrinterState AST gen
351 OperatorTable [ [ unary New "box" ]
353 , unary BitwiseNot "~"
356 , [ binary Multiply "*"
358 , binary Modulus "%" ]
360 , binary Subtract "-" ]
361 , [ binary ShiftLeft "<<"
362 , binary ShiftRight ">>"
363 , binary ZeroFillShiftRight ">>>" ]
364 , [ binary LessThan "<"
365 , binary LessThanOrEqualTo "<="
366 , binary GreaterThan ">"
367 , binary GreaterThanOrEqualTo ">=" ]
368 , [ binary EqualTo "=="
369 , binary NotEqualTo "!=" ]
370 , [ binary BitwiseAnd "&" ]
371 , [ binary BitwiseXor "^" ]
372 , [ binary BitwiseOr "|" ]
373 , [ binary And "&&" ]
377prettyPrintCpp1 :: AST -> Text
378prettyPrintCpp1 = maybe (internalError "Incomplete pattern") runPlainString . flip evalStateT (PrinterState 0) . prettyPrintCpp'
380stringLiteral :: PSString -> Text
381stringLiteral pss | Just s <- decodeString pss = stringLiteral' s
383 stringLiteral' :: Text -> Text
384 stringLiteral' s = "\"" <> T.concatMap encodeChar s <> "\""
385 encodeChar :: Char -> Text
386 encodeChar '\b' = "\\b"
387 encodeChar '\t' = "\\t"
388 encodeChar '\n' = "\\n"
389 encodeChar '\v' = "\\v"
390 encodeChar '\f' = "\\f"
391 encodeChar '\r' = "\\r"
392 encodeChar '"' = "\\\""
393 encodeChar '\\' = "\\\\"
394 encodeChar c = T.singleton $ c
396unbox :: Text -> AST -> Text
397unbox _ v@(NumericLiteral{}) = prettyPrintCpp1 v
398unbox _ v@(BooleanLiteral{}) = prettyPrintCpp1 v
399unbox _ v@(StringLiteral{}) = prettyPrintCpp1 v
400unbox t v = "unbox<" <> t <> ">(" <> prettyPrintCpp1 v <> ")"
402unboxType :: Text -> Maybe Text
404 | t == C.semiringInt ||
407 | t == C.semiringNumber ||
409 t == C.euclideanRingNumber
411 | otherwise = Nothing
413renderOp :: Text -> Text
415 | op == C.add = " + "
416 | op == C.sub = " - "
417 | op == C.mul = " * "
418 | op == C.div = " / "
419 | otherwise = error $ "Unknown operator " <> T.unpack op
421interfaceSource :: Text -> [Ident] -> [Ident] -> Text
422interfaceSource mn exports foreigns =
423 "// Generated by pscpp compiler\n\n" <>
424 "#ifndef " <> mn <> "_H\n" <>
425 "#define " <> mn <> "_H\n\n" <>
426 "#include \"purescript.h\"\n" <>
428 "namespace " <> mn <> " {\n\n" <>
429 "using namespace purescript;\n\n" <>
430 (T.concat $ (\export -> "auto " <> identToCpp export <> "() -> boxed;\n") <$> (exports \\ foreigns)) <>
432 (if null foreigns then "" else ("// Foreign values\n\nauto " <> foreignDict <> "() -> " <> dictType <> "&;\n\n")) <>
433 (T.concat $ (\foreign' -> "inline auto " <>
434 identToCpp foreign' <>
435 "() -> const boxed& { " <>
437 foreignDict <> "().at(\"" <> identToCpp foreign' <> "\"); " <>
439 " };\n") <$> foreigns) <>
441 "} // end namespace " <> mn <>
443 "#endif // " <> mn <> "_H\n\n"
445implHeaderSource :: Text -> [Text] -> Text -> Text
446implHeaderSource mn imports interfaceImport =
447 T.concat imports <> "\n"<>
448 interfaceImport <> "\n\n" <>
449 "namespace " <> mn <> " {\n\n"
451implFooterSource :: Text -> [Ident] -> Text
452implFooterSource mn foreigns =
454 (if null foreigns then "" else ("auto " <> foreignDict <> "() -> " <> dictType <> "& {\n" <>
455 " static " <> dictType <> " _dict_;\n" <>
456 " return _dict_;\n" <>
458 "} // end namespace " <> mn <>
460 if mn == "Main" then mainSource else "\n"
464 \int main(int argc, const char * argv[]) {\n\
465 \ Main::main()(nullptr);\n\
480foreignDict = "_foreign_"
482dispatchOnceBegin :: Text
483dispatchOnceBegin = "static const boxed _value_ = "
485dispatchOnceEnd :: Text
486dispatchOnceEnd = "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