Skip to content

Commit a8cbe81

Browse files
committed
Improve parsing related to missing brackets
1 parent ffbbcbb commit a8cbe81

1 file changed

Lines changed: 23 additions & 7 deletions

File tree

src/parser.rs

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -69,6 +69,22 @@ impl Parser {
6969
}
7070
}
7171

72+
fn expect_end(&mut self, expected: &Token, label: &str) -> Result<Spanned<Token>, ParseError> {
73+
let at = self
74+
.tokens
75+
.get(self.pos.wrapping_sub(1))
76+
.map(|t| Span::point(t.span.end))
77+
.unwrap_or(Span::point(0));
78+
match self.peek() {
79+
Some(s) if &s.token == expected => {
80+
let out = s.clone();
81+
self.pos += 1;
82+
Ok(out)
83+
}
84+
_ => Err(self.err(format!("expected {}", label), Some(at))),
85+
}
86+
}
87+
7288
fn with_context<R>(
7389
&mut self,
7490
ctx: &'static str,
@@ -322,7 +338,7 @@ impl Parser {
322338
}
323339
}
324340

325-
p.expect(&Token::RParen, "')'")?;
341+
p.expect_end(&Token::RParen, "')'")?;
326342

327343
p.expect(&Token::LBrace, "'{'")?;
328344

@@ -377,7 +393,7 @@ impl Parser {
377393
}
378394
}
379395

380-
p.expect(&Token::RParen, "')'")?;
396+
p.expect_end(&Token::RParen, "')'")?;
381397

382398
Ok(args)
383399
})
@@ -393,7 +409,7 @@ impl Parser {
393409

394410
let index = self.parse_expr(0)?;
395411

396-
self.expect(&Token::RBracket, "']'")?;
412+
self.expect_end(&Token::RBracket, "']'")?;
397413

398414
left = Expr::Index {
399415
target: Box::new(left),
@@ -515,7 +531,7 @@ impl Parser {
515531
..
516532
}) => {
517533
let expr = self.parse_expr(0)?;
518-
self.expect(&Token::RParen, "')'")?;
534+
self.expect_end(&Token::RParen, "')'")?;
519535
Ok(expr)
520536
}
521537

@@ -537,7 +553,7 @@ impl Parser {
537553
}
538554
}
539555

540-
p.expect(&Token::RBracket, "']'")?;
556+
p.expect_end(&Token::RBracket, "']'")?;
541557

542558
Ok(Expr::ListLiteral(elements))
543559
}),
@@ -566,7 +582,7 @@ impl Parser {
566582
}
567583
}
568584

569-
p.expect(&Token::RBrace, "'}'")?;
585+
p.expect_end(&Token::RBrace, "'}'")?;
570586

571587
Ok(Expr::RecordLiteral(fields))
572588
}),
@@ -590,7 +606,7 @@ impl Parser {
590606
}
591607
}
592608

593-
p.expect(&Token::RParen, "')'")?;
609+
p.expect_end(&Token::RParen, "')'")?;
594610
p.expect(&Token::LBrace, "'{'")?;
595611

596612
let mut body = Vec::new();

0 commit comments

Comments
 (0)