Semantic predicates in ANTLR4?

In ANTLR v4, there are no longer gated semantic predicates, { … }?=>, and there are also no longer syntactic predicates, ( … )=>, because the parsing algorithm used in v4 can resolve the ambiguities (the need for such predicates are no longer needed). So, this should just work for you: expr : refIdentifier | … Read more

Negating inside lexer- and parser rules

Negating can occur inside lexer and parser rules. Inside lexer rules you can negate characters, and inside parser rules you can negate tokens (lexer rules). But both lexer- and parser rules can only negate either single characters, or single tokens, respectively. A couple of examples: lexer rules To match one or more characters except lowercase … Read more

Handling errors in ANTLR4

Since I’ve had a little bit of a struggle with the two existing answers, I’d like to share the solution I ended up with. First of all I created my own version of an ErrorListener like Sam Harwell suggested: public class ThrowingErrorListener extends BaseErrorListener { public static final ThrowingErrorListener INSTANCE = new ThrowingErrorListener(); @Override public … Read more

How does the ANTLR lexer disambiguate its rules (or why does my parser produce “mismatched input” errors)?

In ANTLR, the lexer is isolated from the parser, which means it will split the text into typed tokens according to the lexer grammar rules, and the parser has no influence on this process (it cannot say “give me an INTEGER now” for instance). It produces a token stream by itself. Furthermore, the parser doesn’t … Read more

If/else statements in ANTLR using listeners

By default, ANTLR 4 generates listeners. But if you give org.antlr.v4.Tool the command line parameter -visitor, ANTLR generates visitor classes for you. These work much like listeners, but give you more control over which (sub) trees are walked/visited. This is particularly useful if you want to exclude certain (sub) trees (like else/if blocks, as in … Read more

ANTLR: Is there a simple example?

Note: this answer is for ANTLR3! If you’re looking for an ANTLR4 example, then this Q&A demonstrates how to create a simple expression parser, and evaluator using ANTLR4. You first create a grammar. Below is a small grammar that you can use to evaluate expressions that are built using the 4 basic math operators: +, … Read more

What is a ‘semantic predicate’ in ANTLR?

ANTLR 4 For predicates in ANTLR 4, checkout these stackoverflow Q&A’s: Syntax of semantic predicates in Antlr4 Semantic predicates in ANTLR4? ANTLR 3 A semantic predicate is a way to enforce extra (semantic) rules upon grammar actions using plain code. There are 3 types of semantic predicates: validating semantic predicates; gated semantic predicates; disambiguating semantic … Read more