module BNFC.Backend.Common.StrUtils where

import Data.Char (ord)

-- | Function that, given an input string, renders it either as a char (if
-- it has legth 1) or a string. It should also excape characters correctly.
-- The first returned value is the 'type' of the string: either C for char
-- or S for string. (used in the C printer to choose the right rendering
-- function)
-- e.g.
-- >>> renderCharOrString "a"
-- ('C',"'a'")
-- >>> renderCharOrString "abc"
-- ('S',"\"abc\"")
-- >>> renderCharOrString "'"
-- ('C',"'\\''")
-- >>> renderCharOrString "\"\\'"
-- ('S',"\"\\\"\\\\\\'\"")
renderCharOrString :: String -> (Char, String)
renderCharOrString :: String -> (Char, String)
renderCharOrString [Char
c] | Char -> Int
ord Char
c Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
255 = (Char
'C', Char -> String
forall a. Show a => a -> String
show Char
c)     -- using show should quote '
renderCharOrString String
s = (Char
'S', String
"\"" String -> String -> String
forall a. [a] -> [a] -> [a]
++ String -> String
escapeChars String
s String -> String -> String
forall a. [a] -> [a] -> [a]
++ String
"\"")

-- | Helper function that escapes characters in strings
-- >>> escapeChars "\\"
-- "\\\\"
-- >>> escapeChars "\""
-- "\\\""
-- >>> escapeChars "'"
-- "\\'"
escapeChars :: String -> String
escapeChars :: String -> String
escapeChars [] = []
escapeChars (Char
'\\':String
xs) = Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
escapeChars String
xs
escapeChars (Char
'\"':String
xs) = Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: Char
'\"' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
escapeChars String
xs
escapeChars (Char
'\'':String
xs) = Char
'\\' Char -> String -> String
forall a. a -> [a] -> [a]
: Char
'\'' Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
escapeChars String
xs
escapeChars (Char
x:String
xs) = Char
x Char -> String -> String
forall a. a -> [a] -> [a]
: String -> String
escapeChars String
xs