on master help sign in
CodegenC: support arbitrary bytes in string literals.
commit543f41d23351ac1af4654e63a7d46cdfbec16c00 authorMatus Tejiscak <ziman@functor.sk> dateSun 19 Jan 2014, 14:01 (13 years ago) parent10c257b
1 file changed+15−1
src/IRTS/CodegenC.hs+15−1
src/IRTS/CodegenC.hs+15−1
@@ -10,6 +10,7 @@ import Idris.Core.TT
1010import Paths_idris
1111import Util.System
1212
13+import Numeric
1314import Data.Char
1415import Data.List (intercalate)
1516import System.Process
@@ -104,6 +105,19 @@ toC f code
104105 indent 1 ++ "INITFRAME;\n" ++
105106 concatMap (bcc 1) code ++ "}\n\n"
106107
108+showCStr :: String -> String
109+showCStr s = '"' : foldr ((++) . showChar) "\"" s
110+ where
111+ showChar :: Char -> String
112+ showChar '"' = "\\\""
113+ showChar '\\' = "\\\\"
114+ showChar c
115+ | ord c < 0x10 = "\\x0" ++ showHex (ord c) ""
116+ | ord c < 0x20 = "\\x" ++ showHex (ord c) ""
117+ | ord c < 0x80 = [c]
118+ | ord c < 0x100 = "\\x" ++ showHex (ord c) ""
119+ | otherwise = error $ "non-8-bit character in string literal: " ++ show c
120+
107121bcc :: Int -> BC -> String
108122bcc i (ASSIGN l r) = indent i ++ creg l ++ " = " ++ creg r ++ ";\n"
109123bcc i (ASSIGNCONST l c)
@@ -114,7 +128,7 @@ bcc i (ASSIGNCONST l c)
114128 | otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"
115129 mkConst (Fl f) = "MKFLOAT(vm, " ++ show f ++ ")"
116130 mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"
117− mkConst (Str s) = "MKSTR(vm, " ++ show s ++ ")"
131+ mkConst (Str s) = "MKSTR(vm, " ++ showCStr s ++ ")"
118132 mkConst (B8 x) = "idris_b8const(vm, " ++ show x ++ ")"
119133 mkConst (B16 x) = "idris_b16const(vm, " ++ show x ++ ")"
120134 mkConst (B32 x) = "idris_b32const(vm, " ++ show x ++ ")"