Exemplo figuras

Recuperando o exemplo das figuras.

Gramática inicial para figuras:

grammar Shapes;
// parser rules:
distance: ’distance’ point point;
point: ’(’ x=NUM ’,’ y=NUM ’)’ ;
// lexer rules:
NUM: [0-9]+;
WS: [ \t \n \r ]+ -> skip ;

Integração num programa

import java.io.IOException;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.*;

public class ShapesMain {
    public static void main(String[] args) {
        try{
         // create a CharStream that reads from standard input:
         CharStream input = charStreams.fromStream(System.in);
         // create a lexer that feed off of input CharStream:
         ShapesLexer lexer = new ShapesLexer(input);
         // create a buffer of tokens pulled from the lexer:
         CommonTokenStream tokens = new ShapesParser(tokens);
         // begin parsing at distance rule:
         ParseTree tree = parser.distance();
         if(parser.getNumberOfSyntaxErrors() == 0){
             // print LISP-style tree:
             // System.out.println(tree.toStringTree(parser));
         }
        }catch(IOException e){
            e.printStackTrace();
            system.exit(1);
        }catch(RecognitionException e){
            e.printStackTrace();
            system.exit(1);
        }
    }
}

O comando antlr4-main gera automaticamente esta classe com uma primeira implementação do método main.

Last updated