Eliminate extra spaces in a given ANTLR grammar

In any grammar that I create in ANTLR, is it possible to parse the grammar, and the result of the parsing can free up extra spaces in the grammar. fe

simple example;

int x=5;

if i write

int x      =          5         ; 

I would like the text to change to int x = 5 without additional spaces. Can the parser return the source text without additional spaces?

+3
source share
1 answer

Can the parser return the source text without additional spaces?

Yes, you need to define a lexer rule that captures these spaces, and then skip()them:

Space
  :  (' ' | '\t') {skip();}
  ;

which will ignore spaces and tabs.

PS. , Java . skip() (skip() #, ). \r \n.

, . , ANTLR, :

grammar T;

parse
  :  stat* EOF
  ;

stat
  :  Type Identifier '=' Int ';'
  ;

Type
  :  'int'
  |  'double'
  |  'boolean'
  ;

Identifier
  :  ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
  ;

Int
  :  '0'..'9'+
  ;

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

:

int x   =      5     ; double y     =5;boolean z      =    0  ;

:

int x=5;
double y=5;
boolean z=0;

( ():

grammar T;

parse returns [String str]
@init{StringBuilder buffer = new StringBuilder();}
@after{$str = buffer.toString();}
  :  (stat {buffer.append($stat.str).append('\n');})* EOF
  ;

stat returns [String str]
  :  Type Identifier '=' Int ';' 
     {$str = $Type.text + " " + $Identifier.text + "=" + $Int.text + ";";}
  ;

Type
  :  'int'
  |  'double'
  |  'boolean'
  ;

Identifier
  :  ('a'..'z' | 'A'..'Z' | '_') ('a'..'z' | 'A'..'Z' | '_' | '0'..'9')*
  ;

Int
  :  '0'..'9'+
  ;

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

:

import org.antlr.runtime.*;

public class Main {
    public static void main(String[] args) throws Exception {
        String source = "int x   =      5     ; double y     =5;boolean z      =    0  ;";
        ANTLRStringStream in = new ANTLRStringStream(source);
        TLexer lexer = new TLexer(in);
        CommonTokenStream tokens = new CommonTokenStream(lexer);
        TParser parser = new TParser(tokens);
        System.out.println("Result:\n"+parser.parse());
    }
}

:

Result:
int x=5;
double y=5;
boolean z=0;
+3

Source: https://habr.com/ru/post/1781131/


All Articles