antlr/antlr4 · error · IllegalArgumentException

invalid tag: "+tagChunk.getTag()+" in pattern: "+pattern

Error message

invalid tag: "+tagChunk.getTag()+" in pattern: "+pattern

What it means

Error "invalid tag: "+tagChunk.getTag()+" in pattern: "+pattern" thrown in antlr/antlr4.

Source

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

				// add special rule token or conjure up new token from name
				if ( Character.isUpperCase(tagChunk.getTag().charAt(0)) ) {
					Integer ttype = parser.getTokenType(tagChunk.getTag());
					if ( ttype==Token.INVALID_TYPE ) {
						throw new IllegalArgumentException("Unknown token "+tagChunk.getTag()+" in pattern: "+pattern);
					}
					TokenTagToken t = new TokenTagToken(tagChunk.getTag(), ttype, tagChunk.getLabel());
					tokens.add(t);
				}
				else if ( Character.isLowerCase(tagChunk.getTag().charAt(0)) ) {
					int ruleIndex = parser.getRuleIndex(tagChunk.getTag());
					if ( ruleIndex==-1 ) {
						throw new IllegalArgumentException("Unknown rule "+tagChunk.getTag()+" in pattern: "+pattern);
					}
					int ruleImaginaryTokenType = parser.getATNWithBypassAlts().ruleToTokenType[ruleIndex];
					tokens.add(new RuleTagToken(tagChunk.getTag(), ruleImaginaryTokenType, tagChunk.getLabel()));
				}
				else {
					throw new IllegalArgumentException("invalid tag: "+tagChunk.getTag()+" in pattern: "+pattern);
				}
			}
			else {
				TextChunk textChunk = (TextChunk)chunk;
				ANTLRInputStream in = new ANTLRInputStream(textChunk.getText());
				lexer.setInputStream(in);
				Token t = lexer.nextToken();
				while ( t.getType()!=Token.EOF ) {
					tokens.add(t);
					t = lexer.nextToken();
				}
			}
		}

//		System.out.println("tokens="+tokens);
		return tokens;
	}

View on GitHub (pinned to 7d5770395b)

Solutions

  1. A tag must be either a valid rule name or a valid token name; fix the tag text inside the delimiters.
  2. If the tag contains special characters, escape them or choose a different delimiter pair via setDelimiters.

Example fix

// instead of an invalid tag like <foo-bar>, use the rule name
ParseTreePattern p = matcher.compile("<fooBar>", MyParser.RULE_fooBar);

When it happens

Trigger: A tag chunk has an invalid form (e.g. bad label/rule combination) in the pattern.

Common situations: Use tags of form <rule>, <token>, or <label:rule>; avoid malformed multi-part tags.


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