1 This module deals with printing C string literals
5 CLabelString, isCLabelString,
8 stringToC, charToC, pprFSInCStyle,
12 #include "HsVersions.h"
14 import Char ( ord, chr, isAlphaNum )
20 type CLabelString = FAST_STRING -- A C label, completely unencoded
22 isCLabelString :: CLabelString -> Bool -- Checks to see if this is a valid C label
26 ok c = isAlphaNum c || c == '_' || c == '.'
27 -- The '.' appears in e.g. "foo.so" in the
28 -- module part of a ExtName. Maybe it should be separate
30 cSEP = SLIT("_") -- official C separator
35 pprFSInCStyle :: FAST_STRING -> SDoc
36 pprFSInCStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
38 stringToC :: String -> String
39 -- Convert a string to the form required by C in a C literal string
40 -- Tthe hassle is what to do w/ strings like "ESC 0"...
42 stringToC [c] = charToC c
44 -- if we have something "octifiable" in "c", we'd better "octify"
45 -- the rest of the string, too.
46 = if (c < ' ' || c > '~')
47 then (charToC c) ++ (concat (map char_to_C cs))
48 else (charToC c) ++ (stringToC cs)
50 char_to_C c | c == '\n' = "\\n" -- use C escapes when we can
52 | c == '\b' = "\\b" -- ToDo: chk some of these...
57 | otherwise = '\\' : (octify (ord c))
59 charToC :: Char -> String
60 -- Convert a character to the form reqd in a C character literal
61 charToC c = if (c >= ' ' && c <= '~') -- non-portable...
74 else '\\' : (octify (ord c))
76 charToEasyHaskell :: Char -> String
77 -- Convert a character to the form reqd in a Haskell character literal
79 = if (c >= 'a' && c <= 'z')
80 || (c >= 'A' && c <= 'Z')
81 || (c >= '0' && c <= '9')
84 _ -> '\\' : show (ord c)
86 octify :: Int -> String
91 octify (n `quot` 8) ++ [chr (n `rem` 8 + ord '0')]