Skip to content
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

Conditionally implement miette::Diagnostic for pest::error:Error #663

Closed
wants to merge 3 commits into from
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 4 additions & 0 deletions pest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,7 @@ ucd-trie = { version = "0.1.1", default-features = false }
serde = { version = "1.0.89", optional = true }
serde_json = { version = "1.0.39", optional = true}
thiserror = { version = "1.0.31", optional = true }
miette = { version = "5.1.1", optional = true }

[dev-dependencies]
miette = { version = "5.1.1", features = ["fancy"] }
15 changes: 13 additions & 2 deletions pest/examples/parens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,20 @@ fn main() {
io::stdin().read_line(&mut line).unwrap();
line.pop();

match ParenParser::parse(Rule::expr, &line) {
let parsed = ParenParser::parse(Rule::expr, &line);
#[cfg(feature = "miette")]
let parsed = parsed
.map_err(Error::into_miette)
.map_err(miette::Report::from);

match parsed {
Ok(pairs) => println!("{:?}", expr(pairs)),
Err(e) => println!("\n{}", e),
// To print pest errors, use Display formatting.
#[cfg(not(feature = "miette"))]
Err(e) => eprintln!("\n{}", e),
// To print miette errors, use Debug formatting.
#[cfg(feature = "miette")]
Err(e) => eprintln!("\n{:?}", e),
CAD97 marked this conversation as resolved.
Show resolved Hide resolved
};
}
}
55 changes: 54 additions & 1 deletion pest/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ use alloc::string::String;
use alloc::string::ToString;
use alloc::vec::Vec;
use core::cmp;
use core::fmt;
use core::mem;

use crate::position::Position;
Expand Down Expand Up @@ -76,6 +77,15 @@ pub enum LineColLocation {
Span((usize, usize), (usize, usize)),
}

impl fmt::Display for LineColLocation {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Pos((l, c)) => write!(f, "({}, {})", l, c),
Self::Span((ls, cs), (le, ce)) => write!(f, "({}, {}) to ({}, {})", ls, cs, le, ce),
}
}
}

impl<R: RuleType> Error<R> {
/// Creates `Error` from `ErrorVariant` and `Position`.
///
Expand Down Expand Up @@ -411,7 +421,7 @@ impl<R: RuleType> Error<R> {
}
}

pub(crate) fn format(&self) -> String {
pub fn format(&self) -> String {
let spacing = self.spacing();
let path = self
.path
Expand Down Expand Up @@ -482,6 +492,12 @@ impl<R: RuleType> Error<R> {
)
}
}

#[cfg(feature = "miette")]
/// Turns an error into a [miette](crates.io/miette) Diagnostic.
pub fn into_miette(self) -> impl ::miette::Diagnostic {
miette::MietteAdapter(self)
}
}

impl<R: RuleType> ErrorVariant<R> {
Expand Down Expand Up @@ -524,6 +540,43 @@ fn visualize_whitespace(input: &str) -> String {
input.to_owned().replace('\r', "␍").replace('\n', "␊")
}

#[cfg(feature = "miette")]
mod miette {
use alloc::string::ToString;
use std::boxed::Box;

use super::{Error, InputLocation, RuleType};

use miette::{Diagnostic, LabeledSpan, SourceCode};

#[derive(thiserror::Error, Debug)]
#[error("Failure to parse at {}", self.0.line_col)]
pub(crate) struct MietteAdapter<R: RuleType>(pub(crate) Error<R>);

impl<R: RuleType> Diagnostic for MietteAdapter<R> {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

errors could also contain path and continued_line -- should those also be included in a Diagnostic (e.g. as additional labels) or would including those make the Miette default formatted print outs look strange?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, it would make the miette-fornatted output strange. Adding it to the Display is fine, though.

Copy link
Contributor

@CAD97 CAD97 Jul 25, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

So, there's a way around it, but it's a bit hacky:

Provide a custom impl SourceCode which reattaches the line to the span offset information, and then the LabeledSpan can carry the correct span. If the label span is outside SourceCode, weird things can happen (mostly just dropping the source pointer, hopefully).

fn source_code(&self) -> Option<&dyn SourceCode> {
Some(&self.0.line)
}

fn labels(&self) -> Option<Box<dyn Iterator<Item = LabeledSpan>>> {
let message = self.0.variant.message().to_string();

let (offset, length) = match self.0.location {
InputLocation::Pos(x) => (x, 0),
InputLocation::Span((x, y)) => (x, y),
};

let span = LabeledSpan::new(Some(message), offset, length);

Some(Box::new(std::iter::once(span)))
}

fn help<'a>(&'a self) -> Option<Box<dyn core::fmt::Display + 'a>> {
Some(Box::new(self.0.variant.message()))
}
}
}

#[cfg(test)]
mod tests {
use super::super::position;
Expand Down