[project @ 2000-02-11 13:07:25 by simonpj]
[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         cSEP, pp_cSEP,
6
7         stringToC, charToC, pprFSInCStyle,
8         charToEasyHaskell
9   ) where
10
11 #include "HsVersions.h"
12
13 import Char     ( ord, chr )
14 import Outputable
15 \end{code}
16
17
18 \begin{code}
19 cSEP    = SLIT("_")     -- official C separator
20 pp_cSEP = char '_'
21
22 stringToC   :: String -> String
23 charToC, charToEasyHaskell :: Char -> String
24
25 pprFSInCStyle :: FAST_STRING -> SDoc
26 pprFSInCStyle fs = doubleQuotes (text (stringToC (_UNPK_ fs)))
27
28 -- stringToC: the hassle is what to do w/ strings like "ESC 0"...
29
30 stringToC ""  = ""
31 stringToC [c] = charToC c
32 stringToC (c:cs)
33     -- if we have something "octifiable" in "c", we'd better "octify"
34     -- the rest of the string, too.
35   = if (c < ' ' || c > '~')
36     then (charToC c) ++ (concat (map char_to_C cs))
37     else (charToC c) ++ (stringToC cs)
38   where
39     char_to_C c | c == '\n' = "\\n"     -- use C escapes when we can
40                 | c == '\a' = "\\a"
41                 | c == '\b' = "\\b"     -- ToDo: chk some of these...
42                 | c == '\r' = "\\r"
43                 | c == '\t' = "\\t"
44                 | c == '\f' = "\\f"
45                 | c == '\v' = "\\v"
46                 | otherwise = '\\' : (octify (ord c))
47
48 charToC c = if (c >= ' ' && c <= '~')   -- non-portable...
49             then case c of
50                   '\'' -> "\\'"
51                   '\\' -> "\\\\"
52                   '"'  -> "\\\""
53                   '\n' -> "\\n"
54                   '\a' -> "\\a"
55                   '\b' -> "\\b"
56                   '\r' -> "\\r"
57                   '\t' -> "\\t"
58                   '\f' -> "\\f"
59                   '\v' -> "\\v"
60                   _    -> [c]
61             else '\\' : (octify (ord c))
62
63 -- really: charToSimpleHaskell
64
65 charToEasyHaskell c
66   = if (c >= 'a' && c <= 'z')
67     || (c >= 'A' && c <= 'Z')
68     || (c >= '0' && c <= '9')
69     then [c]
70     else case c of
71           _    -> '\\' : show (ord c)
72
73 octify :: Int -> String
74 octify n
75   = if n < 8 then
76         [chr (n + ord '0')]
77     else
78         octify (n `quot` 8) ++ [chr (n `rem` 8 + ord '0')]
79 \end{code}
80