Commits

Tobias Dammers committed cd4618e

AST & PHP writer for ternary operator

Comments (0)

Files changed (5)

hpaco-lib/Text/HPaco/AST/Expression.hs

                 | AListExpression [(Expression,Expression)]
                 | VariableReference String
                 | EscapeExpression EscapeMode Expression
+                | TernaryExpression Expression Expression Expression
                 | BinaryExpression BinaryOperator Expression Expression
                 | UnaryExpression UnaryOperator Expression
                 | FunctionCallExpression Expression [Expression]

hpaco-lib/Text/HPaco/Readers/Capo/Statements.hs

 
 block = StatementSequence <$> braced statements
 
-keyword :: String -> Parser ()
-keyword str = do
-    string str
-    assertEndOfWord
-
-assertEndOfWord :: Parser ()
-assertEndOfWord = notFollowedBy $ letter <|> digit <|> char '_'
-
 withSemicolon :: Parser a -> Parser a
 withSemicolon p = do
     v <- p 

hpaco-lib/Text/HPaco/Readers/Common.hs

     , identifier
     , path
     , anyQuotedString, singleQuotedString, doubleQuotedString
-    , assertStartOfInput
-    , assertStartOfLine
+    , assertStartOfInput, assertStartOfLine
+    , assertEndOfWord, assertEndOfOperator
+    , keyword, operatorKeyword
     )
 where
 
 
 path :: Parser s String
 path = many1 $ try $ noneOf " \t\r\n%()"
+
+keyword :: String -> Parser s ()
+keyword str = do
+    string str
+    assertEndOfWord
+
+assertEndOfWord :: Parser s ()
+assertEndOfWord = notFollowedBy $ letter <|> digit <|> char '_'
+
+operatorKeyword :: String -> Parser s ()
+operatorKeyword str = do
+    string str
+    assertEndOfOperator
+
+assertEndOfOperator :: Parser s ()
+assertEndOfOperator = notFollowedBy $ oneOf "!@#$%^&*_-+=;:,./?\\|<>~`"
+

hpaco-lib/Text/HPaco/Readers/Paco/Expressions.hs

 import Text.HPaco.Readers.Common
 import Text.HPaco.AST.Expression
 
-expression = booleanExpression
+expression = ternaryExpression
+
+ternaryExpression = do
+    ex1 <- booleanExpression
+    ss_
+    try (ternaryTail ex1) <|> return ex1
+    where
+        ternaryTail ex1 = do
+            operatorKeyword "?"
+            ss_
+            ex2 <- ternaryExpression
+            ss_
+            char ':'
+            ss_
+            ex3 <- ternaryExpression
+            ss_
+            return $ TernaryExpression ex1 ex2 ex3
 
 booleanExpression =
     binaryExpression

hpaco-lib/Text/HPaco/Writers/PHP.hs

             writeExpression e
             write "))"
 
+        TernaryExpression cond trueBranch falseBranch -> do
+            write "(("
+            writeExpression cond
+            write ") ? ("
+            writeExpression trueBranch
+            write ") : ("
+            writeExpression falseBranch
+            write "))"
+
         BinaryExpression (Flipped op) left right ->
             writeExpression $ BinaryExpression op right left