-1

I have a .g4 file for my grammar and it works fine.

In my java program, user input must follow some rules which are the rules in the .g4 file.

how can I use it in my java code to check if the user input is valid?

BTW, my IDE is IntelliJ IDEA.

here is my antlr code:

grammar CFG;


/*
 * Parser Rules
 */
    cfg: (rull NewLine)+;
    rull: Variable TransitionOperator sententialForm (Or sententialForm)*;
    sententialForm: ((Variable | Literal)+) | Landa;


 /*
  * Lexer Rules
  */

  Literal:  [a-z];
  Variable: [A-Z];
  TransitionOperator: '->';
  Or: '|';
  OpenParenthesis: '(';
  CloseParenthesis: ')';
//  Star: '*';
//  Plus: '+';
  Landa: 'λ';
  WhiteSpace: ' ' -> skip;
  NewLine: '\n';

1 Answer 1

0

That's pretty easy to do: set up your parsing pipeline as usual:

using Antlr4.Runtime;
using Antlr4.Runtime.Tree;

public void MyParseMethod() {
      String input = "your text to parse here";
      ICharStream stream = CharStreams.fromstring(input);
      ITokenSource lexer = new CFGLexer(stream);
      ITokenStream tokens = new CommonTokenStream(lexer);
      MyGrammarParser parser = new CFGParser(tokens);
      // parser.BuildParseTree = true;
      IParseTree tree = parser.cfg();
}

(here written in C#) and once the parse run is done check getNumberOfSyntaxErrors() to see if there was an error in the input. For more finegrained handling set up your own error listener and collect the produced errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.