Debian Codegraph @

src/lexer.rs

raw symbols SCIP
1 use crate::token::{Float, Integer, Location, PreprocessorError, Punct};
2 use std::str::Chars;
3 use unicode_xid::UnicodeXID;
4
5 type CharAndLine = (char, u32);
6
7 // GLSL ES 3.20 specification section 3.10. Logical Phases of Compilation
8 // This iterator implements phases 4 and 5 of the logical phases of compilation:
9 //
10 // 4. Each {carriage-return, line-feed} and {line-feed, carriage return} sequence is replaced by
11 // a single newline. All remaining carriage-return and line-feed characters are then each
12 // replaced by a newline.
13 //
14 // 5. Line numbering for each character, which is equal to the number of preceding newlines plus
15 // one, is noted. Note this can only be subsequently changed by the #line directive and is not
16 // affected by the removal of newlines in phase 6 of compilation.
17 //
18 // It expects that phases 1 to 3 are already done and that valid utf8 is passed in.
19 #[derive(Clone)]
20 pub struct CharsAndLine<'a> {
21 inner: Chars<'a>,
22 line: u32,
23 }
24
25 impl<'a> CharsAndLine<'a> {
26 pub fn new(input: &'a str) -> Self {
27 CharsAndLine {
28 inner: input.chars(),
29 line: 1,
30 }
31 }
32
33 pub fn get_current_ptr(&self) -> *const u8 {
34 self.inner.as_str().as_ptr()
35 }
36 }
37
38 impl<'a> Iterator for CharsAndLine<'a> {
39 type Item = CharAndLine;
40
41 fn next(&mut self) -> Option<Self::Item> {
42 let current = self.inner.next()?;
43
44 match current {
45 '\n' => {
46 // Consume the token but see if we can grab a \r that follows
47 let mut peek_inner = self.inner.clone();
48 if peek_inner.next() == Some('\r') {
49 self.inner = peek_inner;
50 }
51
52 let res = Some(('\n', self.line));
53 self.line += 1;
54 res
55 }
56 '\r' => {
57 // Consume the token but see if we can grab a \n that follows
58 let mut peek_inner = self.inner.clone();
59 if peek_inner.next() == Some('\n') {
60 self.inner = peek_inner;
61 }
62
63 let res = Some(('\n', self.line));
64 self.line += 1;
65 res
66 }
67
68 _ => Some((current, self.line)),
69 }
70 }
71 }
72
73 // An iterator that adds stage 6 on top of CharsAndLocation:
74 //
75 // 6. Wherever a backslash ('\') occurs immediately before a newline, both are deleted. Note that
76 // no whitespace is substituted, thereby allowing a single preprocessing token to span a
77 // newline. This operation is not recursive; any new {backslash newline} sequences generated
78 // are not removed.
79 #[derive(Clone)]
80 pub struct SkipBackslashNewline<'a> {
81 inner: CharsAndLine<'a>,
82 }
83
84 impl<'a> SkipBackslashNewline<'a> {
85 pub fn new(input: &'a str) -> Self {
86 SkipBackslashNewline {
87 inner: CharsAndLine::new(input),
88 }
89 }
90
91 pub fn get_current_ptr(&self) -> *const u8 {
92 self.inner.get_current_ptr()
93 }
94 }
95
96 impl<'a> Iterator for SkipBackslashNewline<'a> {
97 type Item = CharAndLine;
98
99 fn next(&mut self) -> Option<Self::Item> {
100 let mut current = self.inner.next()?;
101
102 while current.0 == '\\' {
103 let mut peek_inner = self.inner.clone();
104 if let Some(('\n', _)) = peek_inner.next() {
105 self.inner = peek_inner;
106 current = self.next()?;
107 } else {
108 return Some(current);
109 }
110 }
111
112 Some(current)
113 }
114 }
115
116 // An iterator that adds stage 7 on top of SkipBackslashNewline:
117 //
118 // 7. All comments are replaced with a single space. All (non-zero) characters and invalid UTF-8
119 // byte sequences are allowed within comments. '//' style comments include the initial '//'
120 // marker and continue up to, but not including, the terminating newline. '/…/' comments
121 // include both the start and end marker.
122 #[derive(Clone)]
123 pub struct ReplaceComments<'a> {
124 inner: SkipBackslashNewline<'a>,
125 }
126
127 // The lexer wants to know when whitespace is a comment to know if a comment was ever processed.
128 // To avoid adding state we use a sentinel value of '\r' because all '\r' have been consumed and
129 // turned into '\n' by CharsAndLocation.
130 pub const COMMENT_SENTINEL_VALUE: char = '\r';
131
132 impl<'a> ReplaceComments<'a> {
133 pub fn new(input: &'a str) -> Self {
134 ReplaceComments {
135 inner: SkipBackslashNewline::new(input),
136 }
137 }
138
139 pub fn get_current_ptr(&self) -> *const u8 {
140 self.inner.get_current_ptr()
141 }
142 }
143
144 impl<'a> Iterator for ReplaceComments<'a> {
145 type Item = CharAndLine;
146
147 fn next(&mut self) -> Option<Self::Item> {
148 let current = self.inner.next()?;
149
150 if current.0 != '/' {
151 debug_assert!(current.0 != COMMENT_SENTINEL_VALUE);
152 return Some(current);
153 }
154
155 let mut peek_inner = self.inner.clone();
156 match peek_inner.next() {
157 // The // case, consume until but not including the next \n
158 Some(('/', _)) => {
159 self.inner = peek_inner.clone();
160 while let Some((next, _)) = peek_inner.next() {
161 if next == '\n' {
162 break;
163 }
164 self.inner = peek_inner.clone();
165 }
166
167 Some((COMMENT_SENTINEL_VALUE, current.1))
168 }
169 // The /*, consume until the next */
170 Some(('*', _)) => {
171 let mut was_star = false;
172 while let Some((next, _)) = peek_inner.next() {
173 if was_star && next == '/' {
174 break;
175 }
176 was_star = next == '*';
177 }
178 self.inner = peek_inner;
179
180 Some((COMMENT_SENTINEL_VALUE, current.1))
181 }
182
183 // Not // or /*, do nothing
184 _ => Some(current),
185 }
186 }
187 }
188
189 // A lexer for GLSL tokens that also emits a couple extra tokens that are useful to the
190 // preprocessor: # and newlines. It also include metadata for the token for whether it is at the
191 // start of the line, or if it has leading whitespace.
192
193 // This is a helper iterator to abstract away the tracking of location data (offset, line) from
194 // `Lexer`. It looks like a Peekable<Iterator<char>> with `next_char` and `peek_char` but also
195 // allows querying the last seen/consumed lines / offset.
196 #[derive(Clone)]
197 struct LexerCharIterator<'a> {
198 inner: ReplaceComments<'a>,
199 peeked: Option<(CharAndLine, *const u8)>,
200 last_consumed: (CharAndLine, *const u8),
201 input_start: *const u8,
202 }
203
204 pub const NONE_CONSUMED_SENTINEL_VALUE: char = '\r';
205
206 impl<'a> LexerCharIterator<'a> {
207 pub fn new(input: &'a str) -> Self {
208 LexerCharIterator {
209 inner: ReplaceComments::new(input),
210 peeked: None,
211 last_consumed: ((NONE_CONSUMED_SENTINEL_VALUE, 0), input.as_bytes().as_ptr()),
212 input_start: input.as_bytes().as_ptr(),
213 }
214 }
215 fn next_char(&mut self) -> Option<char> {
216 self.last_consumed = match self.peeked.take() {
217 Some(v) => v,
218 None => {
219 let ptr = self.inner.get_current_ptr();
220 (self.inner.next()?, ptr)
221 }
222 };
223 Some(self.last_consumed.0 .0)
224 }
225
226 fn peek_char(&mut self) -> Option<char> {
227 match self.peeked {
228 Some(v) => Some(v.0 .0),
229 None => {
230 let ptr = self.inner.get_current_ptr();
231 let next = self.inner.next()?;
232 self.peeked = Some((next, ptr));
233 Some(next.0)
234 }
235 }
236 }
237
238 fn get_last_seen_line(&self) -> u32 {
239 self.peeked.unwrap_or(self.last_consumed).0 .1
240 }
241
242 fn get_last_seen_start_offset(&self) -> usize {
243 self.peeked.unwrap_or(self.last_consumed).1 as usize - self.input_start as usize
244 }
245
246 fn get_last_consumed_end_offset(&self) -> usize {
247 self.last_consumed.1 as usize - self.input_start as usize
248 + self.last_consumed.0 .0.len_utf8()
249 }
250 }
251
252 // A superset of the token value returned by the preprocessor
253 #[derive(Clone, PartialEq, Debug)]
254 pub enum TokenValue {
255 // Preprocessor specific token values
256 Hash,
257 NewLine,
258
259 // Regular token values
260 Ident(String),
261 Integer(Integer),
262 Float(Float),
263 Punct(Punct),
264 }
265
266 impl From<Punct> for TokenValue {
267 fn from(punct: Punct) -> Self {
268 TokenValue::Punct(punct)
269 }
270 }
271
272 #[derive(Clone, PartialEq, Debug)]
273 pub struct Token {
274 pub value: TokenValue,
275 pub location: Location,
276 pub leading_whitespace: bool,
277 pub start_of_line: bool,
278 }
279
280 pub type LexerItem = Result<Token, (PreprocessorError, Location)>;
281 pub struct Lexer<'a> {
282 inner: LexerCharIterator<'a>,
283 leading_whitespace: bool,
284 start_of_line: bool,
285 had_comments: bool,
286 }
287
288 impl<'a> Lexer<'a> {
289 pub fn new(input: &'a str) -> Self {
290 // TODO bail out on source that is too large.
291 Lexer {
292 inner: LexerCharIterator::new(input),
293 leading_whitespace: true,
294 start_of_line: true,
295 had_comments: false,
296 }
297 }
298
299 pub fn had_comments(&self) -> bool {
300 self.had_comments
301 }
302
303 // TODO: Make a runtime flag to toggle unicode identifiers support
304 // The glsl spec only allows ascii identifiers
305 fn parse_identifier(&mut self) -> Result<TokenValue, PreprocessorError> {
306 let mut identifier = String::default();
307
308 if let Some(c) = self.next_char_if(|c| c.is_xid_start() || c == '_') {
309 identifier.push(c);
310 }
311
312 let rest = self.consume_chars(|c| c.is_xid_continue());
313 identifier.push_str(&rest);
314
315 // TODO check if identifier is larger than the limit.
316 Ok(TokenValue::Ident(identifier))
317 }
318
319 fn parse_integer_signedness_suffix(&mut self) -> bool {
320 self.next_char_if(|c| c == 'u' || c == 'U').is_none()
321 }
322
323 fn parse_integer_width_suffix(&mut self) -> Result<i32, PreprocessorError> {
324 match self.inner.peek_char() {
325 Some('l') | Some('L') => Err(PreprocessorError::NotSupported64BitLiteral),
326 Some('s') | Some('S') => Err(PreprocessorError::NotSupported16BitLiteral),
327 _ => Ok(32),
328 }
329 }
330
331 fn parse_float_width_suffix(&mut self) -> Result<i32, PreprocessorError> {
332 match self.inner.peek_char() {
333 Some('l') | Some('L') => Err(PreprocessorError::NotSupported64BitLiteral),
334 Some('h') | Some('H') => Err(PreprocessorError::NotSupported16BitLiteral),
335 Some('f') | Some('F') => {
336 self.inner.next_char();
337 Ok(32)
338 }
339 _ => Ok(32),
340 }
341 }
342
343 fn next_char_if(&mut self, predicate: impl FnOnce(char) -> bool) -> Option<char> {
344 if let Some(c) = self.inner.peek_char() {
345 if predicate(c) {
346 return self.inner.next_char();
347 }
348 }
349 None
350 }
351
352 fn consume_chars(&mut self, filter: impl Fn(char) -> bool) -> String {
353 let mut result: String = Default::default();
354 while let Some(c) = self.next_char_if(&filter) {
355 result.push(c);
356 }
357 result
358 }
359
360 fn parse_number(&mut self, first_char: char) -> Result<TokenValue, PreprocessorError> {
361 let mut is_float = false;
362 let mut integer_radix = 10;
363 let mut raw: String = Default::default();
364 raw.push(first_char);
365
366 // Handle hexadecimal numbers that needs to consume a..f in addition to digits.
367 if first_char == '0' {
368 match self.inner.peek_char() {
369 Some('x') | Some('X') => {
370 self.inner.next_char();
371
372 raw += &self.consume_chars(|c| matches!(c, '0'..='9' | 'a'..='f' | 'A'..='F'));
373 integer_radix = 16;
374 }
375
376 // Octal numbers can also be the prefix of floats, so we need to parse all digits
377 // and not just 0..7 in case it is a float like 00009.0f, the parsing of all digits
378 // is done below, but we still need to remember the radix.
379 Some('0'..='9') => {
380 integer_radix = 8;
381 }
382 _ => {}
383 };
384 }
385
386 if first_char == '.' {
387 is_float = true;
388 } else {
389 // Parse any digits at the end of integers, or for the non-fractional part of floats.
390 raw += &self.consume_chars(|c| ('0'..='9').contains(&c));
391
392 if self.next_char_if(|c| c == '.').is_some() {
393 raw.push('.');
394 is_float = true;
395 }
396 }
397
398 // At this point either we're an integer missing only suffixes, or we're a float with
399 // everything up to the . consumed.
400 if is_float {
401 raw += &self.consume_chars(|c| ('0'..='9').contains(&c));
402 }
403
404 // Handle scientific notation with a (e|E)(+|-|)\d+ suffix when we're a float or an
405 // an integer that could turn into a float if we add a exponent to it (so 0x1E-1
406 // isn't recognized as a float).
407 if (is_float || integer_radix == 8 || integer_radix == 10)
408 && self.next_char_if(|c| c == 'e' || c == 'E').is_some()
409 {
410 raw.push('e');
411 is_float = true;
412
413 match self.inner.peek_char() {
414 Some('+') => {
415 self.inner.next_char();
416 raw.push('+');
417 }
418 Some('-') => {
419 self.inner.next_char();
420 raw.push('-');
421 }
422 _ => {}
423 }
424
425 // TODO: what should we do when there is no number after the exponent?
426 raw += &self.consume_chars(|c| ('0'..='9').contains(&c));
427 }
428
429 if is_float {
430 // TODO: Depending on the GLSL version make it an error to not have the suffix.
431 let width = self.parse_float_width_suffix()?;
432
433 Ok(TokenValue::Float(Float {
434 value: raw
435 .parse::<f32>()
436 .map_err(|_| PreprocessorError::FloatParsingError)?,
437 width,
438 }))
439 } else {
440 let signed = self.parse_integer_signedness_suffix();
441 let width = self.parse_integer_width_suffix()?;
442
443 // Skip the initial 0 in hexa or octal (in hexa we never added the 'x').
444 if integer_radix != 10 {
445 raw = raw.split_off(1);
446 }
447
448 Ok(TokenValue::Integer(Integer {
449 value: u64::from_str_radix(&raw, integer_radix)
450 .map_err(|_err| PreprocessorError::IntegerOverflow)?,
451 signed,
452 width,
453 }))
454 }
455 }
456
457 fn parse_punctuation(&mut self) -> Result<TokenValue, PreprocessorError> {
458 let save_point = self.inner.clone();
459
460 let char0 = self.inner.next_char().unwrap_or('\0');
461 let char1 = self.inner.next_char().unwrap_or('\0');
462 let char2 = self.inner.next_char().unwrap_or('\0');
463
464 let maybe_punct = match (char0, char1, char2) {
465 ('<', '<', '=') => Some((Punct::LeftShiftAssign, 3)),
466 ('<', '<', _) => Some((Punct::LeftShift, 2)),
467 ('<', '=', _) => Some((Punct::LessEqual, 2)),
468 ('<', _, _) => Some((Punct::LeftAngle, 1)),
469
470 ('>', '>', '=') => Some((Punct::RightShiftAssign, 3)),
471 ('>', '>', _) => Some((Punct::RightShift, 2)),
472 ('>', '=', _) => Some((Punct::GreaterEqual, 2)),
473 ('>', _, _) => Some((Punct::RightAngle, 1)),
474
475 ('+', '+', _) => Some((Punct::Increment, 2)),
476 ('+', '=', _) => Some((Punct::AddAssign, 2)),
477 ('+', _, _) => Some((Punct::Plus, 1)),
478
479 ('-', '-', _) => Some((Punct::Decrement, 2)),
480 ('-', '=', _) => Some((Punct::SubAssign, 2)),
481 ('-', _, _) => Some((Punct::Minus, 1)),
482
483 ('&', '&', _) => Some((Punct::LogicalAnd, 2)),
484 ('&', '=', _) => Some((Punct::AndAssign, 2)),
485 ('&', _, _) => Some((Punct::Ampersand, 1)),
486
487 ('|', '|', _) => Some((Punct::LogicalOr, 2)),
488 ('|', '=', _) => Some((Punct::OrAssign, 2)),
489 ('|', _, _) => Some((Punct::Pipe, 1)),
490
491 ('^', '^', _) => Some((Punct::LogicalXor, 2)),
492 ('^', '=', _) => Some((Punct::XorAssign, 2)),
493 ('^', _, _) => Some((Punct::Caret, 1)),
494
495 ('=', '=', _) => Some((Punct::EqualEqual, 2)),
496 ('=', _, _) => Some((Punct::Equal, 1)),
497 ('!', '=', _) => Some((Punct::NotEqual, 2)),
498 ('!', _, _) => Some((Punct::Bang, 1)),
499
500 ('*', '=', _) => Some((Punct::MulAssign, 2)),
501 ('*', _, _) => Some((Punct::Star, 1)),
502 ('/', '=', _) => Some((Punct::DivAssign, 2)),
503 ('/', _, _) => Some((Punct::Slash, 1)),
504 ('%', '=', _) => Some((Punct::ModAssign, 2)),
505 ('%', _, _) => Some((Punct::Percent, 1)),
506
507 ('(', _, _) => Some((Punct::LeftParen, 1)),
508 (')', _, _) => Some((Punct::RightParen, 1)),
509 ('{', _, _) => Some((Punct::LeftBrace, 1)),
510 ('}', _, _) => Some((Punct::RightBrace, 1)),
511 ('[', _, _) => Some((Punct::LeftBracket, 1)),
512 (']', _, _) => Some((Punct::RightBracket, 1)),
513
514 (',', _, _) => Some((Punct::Comma, 1)),
515 (';', _, _) => Some((Punct::Semicolon, 1)),
516 (':', _, _) => Some((Punct::Colon, 1)),
517 ('~', _, _) => Some((Punct::Tilde, 1)),
518 ('?', _, _) => Some((Punct::Question, 1)),
519 // Note that Dot (".") is handled in Lexer::next since it can be
520 // either punctuation or the start of a floating point number.
521 _ => None,
522 };
523
524 if let Some((punct, size)) = maybe_punct {
525 self.inner = save_point;
526 for _ in 0..size {
527 self.inner.next_char();
528 }
529 Ok(punct.into())
530 } else if char0 == '#' {
531 self.inner = save_point;
532 self.inner.next_char();
533 Ok(TokenValue::Hash)
534 } else {
535 Err(PreprocessorError::UnexpectedCharacter)
536 }
537 }
538 }
539
540 impl<'a> Iterator for Lexer<'a> {
541 type Item = LexerItem;
542
543 fn next(&mut self) -> Option<Self::Item> {
544 while let Some(current_char) = self.inner.peek_char() {
545 let had_leading_whitespace = self.leading_whitespace;
546 self.leading_whitespace = false;
547
548 let mut location = Location {
549 line: self.inner.get_last_seen_line(),
550 start: self.inner.get_last_seen_start_offset() as u32,
551 end: 0,
552 };
553
554 let was_start_of_line = self.start_of_line;
555 self.start_of_line = false;
556
557 let value = match current_char {
558 ' ' | '\t' | '\x0b' | '\x0c' | COMMENT_SENTINEL_VALUE => {
559 if current_char == COMMENT_SENTINEL_VALUE {
560 self.had_comments = true;
561 }
562 self.start_of_line = was_start_of_line;
563 self.leading_whitespace = true;
564 self.inner.next_char();
565 continue;
566 }
567 '\n' => {
568 self.leading_whitespace = true;
569 self.start_of_line = true;
570 self.inner.next_char();
571 Ok(TokenValue::NewLine)
572 }
573
574 c @ '0'..='9' => {
575 self.inner.next_char();
576 self.parse_number(c)
577 }
578
579 // Special case . as a punctuation because it can be the start of a float.
580 '.' => {
581 self.inner.next_char();
582
583 match self.inner.peek_char() {
584 Some('0'..='9') => self.parse_number('.'),
585 _ => Ok(TokenValue::Punct(Punct::Dot)),
586 }
587 }
588 _ => {
589 // TODO: see todo in `parse_identifier` for information
590 if current_char.is_xid_start() || current_char == '_' {
591 self.parse_identifier()
592 } else {
593 self.parse_punctuation()
594 }
595 }
596 };
597
598 location.end = self.inner.get_last_consumed_end_offset() as u32;
599
600 return Some(value.map_err(|e| (e, Default::default())).map(|t| Token {
601 value: t,
602 location,
603 leading_whitespace: had_leading_whitespace,
604 start_of_line: was_start_of_line,
605 }));
606 }
607
608 // Do the C hack of always ending with a newline so that preprocessor directives are ended.
609 if !self.start_of_line {
610 self.start_of_line = true;
611
612 let end_offset = self.inner.get_last_consumed_end_offset() as u32;
613
614 Some(Ok(Token {
615 value: TokenValue::NewLine,
616 location: Location {
617 line: self.inner.get_last_seen_line(),
618 start: end_offset,
619 end: end_offset,
620 },
621 leading_whitespace: self.leading_whitespace,
622 start_of_line: false,
623 }))
624 } else {
625 None
626 }
627 }
628 }