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