如果可以获得更通用的令牌,我怎样才能在lexing期间将连接的令牌分开

时间:2013-01-09 03:36:18

标签: antlr token lexer greedy

我正在处理的语言允许某些标记粘在一起(例如“intfloat”),我正在寻找一种方法让词法分析器不将它们变成ID,这样它们就可以在分析时单独使用。我可以提出的最简单的语法证明它是(WS省略):

B: 'B';
C: 'C';
ID: ('a'..'z')+;
doc : (B | C | ID)* EOF;

反对:

bc
abc
bcd

我想从词法分析器中得到什么:

B C
ID (starts with not-a-keyword so it's an ID)
<error> (cannot concat non-keywords)

但我得到的是3个ID,正如预期的那样。

我一直在考虑让ID不贪婪,但是每个角色都会退化为单独的代币。我想我以后可以将它们粘在一起,但感觉应该有更好的方法。

有什么想法吗?

由于

2 个答案:

答案 0 :(得分:2)

这是一个解决方案的开始,使用词法分析器将文本分解为标记。这里的技巧是规则ID每次调用可以发出多个令牌。这是非标准的词法分析器行为,因此有一些警告:

  • 我确信此不会在ANTLR4中工作。

  • 此代码假定所有令牌都排队到tokenQueue

  • 规则ID不会阻止关键字重复,因此intintint会生成令牌INT INT INT。如果这很糟糕,你会想要在词法分析器或解析器方面处理它,这取决于你的语法更有意义。

  • 关键字越短,此解决方案就越脆弱。输入internal是无效的ID,因为它以关键字int开头,但后跟非关键字字符串。

  • 语法产生的警告我没有被删除。如果您使用此代码,我建议您尝试删除它们。

这是语法:

MultiToken.g

grammar MultiToken;


@lexer::members{
    private java.util.LinkedList<Token> tokenQueue = new java.util.LinkedList<Token>();

    @Override
    public Token nextToken() {
            Token t = super.nextToken();
            if (tokenQueue.isEmpty()){
                if (t.getType() == Token.EOF){
                    return t;
                } else { 
                    throw new IllegalStateException("All tokens must be queued!");
                }
            } else { 
                return tokenQueue.removeFirst();
            }
    }

    public void emit(int ttype, int tokenIndex) {
        //This is lifted from ANTLR's Lexer class, 
        //but modified to handle queueing and multiple tokens per rule.
        Token t;

        if (tokenIndex > 0){
            CommonToken last = (CommonToken) tokenQueue.getLast();
            t = new CommonToken(input, ttype, state.channel, last.getStopIndex() + 1, getCharIndex() - 1);
        } else { 
            t = new CommonToken(input, ttype, state.channel, state.tokenStartCharIndex, getCharIndex() - 1);
        }

        t.setLine(state.tokenStartLine);
        t.setText(state.text);
        t.setCharPositionInLine(state.tokenStartCharPositionInLine);
        emit(t);
    }

    @Override
    public void emit(Token t){
        super.emit(t);
        tokenQueue.addLast(t);
    }
}

doc     : (INT | FLOAT | ID | NUMBER)* EOF;

fragment
INT     : 'int';

fragment
FLOAT   : 'float';

NUMBER  : ('0'..'9')+;

ID  
@init {
    int index = 0; 
    boolean rawId = false;
    boolean keyword = false;
}
        : ({!rawId}? INT {emit(INT, index++); keyword = true;}
            | {!rawId}? FLOAT {emit(FLOAT, index++); keyword = true;}
            | {!keyword}? ('a'..'z')+ {emit(ID, index++); rawId = true;} 
          )+
        ;

WS      : (' '|'\t'|'\f'|'\r'|'\n')+ {skip();};

测试用例1:混合关键字

输入

intfloat a
int b
float c
intfloatintfloat d

输出(标记)

[INT : int] [FLOAT : float] [ID : a] 
[INT : int] [ID : b]
[FLOAT : float] [ID : c] 
[INT : int] [FLOAT : float] [INT : int] [FLOAT : float] [ID : d] 

测试用例2:包含关键字的ID

输入

aintfloat
bint
cfloat
dintfloatintfloat

输出(标记)

[ID : aintfloat] 
[ID : bint] 
[ID : cfloat] 
[ID : dintfloatintfloat] 

测试案例3:错误ID#1

输入

internal

输出(令牌和Lexer错误)

[INT : int] [ID : rnal] 
line 1:3 rule ID failed predicate: {!keyword}?

测试案例4:错误ID#2

输入

floatation

输出(令牌和Lexer错误)

[FLOAT : float] [ID : tion] 
line 1:5 rule ID failed predicate: {!keyword}?

测试用例5:非ID规则

输入

int x
float 3 float 4 float 5
5 a 6 b 7 int 8 d

输出(标记)

[INT : int] [ID : x] 
[FLOAT : float] [NUMBER : 3] [FLOAT : float] [NUMBER : 4] [FLOAT : float] [NUMBER : 5] 
[NUMBER : 5] [ID : a] [NUMBER : 6] [ID : b] [NUMBER : 7] [INT : int] [NUMBER : 8] [ID : d] 

答案 1 :(得分:1)

这是ANTLR 4的几乎所有语法解决方案(目标语言只需要一个小谓词):

lexer grammar PackedKeywords;

INT : 'int' -> pushMode(Keywords);
FLOAT : 'float' -> pushMode(Keywords);

fragment ID_CHAR : [a-z];
ID_START : ID_CHAR {Character.isLetter(_input.LA(1))}? -> more, pushMode(Identifier);
ID : ID_CHAR;

// these are the other tokens in the grammar
WS : [ \t]+ -> channel(HIDDEN);
Newline : '\r' '\n'? | '\n' -> channel(HIDDEN);

// The Keywords mode duplicates the default mode, except it replaces ID
// with InvalidKeyword. You can handle InvalidKeyword tokens in whatever way
// suits you best.
mode Keywords;

    Keywords_INT : INT -> type(INT);
    Keywords_FLOAT : FLOAT -> type(FLOAT);
    InvalidKeyword : ID_CHAR;
    // must include every token which can follow the Keywords mode
    Keywords_WS : WS -> type(WS), channel(HIDDEN), popMode;
    Keywords_Newline : Newline -> type(Newline), channel(HIDDEN), popMode;

// The Identifier mode is only entered if we know the current token is an
// identifier with >1 characters and which doesn't start with a keyword. This is
// essentially the default mode without keywords.
mode Identifier;

    Identifier_ID : ID_CHAR+ -> type(ID);
    // must include every token which can follow the Identifiers mode
    Identifier_WS : WS -> type(WS), channel(HIDDEN), popMode;
    Identifier_Newline : Newline -> type(Newline), channel(HIDDEN), popMode;

这个语法也适用于ANTLRWorks 2词法分析器(即将推出!),除了单字符标识符之外的所有内容。由于词法分析器无法评估ID_START中的谓词,因此a<space>之类的输入将(在解释器中)生成单个标记,其中a<space>类型为WS HIDDEN频道。