Skip to content

Fix SourceAnnotation ranges and refactor to std::fmt::Display #27

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 26, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions benches/simple.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
#![allow(clippy::unit_arg)]
#[macro_use]
extern crate criterion;

use criterion::black_box;
use criterion::Criterion;
use criterion::{black_box, Criterion};

use annotate_snippets::display_list::DisplayList;
use annotate_snippets::formatter::DisplayListFormatter;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
use annotate_snippets::{
display_list::{DisplayList, FormatOptions},
snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};

fn create_snippet() {
let snippet = Snippet {
Expand Down Expand Up @@ -56,11 +57,14 @@ fn create_snippet() {
annotation_type: AnnotationType::Error,
}),
footer: vec![],
opt: FormatOptions {
color: true,
anonymized_line_numbers: false,
},
};

let dl = DisplayList::from(snippet);
let dlf = DisplayListFormatter::new(true, false);
let _result = dlf.format(&dl);
let _result = dl.to_string();
}

pub fn criterion_benchmark(c: &mut Criterion) {
Expand Down
11 changes: 6 additions & 5 deletions examples/expected_type.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use annotate_snippets::display_list::DisplayList;
use annotate_snippets::formatter::DisplayListFormatter;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
use annotate_snippets::{
display_list::DisplayList,
snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};

fn main() {
let snippet = Snippet {
Expand Down Expand Up @@ -32,9 +33,9 @@ fn main() {
},
],
}],
opt: Default::default(),
};

let dl = DisplayList::from(snippet);
let dlf = DisplayListFormatter::new(true, false);
println!("{}", dlf.format(&dl));
println!("{}", dl);
}
11 changes: 6 additions & 5 deletions examples/footer.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use annotate_snippets::display_list::DisplayList;
use annotate_snippets::formatter::DisplayListFormatter;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
use annotate_snippets::{
display_list::DisplayList,
snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};

fn main() {
let snippet = Snippet {
Expand Down Expand Up @@ -29,9 +30,9 @@ fn main() {
annotation_type: AnnotationType::Error,
}],
}],
opt: Default::default(),
};

let dl = DisplayList::from(snippet);
let dlf = DisplayListFormatter::new(true, false);
println!("{}", dlf.format(&dl));
println!("{}", dl);
}
11 changes: 6 additions & 5 deletions examples/format.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use annotate_snippets::display_list::DisplayList;
use annotate_snippets::formatter::DisplayListFormatter;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation};
use annotate_snippets::{
display_list::DisplayList,
snippet::{Annotation, AnnotationType, Slice, Snippet, SourceAnnotation},
};

fn main() {
let snippet = Snippet {
Expand Down Expand Up @@ -50,9 +51,9 @@ fn main() {
annotation_type: AnnotationType::Error,
}),
footer: vec![],
opt: Default::default(),
};

let dl = DisplayList::from(snippet);
let dlf = DisplayListFormatter::new(true, false);
println!("{}", dlf.format(&dl));
println!("{}", dl);
}
11 changes: 6 additions & 5 deletions examples/multislice.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
use annotate_snippets::display_list::DisplayList;
use annotate_snippets::formatter::DisplayListFormatter;
use annotate_snippets::snippet::{Annotation, AnnotationType, Slice, Snippet};
use annotate_snippets::{
display_list::DisplayList,
snippet::{Annotation, AnnotationType, Slice, Snippet},
};

fn main() {
let snippet = Snippet {
Expand All @@ -26,9 +27,9 @@ fn main() {
annotations: vec![],
},
],
opt: Default::default(),
};

let dl = DisplayList::from(snippet);
let dlf = DisplayListFormatter::new(true, false);
println!("{}", dlf.format(&dl));
println!("{}", dl);
}
120 changes: 77 additions & 43 deletions src/display_list/from_snippet.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
//! Trait for converting `Snippet` to `DisplayList`.
use super::*;
use crate::snippet;
use crate::{formatter::get_term_style, snippet};

fn format_label(label: Option<&str>, style: Option<DisplayTextStyle>) -> Vec<DisplayTextFragment> {
let mut result = vec![];
if let Some(label) = label {
let elements: Vec<&str> = label.split("__").collect();
for (idx, element) in elements.iter().enumerate() {
for (idx, element) in label.split("__").enumerate() {
let element_style = match style {
Some(s) => s,
None => {
Expand All @@ -26,22 +25,22 @@ fn format_label(label: Option<&str>, style: Option<DisplayTextStyle>) -> Vec<Dis
result
}

fn format_title(annotation: &snippet::Annotation) -> DisplayLine {
let label = annotation.label.clone().unwrap_or_default();
fn format_title(annotation: snippet::Annotation) -> DisplayLine {
let label = annotation.label.unwrap_or_default();
DisplayLine::Raw(DisplayRawLine::Annotation {
annotation: Annotation {
annotation_type: DisplayAnnotationType::from(annotation.annotation_type),
id: annotation.id.clone(),
id: annotation.id,
label: format_label(Some(&label), Some(DisplayTextStyle::Emphasis)),
},
source_aligned: false,
continuation: false,
})
}

fn format_annotation(annotation: &snippet::Annotation) -> Vec<DisplayLine> {
fn format_annotation(annotation: snippet::Annotation) -> Vec<DisplayLine> {
let mut result = vec![];
let label = annotation.label.clone().unwrap_or_default();
let label = annotation.label.unwrap_or_default();
for (i, line) in label.lines().enumerate() {
result.push(DisplayLine::Raw(DisplayRawLine::Annotation {
annotation: Annotation {
Expand All @@ -56,11 +55,14 @@ fn format_annotation(annotation: &snippet::Annotation) -> Vec<DisplayLine> {
result
}

fn format_slice(slice: &snippet::Slice, is_first: bool, has_footer: bool) -> Vec<DisplayLine> {
fn format_slice(mut slice: snippet::Slice, is_first: bool, has_footer: bool) -> Vec<DisplayLine> {
let main_range = slice.annotations.get(0).map(|x| x.range.0);
let row = slice.line_start;
let origin = slice.origin.take();
let mut body = format_body(slice, has_footer);
let header = format_header(origin, main_range, row, &body, is_first);
let mut result = vec![];

let header = format_header(slice, &body, is_first);
if let Some(header) = header {
result.push(header);
}
Expand All @@ -69,46 +71,45 @@ fn format_slice(slice: &snippet::Slice, is_first: bool, has_footer: bool) -> Vec
}

fn format_header(
slice: &snippet::Slice,
origin: Option<String>,
main_range: Option<usize>,
mut row: usize,
body: &[DisplayLine],
is_first: bool,
) -> Option<DisplayLine> {
let main_annotation = slice.annotations.get(0);

let display_header = if is_first {
DisplayHeaderType::Initial
} else {
DisplayHeaderType::Continuation
};

if let Some(annotation) = main_annotation {
if let Some(main_range) = main_range {
let mut col = 1;
let mut row = slice.line_start;

for item in body.iter() {
for item in body {
if let DisplayLine::Source {
line: DisplaySourceLine::Content { range, .. },
..
} = item
{
if annotation.range.0 >= range.0 && annotation.range.0 <= range.1 {
col = annotation.range.0 - range.0 + 1;
if main_range >= range.0 && main_range <= range.1 {
col = main_range - range.0 + 1;
break;
}
row += 1;
}
}
if let Some(ref path) = slice.origin {
if let Some(path) = origin {
return Some(DisplayLine::Raw(DisplayRawLine::Origin {
path: path.to_string(),
path,
pos: Some((row, col)),
header_type: display_header,
}));
}
}
if let Some(ref path) = slice.origin {
if let Some(path) = origin {
return Some(DisplayLine::Raw(DisplayRawLine::Origin {
path: path.to_string(),
path,
pos: None,
header_type: display_header,
}));
Expand Down Expand Up @@ -175,15 +176,30 @@ fn fold_body(body: &[DisplayLine]) -> Vec<DisplayLine> {
new_body
}

fn format_body(slice: &snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
let mut body = vec![];
fn format_body(slice: snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
let source_len = slice.source.chars().count();
if let Some(bigger) = slice.annotations.iter().find_map(|x| {
if source_len < x.range.1 {
Some(x.range)
} else {
None
}
}) {
panic!(
"SourceAnnotation range `{:?}` is bigger than source length `{}`",
bigger, source_len
)
}

let mut body = vec![];
let mut current_line = slice.line_start;
let mut current_index = 0;
let mut line_index_ranges = vec![];

for line in slice.source.lines() {
let line_length = line.chars().count() + 1;
let lines = slice.source.lines();
let lines_len = lines.clone().count();
for (i, line) in lines.enumerate() {
let line_length = line.chars().count();
let line_range = (current_index, current_index + line_length);
body.push(DisplayLine::Source {
lineno: Some(current_line),
Expand All @@ -195,13 +211,14 @@ fn format_body(slice: &snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
});
line_index_ranges.push(line_range);
current_line += 1;
current_index += line_length + 1;
if i + 1 < lines_len {
current_index += line_length + 1;
}
}

let mut annotation_line_count = 0;
let mut annotations = slice.annotations.clone();
for idx in 0..body.len() {
let (line_start, line_end) = line_index_ranges[idx];
let mut annotations = slice.annotations;
for (idx, (line_start, line_end)) in line_index_ranges.into_iter().enumerate() {
// It would be nice to use filter_drain here once it's stable.
annotations = annotations
.into_iter()
Expand All @@ -214,7 +231,10 @@ fn format_body(slice: &snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
};
match annotation.range {
(start, _) if start > line_end => true,
(start, end) if start >= line_start && end <= line_end => {
(start, end)
if start >= line_start && end <= line_end
|| start == line_end && end - start <= 1 =>
{
let range = (start - line_start, end - line_start);
body.insert(
body_idx + 1,
Expand Down Expand Up @@ -305,6 +325,7 @@ fn format_body(slice: &snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
),
});
}

let range = (end - line_start, end - line_start + 1);
body.insert(
body_idx + 1,
Expand Down Expand Up @@ -367,26 +388,39 @@ fn format_body(slice: &snippet::Slice, has_footer: bool) -> Vec<DisplayLine> {
body
}

// TODO: From reference to DisplayList<'a>
impl From<snippet::Snippet> for DisplayList {
fn from(snippet: snippet::Snippet) -> Self {
fn from(
snippet::Snippet {
title,
footer,
slices,
opt,
}: snippet::Snippet,
) -> Self {
let mut body = vec![];
if let Some(annotation) = snippet.title {
body.push(format_title(&annotation));
if let Some(annotation) = title {
body.push(format_title(annotation));
}

for (idx, slice) in snippet.slices.iter().enumerate() {
body.append(&mut format_slice(
&slice,
idx == 0,
!snippet.footer.is_empty(),
));
for (idx, slice) in slices.into_iter().enumerate() {
body.append(&mut format_slice(slice, idx == 0, !footer.is_empty()));
}

for annotation in snippet.footer {
body.append(&mut format_annotation(&annotation));
for annotation in footer {
body.append(&mut format_annotation(annotation));
}

Self { body }
let FormatOptions {
color,
anonymized_line_numbers,
} = opt;

Self {
body,
stylesheet: get_term_style(color),
anonymized_line_numbers,
}
}
}

Expand Down
2 changes: 1 addition & 1 deletion src/display_list/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@
//!
//! The above snippet has been built out of the following structure:
//!
//! ```
//! ```rust,ignore
//! use annotate_snippets::display_list::*;
//!
//! let dl = DisplayList {
Expand Down
Loading