01: package persistence.antlr;
02:
03: /* ANTLR Translator Generator
04: * Project led by Terence Parr at http://www.jGuru.com
05: * Software rights: http://www.antlr.org/license.html
06: *
07: */
08:
09: // C++ code generator by Pete Wells: pete@yamuna.demon.co.uk
10: class CppCharFormatter implements CharFormatter {
11:
12: /** Given a character value, return a string representing the character
13: * that can be embedded inside a string literal or character literal
14: * This works for Java/C/C++ code-generation and languages with compatible
15: * special-character-escapment.
16: *
17: * Used internally in CppCharFormatter and in
18: * CppCodeGenerator.converJavaToCppString.
19: *
20: * @param c The character of interest.
21: * @param forCharLiteral true to escape for char literal, false for string literal
22: */
23: public String escapeChar(int c, boolean forCharLiteral) {
24: // System.out.println("CppCharFormatter.escapeChar("+c+")");
25: switch (c) {
26: case '\n':
27: return "\\n";
28: case '\t':
29: return "\\t";
30: case '\r':
31: return "\\r";
32: case '\\':
33: return "\\\\";
34: case '\'':
35: return forCharLiteral ? "\\'" : "'";
36: case '"':
37: return forCharLiteral ? "\"" : "\\\"";
38: default:
39: if (c < ' ' || c > 126) {
40: if (c > 255) {
41: String s = Integer.toString(c, 16);
42: // put leading zeroes in front of the thing..
43: while (s.length() < 4)
44: s = '0' + s;
45: return "\\u" + s;
46: } else {
47: return "\\" + Integer.toString(c, 8);
48: }
49: } else {
50: return String.valueOf((char) c);
51: }
52: }
53: }
54:
55: /** Converts a String into a representation that can be use as a literal
56: * when surrounded by double-quotes.
57: *
58: * Used for escaping semantic predicate strings for exceptions.
59: *
60: * @param s The String to be changed into a literal
61: */
62: public String escapeString(String s) {
63: String retval = new String();
64: for (int i = 0; i < s.length(); i++)
65: retval += escapeChar(s.charAt(i), false);
66:
67: return retval;
68: }
69:
70: /** Given a character value, return a string representing the character
71: * literal that can be recognized by the target language compiler.
72: * This works for languages that use single-quotes for character literals.
73: * @param c The character of interest.
74: */
75: public String literalChar(int c) {
76: String ret = "0x" + Integer.toString(c, 16);
77: if (c >= 0 && c <= 126)
78: ret += " /* '" + escapeChar(c, true) + "' */ ";
79: return ret;
80: }
81:
82: /** Converts a String into a string literal
83: * This works for languages that use double-quotes for string literals.
84: * Code-generators for languages should override this method.
85: *
86: * Used for the generation of the tables with token names
87: *
88: * @param s The String to be changed into a literal
89: */
90: public String literalString(String s) {
91: return "\"" + escapeString(s) + "\"";
92: }
93:
94: }
|