on master help sign in
Merge pull request #784 from ziman/c-strings
2c2a206Edwin Brady
src/IRTS/CodegenC.hs+18−1
@@ -10,6 +10,7 @@ import Idris.Core.TT
10import Paths_idris
10import Paths_idris
11import Util.System
11import Util.System
12
12
13+import Numeric
13import Data.Char
14import Data.Char
14import Data.List (intercalate)
15import Data.List (intercalate)
15import System.Process
16import System.Process
@@ -104,6 +105,22 @@ toC f code
104 indent 1 ++ "INITFRAME;\n" ++
105 indent 1 ++ "INITFRAME;\n" ++
105 concatMap (bcc 1) code ++ "}\n\n"
106 concatMap (bcc 1) code ++ "}\n\n"
106
107
108+showCStr :: String -> String
109+showCStr s = '"' : foldr ((++) . showChar) "\"" s
110+ where
111+ showChar :: Char -> String
112+ showChar '"' = "\\\""
113+ showChar '\\' = "\\\\"
114+ showChar c
115+ -- Note: we need the double quotes around the codes because otherwise
116+ -- "\n3" would get encoded as "\x0a3", which is incorrect.
117+ -- Instead, we opt for "\x0a""3" and let the C compiler deal with it.
118+ | ord c < 0x10 = "\"\"\\x0" ++ showHex (ord c) "\"\""
119+ | ord c < 0x20 = "\"\"\\x" ++ showHex (ord c) "\"\""
120+ | ord c < 0x7f = [c] -- 0x7f = \DEL
121+ | ord c < 0x100 = "\"\"\\x" ++ showHex (ord c) "\"\""
122+ | otherwise = error $ "non-8-bit character in string literal: " ++ show c
123+
107bcc :: Int -> BC -> String
124bcc :: Int -> BC -> String
108bcc i (ASSIGN l r) = indent i ++ creg l ++ " = " ++ creg r ++ ";\n"
125bcc i (ASSIGN l r) = indent i ++ creg l ++ " = " ++ creg r ++ ";\n"
109bcc i (ASSIGNCONST l c)
126bcc i (ASSIGNCONST l c)
@@ -114,7 +131,7 @@ bcc i (ASSIGNCONST l c)
114 | otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"
131 | otherwise = "MKBIGC(vm,\"" ++ show i ++ "\")"
115 mkConst (Fl f) = "MKFLOAT(vm, " ++ show f ++ ")"
132 mkConst (Fl f) = "MKFLOAT(vm, " ++ show f ++ ")"
116 mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"
133 mkConst (Ch c) = "MKINT(" ++ show (fromEnum c) ++ ")"
117− mkConst (Str s) = "MKSTR(vm, " ++ show s ++ ")"
134+ mkConst (Str s) = "MKSTR(vm, " ++ showCStr s ++ ")"
118 mkConst (B8 x) = "idris_b8const(vm, " ++ show x ++ ")"
135 mkConst (B8 x) = "idris_b8const(vm, " ++ show x ++ ")"
119 mkConst (B16 x) = "idris_b16const(vm, " ++ show x ++ ")"
136 mkConst (B16 x) = "idris_b16const(vm, " ++ show x ++ ")"
120 mkConst (B32 x) = "idris_b32const(vm, " ++ show x ++ ")"
137 mkConst (B32 x) = "idris_b32const(vm, " ++ show x ++ ")"
test/reg031/expectednew file+1
@@ -0,0 +1 @@
1+[10, -128, -55, -1, 10, 51, 10, 52]
test/reg031/reg031.idrnew file+4
@@ -0,0 +1,4 @@
1+module Main
2+
3+main : IO ()
4+main = print . map ord . unpack $ "\x0a\x80\xC9\xFF\n3\n4"
test/reg031/runnew file+4
@@ -0,0 +1,4 @@
1+#!/usr/bin/env bash
2+idris $@ reg031.idr -o reg031
3+./reg031
4+rm -f *.ibc reg031