Coder Social home page Coder Social logo

zkat / miette Goto Github PK

View Code? Open in Web Editor NEW
1.8K 13.0 99.0 1.87 MB

Fancy extension for std::error::Error with pretty, detailed diagnostic printing.

Home Page: https://docs.rs/miette

License: Apache License 2.0

Rust 100.00%
error-handling error-reporting hacktoberfest hacktoberfest2021 rust

miette's Introduction

miette

You run miette? You run her code like the software? Oh. Oh! Error code for coder! Error code for One Thousand Lines!

About

miette is a diagnostic library for Rust. It includes a series of traits/protocols that allow you to hook into its error reporting facilities, and even write your own error reports! It lets you define error types that can print out like this (or in any format you like!):

Hi! miette also includes a screen-reader-oriented diagnostic printer that's enabled in various situations, such as when you use NO_COLOR or CLICOLOR settings, or on CI. This behavior is also fully configurable and customizable. For example, this is what this particular diagnostic will look like when the narrated printer is enabled:
\
Error: Received some bad JSON from the source. Unable to parse.
Caused by: missing field `foo` at line 1 column 1700
\
Begin snippet for https://api.nuget.org/v3/registration5-gz-semver2/json.net/index.json starting
at line 1, column 1659
\
snippet line 1: gs":["json"],"title":"","version":"1.0.0"},"packageContent":"https://api.nuget.o
highlight starting at line 1, column 1699: last parsing location
\
diagnostic help: This is a bug. It might be in ruget, or it might be in the
source you're using, but it's definitely a bug and should be reported.
diagnostic error code: ruget::api::bad_json

NOTE: You must enable the "fancy" crate feature to get fancy report output like in the screenshots above. You should only do this in your toplevel crate, as the fancy feature pulls in a number of dependencies that libraries and such might not want.

Table of Contents

Features

  • Generic Diagnostic protocol, compatible (and dependent on) std::error::Error.
  • Unique error codes on every Diagnostic.
  • Custom links to get more details on error codes.
  • Super handy derive macro for defining diagnostic metadata.
  • Replacements for anyhow/eyre types Result, Report and the miette! macro for the anyhow!/eyre! macros.
  • Generic support for arbitrary SourceCodes for snippet data, with default support for Strings included.

The miette crate also comes bundled with a default ReportHandler with the following features:

  • Fancy graphical diagnostic output, using ANSI/Unicode text
  • single- and multi-line highlighting support
  • Screen reader/braille support, gated on NO_COLOR, and other heuristics.
  • Fully customizable graphical theming (or overriding the printers entirely).
  • Cause chain printing
  • Turns diagnostic codes into links in supported terminals.

Installing

$ cargo add miette

If you want to use the fancy printer in all these screenshots:

$ cargo add miette --features fancy

Example

/*
You can derive a `Diagnostic` from any `std::error::Error` type.

`thiserror` is a great way to define them, and plays nicely with `miette`!
*/
use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Error, Debug, Diagnostic)]
#[error("oops!")]
#[diagnostic(
    code(oops::my::bad),
    url(docsrs),
    help("try doing it better next time?")
)]
struct MyBad {
    // The Source that we're gonna be printing snippets out of.
    // This can be a String if you don't have or care about file names.
    #[source_code]
    src: NamedSource<String>,
    // Snippets and highlights can be included in the diagnostic!
    #[label("This bit here")]
    bad_bit: SourceSpan,
}

/*
Now let's define a function!

Use this `Result` type (or its expanded version) as the return type
throughout your app (but NOT your libraries! Those should always return
concrete types!).
*/
use miette::{NamedSource, Result};
fn this_fails() -> Result<()> {
    // You can use plain strings as a `Source`, or anything that implements
    // the one-method `Source` trait.
    let src = "source\n  text\n    here".to_string();

    Err(MyBad {
        src: NamedSource::new("bad_file.rs", src),
        bad_bit: (9, 4).into(),
    })?;

    Ok(())
}

/*
Now to get everything printed nicely, just return a `Result<()>`
and you're all set!

Note: You can swap out the default reporter for a custom one using
`miette::set_hook()`
*/
fn pretend_this_is_main() -> Result<()> {
    // kaboom~
    this_fails()?;

    Ok(())
}

And this is the output you'll get if you run this program:

<img src="https://raw.githubusercontent.com/zkat/miette/main/images/single-line-example.png" alt=" Narratable printout:
diagnostic error code: oops::my::bad (link) Error: oops!


Begin snippet for bad_file.rs starting at line 2, column 3
snippet line 1: source


snippet line 2: text highlight starting at line 1, column 3: This bit here
snippet line 3: here
diagnostic help: try doing it better next time?">

Using

... in libraries

miette is fully compatible with library usage. Consumers who don't know about, or don't want, miette features can safely use its error types as regular std::error::Error.

We highly recommend using something like thiserror to define unique error types and error wrappers for your library.

While miette integrates smoothly with thiserror, it is not required. If you don't want to use the Diagnostic derive macro, you can implement the trait directly, just like with std::error::Error.

// lib/error.rs
use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
pub enum MyLibError {
    #[error(transparent)]
    #[diagnostic(code(my_lib::io_error))]
    IoError(#[from] std::io::Error),

    #[error("Oops it blew up")]
    #[diagnostic(code(my_lib::bad_code))]
    BadThingHappened,

    #[error(transparent)]
    // Use `#[diagnostic(transparent)]` to wrap another [`Diagnostic`]. You won't see labels otherwise
    #[diagnostic(transparent)]
    AnotherError(#[from] AnotherError),
}

#[derive(Error, Diagnostic, Debug)]
#[error("another error")]
pub struct AnotherError {
   #[label("here")]
   pub at: SourceSpan
}

Then, return this error type from all your fallible public APIs. It's a best practice to wrap any "external" error types in your error enum instead of using something like Report in a library.

... in application code

Application code tends to work a little differently than libraries. You don't always need or care to define dedicated error wrappers for errors coming from external libraries and tools.

For this situation, miette includes two tools: Report and IntoDiagnostic. They work in tandem to make it easy to convert regular std::error::Errors into Diagnostics. Additionally, there's a Result type alias that you can use to be more terse.

When dealing with non-Diagnostic types, you'll want to .into_diagnostic() them:

// my_app/lib/my_internal_file.rs
use miette::{IntoDiagnostic, Result};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    "1.2.x".parse().into_diagnostic()
}

miette also includes an anyhow/eyre-style Context/WrapErr traits that you can import to add ad-hoc context messages to your Diagnostics, as well, though you'll still need to use .into_diagnostic() to make use of it:

// my_app/lib/my_internal_file.rs
use miette::{IntoDiagnostic, Result, WrapErr};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    "1.2.x"
        .parse()
        .into_diagnostic()
        .wrap_err("Parsing this tool's semver version failed.")
}

To construct your own simple adhoc error use the [miette!] macro:

// my_app/lib/my_internal_file.rs
use miette::{miette, Result};
use semver::Version;

pub fn some_tool() -> Result<Version> {
    let version = "1.2.x";
    version
        .parse()
        .map_err(|_| miette!("Invalid version {}", version))
}

There are also similar [bail!] and [ensure!] macros.

... in main()

main() is just like any other part of your application-internal code. Use Result as your return value, and it will pretty-print your diagnostics automatically.

NOTE: You must enable the "fancy" crate feature to get fancy report output like in the screenshots here.** You should only do this in your toplevel crate, as the fancy feature pulls in a number of dependencies that libraries and such might not want.

use miette::{IntoDiagnostic, Result};
use semver::Version;

fn pretend_this_is_main() -> Result<()> {
    let version: Version = "1.2.x".parse().into_diagnostic()?;
    println!("{}", version);
    Ok(())
}

Please note: in order to get fancy diagnostic rendering with all the pretty colors and arrows, you should install miette with the fancy feature enabled:

miette = { version = "X.Y.Z", features = ["fancy"] }

Another way to display a diagnostic is by printing them using the debug formatter. This is, in fact, what returning diagnostics from main ends up doing. To do it yourself, you can write the following:

use miette::{IntoDiagnostic, Result};
use semver::Version;

fn just_a_random_function() {
    let version_result: Result<Version> = "1.2.x".parse().into_diagnostic();
    match version_result {
        Err(e) => println!("{:?}", e),
        Ok(version) => println!("{}", version),
    }
}

... diagnostic code URLs

miette supports providing a URL for individual diagnostics. This URL will be displayed as an actual link in supported terminals, like so:

 Example showing the graphical report printer for miette
pretty-printing an error code. The code is underlined and followed by text
saying to 'click here'. A hover tooltip shows a full-fledged URL that can be
Ctrl+Clicked to open in a browser.
\
This feature is also available in the narratable printer. It will add a line
after printing the error code showing a plain URL that you can visit.

To use this, you can add a url() sub-param to your #[diagnostic] attribute:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
#[error("kaboom")]
#[diagnostic(
    code(my_app::my_error),
    // You can do formatting!
    url("https://my_website.com/error_codes#{}", self.code().unwrap())
)]
struct MyErr;

Additionally, if you're developing a library and your error type is exported from your crate's top level, you can use a special url(docsrs) option instead of manually constructing the URL. This will automatically create a link to this diagnostic on docs.rs, so folks can just go straight to your (very high quality and detailed!) documentation on this diagnostic:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Error, Diagnostic, Debug)]
#[diagnostic(
    code(my_app::my_error),
    // Will link users to https://docs.rs/my_crate/0.0.0/my_crate/struct.MyErr.html
    url(docsrs)
)]
#[error("kaboom")]
struct MyErr;

... snippets

Along with its general error handling and reporting features, miette also includes facilities for adding error spans/annotations/labels to your output. This can be very useful when an error is syntax-related, but you can even use it to print out sections of your own source code!

To achieve this, miette defines its own lightweight SourceSpan type. This is a basic byte-offset and length into an associated SourceCode and, along with the latter, gives miette all the information it needs to pretty-print some snippets! You can also use your own Into<SourceSpan> types as label spans.

The easiest way to define errors like this is to use the derive(Diagnostic) macro:

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic(code(my_lib::random_error))]
pub struct MyErrorType {
    // The `Source` that miette will use.
    #[source_code]
    src: String,

    // This will underline/mark the specific code inside the larger
    // snippet context.
    #[label = "This is the highlight"]
    err_span: SourceSpan,

    // You can add as many labels as you want.
    // They'll be rendered sequentially.
    #[label("This is bad")]
    snip2: (usize, usize), // `(usize, usize)` is `Into<SourceSpan>`!

    // Snippets can be optional, by using Option:
    #[label("some text")]
    snip3: Option<SourceSpan>,

    // with or without label text
    #[label]
    snip4: Option<SourceSpan>,
}

... help text

miette provides two facilities for supplying help text for your errors:

The first is the #[help()] format attribute that applies to structs or enum variants:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic(help("try doing this instead"))]
struct Foo;

The other is by programmatically supplying the help text as a field to your diagnostic:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic()]
struct Foo {
    #[help]
    advice: Option<String>, // Can also just be `String`
}

let err = Foo {
    advice: Some("try doing this instead".to_string()),
};

... severity level

miette provides a way to set the severity level of a diagnostic.

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("welp")]
#[diagnostic(severity(Warning))]
struct Foo;

... multiple related errors

miette supports collecting multiple errors into a single diagnostic, and printing them all together nicely.

To do so, use the #[related] tag on any IntoIter field in your Diagnostic type:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Error, Diagnostic)]
#[error("oops")]
struct MyError {
    #[related]
    others: Vec<MyError>,
}

... delayed source code

Sometimes it makes sense to add source code to the error message later. One option is to use with_source_code() method for that:

use miette::{Diagnostic, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic()]
pub struct MyErrorType {
    // Note: label but no source code
    #[label]
    err_span: SourceSpan,
}

fn do_something() -> miette::Result<()> {
    // This function emits actual error with label
    return Err(MyErrorType {
        err_span: (7..11).into(),
    })?;
}

fn main() -> miette::Result<()> {
    do_something().map_err(|error| {
        // And this code provides the source code for inner error
        error.with_source_code(String::from("source code"))
    })
}

Also source code can be provided by a wrapper type. This is especially useful in combination with related, when multiple errors should be emitted at the same time:

use miette::{Diagnostic, Report, SourceSpan};
use thiserror::Error;

#[derive(Diagnostic, Debug, Error)]
#[error("oops")]
#[diagnostic()]
pub struct InnerError {
    // Note: label but no source code
    #[label]
    err_span: SourceSpan,
}

#[derive(Diagnostic, Debug, Error)]
#[error("oops: multiple errors")]
#[diagnostic()]
pub struct MultiError {
    // Note source code by no labels
    #[source_code]
    source_code: String,
    // The source code above is used for these errors
    #[related]
    related: Vec<InnerError>,
}

fn do_something() -> Result<(), Vec<InnerError>> {
    Err(vec![
        InnerError {
            err_span: (0..6).into(),
        },
        InnerError {
            err_span: (7..11).into(),
        },
    ])
}

fn main() -> miette::Result<()> {
    do_something().map_err(|err_list| MultiError {
        source_code: "source code".into(),
        related: err_list,
    })?;
    Ok(())
}

... Diagnostic-based error sources.

When one uses the #[source] attribute on a field, that usually comes from thiserror, and implements a method for [std::error::Error::source]. This works in many cases, but it's lossy: if the source of the diagnostic is a diagnostic itself, the source will simply be treated as an std::error::Error.

While this has no effect on the existing reporters, since they don't use that information right now, APIs who might want this information will have no access to it.

If it's important for you for this information to be available to users, you can use #[diagnostic_source] alongside #[source]. Not that you will likely want to use both:

use miette::Diagnostic;
use thiserror::Error;

#[derive(Debug, Diagnostic, Error)]
#[error("MyError")]
struct MyError {
    #[source]
    #[diagnostic_source]
    the_cause: OtherError,
}

#[derive(Debug, Diagnostic, Error)]
#[error("OtherError")]
struct OtherError;

... handler options

MietteHandler is the default handler, and is very customizable. In most cases, you can simply use MietteHandlerOpts to tweak its behavior instead of falling back to your own custom handler.

Usage is like so:

miette::set_hook(Box::new(|_| {
    Box::new(
        miette::MietteHandlerOpts::new()
            .terminal_links(true)
            .unicode(false)
            .context_lines(3)
            .tab_width(4)
            .break_words(true)
            .build(),
    )
}))

See the docs for MietteHandlerOpts for more details on what you can customize!

... dynamic diagnostics

If you...

  • ...don't know all the possible errors upfront
  • ...need to serialize/deserialize errors then you may want to use miette!, diagnostic! macros or MietteDiagnostic directly to create diagnostic on the fly.
let source = "2 + 2 * 2 = 8".to_string();
let report = miette!(
  labels = vec![
      LabeledSpan::at(12..13, "this should be 6"),
  ],
  help = "'*' has greater precedence than '+'",
  "Wrong answer"
).with_source_code(source);
println!("{:?}", report)

... syntax highlighting

miette can be configured to highlight syntax in source code snippets.

To use the built-in highlighting functionality, you must enable the syntect-highlighter crate feature. When this feature is enabled, miette will automatically use the [syntect] crate to highlight the #[source_code] field of your Diagnostic.

Syntax detection with [syntect] is handled by checking 2 methods on the [SpanContents] trait, in order:

  • language() - Provides the name of the language as a string. For example "Rust" will indicate Rust syntax highlighting. You can set the language of the [SpanContents] produced by a [NamedSource] via the with_language method.
  • name() - In the absence of an explicitly set language, the name is assumed to contain a file name or file path. The highlighter will check for a file extension at the end of the name and try to guess the syntax from that.

If you want to use a custom highlighter, you can provide a custom implementation of the Highlighter trait to MietteHandlerOpts by calling the with_syntax_highlighting method. See the [highlighters] module docs for more details.

... collection of labels

When the number of labels is unknown, you can use a collection of SourceSpan (or any type convertible into SourceSpan). For this, add the collection parameter to label and use any type than can be iterated over for the field.

#[derive(Debug, Diagnostic, Error)]
#[error("oops!")]
struct MyError {
    #[label("main issue")]
    primary_span: SourceSpan,

    #[label(collection, "related to this")]
    other_spans: Vec<Range<usize>>,
}

let report: miette::Report = MyError {
    primary_span: (6, 9).into(),
    other_spans: vec![19..26, 30..41],
}.into();

println!("{:?}", report.with_source_code("About something or another or yet another ...".to_string()));

A collection can also be of LabeledSpan if you want to have different text for different labels. Labels with no text will use the one from the label attribute

#[derive(Debug, Diagnostic, Error)]
#[error("oops!")]
struct MyError {
    #[label("main issue")]
    primary_span: SourceSpan,

    #[label(collection, "related to this")]
    other_spans: Vec<LabeledSpan>, // LabeledSpan
}

let report: miette::Report = MyError {
    primary_span: (6, 9).into(),
    other_spans: vec![
        LabeledSpan::new(None, 19, 7), // Use default text `related to this`
        LabeledSpan::new(Some("and also this".to_string()), 30, 11), // Use specific text
    ],
}.into();

println!("{:?}", report.with_source_code("About something or another or yet another ...".to_string()));

MSRV

This crate requires rustc 1.70.0 or later.

Acknowledgements

miette was not developed in a void. It owes enormous credit to various other projects and their authors:

  • anyhow and color-eyre: these two enormously influential error handling libraries have pushed forward the experience of application-level error handling and error reporting. miette's Report type is an attempt at a very very rough version of their Report types.
  • thiserror for setting the standard for library-level error definitions, and for being the inspiration behind miette's derive macro.
  • rustc and @estebank for their state-of-the-art work in compiler diagnostics.
  • ariadne for pushing forward how pretty these diagnostics can really look!

License

miette is released to the Rust community under the Apache license 2.0.

It also includes code taken from eyre, and some from thiserror, also under the Apache License. Some code is taken from ariadne, which is MIT licensed.

miette's People

Contributors

0x009922 avatar andrewhickman avatar attila-lin avatar benjamin-l avatar bnjjj avatar boshen avatar cad97 avatar cormacrelf avatar dbanty avatar erratic-pattern avatar g-plane avatar gankra avatar gavrilikhin-d avatar icewind1991 avatar jdonszelmann avatar manicmarrc avatar matthiasbeyer avatar mattx avatar nahor avatar nathanwhit avatar phantomical avatar sunshowers avatar tailhook avatar thelostlambda avatar theneikos avatar trapincho avatar virtualritz avatar waywardmonkeys avatar zanieb avatar zkat avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

miette's Issues

address accessibility story

How accessible are these errors? What changes could be made to make them easier to consume for visually impaired folks? We should have a reasonable story for this before 1.0 goes out. Right now, I don't imagine it's very useful to get these error messages.

toplevel error footer

Miette should be able to automatically print a static or customizable error message as a footer to all generic errors for you.

For example:

Need help? Check out https://voltpkg.com/troubleshoot/internet::connection::404 <- notice the fact that i can add my custom error code here

Support for multiple diagnostics

Right now, miette supports multiple snippets. It also supports a single cause chain (though all .source()s have to be StdError instead of Diagnostic.

It would be nice for miette, maybe at the Report level, to support multiple diagnostics in some way that makes sense. This issue needs some thinking and investigation into actual use-cases before implementation/proposal.

Syntax highlighting support

Add support for syntax highlighting through syntect.

I figure this can be done by having the graphical handler take an optional SyntaxSet, and have an optional identifier token method as part of SpanContents, so the renderer can color code accordingly.

The biggest challenge here is designing things such that things are appropriately feature flagged and don't grow binaries too much?

Prepare docs for 1.0

everything, including the derive macro, should be well-documented, with reasonable guide-level documentation showing folks how to use miette!

`#[document_codes]` attribute macro

So it turns out that derive macros can't expand anything in-place: they can only generate new code in a completely different area.

We need a #[document_codes] attribute macro that you can slap at the toplevel of anything using the Diagnostic derive, which goes through and adds #[doc(alias = "my::code::here")] to the error struct or enum, in the appropriate places.

This might be tricky because you're injecting stuff in the middle of a tokenstream, but maybe it's easier than it sounds?

[Epic]: Nicer reporter

The current reporter is "okay", but it's nothing to write home about. This is a tracking issue for writing a version of the reporter that we can really show off!

Snippet message not rendered when source is not named

This goes back to #23, when the "header" concept was introduced. The header is not rendered at all when the source returns None for .name(). (Back in v0.12 you needed SourceSpan::new_labeled.)

Workaround atm is to give every source a name. But given Source is implemented for unnamed String/Arc<String> miette should be able to render the header without a name.

Using String/ Arc<String>

Error: ────[code::here]────────────────────

    × std::error::Error display message

 1 │ one two thre
   ·     ─┬─
   ·      ╰── highlight message

Using NamedSource

Error: ────[code::here]────────────────────

    × std::error::Error display message

   ╭───[example.txt:1:1] snippet message:
 1 │ one two thre
   ·     ─┬─
   ·      ╰── highlight message


Now that I figured out the issue, it's like a few lines to edit across a few printers, so lemme give it a go.

While I'm thinking about this, I think we could implement Source on &'static str because these can be cloned just as freely as the others and are obviously 'static. Not super useful except for testing.

forwarding compile test succeeded when it should have failed

I'm getting the following on cargo t:

failures:

---- src\compile_test.rs - compile_test::ForwardWithoutCode (line 113) stdout ----
Test compiled successfully, but it's marked `compile_fail`.
---- src\compile_test.rs - compile_test::ForwardWithoutCode (line 98) stdout ----
Test compiled successfully, but it's marked `compile_fail`.

failures:
    src\compile_test.rs - compile_test::ForwardWithoutCode (line 113)
    src\compile_test.rs - compile_test::ForwardWithoutCode (line 98)

@cormacrelf does this make any sense to you? Did your more recent changes make this issue moot?

Provide clickable links for error codes in terminal output

Some modern terminal support escape codes that can be used to insert clickable links on terminal text. These are used, for example, in GCC's diagnostic output.

It would be great if the error codes output by miette's terminal formatter would be clickable links that directly open the documentation page for the error.

Some information about the terminal escapes for links is here: https://gist.github.com/egmontkob/eb114294efbcd5adb1944c9f3cb5feda

Derive macro: single field for multiple snippets

Allowing dynamic list of spans to provide highlights you can be good for using miette to wrap tools like TypeScript (tsc).

Looking at the source code, maybe Vec<SourceSpan> might not cut it, but introducing a new LabelledSourceSpan and allowing everything that is Into<Vec<LabelledSourceSpan>> could also make sense.

What do you think?

Snippet-level help/info text

Miette currently only supports a single "help" message, at the end of a whole diagnostic. It might be handy to do something like what rustc does, where multiple info/help messages can be attached to snippets themselves? This might potentially be resolved instead by whatever #47 ends up looking like, with the addition of multiple "footer" labels (help/info/suggestion/etc).

Issue with whitespaces and byteoffset

I try to use miette with a parser, if the node parsed is of type error then I use miette to render the error. I have an issue because in miette it seems you're skipping '\n' and whitespaces into the source code. Then when I try to specify my SourceSpan thanks to the byte position it doesn't work at all because it the byte position with whitespaces and in your code you use the source_code string without any whitespaces.

How can I do this correctly ?

example of my code:

let err = ParsingError {
	bad_bit: (node.start_byte(), node.end_byte()).into(), // ISSUE HERE
	src: src.to_string(),
};

Diagnostic suggestion support

One really cool relatively recent addition to rustc is the ability to add suggestions (in green) that propose specific changes to a snippet and highlight the changed text. It would be nice for this to have first-class support in miette. Maybe it can be implemented by just adding a "type" to DiagnosticSnippet to change its display mode?

Error message should provide link to ruget + miette bug trackers

In @zkat's tweet https://twitter.com/zkat__/status/1428962008699793412/photo/1, the final message is

This is a bug. It might be in ruget, or it might be in the source
you're using, but it's definitely a bug and should be reported.

The question arises, to whom or what should the bug be reported?

Providing a link to both ruget and miette's Issues pages would be a great start, and if it's not in miette or ruget then whoever is maintaining those projects can guide the submitter to a more appropriate project to file a bug with.

Weird tab character rendering

I'm using miette in a parser that deals with tab \t indents and so far noticed the following:

  • miette renders one \t as the number of spaces configured in the terminal (OK)
  • miette counts one \t's width as equal to one space and displays the arrow/label according to this width (Breaks because of the above, but should be possible to deal with by the developer)

So I decided to calculate number of tabs in the line, multiply it by tab width, and add that to the offset minus the number of tabs. Example:

  1. \t\t with tab width 4 = 8
  2. Offset of some char that caused the error is 10
  3. We add 10 + 8 and subtract 2 (number of tabs) and give that number as SourceSpan (16, 0)

In my repro this places the arrow in the correct position. But weird stuff happens if I have a really big offset (exactly 37 and more chars). It either just renders the line without rendering arrow/label or simply panics with this error:

thread 'main' panicked at 'failed printing to stderr: formatter error', library/std/src/io/stdio.rs:935:9
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace

Here's a reproduction:
https://github.com/jlkiri/miette-tab-error-repro

`Report` doesn't forward diagnostic fields

The wrapper Diagnostic types that Report uses should be marked as transparent diagnostics, so stuff like snippets and codes show up when you .context() on something. Oops!

More flexible and customizable ReportHandler situation

The default reporters are fantastic, and there's even hooks to customize them with, but you're kinda stuck with the overall look beyond what the GraphicalTheme provides.

It's not ideal for everyone using miette to have "the miette look". It should be possible (and easy!) to piece together your own handler while still taking advantage of the fairly complex snippet and such reporting code.

This might also involve merging the graphical and narrated handlers into two modes of one big handler (maybe even include #29 in that). Also all the logic for switching between them and figuring out some terminal specific things.

derive: snippet support

The current derive macro supports code, help, and derive, but doesn't really handle the snippet part of miette. Extend the macro so that you can write stuff like this:

#[derive(Debug, Error, Diagnostic)]
#[diagnostic(code(math::bad_arithmetic))]
#[error("Tried to add a {bad_type} to a {good_type}")]
pub struct MyErr {
  good_type: Type,
  bad_type: Type,
  bad_var: Var,
  src: PathBuf,

  // The overall span of code that will be rendered.
  #[context(src, "This region is where things went wrong")]
  ctx: SourceSpan,

  // A highlight (basically something to underline)
  #[highlight(ctx, "This is a {bad_type}")]
  bad_var_span: SourceSpan,

  // Can have multiple highlights.
  #[highlight(ctx, "This is a {good_type}")]
  good_var_span: SourceSpan,
}

MietteReporter: Add multiline highlight support

One of the nice things that miette should handle out of the box is having highlights that point to multi-line code blocks.

The protocol as it is right now should be able to handle it just fine, but this seems like just a generally pretty hard thing to write a reporter for, so I'm struggling.

Let me know if you care a lot about this and I'll gladly leave it in your hands, though!

full format capabilities for `help()`

Right now, help is pretty limited as far as formatting goes. It should be expanded to allow everything thiserror supports, including shorthand format strings and enum variant access.

Label span is rendered incorrectly in report.

I'm implementing Diagnostic manually for an error type so that it can provide different labels depending on the nature of the error. While testing, I noticed this report, which seems to render the span of the here label incorrectly:

Error: glob::rule

  x invalid glob expression: singular tree wildcard `**` in alternative

   ,----
 1 | {foo,**,bar,baz}
   : ^^^^^^^^|^^^^^^^
   :         |`-- here
   :         `-- in this alternative
   `----

I printed the LabeledSpans provided by Diagnostic::labels and they look correct to me:

[LabeledSpan { label: Some("in this alternative"), span: SourceSpan { offset: SourceOffset(0), length: SourceOffset(16) } }, LabeledSpan { label: Some("here"), span: SourceSpan { offset: SourceOffset(5), length: SourceOffset(2) } }]

Note that the span for the here label has an offset of 5 and length of 2, which should isolate ** in the source text for this error. I've tried relocating the token that ultimately emits this error and the span always appears correct but renders in the same way (spanning the entire alternative token). It almost looks as if the span is being replaced by the span of the in this alternative label.

I'm using version 3.0.0 of miette and other cases using as many as three separate labels render as expected. Any ideas? Thanks!

split off DiagnosticReport + reporters into their own library?

No rush, I think, because the intention is very much that anyone using miette will also probably be using the reporter, but I'm hoping people write their own bespoke reporters against the "protocol".

...maybe that means we need miette-protocol, and miette is the Big Chonker library? That would let us do this refactor without being semver-breaking. 🤔

Words on the first line being dropped?

Hey,

First up, this library is dope. Love your work. 🚀

I'm having one small issue though - if I have a SourceSpan that points somewhere in the first line of some source code, that first line seems to get chopped.

Here's a test to reproduce:

#[cfg(test)]
mod miette_test {
    use miette::{
        Diagnostic, GraphicalReportHandler, GraphicalTheme, SourceSpan, ThemeCharacters,
        ThemeStyles,
    };
    use thiserror::Error;

    #[derive(Error, Debug, Diagnostic)]
    #[error("some error")]
    #[diagnostic(help("where did the word 'imagine' go!?"))]
    struct SomeError {
        #[source_code]
        some_code: String,
        #[label("'imagine' should come before this")]
        some_span: SourceSpan,
    }

    #[test]
    fn whytho() {
        let mut rendered = String::new();
        let diagnostic = SomeError {
            some_code: "imagine this is some code\n\nyou're seeing all of this line".to_owned(),
            some_span: (8, 0).into(),
        };

        GraphicalReportHandler::new()
            .with_theme(GraphicalTheme {
                characters: ThemeCharacters::ascii(),
                styles: ThemeStyles::none(),
            })
            .with_context_lines(3)
            .render_report(&mut rendered, &diagnostic)
            .unwrap();
        assert_eq!(
            &rendered,
            r#"
  x some error
   ,-[1:1]
 1 | this is some code
   : ^
   : `-- 'imagine' should come before this
 2 | 
 3 | you're seeing all of this line
   `----
  help: where did the word 'imagine' go!?
"#
        );
    }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.