zesterer / ariadne

A fancy diagnostics & error reporting crate
https://crates.io/crates/ariadne
MIT License
1.74k stars 76 forks source link

How to use this crate with syn/proc-macro2? #35

Open msrd0 opened 2 years ago

msrd0 commented 2 years ago

How can I use this crate when using syn and proc-macro2 for parsing my input? proc_macro2::Span gives me a start and end proc_macro2::LineColumn, not an offset as this crate expects. It seems like there's no obvious way to use offsets that are broken down into line and column already with this crate. How can I accomplish this?

zesterer commented 2 years ago

You'll probably need to count through the input to get the offset.

dmgolembiowski commented 2 years ago

@msrd0 I'm also curious about this. @zesterer's suggestion seems right to me, and so it seems like std::iter::fold is useful, so that a (/* line: */ mut usize, /* column: */ mut usize) can be updated at each successive input element.·

msrd0 commented 2 years ago

@dmgolembiowski I'm using this code as a workaround:

fn offset(&self, at: proc_macro2::LineColumn) -> usize {
    let line_offset: usize = self
        .code
        .split('\n')
        .take(at.line - 1)
        .map(|line| line.chars().count() + 1)
        .sum();
    line_offset + at.column
}

(Source: https://github.com/msrd0/cargo-doc2readme/blob/990595f11ad3459309b1c3da9d46ac096d5bbb14/src/diagnostic.rs#L39-L47)

zesterer commented 2 years ago

Is this addressed?

msrd0 commented 2 years ago

@zesterer There exists a way to use this crate by calculating the offset from the line and column information from proc-macro. I'd still prefer a way to just pass the information directly. If this is something you'd like to incorporate into the api, and if this is something that could potentially save some computation on your end since you do output line and column information in the error message, is something you need to decide.