antlr/antlr4 · error · ArgumentException

replace: range invalid: {from}..{to}(size={size})

Error message

replace: range invalid: {from}..{to}(size={size})

What it means

Error "replace: range invalid: {from}..{to}(size={size})" thrown in antlr/antlr4.

Source

Thrown at runtime/CSharp/src/TokenStreamRewriter.cs:341

        {
            Replace(DefaultProgramName, from, to, text);
        }

        public virtual void Replace(IToken indexT, object text)
        {
            Replace(DefaultProgramName, indexT, indexT, text);
        }

        public virtual void Replace(IToken from, IToken to, object text)
        {
            Replace(DefaultProgramName, from, to, text);
        }

        public virtual void Replace(string programName, int from, int to, object text)
        {
            if (from > to || from < 0 || to < 0 || to >= tokens.Size)
            {
                throw new ArgumentException("replace: range invalid: " + from + ".." + to + "(size=" + tokens.Size + ")");
            }
            TokenStreamRewriter.RewriteOperation op = new TokenStreamRewriter.ReplaceOp(tokens, from, to, text);
            IList<TokenStreamRewriter.RewriteOperation> rewrites = GetProgram(programName);
            op.instructionIndex = rewrites.Count;
            rewrites.Add(op);
        }

        public virtual void Replace(string programName, IToken from, IToken to, object text)
        {
            Replace(programName, from.TokenIndex, to.TokenIndex, text);
        }

        public virtual void Delete(int index)
        {
            Delete(DefaultProgramName, index, index);
        }

        public virtual void Delete(int from, int to)

View on GitHub (pinned to 7d5770395b)

Solutions

  1. Ensure the replace range [from..to] lies within 0..tokens.Count-1 and from <= to before calling Replace.
  2. Validate indices against the token stream size before rewriting.

Example fix

if (from >= 0 && to < tokens.Size && from <= to)
    rewriter.Replace(from, to, "newText");

When it happens

Trigger: TokenStreamRewriter.Replace called with from/to indices outside 0..tokens.Count-1.

Common situations: Validate from and to against the token stream size before Replace; remember stream is 0-based and to is inclusive.


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