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 1 commit
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
6 changes: 6 additions & 0 deletions pest/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,15 @@ std = ["ucd-trie/std", "thiserror"]
pretty-print = ["serde", "serde_json"]
# Enable const fn constructor for `PrecClimber`
const_prec_climber = []
# Enables error compatibility with miette
miette = ["dep:miette", "std"]

[dependencies]
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"] }
19 changes: 19 additions & 0 deletions pest/examples/parens.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@ extern crate pest;

use std::io::{self, Write};

#[cfg(feature = "miette")]
use miette::IntoDiagnostic;

use pest::error::Error;
use pest::iterators::Pairs;
use pest::{state, ParseResult, Parser, ParserState};
Expand Down Expand Up @@ -57,6 +60,7 @@ fn expr(pairs: Pairs<Rule>) -> Vec<Paren> {
.collect()
}

#[cfg(not(feature = "miette"))]
fn main() {
loop {
let mut line = String::new();
Expand All @@ -73,3 +77,18 @@ fn main() {
};
}
}

#[cfg(feature = "miette")]
fn main() -> miette::Result<()> {
loop {
let mut line = String::new();

print!("> ");
io::stdout().flush().into_diagnostic()?;

io::stdin().read_line(&mut line).into_diagnostic()?;
line.pop();

ParenParser::parse(Rule::expr, &line)?;
}
}
CAD97 marked this conversation as resolved.
Show resolved Hide resolved
42 changes: 40 additions & 2 deletions pest/src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,17 @@

//! Types for different kinds of parsing failures.

#[cfg(feature = "miette")]
use std::boxed::Box;

use alloc::borrow::Cow;
use alloc::borrow::ToOwned;
use alloc::format;
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 All @@ -25,7 +29,8 @@ use crate::RuleType;
/// Parse-related error type.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
#[cfg_attr(feature = "std", error("{}", self.format()))]
#[cfg_attr(all(feature = "std", not(feature = "miette")), error("{}", self.format()))]
#[cfg_attr(all(feature = "std", feature = "miette"), error("Failed to parse at {}", self.line_col))]
pub struct Error<R: RuleType> {
/// Variant of the error
pub variant: ErrorVariant<R>,
Expand All @@ -38,6 +43,30 @@ pub struct Error<R: RuleType> {
continued_line: Option<String>,
}

#[cfg(feature = "miette")]
impl<R: RuleType> miette::Diagnostic for Error<R> {
fn source_code(&self) -> Option<&dyn miette::SourceCode> {
Some(&self.line)
}

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

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

let span = miette::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.variant.message()))
}
}

/// Different kinds of parsing errors.
#[derive(Clone, Debug, Eq, Hash, PartialEq)]
#[cfg_attr(feature = "std", derive(thiserror::Error))]
Expand Down Expand Up @@ -76,6 +105,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 +449,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