antlr/antlr4 · error · ArgumentException

text cannot be null

Error message

text cannot be null

What it means

TextChunk's constructor rejects a null text argument. A TextChunk is the literal-text part of a split pattern; a null text would NPE later during ToString/concatenation in the matcher, so the constructor fails fast. Note empty text is allowed (only null is rejected), unlike TagChunk which rejects both.

Source

Thrown at runtime/CSharp/src/Tree/Pattern/TextChunk.cs:48

        /// <summary>
        /// Constructs a new instance of
        /// <see cref="TextChunk"/>
        /// with the specified text.
        /// </summary>
        /// <param name="text">The text of this chunk.</param>
        /// <exception>
        /// IllegalArgumentException
        /// if
        /// <paramref name="text"/>
        /// is
        /// <see langword="null"/>
        /// .
        /// </exception>
        public TextChunk(string text)
        {
            if (text == null)
            {
                throw new ArgumentException("text cannot be null");
            }
            this.text = text;
        }

        /// <summary>Gets the raw text of this chunk.</summary>
        /// <remarks>Gets the raw text of this chunk.</remarks>
        /// <returns>The text of the chunk.</returns>
        [NotNull]
        public string Text
        {
            get
            {
                return text;
            }
        }

        /// <summary>
        /// <inheritDoc/>

View on GitHub (pinned to 7d5770395b)

Solutions

  1. Pass a non-null string — use string.Empty when there is no text.
  2. Guard nullable inputs: text == null ? string.Empty : text.
  3. Rely on the matcher's Compile path, which always produces non-null TextChunks from the pattern string.

Example fix

// before
chunks.Add(new TextChunk(prefix)); // prefix may be null

// after
chunks.Add(new TextChunk(prefix ?? string.Empty));
Defensive patterns

Strategy: validation

Validate before calling

chunks.Add(new TextChunk(text ?? string.Empty));

Type guard

static bool HasText(string s) => s != null;

Prevention

When it happens

Trigger: Direct construction new TextChunk(null); a helper that maps optional text segments (e.g. the substring before the first tag) to TextChunk without handling the absent case.

Common situations: Building pattern chunks by hand instead of via ParseTreePatternMatcher.Compile; C# port differences where Java code relied on empty-string defaults; nullable string fields forwarded into chunk construction.

Related errors


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