Skip to content

Commit

Permalink
break!: make Label::new panic for backward spans
Browse files Browse the repository at this point in the history
This should help tracking down backward spans and
it's better to have one method that can panic rather
than 4 methods that can panic (Report::write,
Report::write_for_stdout, Report::print, Report::eprint).
  • Loading branch information
not-my-profile authored and zesterer committed Aug 30, 2023
1 parent 9bead87 commit 12170aa
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 15 deletions.
8 changes: 8 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

# Unreleased

### Breaking changes

- Added missing `S: Span` bound for `Label::new` constructor.

- Previously labels with backwards spans could be constructed and
only resulted in a panic when writing (or printing) the report.
Now `Label::new` panics immediately when passed a backwards span.

### Added

### Removed
Expand Down
17 changes: 16 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -78,10 +78,19 @@ pub struct Label<S = Range<usize>> {
priority: i32,
}

impl<S> Label<S> {
impl<S: Span> Label<S> {
/// Create a new [`Label`].
/// If the span is specified as a `Range<usize>` the numbers have to be zero-indexed character offsets.
///
/// # Panics
///
/// Panics if the given span is backwards.
pub fn new(span: S) -> Self {
assert!(
span.start() <= span.end(),
"Label start is after its end"
);

Self {
span,
msg: None,
Expand Down Expand Up @@ -427,3 +436,9 @@ impl Default for Config {
}
}
}

#[test]
#[should_panic]
fn backwards_label_should_panic() {
Label::new(1..0);
}
14 changes: 0 additions & 14 deletions src/write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,11 +42,6 @@ impl<S: Span> Report<'_, S> {
}
};

assert!(
label.span.start() <= label.span.end(),
"Label start is after its end"
);

let start_line = src.get_offset_line(label.span.start()).map(|(_, l, _)| l);
let end_line = src
.get_offset_line(label.span.end().saturating_sub(1).max(label.span.start()))
Expand Down Expand Up @@ -884,15 +879,6 @@ mod tests {
"###);
}

#[test]
#[should_panic]
fn backwards_label_should_panic() {
let _ = Report::<Range<usize>>::build(ReportKind::Error, (), 0)
.with_label(Label::new(5..0))
.finish()
.write_to_string(Source::from(""));
}

#[test]
fn label_at_end_of_long_line() {
let source = format!("{}orange", "apple == ".repeat(100));
Expand Down

0 comments on commit 12170aa

Please sign in to comment.