antlr/antlr4 · error · NotSupportedException
Unbuffered stream cannot know its size
Error message
Unbuffered stream cannot know its size
What it means
UnbufferedCharStream deliberately does not track total input length because it has not necessarily read the whole source. Its Size property therefore always throws NotSupportedException. Code that asks for the size of an ICharStream must be prepared for streams that cannot know it.
Source
Thrown at runtime/CSharp/src/UnbufferedCharStream.cs:410
}
}
p = i;
currentCharIndex = index;
if (p == 0)
{
lastChar = lastCharBufferStart;
}
else
{
lastChar = data[p - 1];
}
}
public virtual int Size
{
get
{
throw new NotSupportedException("Unbuffered stream cannot know its size");
}
}
public virtual string SourceName
{
get
{
if (string.IsNullOrEmpty(name))
{
return IntStreamConstants.UnknownSourceName;
}
return name;
}
}
public virtual string GetText(Interval interval)
{
if (interval.a < 0 || interval.b < interval.a - 1)View on GitHub (pinned to 7d5770395b)
Solutions
- Do not read Size from UnbufferedCharStream.
- Use stream.Index for the current absolute position when appropriate.
- Use AntlrInputStream if input can be fully buffered and Size is required.
- Compute total length separately from the source if absolutely necessary.
Example fix
// before int size = unbuffered.Size; // after var buffered = new AntlrInputStream(reader); int size = buffered.Size;
Defensive patterns
Strategy: type-guard
Validate before calling
if (stream is UnbufferedCharStream)
throw new InvalidOperationException("Size is unavailable; buffer the input first."); Type guard
static bool HasKnownSize(ICharStream stream) => stream is not UnbufferedCharStream;
Try / catch
try { int size = stream.Size; }
catch (NotSupportedException ex) when (ex.Message == "Unbuffered stream cannot know its size") { /* use stream.Index or AntlrInputStream */ } Prevention
- Never call Size on unbuffered streams.
- Use AntlrInputStream when total length is needed.
- Design utilities around Index rather than Size for streaming inputs.
When it happens
Trigger: Accessing stream.Size on UnbufferedCharStream, including logging, progress reporting, bounds checks, or generic algorithms that assume every character stream has a known length.
Common situations: Porting code from AntlrInputStream, which does expose Size; generic ICharStream utilities; or test harnesses that print input length before parsing.
Related errors
- cannot consume EOF
- release() called with an invalid marker.
- cannot seek to negative index ${index}
- seek to index outside buffer: ${index} not in ${bufferStartI
- interval ${interval} outside buffer: ${bufferStartIndex}..${
AI-assisted analysis of antlr/antlr4@7d5770395b (2026-08-14).
Data as JSON: /api/errors/52bf97c563b75b6e.
Report an issue: GitHub.