Skip to content

Commit cb31465

Browse files
refactor(wgsl-in): add Lexer::peek_ident_with_span
1. Break out `word_as_ident*` helpers to keep validation of identifiers DRY. 2. Add `peek_*` variant of `Lexer::next_ident_with_span`. This will be consumed immediately in the subsequent commit.
1 parent f669024 commit cb31465

File tree

1 file changed

+28
-12
lines changed

1 file changed

+28
-12
lines changed

naga/src/front/wgsl/parse/lexer.rs

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -350,27 +350,43 @@ impl<'a> Lexer<'a> {
350350
&mut self,
351351
) -> Result<(&'a str, Span), Error<'a>> {
352352
match self.next() {
353-
(Token::Word("_"), span) => Err(Error::InvalidIdentifierUnderscore(span)),
354-
(Token::Word(word), span) if word.starts_with("__") => {
355-
Err(Error::ReservedIdentifierPrefix(span))
356-
}
357-
(Token::Word(word), span) => Ok((word, span)),
353+
(Token::Word(word), span) => Self::word_as_ident_with_span(word, span),
354+
other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)),
355+
}
356+
}
357+
358+
#[allow(dead_code)]
359+
pub(in crate::front::wgsl) fn peek_ident_with_span(
360+
&mut self,
361+
) -> Result<(&'a str, Span), Error<'a>> {
362+
match self.peek() {
363+
(Token::Word(word), span) => Self::word_as_ident_with_span(word, span),
358364
other => Err(Error::Unexpected(other.1, ExpectedToken::Identifier)),
359365
}
360366
}
361367

368+
fn word_as_ident_with_span(word: &'a str, span: Span) -> Result<(&'a str, Span), Error<'a>> {
369+
match word {
370+
"_" => Err(Error::InvalidIdentifierUnderscore(span)),
371+
word if word.starts_with("__") => Err(Error::ReservedIdentifierPrefix(span)),
372+
word => Ok((word, span)),
373+
}
374+
}
375+
362376
pub(in crate::front::wgsl) fn next_ident(
363377
&mut self,
364378
) -> Result<super::ast::Ident<'a>, Error<'a>> {
365-
let ident = self
366-
.next_ident_with_span()
367-
.map(|(name, span)| super::ast::Ident { name, span })?;
379+
self.next_ident_with_span()
380+
.and_then(|(word, span)| Self::word_as_ident(word, span))
381+
.map(|(name, span)| super::ast::Ident { name, span })
382+
}
368383

369-
if crate::keywords::wgsl::RESERVED.contains(&ident.name) {
370-
return Err(Error::ReservedKeyword(ident.span));
384+
fn word_as_ident(word: &'a str, span: Span) -> Result<(&'a str, Span), Error<'a>> {
385+
if crate::keywords::wgsl::RESERVED.contains(&word) {
386+
Err(Error::ReservedKeyword(span))
387+
} else {
388+
Ok((word, span))
371389
}
372-
373-
Ok(ident)
374390
}
375391

376392
/// Parses a generic scalar type, for example `<f32>`.

0 commit comments

Comments
 (0)