[project @ 1999-03-02 17:12:54 by sof]
[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,
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 -- stringToC: the hassle is what to do w/ strings like "ESC 0"...
26
27 stringToC ""  = ""
28 stringToC [c] = charToC c
29 stringToC (c:cs)
30     -- if we have something "octifiable" in "c", we'd better "octify"
31     -- the rest of the string, too.
32   = if (c < ' ' || c > '~')
33     then (charToC c) ++ (concat (map char_to_C cs))
34     else (charToC c) ++ (stringToC cs)
35   where
36     char_to_C c | c == '\n' = "\\n"     -- use C escapes when we can
37                 | c == '\a' = "\\a"
38                 | c == '\b' = "\\b"     -- ToDo: chk some of these...
39                 | c == '\r' = "\\r"
40                 | c == '\t' = "\\t"
41                 | c == '\f' = "\\f"
42                 | c == '\v' = "\\v"
43                 | otherwise = '\\' : (octify (ord c))
44
45 charToC c = if (c >= ' ' && c <= '~')   -- non-portable...
46             then case c of
47                   '\'' -> "\\'"
48                   '\\' -> "\\\\"
49                   '"'  -> "\\\""
50                   '\n' -> "\\n"
51                   '\a' -> "\\a"
52                   '\b' -> "\\b"
53                   '\r' -> "\\r"
54                   '\t' -> "\\t"
55                   '\f' -> "\\f"
56                   '\v' -> "\\v"
57                   _    -> [c]
58             else '\\' : (octify (ord c))
59
60 -- really: charToSimpleHaskell
61
62 charToEasyHaskell c
63   = if (c >= 'a' && c <= 'z')
64     || (c >= 'A' && c <= 'Z')
65     || (c >= '0' && c <= '9')
66     then [c]
67     else case c of
68           _    -> '\\' : show (ord c)
69
70 octify :: Int -> String
71 octify n
72   = if n < 8 then
73         [chr (n + ord '0')]
74     else
75         octify (n `quot` 8) ++ [chr (n `rem` 8 + ord '0')]
76 \end{code}
77