Beispiel #1
0
  /**
   * Convert from an ANTLR char literal found in a grammar file to an equivalent char literal in the
   * target language. For most languages, this means leaving 'x' as 'x'. Actually, we need to escape
   * '\u000A' so that it doesn't get converted to \n by the compiler. Convert the literal to the
   * char value and then to an appropriate target char literal.
   *
   * <p>Expect single quotes around the incoming literal.
   */
  public String getTargetCharLiteralFromANTLRCharLiteral(CodeGenerator generator, String literal) {
    StringBuffer buf = new StringBuffer();
    buf.append('\'');
    int c = Grammar.getCharValueFromGrammarCharLiteral(literal);
    if (c < Label.MIN_CHAR_VALUE) {
      return "'\u0000'";
    }
    if (c < targetCharValueEscape.length && targetCharValueEscape[c] != null) {
      buf.append(targetCharValueEscape[c]);
    } else if (Character.UnicodeBlock.of((char) c) == Character.UnicodeBlock.BASIC_LATIN
        && !Character.isISOControl((char) c)) {
      // normal char
      buf.append((char) c);
    } else {
      // must be something unprintable...use \\uXXXX
      // turn on the bit above max "\\uFFFF" value so that we pad with zeros
      // then only take last 4 digits
      String hex = Integer.toHexString(c | 0x10000).toUpperCase().substring(1, 5);
      buf.append("\\u");
      buf.append(hex);
    }

    buf.append('\'');
    return buf.toString();
  }
Beispiel #2
0
  @Override
  public String getTargetCharLiteralFromANTLRCharLiteral(
      final CodeGenerator generator, final String literal) {
    final StringBuffer buf = new StringBuffer(10);

    final int c = Grammar.getCharValueFromGrammarCharLiteral(literal);
    if (c < Label.MIN_CHAR_VALUE) {
      buf.append("\\x{0000}");
    } else if (c < targetCharValueEscape.length && targetCharValueEscape[c] != null) {
      buf.append(targetCharValueEscape[c]);
    } else if (Character.UnicodeBlock.of((char) c) == Character.UnicodeBlock.BASIC_LATIN
        && !Character.isISOControl((char) c)) {
      // normal char
      buf.append((char) c);
    } else {
      // must be something unprintable...use \\uXXXX
      // turn on the bit above max "\\uFFFF" value so that we pad with zeros
      // then only take last 4 digits
      String hex = Integer.toHexString(c | 0x10000).toUpperCase().substring(1, 5);
      buf.append("\\x{");
      buf.append(hex);
      buf.append("}");
    }

    if (buf.indexOf("\\") == -1) {
      // no need for interpolation, use single quotes
      buf.insert(0, '\'');
      buf.append('\'');
    } else {
      // need string interpolation
      buf.insert(0, '\"');
      buf.append('\"');
    }

    return buf.toString();
  }
Beispiel #3
0
 public String getTargetCharLiteralFromANTLRCharLiteral(CodeGenerator generator, String literal) {
   int c = Grammar.getCharValueFromGrammarCharLiteral(literal);
   return String.valueOf(c);
 }