1 This module deals with printing C string literals
5 CLabelString, isCLabelString, pprCLabelString,
9 stringToC, charToC, pprFSInCStyle, pprStringInCStyle,
13 #include "HsVersions.h"
15 import Char ( ord, chr, isAlphaNum )
21 type CLabelString = FAST_STRING -- A C label, completely unencoded
23 pprCLabelString lbl = ptext lbl
25 isCLabelString :: CLabelString -> Bool -- Checks to see if this is a valid C label
29 ok c = isAlphaNum c || c == '_' || c == '.'
30 -- The '.' appears in e.g. "foo.so" in the
31 -- module part of a ExtName. Maybe it should be separate
33 cSEP = SLIT("_") -- official C separator
38 pprFSInCStyle :: FAST_STRING -> SDoc
39 pprFSInCStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
41 pprStringInCStyle :: String -> SDoc
42 pprStringInCStyle s = doubleQuotes (text (stringToC s))
44 stringToC :: String -> String
45 -- Convert a string to the form required by C in a C literal string
46 -- Tthe hassle is what to do w/ strings like "ESC 0"...
48 stringToC [c] = charToC c
50 -- if we have something "octifiable" in "c", we'd better "octify"
51 -- the rest of the string, too.
52 = if (c < ' ' || c > '~')
53 then (charToC c) ++ (concat (map char_to_C cs))
54 else (charToC c) ++ (stringToC cs)
56 char_to_C c | c == '\n' = "\\n" -- use C escapes when we can
58 | c == '\b' = "\\b" -- ToDo: chk some of these...
63 | otherwise = '\\' : (octify (ord c))
65 charToC :: Char -> String
66 -- Convert a character to the form reqd in a C character literal
67 charToC c = if (c >= ' ' && c <= '~') -- non-portable...
80 else '\\' : (octify (ord c))
82 charToEasyHaskell :: Char -> String
83 -- Convert a character to the form reqd in a Haskell character literal
85 = if (c >= 'a' && c <= 'z')
86 || (c >= 'A' && c <= 'Z')
87 || (c >= '0' && c <= '9')
90 _ -> '\\' : show (ord c)
92 octify :: Int -> String
97 octify (n `quot` 8) ++ [chr (n `rem` 8 + ord '0')]