antlr/antlr4 · error · IllegalArgumentException

patternTree cannot be null

Error message

patternTree cannot be null

What it means

Error "patternTree cannot be null" thrown in antlr/antlr4.

Source

Thrown at runtime/Java/src/org/antlr/v4/runtime/tree/pattern/ParseTreePatternMatcher.java:265

	 * Recursively walk {@code tree} against {@code patternTree}, filling
	 * {@code match.}{@link ParseTreeMatch#labels labels}.
	 *
	 * @return the first node encountered in {@code tree} which does not match
	 * a corresponding node in {@code patternTree}, or {@code null} if the match
	 * was successful. The specific node returned depends on the matching
	 * algorithm used by the implementation, and may be overridden.
	 */

	protected ParseTree matchImpl(ParseTree tree,
								  ParseTree patternTree,
								  MultiMap<String, ParseTree> labels)
	{
		if (tree == null) {
			throw new IllegalArgumentException("tree cannot be null");
		}

		if (patternTree == null) {
			throw new IllegalArgumentException("patternTree cannot be null");
		}

		// x and <ID>, x and y, or x and x; or could be mismatched types
		if ( tree instanceof TerminalNode && patternTree instanceof TerminalNode ) {
			TerminalNode t1 = (TerminalNode)tree;
			TerminalNode t2 = (TerminalNode)patternTree;
			ParseTree mismatchedNode = null;
			// both are tokens and they have same type
			if ( t1.getSymbol().getType() == t2.getSymbol().getType() ) {
				if ( t2.getSymbol() instanceof TokenTagToken ) { // x and <ID>
					TokenTagToken tokenTagToken = (TokenTagToken)t2.getSymbol();
					// track label->list-of-nodes for both token name and label (if any)
					labels.map(tokenTagToken.getTokenName(), tree);
					if ( tokenTagToken.getLabel()!=null ) {
						labels.map(tokenTagToken.getLabel(), tree);
					}
				}
				else if ( t1.getText().equals(t2.getText()) ) {

View on GitHub (pinned to 7d5770395b)

Solutions

  1. Pass a non-null pattern tree when constructing the pattern-matching internals.
  2. Use ParseTreePatternMatcher.compile(pattern, ruleIndex) which builds the pattern tree for you, instead of hand-constructing it.

Example fix

ParseTreePattern p = matcher.compile("<ID> = <expr>;", MyParser.RULE_assign);

When it happens

Trigger: ParseTreePatternMatcher.matchImpl() invoked with a null patternTree.

Common situations: Compile patterns via compile() before matching; do not pass a null pattern tree into matchImpl.


AI-assisted analysis of antlr/antlr4@7d5770395b (2026-08-14). Data as JSON: /api/errors/57e3a02665437038. Report an issue: GitHub.