summaryrefslogtreecommitdiff
path: root/Language
diff options
context:
space:
mode:
Diffstat (limited to 'Language')
-rw-r--r--Language/C.hs4
-rw-r--r--Language/C/Print.hs23
2 files changed, 23 insertions, 4 deletions
diff --git a/Language/C.hs b/Language/C.hs
index 9a65115..8b2a9d5 100644
--- a/Language/C.hs
+++ b/Language/C.hs
@@ -44,6 +44,9 @@ data Stmt
| SCall Name [Expr]
-- | @SFor ty i lo hi body@: @for (ty i = lo; i < hi; i++) body@
| SFor Type Name Expr Expr [Stmt]
+ -- | @SWhile pre cond post@: @while (true) { pre; if (!cond) break; post; }@
+ -- Special case if @pre == []@: @while (cond) { post; }
+ | SWhile [Stmt] Expr [Stmt]
| SIf Expr [Stmt] [Stmt]
deriving (Show, Eq)
@@ -56,6 +59,7 @@ data Expr
| EIndex Name Expr
| EPtrTo Expr
| ESizeOf Type
+ | ECast Type Expr
deriving (Show, Eq)
diff --git a/Language/C/Print.hs b/Language/C/Print.hs
index 5852601..3d7688c 100644
--- a/Language/C/Print.hs
+++ b/Language/C/Print.hs
@@ -50,10 +50,14 @@ printType = printString . showType
printBits B64 = "64"
printBlock :: [Stmt] -> PrintS
-printBlock ss =
- printString "{\n "
- % addIndent 2 (intercalates "\n" (map printStmt ss))
- % printString "\n}"
+printBlock ss = printBlock' (intercalates "\n" (map printStmt ss))
+
+printBlock' :: PrintS -> PrintS
+printBlock' body =
+ getIndent $ \d ->
+ printString ("{\n" ++ replicate (d + 2) ' ')
+ % addIndent 2 body
+ % printString "\n}"
printStmt :: Stmt -> PrintS
printStmt (SDecl ty name rhs) =
@@ -75,6 +79,13 @@ printStmt (SFor ty name lo hi body) =
% printString "; "
% printName name % printString "++) "
% printBlock body
+printStmt (SWhile [] cond body) =
+ printString "while (" % printExpr cond % printString ") " % printBlock body
+printStmt (SWhile pre cond post) =
+ printString "while (true) "
+ % printBlock' (intercalates "\n" (map printStmt pre)
+ % printString "\nif (" % printExpr cond % printString ") break;\n"
+ % intercalates "\n" (map printStmt post))
printStmt (SIf e b1 b2) =
printString "if (" % printExpr e % printString ") "
% printBlock b1 % printString " else " % printBlock b2
@@ -93,6 +104,7 @@ printExpr (ECall name args) =
printExpr (EIndex name e) = printName name % printString "[" % printExpr e % printString "]"
printExpr (EPtrTo e) = printString "&(" % printExpr e % printString ")"
printExpr (ESizeOf t) = printString "(sizeof (" % printType t % printString "))"
+printExpr (ECast t e) = printString "(" % printType t % printString ")(" % printExpr e % printString ")"
addIndent :: Int -> PrintS -> PrintS
@@ -101,6 +113,9 @@ addIndent plusd f d = f (d + plusd)
withIndent :: Int -> PrintS -> PrintS
withIndent d f _ = f d
+getIndent :: (Int -> PrintS) -> PrintS
+getIndent f d = f d d
+
intercalates :: String -> [PrintS] -> PrintS
intercalates sep l = foldr (%) (\_ -> id) $ intersperse (printString sep) l