Skip to main content

antlr4_runtime/
byte_stream.rs

1//! A byte-oriented [`CharStream`] for parsing binary formats.
2//!
3//! ANTLR grammars normally consume Unicode text, but many real-world formats
4//! are raw bytes: chunk containers (RIFF/WAV), fixed-width records (tar), and
5//! self-describing tag streams (CBOR, Standard MIDI). The reference runtimes
6//! parse these by treating each byte as a codepoint in `U+0000..=U+00FF` (a
7//! "Latin-1" view) and writing lexer rules over `' '..'ÿ'`.
8//!
9//! [`InputStream`](crate::InputStream) can do this too, but only after decoding
10//! the bytes into a `String`: any byte `>= 0x80` is not valid UTF-8 on its own,
11//! so the whole input takes the non-ASCII path and is materialized into a
12//! `Vec<char>` plus a byte-offset table — roughly 12 bytes of heap per input
13//! byte, and the compiled-DFA ASCII scanner is disabled.
14//!
15//! `ByteStream` avoids all of that. It is generic over any `AsRef<[u8]>`
16//! backing store, so stream index equals byte offset, lookahead is a single
17//! array read, and there is no transcoding or auxiliary allocation.
18//!
19//! # Mapping to Rust IO primitives
20//!
21//! ANTLR parsing needs random access — the lexer and parser `seek`, look
22//! behind with `la(-1)`, and `mark`/`release` for prediction — so the bytes
23//! must live fully in memory; `ByteStream` cannot lazily pull from a socket
24//! mid-parse. The design instead meets the two IO shapes that matter:
25//!
26//! - **Bytes you already hold** (a network read buffer, an `mmap`, a slice of a
27//!   larger frame): borrow them zero-copy with `ByteStream::new(&buf[..])`.
28//!   Nothing is copied; the stream lives as long as the borrow.
29//! - **A reader** (`File`, `TcpStream`, `Stdin`, `Cursor`): drain it into an
30//!   owned buffer with [`ByteStream::from_reader`], which is just a thin
31//!   wrapper over [`std::io::Read::read_to_end`].
32//! - **An owned `Vec<u8>`**: hand it over with `ByteStream::new(vec)` and the
33//!   stream takes ownership without copying.
34//!
35//! ```ignore
36//! // From a file:
37//! let stream = ByteStream::from_reader(std::fs::File::open(path)?)?;
38//! // Zero-copy from an in-memory buffer (e.g. bytes read off a socket):
39//! let stream = ByteStream::new(&packet[..]);
40//!
41//! // Feed it to any generated parser built from a byte-oriented grammar.
42//! let parsed =
43//!     foo_parser::parse_stream(stream, FooLexer::new, FooParser::entry_rule)?;
44//! ```
45//!
46//! Write lexer rules against the byte range, e.g. `BYTE : ' ' .. 'ÿ';`. A
47//! complete worked example — a Standard MIDI File grammar parsed over a
48//! `ByteStream` — lives under `tests/fixtures/antlr4-rust-gen/midi-binary/`.
49//!
50//! # Token text is hex
51//!
52//! Because the bytes are not text, [`CharStream::text`] renders the matched
53//! span as a lowercase hex string with no separators (`[0xDE, 0xAD]` becomes
54//! `"dead"`). Token *positions* are still exact byte offsets; use
55//! [`crate::IntStream::index`] or a token's byte span when you need to slice
56//! the original bytes.
57
58use std::io;
59
60use crate::char_stream::{CharStream, PositionSummary, TextInterval};
61use crate::int_stream::{EOF, IntStream, UNKNOWN_SOURCE_NAME};
62
63/// A [`CharStream`] backed by raw bytes, where each byte is one symbol in
64/// `0..=255` and the stream index is the byte offset.
65///
66/// Generic over the backing store `B: AsRef<[u8]>`: use `Vec<u8>` for owned
67/// bytes or `&[u8]` to borrow an existing buffer zero-copy. See the
68/// [module documentation](self) for how this maps onto Rust IO primitives.
69#[derive(Clone, Debug)]
70pub struct ByteStream<B = Vec<u8>> {
71    bytes: B,
72    cursor: usize,
73    source_name: String,
74}
75
76impl ByteStream<Vec<u8>> {
77    /// Creates a byte stream by draining a [`std::io::Read`] into an owned
78    /// buffer — the bridge for files, sockets, stdin, and [`std::io::Cursor`].
79    ///
80    /// # Errors
81    ///
82    /// Returns any error produced while reading `reader` to end.
83    pub fn from_reader(mut reader: impl io::Read) -> io::Result<Self> {
84        let mut bytes = Vec::new();
85        reader.read_to_end(&mut bytes)?;
86        Ok(Self::new(bytes))
87    }
88}
89
90impl<B: AsRef<[u8]>> ByteStream<B> {
91    /// Creates a byte stream over `bytes`, using ANTLR's unknown source-name
92    /// placeholder.
93    ///
94    /// `bytes` may be an owned `Vec<u8>` or a borrowed `&[u8]` (zero-copy).
95    pub fn new(bytes: B) -> Self {
96        Self::with_source_name(bytes, UNKNOWN_SOURCE_NAME)
97    }
98
99    /// Creates a byte stream with an explicit source name for tokens and
100    /// diagnostics.
101    pub fn with_source_name(bytes: B, source_name: impl Into<String>) -> Self {
102        Self {
103            bytes,
104            cursor: 0,
105            source_name: source_name.into(),
106        }
107    }
108
109    /// Returns the backing bytes.
110    #[must_use]
111    pub fn bytes(&self) -> &[u8] {
112        self.bytes.as_ref()
113    }
114
115    /// Returns true when the cursor has reached or passed the end of input.
116    #[must_use]
117    pub fn is_eof(&self) -> bool {
118        self.cursor >= self.bytes.as_ref().len()
119    }
120}
121
122impl<B: AsRef<[u8]>> IntStream for ByteStream<B> {
123    fn consume(&mut self) {
124        if !self.is_eof() {
125            self.cursor += 1;
126        }
127    }
128
129    fn la(&mut self, offset: isize) -> i32 {
130        if offset == 0 {
131            return 0;
132        }
133
134        // Mirror `InputStream::la`: `+1` is the symbol under the cursor, and
135        // negative offsets look behind. `checked_*` keeps `isize::MIN` and
136        // out-of-range lookahead on the EOF path instead of panicking.
137        let absolute = if offset > 0 {
138            self.cursor.checked_add((offset - 1).cast_unsigned())
139        } else {
140            offset
141                .checked_neg()
142                .and_then(|distance| usize::try_from(distance).ok())
143                .and_then(|distance| self.cursor.checked_sub(distance))
144        };
145
146        absolute.map_or(EOF, |index| self.symbol_at(index).unwrap_or(EOF))
147    }
148
149    fn index(&self) -> usize {
150        self.cursor
151    }
152
153    fn seek(&mut self, index: usize) {
154        self.cursor = index.min(self.bytes.as_ref().len());
155    }
156
157    fn size(&self) -> usize {
158        self.bytes.as_ref().len()
159    }
160
161    fn source_name(&self) -> &str {
162        &self.source_name
163    }
164}
165
166impl<B: AsRef<[u8]>> CharStream for ByteStream<B> {
167    /// Renders the inclusive byte interval as a lowercase, separator-free hex
168    /// string. See the [module documentation](self) for the rationale.
169    fn text(&self, interval: TextInterval) -> String {
170        // Clamp `stop` before any `+1`, mirroring `InputStream`: a caller
171        // passing `TextInterval::new(_, usize::MAX)` (e.g. an EOF token span)
172        // must not overflow.
173        let bytes = self.bytes.as_ref();
174        let len = bytes.len();
175        if interval.is_empty() || len == 0 {
176            return String::new();
177        }
178        let start = interval.start.min(len);
179        let stop = interval.stop.min(len - 1);
180        if start > stop {
181            return String::new();
182        }
183        use std::fmt::Write as _;
184        bytes[start..=stop].iter().fold(
185            String::with_capacity((stop - start + 1) * 2),
186            |mut acc, byte| {
187                // Writing to a String is infallible.
188                let _ = write!(acc, "{byte:02x}");
189                acc
190            },
191        )
192    }
193
194    fn symbol_at(&self, index: usize) -> Option<i32> {
195        Some(
196            self.bytes
197                .as_ref()
198                .get(index)
199                .map_or(EOF, |&byte| i32::from(byte)),
200        )
201    }
202
203    // NOTE: `contiguous_ascii` is deliberately NOT implemented. That fast path
204    // feeds bytes into a 128-wide ASCII DFA row (`ascii_target`), which is only
205    // valid for 7-bit input; bytes `>= 0x80` route correctly through the
206    // generic path's `wide_rows` instead.
207
208    /// Summarizes line/column movement over `[start, end)` by scanning the raw
209    /// bytes.
210    ///
211    /// Without this, [`BaseLexer`](crate::lexer::BaseLexer) would fall back to
212    /// iterating [`Self::text`], which is hex — so a span of N bytes would count
213    /// as 2N columns and `0x0A` newline bytes would be invisible, corrupting the
214    /// line/column of split or synthesized tokens.
215    fn position_summary(&self, start: usize, end: usize) -> Option<PositionSummary> {
216        let bytes = self.bytes.as_ref();
217        let len = bytes.len();
218        if start > end {
219            return None;
220        }
221        let start = start.min(len);
222        let end = end.min(len);
223        let mut summary = PositionSummary::default();
224        for &byte in &bytes[start..end] {
225            if byte == b'\n' {
226                summary.line_breaks += 1;
227                summary.trailing_columns = 0;
228            } else {
229                summary.trailing_columns += 1;
230            }
231        }
232        Some(summary)
233    }
234
235    fn byte_interval(&self, interval: TextInterval) -> Option<(usize, usize)> {
236        // Index == byte offset, so the byte span is exact. Clamp `stop` before
237        // the `+1` for the same overflow reason as `text`.
238        let len = self.bytes.as_ref().len();
239        if interval.is_empty() || len == 0 {
240            return None;
241        }
242        let start = interval.start.min(len);
243        let stop = interval.stop.min(len - 1);
244        (start <= stop).then_some((start, stop + 1))
245    }
246}
247
248#[cfg(test)]
249#[allow(clippy::disallowed_methods)] // insta assertion macros unwrap internal I/O.
250mod tests {
251    use super::*;
252
253    #[test]
254    fn lookahead_reads_bytes_including_high_bytes() {
255        let mut stream = ByteStream::new(vec![0x00, 0x7F, 0x80, 0xFF]);
256        assert_eq!(stream.la(0), 0, "la(0) is the ANTLR sentinel, not EOF");
257        assert_eq!(stream.la(1), 0x00);
258        assert_eq!(stream.la(2), 0x7F);
259        assert_eq!(stream.la(3), 0x80, "high byte is 128, not sign-extended");
260        assert_eq!(stream.la(4), 0xFF);
261        assert_eq!(stream.la(5), EOF);
262        stream.consume();
263        assert_eq!(stream.index(), 1);
264        assert_eq!(stream.la(-1), 0x00);
265        assert_eq!(stream.la(isize::MIN), EOF, "no panic on extreme offset");
266    }
267
268    #[test]
269    fn consume_stops_at_eof_and_seek_clamps() {
270        let mut stream = ByteStream::new(vec![0x01, 0x02]);
271        assert_eq!(stream.size(), 2);
272        stream.consume();
273        stream.consume();
274        stream.consume(); // past EOF is a no-op
275        assert_eq!(stream.index(), 2);
276        assert!(stream.is_eof());
277        stream.seek(99);
278        assert_eq!(stream.index(), 2, "seek clamps to size");
279        stream.seek(1);
280        assert_eq!(stream.la(1), 0x02);
281    }
282
283    #[test]
284    fn text_is_lowercase_hex_and_byte_interval_is_exact() {
285        let stream = ByteStream::new(vec![0xDE, 0xAD, 0xBE, 0xEF]);
286        assert_eq!(stream.text(TextInterval::new(0, 3)), "deadbeef");
287        assert_eq!(stream.text(TextInterval::new(1, 2)), "adbe");
288        assert_eq!(stream.text(TextInterval::empty()), "");
289        // Inclusive char interval [1, 2] -> half-open byte span [1, 3).
290        assert_eq!(stream.byte_interval(TextInterval::new(1, 2)), Some((1, 3)));
291        assert_eq!(stream.byte_interval(TextInterval::empty()), None);
292        assert_eq!(stream.symbol_at(0), Some(0xDE));
293        assert_eq!(stream.symbol_at(4), Some(EOF));
294    }
295
296    #[test]
297    fn text_and_byte_interval_clamp_usize_max_without_overflow() {
298        // An EOF-token span can carry `stop == usize::MAX`; clamping before the
299        // `+1` must not overflow (debug panic / release wrap).
300        let stream = ByteStream::new(vec![0xDE, 0xAD]);
301        assert_eq!(stream.text(TextInterval::new(0, usize::MAX)), "dead");
302        assert_eq!(
303            stream.byte_interval(TextInterval::new(0, usize::MAX)),
304            Some((0, 2)),
305        );
306        // Out-of-range start clamps to empty rather than panicking.
307        assert_eq!(stream.text(TextInterval::new(5, usize::MAX)), "");
308    }
309
310    #[test]
311    fn position_summary_scans_raw_bytes_not_hex() {
312        // Bytes, not hex: a newline byte (0x0A) is one line break, and each
313        // other byte is one column — never doubled as the hex rendering would.
314        let stream = ByteStream::new(vec![0x41, 0x0A, 0x42, 0x43]);
315        assert_eq!(
316            stream.position_summary(0, 4),
317            Some(PositionSummary {
318                line_breaks: 1,
319                trailing_columns: 2,
320            }),
321        );
322        // No newline in [2, 4): two raw bytes are two columns (hex would say
323        // four).
324        assert_eq!(
325            stream.position_summary(2, 4),
326            Some(PositionSummary {
327                line_breaks: 0,
328                trailing_columns: 2,
329            }),
330        );
331        assert_eq!(stream.position_summary(4, 2), None);
332    }
333
334    #[test]
335    fn borrows_bytes_zero_copy() {
336        // The network-buffer case: parse a slice we already hold without
337        // handing ownership to the stream.
338        let buffer: [u8; 4] = [0xCA, 0xFE, 0xBA, 0xBE];
339        let mut stream = ByteStream::new(&buffer[..]);
340        assert_eq!(stream.la(1), 0xCA);
341        assert_eq!(stream.size(), 4);
342        // `buffer` is still ours afterwards.
343        assert_eq!(buffer[0], 0xCA);
344    }
345
346    #[test]
347    fn from_reader_drains_any_read() {
348        // The file/socket case, exercised here with an in-memory Cursor that
349        // implements the same `io::Read` contract as `File`/`TcpStream`.
350        let source = io::Cursor::new(vec![0x4D, 0x54, 0x68, 0x64]); // "MThd"
351        let mut stream = ByteStream::from_reader(source).expect("cursor read is infallible");
352        assert_eq!(stream.size(), 4);
353        assert_eq!(stream.la(1), 0x4D);
354        assert_eq!(stream.text(TextInterval::new(0, 3)), "4d546864");
355    }
356}