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 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440
//! An input cursor. use std::ops::{Bound, RangeBounds}; use std::str::Chars; use crate::span::Position; /// An input cursor. #[derive(Clone, Debug)] pub struct InputCursor<'a> { buf: &'a str, iter: Chars<'a>, position: Position, prev_position: Option<Position>, newline: bool, keep_column: bool, eof: bool, } impl<'a> InputCursor<'a> { /// Create a new cursor from a buffer. pub fn new(buf: &'a str) -> Self { Self { buf, iter: buf.chars(), position: Position { byte: 0, line: 1, col: 1, }, prev_position: None, newline: false, keep_column: false, eof: false, } } /// Returns the `n`th character after the cursor without advancing the cursor. /// /// ```rust /// # use luaparse::InputCursor; /// let cursor = InputCursor::new("hello world!"); /// assert_eq!(cursor.peek_nth(0), Some('h')); /// assert_eq!(cursor.peek_nth(2), Some('l')); /// ``` pub fn peek_nth(&self, n: usize) -> Option<char> { self.iter.clone().nth(n) } /// Returns the next character without advancing the cursor. Equivalent to `peek_nth(0)`. /// /// ```rust /// # use luaparse::InputCursor; /// let cursor = InputCursor::new("hello world!"); /// assert_eq!(cursor.peek(), Some('h')); /// assert_eq!(cursor.peek(), cursor.peek_nth(0)); /// ``` pub fn peek(&self) -> Option<char> { self.peek_nth(0) } /// Returns the position of the following character. /// /// ```rust /// # use luaparse::InputCursor; /// # use luaparse::Position; /// let mut cursor = InputCursor::new("hello\nworld"); /// assert_eq!(cursor.pos(), Position { /// byte: 0, /// line: 1, /// col: 1, /// }); /// cursor.skip_n(5); /// assert_eq!(cursor.pos(), Position { /// byte: 5, /// line: 1, /// col: 6, /// }); /// cursor.next(); /// assert_eq!(cursor.pos(), Position { /// byte: 6, /// line: 2, /// col: 1, /// }); /// ``` pub fn pos(&self) -> Position { if self.newline { Position { byte: self.position.byte, line: self.position.line + 1, col: 1, } } else { self.position } } /// Returns the position of the following character. /// /// Only differs from `pos` when the cursor is immediately after a newline character. /// In that case, unlike `pos`, this method does not go to the next line. /// /// ```rust /// # use luaparse::InputCursor; /// # use luaparse::Position; /// let mut cursor = InputCursor::new("hello\nworld"); /// assert_eq!(cursor.pos(), Position { /// byte: 0, /// line: 1, /// col: 1, /// }); /// cursor.skip_n(5); /// assert_eq!(cursor.pos(), Position { /// byte: 5, /// line: 1, /// col: 6, /// }); /// cursor.next(); /// assert_eq!(cursor.pos(), Position { /// byte: 6, /// line: 1, /// col: 7, /// }); /// ``` pub fn pos_no_newline(&self) -> Position { self.position } /// Returns the position of the preceding character. /// /// ```rust /// # use luaparse::InputCursor; /// # use luaparse::Position; /// let mut cursor = InputCursor::new("hello\nworld"); /// assert_eq!(cursor.prev_pos(), Position { /// byte: 0, /// line: 1, /// col: 1, /// }); /// cursor.skip_n(5); /// assert_eq!(cursor.prev_pos(), Position { /// byte: 4, /// line: 1, /// col: 5, /// }); /// cursor.next(); /// assert_eq!(cursor.prev_pos(), Position { /// byte: 5, /// line: 1, /// col: 6, /// }); /// ``` pub fn prev_pos(&self) -> Position { self.prev_position.unwrap_or(Position { byte: 0, line: 1, col: 1, }) } /// Returns the remaining string as a subslice. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world"); /// cursor.skip_n(6); /// assert_eq!(cursor.remaining(), "world"); /// ``` pub fn remaining(&self) -> &'a str { self.iter.as_str() } /// Returns a substring of the buffer. /// /// Accepts a range defined by two `Position`s. /// /// The positions must be previously obtained using `pos` or its variant. The function may /// panic if the position is invalid. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world!"); /// let start = cursor.pos(); /// cursor.skip_n(5); /// let end = cursor.prev_pos(); /// assert_eq!(cursor.substr(start..=end), "hello"); /// ``` pub fn substr<I>(&self, range: I) -> &'a str where I: RangeBounds<Position>, { use Bound::*; let char_len_at = |b: usize| { self.buf[b..] .chars() .next() .map(char::len_utf8) .unwrap_or(0) }; let start = match range.start_bound() { Included(pos) => Included(pos.byte), Excluded(pos) => Included(pos.byte + char_len_at(pos.byte)), Unbounded => Unbounded, }; let end = match range.end_bound() { Included(pos) => Excluded(pos.byte + char_len_at(pos.byte)), Excluded(pos) => Excluded(pos.byte), Unbounded => Unbounded, }; match (start, end) { (Included(s), Excluded(e)) => &self.buf[s..e], (Included(s), Unbounded) => &self.buf[s..], (Unbounded, Excluded(e)) => &self.buf[..e], (Unbounded, Unbounded) => &self.buf[..], _ => unreachable!(), } } /// Advances the cursor by `n` characters. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world!"); /// cursor.skip_n(6); /// assert_eq!(cursor.remaining(), "world!"); /// ``` pub fn skip_n(&mut self, n: usize) { for _ in 0..n { self.next(); } } /// Consumes `n` characters starting from the current position. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world!"); /// let s = cursor.consume_n(5); /// assert_eq!(s, "hello"); /// assert_eq!(cursor.remaining(), " world!"); /// ``` pub fn consume_n(&mut self, n: usize) -> &'a str { let start = self.pos(); self.skip_n(n); let end = self.pos(); self.substr(start..end) } /// Consumes `n` characters starting from the current position if the consumed string satisfies /// a predicate. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world!"); /// assert_eq!(cursor.consume_n_if(5, |s| s.chars().all(|c| c.is_ascii_alphanumeric())), Some("hello")); /// assert_eq!(cursor.remaining(), " world!"); /// assert_eq!(cursor.consume_n_if(5, |s| s.chars().all(|c| c.is_ascii_alphanumeric())), None); /// assert_eq!(cursor.remaining(), " world!"); /// assert_eq!(cursor.consume_n_if(100, |_| true), None); /// ``` pub fn consume_n_if<P>(&mut self, n: usize, predicate: P) -> Option<&'a str> where P: FnOnce(&str) -> bool, { let iter = self.iter.clone().take(n); let count = iter.clone().count(); let len = iter.map(char::len_utf8).sum(); let start = self.pos(); let s = &self.remaining()[..len]; if count == n && predicate(s) { self.skip_n(n); Some(&self.substr(start..self.pos())) } else { None } } /// Consumes the following character if it satisfies the predicate. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello world!"); /// assert_eq!(cursor.consume_if(|c| c.is_ascii_alphanumeric()), Some('h')); /// assert_eq!(cursor.consume_if(|c| c == ' '), None); /// ``` pub fn consume_if<P>(&mut self, predicate: P) -> Option<char> where P: FnOnce(char) -> bool, { if predicate(self.peek()?) { self.next() } else { None } } /// Consumes characters while the predicate is satisfied. Returns `None` if the string is /// empty. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello\nworld!"); /// assert_eq!(cursor.consume_while(|c| c != '\n'), Some("hello")); /// assert_eq!(cursor.consume_while(|c| c != '\n'), None); /// assert_eq!(cursor.next(), Some('\n')); /// ``` pub fn consume_while<P>(&mut self, mut predicate: P) -> Option<&'a str> where P: FnMut(char) -> bool, { let n = self.iter.clone().take_while(|&c| predicate(c)).count(); if n == 0 { return None; } let start = self.pos(); self.skip_n(n); Some(self.substr(start..self.pos())) } /// Consumes no more than `n` characters while they satisfy the predicate. Returns `None` if /// the string is empty. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello\nworld!"); /// assert_eq!(cursor.consume_first_n_while(4, |c| c != '\n'), Some("hell")); /// assert_eq!(cursor.consume_first_n_while(4, |c| c != '\n'), Some("o")); /// assert_eq!(cursor.consume_first_n_while(4, |c| c != '\n'), None); /// ``` pub fn consume_first_n_while<P>(&mut self, n: usize, mut predicate: P) -> Option<&'a str> where P: FnMut(char) -> bool, { let n = self .iter .clone() .take_while(|&c| predicate(c)) .take(n) .count(); if n == 0 { return None; } let start = self.pos(); self.skip_n(n); Some(self.substr(start..self.pos())) } /// Checks whether the remaining string starts with the given substring. /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello\nworld!"); /// assert!(cursor.starts_with("hell")); /// cursor.skip_n(2); /// assert!(cursor.starts_with("llo\nw")); /// assert!(!cursor.starts_with("jelly")); /// ``` pub fn starts_with(&self, s: &str) -> bool { self.remaining().starts_with(s) } /// Skips the characters until the next line. Returns the position of the character preceding /// the line terminator (`\r`, `\n`, `\r\n`, `\n\r`). /// /// ```rust /// # use luaparse::InputCursor; /// let mut cursor = InputCursor::new("hello\r\nworld!"); /// let start = cursor.pos(); /// let end = cursor.skip_line(); /// assert_eq!(cursor.substr(start..=end), "hello"); /// assert_eq!(cursor.remaining(), "world!"); /// ``` pub fn skip_line(&mut self) -> Position { self.consume_while(|c| c != '\r' && c != '\n'); let end_pos = self.prev_pos(); if self .consume_n_if(2, |s| s == "\r\n" || s == "\n\r") .is_none() { self.consume_if(|s| s == '\r' || s == '\n'); } end_pos } } impl<'a> Iterator for InputCursor<'a> { type Item = char; fn next(&mut self) -> Option<char> { let c = self.iter.next(); self.prev_position.replace(self.pos()); self.position.byte += if let Some(c) = c { c.len_utf8() } else { 0 }; if !self.eof { if self.newline { self.position.line += 1; self.position.col = 1; self.newline = false; } if self.keep_column { self.keep_column = false; } else { self.position.col += 1; } } if c.is_none() { self.eof = true; } let c = c?; match c { '\r' => match self.peek() { Some('\n') => self.keep_column = true, _ => self.newline = true, }, '\n' => self.newline = true, _ => {} } Some(c) } }