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: class JavaCharFormatter implements CharFormatter {
10:
11: /** Given a character value, return a string representing the character
12: * that can be embedded inside a string literal or character literal
13: * This works for Java/C/C++ code-generation and languages with compatible
14: * special-character-escapment.
15: * Code-generators for languages should override this method.
16: * @param c The character of interest.
17: * @param forCharLiteral true to escape for char literal, false for string literal
18: */
19: public String escapeChar(int c, boolean forCharLiteral) {
20: switch (c) {
21: // case GrammarAnalyzer.EPSILON_TYPE : return "<end-of-token>";
22: case '\n':
23: return "\\n";
24: case '\t':
25: return "\\t";
26: case '\r':
27: return "\\r";
28: case '\\':
29: return "\\\\";
30: case '\'':
31: return forCharLiteral ? "\\'" : "'";
32: case '"':
33: return forCharLiteral ? "\"" : "\\\"";
34: default:
35: if (c < ' ' || c > 126) {
36: if ((0x0000 <= c) && (c <= 0x000F)) {
37: return "\\u000" + Integer.toString(c, 16);
38: } else if ((0x0010 <= c) && (c <= 0x00FF)) {
39: return "\\u00" + Integer.toString(c, 16);
40: } else if ((0x0100 <= c) && (c <= 0x0FFF)) {
41: return "\\u0" + Integer.toString(c, 16);
42: } else {
43: return "\\u" + Integer.toString(c, 16);
44: }
45: } else {
46: return String.valueOf((char) c);
47: }
48: }
49: }
50:
51: /** Converts a String into a representation that can be use as a literal
52: * when surrounded by double-quotes.
53: * @param s The String to be changed into a literal
54: */
55: public String escapeString(String s) {
56: String retval = new String();
57: for (int i = 0; i < s.length(); i++) {
58: retval += escapeChar(s.charAt(i), false);
59: }
60: return retval;
61: }
62:
63: /** Given a character value, return a string representing the character
64: * literal that can be recognized by the target language compiler.
65: * This works for languages that use single-quotes for character literals.
66: * Code-generators for languages should override this method.
67: * @param c The character of interest.
68: */
69: public String literalChar(int c) {
70: return "'" + escapeChar(c, true) + "'";
71: }
72:
73: /** Converts a String into a string literal
74: * This works for languages that use double-quotes for string literals.
75: * Code-generators for languages should override this method.
76: * @param s The String to be changed into a literal
77: */
78: public String literalString(String s) {
79: return "\"" + escapeString(s) + "\"";
80: }
81: }
|