1 This module deals with printing C string literals
5 CLabelString, isCLabelString, pprCLabelString,
9 stringToC, charToC, pprFSInCStyle,
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 stringToC :: String -> String
42 -- Convert a string to the form required by C in a C literal string
43 -- Tthe hassle is what to do w/ strings like "ESC 0"...
45 stringToC [c] = charToC c
47 -- if we have something "octifiable" in "c", we'd better "octify"
48 -- the rest of the string, too.
49 = if (c < ' ' || c > '~')
50 then (charToC c) ++ (concat (map char_to_C cs))
51 else (charToC c) ++ (stringToC cs)
53 char_to_C c | c == '\n' = "\\n" -- use C escapes when we can
55 | c == '\b' = "\\b" -- ToDo: chk some of these...
60 | otherwise = '\\' : (octify (ord c))
62 charToC :: Char -> String
63 -- Convert a character to the form reqd in a C character literal
64 charToC c = if (c >= ' ' && c <= '~') -- non-portable...
77 else '\\' : (octify (ord c))
79 charToEasyHaskell :: Char -> String
80 -- Convert a character to the form reqd in a Haskell character literal
82 = if (c >= 'a' && c <= 'z')
83 || (c >= 'A' && c <= 'Z')
84 || (c >= '0' && c <= '9')
87 _ -> '\\' : show (ord c)
89 octify :: Int -> String
94 octify (n `quot` 8) ++ [chr (n `rem` 8 + ord '0')]