In this article we are going to talk about a little known, but quite useful feature of ANTLR: pattern matching. It is a feature that allows you to find nodes that follow a specified pattern. This makes it easier to do stuff like collecting all static methods inside a class declaration.
ANTLR offers visitors and listeners to execute some action when you encounter a node of a certain type, for example a node of type VariableDeclaration. This works great when you need to perform the same operation every time. However, sometimes you need to find patterns in the tree rather than individual nodes.
For example, you need to do something whenever you find a method inside a class declaration. You might also want to do something for some concrete case, for instance whenever you find all assignments to 0. This is where pattern matching shines. You just ask to find all instances matching a specific pattern, and you get them.
You could also use pattern matching in place of visitors or listeners, for example to find all assignments. Instead of executing an action whenever you match a node of type Assignment, you ask to match all assignment patterns. You may opt for this solution because it is easier or quicker than building a whole listener or visitor.