Float literal and range parameter in ANTLR

陌路散爱 提交于 2019-12-20 01:15:06

问题


I'm working on a parser for the language D and I ran in to trouble when I tried to add the "slice" operator rule. You can find the ANTLR grammar for it here. Basically the problem is that if the lexer encounters a string like this: "1..2" it gets completely lost, and it ends up being as a single float value and therefore the postfixExpression rule for a string like "a[10..11]" ends up being a ExpArrIndex object with a ExpLiteralReal argument. Can somebody explain what is exactly wrong with the numeric literals? (as far as I understand it fails somewhere around these tokens)


回答1:


You can do that by emitting two tokens (an Int and Range token) when you encounter a ".." inside a float rule. You need to override two methods in your lexer to accomplish this.

A demo with a small part of your Dee grammar:

grammar Dee;

@lexer::members {

  java.util.Queue<Token> tokens = new java.util.LinkedList<Token>();

  public void offer(int ttype, String ttext) {
    this.emit(new CommonToken(ttype, ttext));
  }

  @Override
  public void emit(Token t) {
    state.token = t;
    tokens.offer(t);
  }

  @Override
  public Token nextToken() {
    super.nextToken();
    return tokens.isEmpty() ? Token.EOF_TOKEN : tokens.poll();
  }
}
parse
 : (t=. {System.out.printf("\%-15s '\%s'\n", tokenNames[$t.type], $t.text);})* EOF
 ;

Range
 : '..'
 ;

IntegerLiteral 
 : Integer IntSuffix?
 ;

FloatLiteral 
 : Float ImaginarySuffix? 
 ;

// skipping
Space
 : ' ' {skip();}
 ;

// fragments
fragment Float
 : d=DecimalDigits ( options {greedy = true; } : FloatTypeSuffix 
                   | '..' {offer(IntegerLiteral, $d.text); offer(Range, "..");}
                   | '.' DecimalDigits DecimalExponent?
                   )
 | '.' DecimalDigits DecimalExponent?
 ;

fragment DecimalExponent : 'e' | 'E' | 'e+' | 'E+' | 'e-' | 'E-' DecimalDigits;
fragment DecimalDigits   : ('0'..'9'|'_')+ ;
fragment FloatTypeSuffix : 'f' | 'F' | 'L';
fragment ImaginarySuffix : 'i';
fragment IntSuffix       : 'L'|'u'|'U'|'Lu'|'LU'|'uL'|'UL' ;
fragment Integer         : Decimal| Binary| Octal| Hexadecimal ;
fragment Decimal         : '0' | '1'..'9' (DecimalDigit | '_')* ;
fragment Binary          : ('0b' | '0B') ('0' | '1' | '_')+ ;
fragment Octal           : '0' (OctalDigit | '_')+ ;
fragment Hexadecimal     : ('0x' | '0X') (HexDigit | '_')+;  
fragment DecimalDigit    : '0'..'9' ;
fragment OctalDigit      : '0'..'7' ;
fragment HexDigit        : ('0'..'9'|'a'..'f'|'A'..'F') ;

Test the grammar with the class:

import org.antlr.runtime.*;

public class Main {
  public static void main(String[] args) throws Exception {
    DeeLexer lexer = new DeeLexer(new ANTLRStringStream("1..2 .. 33.33 ..21.0"));
    DeeParser parser = new DeeParser(new CommonTokenStream(lexer));
    parser.parse();
  }
}

And when you run Main, the following output is produced:

IntegerLiteral  '1'
Range           '..'
IntegerLiteral  '2'
Range           '..'
FloatLiteral    '33.33'
Range           '..'
FloatLiteral    '21.0'

EDIT

Yeah, as you indicated in the comments, a lexer rule can only emit 1 single token. But, as you yourself already tried, semantic predicates can indeed be used to force the lexer to look ahead in the char-stream to ensure there is actually a ".." after an IntegerLiteral token before trying to match a FloatLiteral.

The following grammar would produce the same tokens as the first demo.

grammar Dee;

parse
 : (t=. {System.out.printf("\%-15s '\%s'\n", tokenNames[$t.type], $t.text);})* EOF
 ;

Range
 : '..'
 ;

Number
 : (IntegerLiteral Range)=> IntegerLiteral {$type=IntegerLiteral;}
 | (FloatLiteral)=>         FloatLiteral   {$type=FloatLiteral;}
 |                          IntegerLiteral {$type=IntegerLiteral;}
 ;

// skipping
Space
 : ' ' {skip();}
 ;

// fragments
fragment DecimalExponent : 'e' | 'E' | 'e+' | 'E+' | 'e-' | 'E-' DecimalDigits;
fragment DecimalDigits   : ('0'..'9'|'_')+ ;
fragment FloatLiteral    : Float ImaginarySuffix?;
fragment IntegerLiteral  : Integer IntSuffix?;
fragment FloatTypeSuffix : 'f' | 'F' | 'L';
fragment ImaginarySuffix : 'i';
fragment IntSuffix       : 'L'|'u'|'U'|'Lu'|'LU'|'uL'|'UL' ;
fragment Integer         : Decimal| Binary| Octal| Hexadecimal ;
fragment Decimal         : '0' | '1'..'9' (DecimalDigit | '_')* ;
fragment Binary          : ('0b' | '0B') ('0' | '1' | '_')+ ;
fragment Octal           : '0' (OctalDigit | '_')+ ;
fragment Hexadecimal     : ('0x' | '0X') (HexDigit | '_')+;  
fragment DecimalDigit    : '0'..'9' ;
fragment OctalDigit      : '0'..'7' ;
fragment HexDigit        : ('0'..'9'|'a'..'f'|'A'..'F') ;
fragment Float
 : d=DecimalDigits ( options {greedy = true; } : FloatTypeSuffix 
                   | '.' DecimalDigits DecimalExponent?
                   )
 | '.' DecimalDigits DecimalExponent?
 ;



回答2:


from the D lexer doc

The source text is split into tokens using the maximal munch technique, i.e., the lexical analyzer tries to make the longest token it can. For example >> is a right shift token, not two greater than tokens. An exception to this rule is that a .. embedded inside what looks like two floating point literals, as in 1..2, is interpreted as if the .. was separated by a space from the first integer.

maybe do a pre parse which does s/(\d)\.\.(\d)/$1 .. $2/



来源:https://stackoverflow.com/questions/8639783/float-literal-and-range-parameter-in-antlr

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!