[project @ 2004-08-13 10:45:16 by simonmar]
[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         pp_cSEP,
8
9         pprFSInCStyle, pprStringInCStyle
10   ) where
11
12 #include "HsVersions.h"
13
14 import Char     ( ord, chr, isAlphaNum )
15 import FastString
16 import Outputable
17 \end{code}
18
19
20 \begin{code}
21 type CLabelString = FastString          -- A C label, completely unencoded
22
23 pprCLabelString :: CLabelString -> SDoc
24 pprCLabelString lbl = ftext lbl
25
26 isCLabelString :: CLabelString -> Bool  -- Checks to see if this is a valid C label
27 isCLabelString lbl 
28   = all ok (unpackFS lbl)
29   where
30     ok c = isAlphaNum c || c == '_' || c == '.'
31         -- The '.' appears in e.g. "foo.so" in the 
32         -- module part of a ExtName.  Maybe it should be separate
33
34 pp_cSEP = char '_'
35 \end{code}
36
37 \begin{code}
38 pprFSInCStyle :: FastString -> SDoc
39 -- Assumes it contains only characters '\0'..'\xFF'!
40 pprFSInCStyle fs = pprStringInCStyle (unpackFS fs)
41
42 pprStringInCStyle :: String -> SDoc
43 pprStringInCStyle s = doubleQuotes (text (concatMap charToC s))
44
45 charToC :: Char -> String
46 charToC '\"' = "\\\""
47 charToC '\'' = "\\\'"
48 charToC '\\' = "\\\\"
49 charToC c | c >= ' ' && c <= '~' = [c]
50           | c > '\xFF' = panic ("charToC "++show c)
51           | otherwise = ['\\',
52                          chr (ord '0' + ord c `div` 64),
53                          chr (ord '0' + ord c `div` 8 `mod` 8),
54                          chr (ord '0' + ord c         `mod` 8)]
55 \end{code}