1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
//! This module contains a bunch of traits necessary for processing byte strings. //! //! Most notable are: //! * `Source` - implemented by default for `&str` and `&[u8]`, used by the `Lexer`. //! * `Slice` - slices of `Source`, returned by `Lexer::slice`. use std::fmt::Debug; use std::ops::Range; /// Trait for a `Slice` of a `Source` that the `Lexer` can consume. /// /// Most commonly, those will be the same types: /// * `&str` slice for `&str` source. /// * `&[u8]` slice for `&[u8]` source. pub trait Slice<'source>: Sized + PartialEq + Eq + Debug { /// In all implementations we should at least be able to obtain a /// slice of bytes as the lowest level common denominator. fn as_bytes(&self) -> &'source [u8]; } impl<'source> Slice<'source> for &'source str { fn as_bytes(&self) -> &'source [u8] { (*self).as_bytes() } } impl<'source> Slice<'source> for &'source [u8] { fn as_bytes(&self) -> &'source [u8] { *self } } /// Trait for types the `Lexer` can read from. /// /// Most notably this is implemented for `&str`. It is unlikely you will /// ever want to use this Trait yourself, unless implementing a new `Source` /// the `Lexer` can use. pub trait Source<'source> { /// A type this `Source` can be sliced into. type Slice: self::Slice<'source>; /// Length of the source fn len(&self) -> usize; /// Read a chunk of bytes into an array. Returns `None` when reading /// out of bounds would occur. /// /// This is very useful for matching fixed-size byte arrays, and tends /// to be very fast at it too, since the compiler knows the byte lengths. /// /// ```rust /// use logos::Source; /// /// fn main() { /// let foo = "foo"; /// /// assert_eq!(foo.read(0), Some(b"foo")); // Option<&[u8; 3]> /// assert_eq!(foo.read(0), Some(b"fo")); // Option<&[u8; 2]> /// assert_eq!(foo.read(2), Some(b'o')); // Option<u8> /// assert_eq!(foo.read::<&[u8; 4]>(0), None); // Out of bounds /// assert_eq!(foo.read::<&[u8; 2]>(2), None); // Out of bounds /// } /// ``` fn read<Chunk>(&self, offset: usize) -> Option<Chunk> where Chunk: self::Chunk<'source>; /// Get a slice of the source at given range. This is analogous to /// `slice::get(range)`. /// /// ```rust /// use logos::Source; /// /// fn main() { /// let foo = "It was the year when they finally immanentized the Eschaton."; /// /// assert_eq!(Source::slice(&foo, 51..59), Some("Eschaton")); /// } /// ``` fn slice(&self, range: Range<usize>) -> Option<Self::Slice>; /// Get a slice of the source at given range. This is analogous to /// `slice::get_unchecked(range)`. /// /// **Using this method with range out of bounds is undefined behavior!** /// /// ```rust /// use logos::Source; /// /// fn main() { /// let foo = "It was the year when they finally immanentized the Eschaton."; /// /// unsafe { /// assert_eq!(Source::slice_unchecked(&foo, 51..59), "Eschaton"); /// } /// } /// ``` unsafe fn slice_unchecked(&self, range: Range<usize>) -> Self::Slice; /// For `&str` sources attempts to find the closest `char` boundary at which source /// can be sliced, starting from `index`. /// /// For binary sources (`&[u8]`) this should just return `index` back. fn find_boundary(&self, index: usize) -> usize { index } } /// Marker trait for any `Source` that can be sliced into arbitrary byte chunks, /// with no regard for UTF-8 (or any other) character encoding. pub trait BinarySource<'source>: Source<'source> {} /// Marker trait for any `Logos`, which will constrain it to a specific subset of /// `Source`s. /// /// In particular, if your token definitions would allow reading invalid UTF-8, /// the `Logos` derive macro will restrict you to lexing on `Source`s that also /// implement the `BinarySource` marker (`&[u8]` is provided). /// /// **Note:** You shouldn't implement this trait yourself, `#[derive(Logos)]` will /// do it for you. pub trait WithSource<Source> {} impl<'source> Source<'source> for &'source str { type Slice = &'source str; #[inline] fn len(&self) -> usize { (*self).len() } #[inline] fn read<Chunk>(&self, offset: usize) -> Option<Chunk> where Chunk: self::Chunk<'source>, { if offset + (Chunk::SIZE - 1) < (*self).len() { Some(unsafe { Chunk::from_ptr((*self).as_ptr().add(offset)) }) } else { None } } #[inline] fn slice(&self, range: Range<usize>) -> Option<&'source str> { self.get(range) } #[inline] unsafe fn slice_unchecked(&self, range: Range<usize>) -> &'source str { debug_assert!( range.start <= self.len() && range.end <= self.len(), "Reading out of bounds {:?} for {}!", range, self.len() ); self.get_unchecked(range) } #[inline] fn find_boundary(&self, mut index: usize) -> usize { while !self.is_char_boundary(index) { index += 1; } index } } impl<'source> Source<'source> for &'source [u8] { type Slice = &'source [u8]; #[inline] fn len(&self) -> usize { (*self).len() } #[inline] fn read<Chunk>(&self, offset: usize) -> Option<Chunk> where Chunk: self::Chunk<'source>, { if offset + (Chunk::SIZE - 1) < (*self).len() { Some(unsafe { Chunk::from_ptr((*self).as_ptr().add(offset)) }) } else { None } } #[inline] fn slice(&self, range: Range<usize>) -> Option<&'source [u8]> { self.get(range) } #[inline] unsafe fn slice_unchecked(&self, range: Range<usize>) -> &'source [u8] { debug_assert!( range.start <= self.len() && range.end <= self.len(), "Reading out of bounds {:?} for {}!", range, self.len() ); self.get_unchecked(range) } } impl<'source> BinarySource<'source> for &'source [u8] {} /// A fixed, statically sized chunk of data that can be read from the `Source`. /// /// This is implemented for `u8`, as well as byte arrays `&[u8; 1]` to `&[u8; 16]`. pub trait Chunk<'source>: Sized + Copy + PartialEq + Eq { /// Size of the chunk being accessed in bytes. const SIZE: usize; /// Create a chunk from a raw byte pointer. unsafe fn from_ptr(ptr: *const u8) -> Self; } /// A trait implemented for byte arrays that allow splitting them into two, /// with the resulting sizes known at compile time. pub trait Split<Target> { /// Remainder after splitting. This must be statically safe so that /// `Target` + `Remainder` = `Self`. /// /// **Implementations must guarantee that these are not overlapping!** type Remainder; /// Split self into `Target` and `Remainder`. /// /// ```rust /// use logos::source::Split; /// /// fn main() { /// let bytes = b"foobar"; /// /// assert_eq!(bytes.split(), (b'f', b"oobar")); // (u8, &[u8; 5]) /// assert_eq!(bytes.split(), (b"f", b"oobar")); // (&[u8; 1], &[u8; 5]) /// assert_eq!(bytes.split(), (b"fo", b"obar")); // ... /// assert_eq!(bytes.split(), (b"foo", b"bar")); /// assert_eq!(bytes.split(), (b"foob", b"ar")); /// assert_eq!(bytes.split(), (b"fooba", b"r")); /// } fn split(self) -> (Target, Self::Remainder); } impl<'source> Chunk<'source> for u8 { const SIZE: usize = 1; #[inline] unsafe fn from_ptr(ptr: *const u8) -> Self { *ptr } } macro_rules! impl_array { (@byte $size:expr, 1) => ( impl<'source> Split<u8> for &'source [u8; $size] { type Remainder = &'source [u8; $size - 1]; #[inline] fn split(self) -> (u8, &'source [u8; $size - 1]) { unsafe {( self[0], Chunk::from_ptr((self as *const u8).add(1)), )} } } ); (@byte $size:expr, $ignore:tt) => (); ($($size:expr => ( $( $split:tt ),* ))*) => ($( impl<'source> Chunk<'source> for &'source [u8; $size] { const SIZE: usize = $size; #[inline] unsafe fn from_ptr(ptr: *const u8) -> Self { &*(ptr as *const [u8; $size]) } } $( impl_array! { @byte $size, $split } impl<'source> Split<&'source [u8; $split]> for &'source [u8; $size] { type Remainder = &'source [u8; $size - $split]; #[inline] fn split(self) -> (&'source [u8; $split], &'source [u8; $size - $split]) { unsafe {( Chunk::from_ptr(self as *const u8), Chunk::from_ptr((self as *const u8).add($split)), )} } } )* )*); } impl_array! { 1 => () 2 => (1) 3 => (1, 2) 4 => (1, 2, 3) 5 => (1, 2, 3, 4) 6 => (1, 2, 3, 4, 5) 7 => (1, 2, 3, 4, 5, 6) 8 => (1, 2, 3, 4, 5, 6, 7) 9 => (1, 2, 3, 4, 5, 6, 7, 8) 10 => (1, 2, 3, 4, 5, 6, 7, 8, 9) 11 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10) 12 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11) 13 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12) 14 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13) 15 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14) 16 => (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15) }