mirror of
https://github.com/google/comprehensive-rust.git
synced 2025-01-02 06:32:19 +02:00
Simplify some code in the parsing exercise (#1594)
`let Some(x) = E else { return None; }` is equivalent to `let Some(x) = E?`. That latter is shorter and more idiomatic, so let's use that. A pattern of the form `c @ P1 | c @ P1` has the disadvantage that the name `c` is repeated. Let's replace it with `c @ (P1 | P2)`. An `x: Option<Result<T, E>>` can be handled more succinctly with `x.ok_or(...)??`.
This commit is contained in:
parent
9a6a16e4ee
commit
a35841992e
@ -61,9 +61,7 @@ impl<'a> Iterator for Tokenizer<'a> {
|
||||
type Item = Result<Token, TokenizerError>;
|
||||
|
||||
fn next(&mut self) -> Option<Result<Token, TokenizerError>> {
|
||||
let Some(c) = self.0.next() else {
|
||||
return None;
|
||||
};
|
||||
let c = self.0.next()?;
|
||||
match c {
|
||||
'0'..='9' => {
|
||||
let mut num = String::from(c);
|
||||
@ -75,7 +73,7 @@ impl<'a> Iterator for Tokenizer<'a> {
|
||||
}
|
||||
'a'..='z' => {
|
||||
let mut ident = String::from(c);
|
||||
while let Some(c @ 'a'..='z' | c @ '_' | c @ '0'..='9') = self.0.peek() {
|
||||
while let Some(c @ ('a'..='z' | '_' | '0'..='9')) = self.0.peek() {
|
||||
ident.push(*c);
|
||||
self.0.next();
|
||||
}
|
||||
@ -104,9 +102,7 @@ fn parse(input: &str) -> Result<Expression, ParserError> {
|
||||
let mut tokens = tokenize(input);
|
||||
|
||||
fn parse_expr<'a>(tokens: &mut Tokenizer<'a>) -> Result<Expression, ParserError> {
|
||||
let Some(tok) = tokens.next().transpose()? else {
|
||||
return Err(ParserError::UnexpectedEOF);
|
||||
};
|
||||
let tok = tokens.next().ok_or(ParserError::UnexpectedEOF)??;
|
||||
let expr = match tok {
|
||||
Token::Number(num) => {
|
||||
let v = num.parse()?;
|
||||
@ -148,9 +144,7 @@ impl<'a> Iterator for Tokenizer<'a> {
|
||||
type Item = Token;
|
||||
|
||||
fn next(&mut self) -> Option<Token> {
|
||||
let Some(c) = self.0.next() else {
|
||||
return None;
|
||||
};
|
||||
let c = self.0.next()?;
|
||||
match c {
|
||||
'0'..='9' => {
|
||||
let mut num = String::from(c);
|
||||
@ -162,7 +156,7 @@ impl<'a> Iterator for Tokenizer<'a> {
|
||||
}
|
||||
'a'..='z' => {
|
||||
let mut ident = String::from(c);
|
||||
while let Some(c @ 'a'..='z' | c @ '_' | c @ '0'..='9') = self.0.peek() {
|
||||
while let Some(c @ ('a'..='z' | '_' | '0'..='9')) = self.0.peek() {
|
||||
ident.push(*c);
|
||||
self.0.next();
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user