如何编写引用字符的词法分析器规则?

How to write a lexer rule that references a character?

我想创建一个词法分析器规则,它可以读取定义了自己的定界符(特别是 Oracle 引号定界字符串)的字符串文字:

q'!My string which can contain 'single quotes'!'

其中 ! 作为分隔符,但理论上可以是任何字符。

是否可以通过词法分析器规则来做到这一点,而不引入对给定语言目标的依赖?

Is it possible to do this via a lexer rule, without introducing a dependency on a given language target?

不,这种事情需要目标相关代码。

以防万一您或阅读此问答的其他人想知道如何使用目标代码完成此操作,这里有一个快速演示:

lexer grammar TLexer;

@members {
  boolean ahead(String text) {
    for (int i = 0; i < text.length(); i++) {
      if (_input.LA(i + 1) != text.charAt(i)) {
        return false;
      }
    }
    return true;
  }
}

TEXT
 : [nN]? ( ['] ( [']['] | ~['] )* [']
         | [qQ] ['] QUOTED_TEXT [']
         )
 ;

// Skip everything other than TEXT tokens
OTHER
 : . -> skip
 ;

fragment QUOTED_TEXT
 : '[' ( {!ahead("]'")}?                      . )* ']'
 | '{' ( {!ahead("}'")}?                      . )* '}'
 | '<' ( {!ahead(">'")}?                      . )* '>'
 | '(' ( {!ahead(")'")}?                      . )* ')'
 |  .  ( {!ahead(getText().charAt(0) + "'")}? . )*  .
 ;

可以用class进行测试:

public class Main {

    static void test(String input) {
        TLexer lexer = new TLexer(new ANTLRInputStream(input));
        CommonTokenStream tokenStream = new CommonTokenStream(lexer);
        tokenStream.fill();

        System.out.printf("input: `%s`\n", input);

        for (Token token : tokenStream.getTokens()) {
            if (token.getType() != TLexer.EOF) {
                System.out.printf("  token: -> %s\n", token.getText());
            }
        }

        System.out.println();
    }

    public static void main(String[] args) throws Exception {
        test("foo q'!My string which can contain 'single quotes'!' bar");
        test("foo q'(My string which can contain 'single quotes')' bar");
        test("foo 'My string which can contain ''single quotes' bar");
    }
}

这将打印:

input: `foo q'!My string which can contain 'single quotes'!' bar`
  token: -> q'!My string which can contain 'single quotes'!'

input: `foo q'(My string which can contain 'single quotes')' bar`
  token: -> q'(My string which can contain 'single quotes')'

input: `foo 'My string which can contain ''single quotes' bar`
  token: -> 'My string which can contain ''single quotes'

替代

中的.
|  .  ( {!ahead(getText().charAt(0) + "'")}? . )*  .

可能有点过于宽松,但可以通过将其替换为否定字符集或常规字符集来进行调整。