Skip to content

Commit 5e7d566

Browse files
committed
Graceful (programming) error handling
1 parent b20cdd1 commit 5e7d566

File tree

2 files changed

+19
-14
lines changed

2 files changed

+19
-14
lines changed

src/ast/comments.rs

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -29,14 +29,19 @@ use crate::tokenizer::{Location, Span};
2929
pub struct Comments(Vec<CommentWithSpan>);
3030

3131
impl Comments {
32-
pub(crate) fn push(&mut self, comment: CommentWithSpan) {
33-
debug_assert!(
34-
self.0
35-
.last()
36-
.map(|last| last.span < comment.span)
37-
.unwrap_or(true)
38-
);
39-
self.0.push(comment);
32+
/// Accepts `comment` if its the first or is located strictly after the
33+
/// last accepted comment. In other words, this method will skip the
34+
/// comment if its comming out of order (as encountered in the parsed
35+
/// source code.)
36+
pub(crate) fn offer(&mut self, comment: CommentWithSpan) {
37+
if self
38+
.0
39+
.last()
40+
.map(|last| last.span < comment.span)
41+
.unwrap_or(true)
42+
{
43+
self.0.push(comment);
44+
}
4045
}
4146

4247
/// Finds comments starting within the given location range. The order of
@@ -221,25 +226,25 @@ mod tests {
221226
// */
222227
// ```
223228
let mut c = Comments(Vec::new());
224-
c.push(CommentWithSpan {
229+
c.offer(CommentWithSpan {
225230
comment: Comment::SingleLine {
226231
content: " abc".into(),
227232
prefix: "--".into(),
228233
},
229234
span: Span::new((1, 1).into(), (1, 7).into()),
230235
});
231-
c.push(CommentWithSpan {
236+
c.offer(CommentWithSpan {
232237
comment: Comment::MultiLine(" hello ".into()),
233238
span: Span::new((2, 3).into(), (2, 14).into()),
234239
});
235-
c.push(CommentWithSpan {
240+
c.offer(CommentWithSpan {
236241
comment: Comment::SingleLine {
237242
content: ", world".into(),
238243
prefix: "--".into(),
239244
},
240245
span: Span::new((2, 14).into(), (2, 21).into()),
241246
});
242-
c.push(CommentWithSpan {
247+
c.offer(CommentWithSpan {
243248
comment: Comment::MultiLine(" def\n ghi\n jkl\n".into()),
244249
span: Span::new((3, 3).into(), (7, 1).into()),
245250
});

src/parser/mod.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -551,7 +551,7 @@ impl<'a> Parser<'a> {
551551
for t in self.tokens.into_iter() {
552552
match t.token {
553553
Token::Whitespace(Whitespace::SingleLineComment { comment, prefix }) => {
554-
comments.push(comments::CommentWithSpan {
554+
comments.offer(comments::CommentWithSpan {
555555
comment: comments::Comment::SingleLine {
556556
content: comment,
557557
prefix,
@@ -560,7 +560,7 @@ impl<'a> Parser<'a> {
560560
});
561561
}
562562
Token::Whitespace(Whitespace::MultiLineComment(comment)) => {
563-
comments.push(comments::CommentWithSpan {
563+
comments.offer(comments::CommentWithSpan {
564564
comment: comments::Comment::MultiLine(comment),
565565
span: t.span,
566566
});

0 commit comments

Comments
 (0)