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