[project @ 2000-08-07 23:37:19 by qrczak]
[ghc-hetmet.git] / ghc / compiler / absCSyn / CStrings.lhs
1 This module deals with printing C string literals 
2
3 \begin{code}
4 module CStrings(
5         CLabelString, isCLabelString, pprCLabelString,
6
7         cSEP, pp_cSEP,
8
9         pprFSInCStyle, pprStringInCStyle
10   ) where
11
12 #include "HsVersions.h"
13
14 import Char     ( ord, chr, isAlphaNum )
15 import Outputable
16 \end{code}
17
18
19 \begin{code}
20 type CLabelString = FAST_STRING         -- A C label, completely unencoded
21
22 pprCLabelString lbl = ptext lbl
23
24 isCLabelString :: CLabelString -> Bool  -- Checks to see if this is a valid C label
25 isCLabelString lbl 
26   = all ok (_UNPK_ lbl)
27   where
28     ok c = isAlphaNum c || c == '_' || c == '.'
29         -- The '.' appears in e.g. "foo.so" in the 
30         -- module part of a ExtName.  Maybe it should be separate
31
32 cSEP    = SLIT("_")     -- official C separator
33 pp_cSEP = char '_'
34 \end{code}
35
36 \begin{code}
37 pprFSInCStyle :: FAST_STRING -> SDoc
38 -- Assumes it contains only characters '\0'..'\xFF'!
39 pprFSInCStyle fs = pprStringInCStyle (_UNPK_ fs)
40
41 pprStringInCStyle :: String -> SDoc
42 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
43
44 charToC :: Char -> String
45 charToC '\"' = "\\\""
46 charToC '\'' = "\\\'"
47 charToC '\\' = "\\\\"
48 charToC c | c >= ' ' && c <= '~' = [c]
49           | c > '\xFF' = panic ("charToC "++show c)
50           | otherwise = ['\\',
51                          chr (ord '0' + ord c `div` 64),
52                          chr (ord '0' + ord c `div` 8 `mod` 8),
53                          chr (ord '0' + ord c         `mod` 8)]
54 \end{code}