proc-macro2-diagnostics-0.10.1/.cargo_vcs_info.json0000644000000001360000000000100155440ustar { "git": { "sha1": "45fa2d68669d10daeaf0f9b664a96576626fae16" }, "path_in_vcs": "" }proc-macro2-diagnostics-0.10.1/.github/workflows/ci.yml000064400000000000000000000015101046102023000210440ustar 00000000000000name: CI on: [push, pull_request] env: CARGO_TERM_COLOR: always jobs: test: name: "${{ matrix.os.name }} ${{ matrix.test.name }} (${{ matrix.toolchain }})" continue-on-error: false runs-on: ${{ matrix.os.distro }} strategy: fail-fast: false matrix: os: - { name: Linux, distro: ubuntu-latest } - { name: Windows, distro: windows-latest } - { name: macOS, distro: macOS-latest } toolchain: [nightly, stable] steps: - name: Checkout Sources uses: actions/checkout@v2 - name: Install Rust uses: actions-rs/toolchain@v1 with: profile: minimal toolchain: ${{ matrix.toolchain }} override: true - name: Run Tests uses: actions-rs/cargo@v1 with: command: test proc-macro2-diagnostics-0.10.1/.gitignore000064400000000000000000000000261046102023000163220ustar 00000000000000target Cargo.lock wip proc-macro2-diagnostics-0.10.1/Cargo.toml0000644000000022730000000000100135460ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "proc-macro2-diagnostics" version = "0.10.1" authors = ["Sergio Benitez "] description = "Diagnostics for proc-macro2." homepage = "https://github.com/SergioBenitez/proc-macro2-diagnostics" documentation = "https://docs.rs/proc-macro2-diagnostics" readme = "README.md" license = "MIT/Apache-2.0" repository = "https://github.com/SergioBenitez/proc-macro2-diagnostics" [dependencies.proc-macro2] version = "1.0" [dependencies.quote] version = "1.0" [dependencies.syn] version = "2.0" [dependencies.yansi] version = "1.0.0-rc" optional = true [dev-dependencies.trybuild] version = "1.0" [build-dependencies.version_check] version = "0.9.4" [features] colors = ["yansi"] default = ["colors"] proc-macro2-diagnostics-0.10.1/Cargo.toml.orig000064400000000000000000000013021046102023000172170ustar 00000000000000[package] name = "proc-macro2-diagnostics" version = "0.10.1" authors = ["Sergio Benitez "] description = "Diagnostics for proc-macro2." license = "MIT/Apache-2.0" edition = "2018" readme = "README.md" repository = "https://github.com/SergioBenitez/proc-macro2-diagnostics" homepage = "https://github.com/SergioBenitez/proc-macro2-diagnostics" documentation = "https://docs.rs/proc-macro2-diagnostics" [features] default = ["colors"] colors = ["yansi"] [dependencies] quote = "1.0" proc-macro2 = "1.0" syn = "2.0" yansi = { version = "1.0.0-rc", optional = true } [build-dependencies] version_check = "0.9.4" [dev-dependencies] trybuild = "1.0" diagnostic-example = { path = "example/" } proc-macro2-diagnostics-0.10.1/LICENSE-APACHE000064400000000000000000000227731046102023000162730ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS proc-macro2-diagnostics-0.10.1/LICENSE-MIT000064400000000000000000000020751046102023000157740ustar 00000000000000The MIT License (MIT) Copyright (c) 2016-2020 Sergio Benitez Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. proc-macro2-diagnostics-0.10.1/README.md000064400000000000000000000036361046102023000156230ustar 00000000000000# proc-macro2-diagnostics   [![crates.io]][crate] [![docs.rs]][docs] [crates.io]: https://img.shields.io/crates/v/proc-macro2-diagnostics.svg [crate]: https://crates.io/crates/proc-macro2-diagnostics [docs.rs]: https://docs.rs/proc-macro2-diagnostics/badge.svg [docs]: https://docs.rs/proc-macro2-diagnostics Diagnostics for stable and nightly proc-macros! ## Usage 1. Depend on the library in your proc-macro. ```toml [dependencies] proc_macro2_diagnostics = "0.10" ``` 2. Import `SpanDiagnosticExt` and use its methods on a `proc_macro2::Span` to create `Diagnostic`s: ```rust use syn::spanned::Spanned; use proc_macro2::TokenStream; use proc_macro2_diagnostics::{SpanDiagnosticExt, Diagnostic}; fn my_macro(input: TokenStream) -> Result { Err(input.span().error("there's a problem here...")) } ``` 3. If there's an error, emit the diagnostic as tokens: ```rust extern crate proc_macro; pub fn real_macro(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream { match my_macro(tokens.into()) { Ok(tokens) => tokens.into(), Err(diag) => diag.emit_as_expr_tokens().into() } } ``` This does the right thing on nightly _or_ stable. ### Caveats On stable, due to limitations, any top-level, non-error diagnostics are emitted as errors. This will abort compilation. To avoid this, you may want to `cfg`-gate emitting non-error diagnostics to nightly. ### Colors By default, error messages are colored on stable. To disable, disable default features: ```toml [dependencies] proc_macro2_diagnostics = { version = "0.10", default-features = false } ``` The compiler always colors diagnostics on nightly. ## License Licensed under either of the following, at your option: * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or http://www.apache.org/licenses/LICENSE-2.0) * MIT License ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) proc-macro2-diagnostics-0.10.1/build.rs000064400000000000000000000003451046102023000160030ustar 00000000000000fn main() { if let Some((version, channel, _)) = version_check::triple() { if version.at_least("1.31.0") && channel.supports_features() { println!("cargo:rustc-cfg=nightly_diagnostics"); } } } proc-macro2-diagnostics-0.10.1/src/diagnostic.rs000064400000000000000000000250761046102023000176270ustar 00000000000000use proc_macro2::{Span, TokenStream}; use crate::SpanDiagnosticExt; use crate::line::Line; /// Trait implemented by types that can be converted into a set of `Span`s. pub trait MultiSpan { /// Converts `self` into a `Vec`. fn into_spans(self) -> Vec; } impl MultiSpan for Span { fn into_spans(self) -> Vec { vec![self] } } impl MultiSpan for Vec { fn into_spans(self) -> Vec { self } } impl<'a> MultiSpan for &'a [Span] { fn into_spans(self) -> Vec { self.to_vec() } } /// An enum representing a diagnostic level. #[non_exhaustive] #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Level { /// An error. Error, /// A warning. Warning, /// A note. Note, /// A help message. Help, } impl std::str::FromStr for Level { type Err = (); fn from_str(s: &str) -> Result { if s.contains(Level::Error.as_str()) { Ok(Level::Error) } else if s.contains(Level::Warning.as_str()) { Ok(Level::Warning) } else if s.contains(Level::Note.as_str()) { Ok(Level::Note) } else if s.contains(Level::Help.as_str()) { Ok(Level::Help) } else { Err(()) } } } impl Level { fn as_str(self) -> &'static str { match self { Level::Error => "error", Level::Warning => "warning", Level::Note => "note", Level::Help => "help", } } } impl std::fmt::Display for Level { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { self.as_str().fmt(f) } } /// A structure representing a diagnostic message and associated children /// messages. #[derive(Clone, Debug)] pub struct Diagnostic { level: Level, message: String, spans: Vec, children: Vec } macro_rules! diagnostic_child_methods { ($spanned:ident, $regular:ident, $level:expr) => ( /// Adds a new child diagnostic message to `self` with the level /// identified by this method's name with the given `spans` and /// `message`. pub fn $spanned(self, spans: S, message: T) -> Diagnostic where S: MultiSpan, T: Into { self.spanned_child(spans, $level, message) } /// Adds a new child diagnostic message to `self` with the level /// identified by this method's name with the given `message`. pub fn $regular>(self, message: T) -> Diagnostic { self.child($level, message) } ) } impl Diagnostic { /// Creates a new diagnostic with the given `level` and `message`. pub fn new>(level: Level, message: T) -> Diagnostic { Diagnostic { level, message: message.into(), spans: vec![], children: vec![] } } /// Creates a new diagnostic with the given `level` and `message` pointing /// to the given set of `spans`. pub fn spanned(spans: S, level: Level, message: T) -> Diagnostic where S: MultiSpan, T: Into { Diagnostic { level, message: message.into(), spans: spans.into_spans(), children: vec![] } } /// Adds a new child diagnostic message to `self` with the `level` and the /// given `spans` and `message`. pub fn spanned_child(mut self, spans: S, level: Level, message: T) -> Diagnostic where S: MultiSpan, T: Into { self.children.push(Diagnostic::spanned(spans, level, message)); self } /// Adds a new child diagnostic message to `self` with `level` and the given /// `message`. pub fn child>(mut self, level: Level, message: T) -> Diagnostic { self.children.push(Diagnostic::new(level, message)); self } diagnostic_child_methods!(span_error, error, Level::Error); diagnostic_child_methods!(span_warning, warning, Level::Warning); diagnostic_child_methods!(span_note, note, Level::Note); diagnostic_child_methods!(span_help, help, Level::Help); /// Return the children diagnostics of `self`. pub fn children(&self) -> impl Iterator { self.children.iter() } /// Return the `level` of `self`. pub fn level(&self) -> Level { self.level } fn stable_emit_as_tokens(self, item: bool) -> TokenStream { let error: syn::parse::Error = self.into(); if item { error.to_compile_error() } else { let compile_error_calls = error.into_iter().map(|e| { let compile_error = e.to_compile_error(); quote::quote_spanned!(e.span() => #compile_error;) }); quote::quote!({ #(#compile_error_calls)* }) } } /// Emit the diagnostic as tokens. #[cfg(not(nightly_diagnostics))] fn emit_as_tokens(self, item: bool, _: TokenStream) -> TokenStream { self.stable_emit_as_tokens(item) } /// Emit the diagnostic as tokens. #[cfg(nightly_diagnostics)] fn emit_as_tokens(self, item: bool, default: TokenStream) -> TokenStream { if !crate::nightly_works() { return self.stable_emit_as_tokens(item); } proc_macro::Diagnostic::from(self).emit(); default } /// Emit tokens, suitable for item contexts, to generate a comple-time /// diagnostic corresponding to `self`. On nightly, this directly emits the /// error and returns an empty token stream. pub fn emit_as_item_tokens(self) -> TokenStream { self.emit_as_tokens(true, TokenStream::new()) } /// Emit tokens, suitable for item contexts, to generate a comple-time /// diagnostic corresponding to `self`. On nightly, this directly emits the /// error and returns `default`. pub fn emit_as_item_tokens_or(self, default: TokenStream) -> TokenStream { self.emit_as_tokens(true, default) } /// Emit tokens, suitable for expression contexts, to generate a comple-time /// diagnostic corresponding to `self`. On nightly, this directly emits the /// error and returns a `()` token stream. pub fn emit_as_expr_tokens(self) -> TokenStream { self.emit_as_tokens(false, quote::quote!({})) } /// Emit tokens, suitable for expressioon contexts, to generate a /// comple-time diagnostic corresponding to `self`. On nightly, this /// directly emits the error and returns `default`. pub fn emit_as_expr_tokens_or(self, default: TokenStream) -> TokenStream { self.emit_as_tokens(false, default) } } impl From for syn::parse::Error { fn from(diag: Diagnostic) -> syn::parse::Error { fn diag_to_msg(diag: &Diagnostic) -> String { let (spans, level, msg) = (&diag.spans, diag.level, &diag.message); if spans.is_empty() { Line::joined(level, msg).to_string() } else { if level == Level::Error { return msg.into(); } Line::new(level, msg).to_string() } } fn diag_to_span(diag: &Diagnostic) -> Span { diag.spans.get(0).cloned().unwrap_or_else(|| Span::call_site()) } let mut msg = diag_to_msg(&diag); let mut span = diag_to_span(&diag); let mut error: Option = None; for child in diag.children { if child.spans.is_empty() { // Join to the current error we're building up. msg.push_str(&format!("\n{}", diag_to_msg(&child))); } else { // This creates a new error with all of the diagnostic messages // that have been joined thus far in `msg`. let new_error = syn::parse::Error::new(span, &msg); if let Some(ref mut error) = error { error.combine(new_error); } else { error = Some(new_error); } // Start a new error to be built from `child`. span = diag_to_span(&child); msg = diag_to_msg(&child); } } if let Some(mut error) = error { error.combine(syn::parse::Error::new(span, &msg)); error } else { syn::parse::Error::new(span, &msg) } } } impl From for Diagnostic { fn from(error: syn::parse::Error) -> Diagnostic { let mut diag: Option = None; for e in &error { for line in e.to_string().lines() { if let Some(line) = Line::parse(line) { if line.is_new() { diag = diag.map(|d| d.spanned_child(e.span(), line.level, line.msg)) .or_else(|| Some(Diagnostic::spanned(e.span(), line.level, line.msg))); } else { diag = diag.map(|d| d.child(line.level, line.msg)); } } else { diag = diag.map(|d| d.span_error(e.span(), line)) .or_else(|| Some(e.span().error(line))); } } } diag.unwrap_or_else(|| error.span().error(error.to_string())) } } #[cfg(nightly_diagnostics)] impl From for proc_macro::Diagnostic { fn from(diag: Diagnostic) -> proc_macro::Diagnostic { fn spans_to_proc_macro_spans(spans: Vec) -> Vec { spans.into_iter() .map(|s| s.unstable()) .collect::>() } let spans = spans_to_proc_macro_spans(diag.spans); let level = match diag.level { Level::Error => proc_macro::Level::Error, Level::Warning => proc_macro::Level::Warning, Level::Note => proc_macro::Level::Note, Level::Help => proc_macro::Level::Help, }; let mut proc_diag = proc_macro::Diagnostic::spanned(spans, level, diag.message); for child in diag.children { // FIXME: proc_macro::Diagnostic needs a `push` method. let spans = spans_to_proc_macro_spans(child.spans); proc_diag = match child.level { Level::Error => proc_diag.span_error(spans, child.message), Level::Warning => proc_diag.span_warning(spans, child.message), Level::Note => proc_diag.span_note(spans, child.message), Level::Help => proc_diag.span_help(spans, child.message), }; } proc_diag } } proc-macro2-diagnostics-0.10.1/src/ext.rs000064400000000000000000000027251046102023000162770ustar 00000000000000use proc_macro2::Span; use crate::diagnostic::{Level, Diagnostic}; macro_rules! diagnostic_def { ($name:ident) => ( /// Create a new `Diagnostic` of the kind of this method's name with the /// span `self`. fn $name>(self, message: T) -> Diagnostic; ) } /// Extension trait for `proc_macro2::Span` emulating the proc-macro diagnostic /// API on stable and nightly. /// /// # Example /// /// ```rust /// use proc_macro2::Span; /// use proc_macro2_diagnostics::SpanDiagnosticExt; /// /// let span = Span::call_site(); /// let diag = span.error("there's a problem here..."); /// /// // emit into an expression context. /// # let diag = span.error("there's a problem here..."); /// let tokens = diag.emit_as_expr_tokens(); /// /// // or emit into an item context. /// # let diag = span.error("there's a problem here..."); /// let tokens = diag.emit_as_item_tokens(); /// ``` pub trait SpanDiagnosticExt { diagnostic_def!(error); diagnostic_def!(warning); diagnostic_def!(note); diagnostic_def!(help); } macro_rules! diagnostic_method { ($name:ident, $level:expr) => ( fn $name>(self, message: T) -> Diagnostic { Diagnostic::spanned(self, $level, message) } ) } impl SpanDiagnosticExt for Span { diagnostic_method!(error, Level::Error); diagnostic_method!(warning, Level::Warning); diagnostic_method!(note, Level::Note); diagnostic_method!(help, Level::Help); } proc-macro2-diagnostics-0.10.1/src/lib.rs000064400000000000000000000112371046102023000162430ustar 00000000000000#![cfg_attr(nightly_diagnostics, feature(proc_macro_diagnostic, proc_macro_span))] //! Diagnostic emulation on stable and nightly. //! //! # Usage //! //! 1. Depend on the library in your proc-macro. //! //! ```toml //! [dependencies] //! proc_macro2_diagnostics = "0.10" //! ``` //! //! 2. Import [`SpanDiagnosticExt`] and use its methods on a //! [`proc_macro2::Span`] to create [`Diagnostic`]s: //! //! ```rust //! use syn::spanned::Spanned; //! use proc_macro2::TokenStream; //! use proc_macro2_diagnostics::{SpanDiagnosticExt, Diagnostic}; //! //! fn my_macro(input: TokenStream) -> Result { //! Err(input.span().error("there's a problem here...")) //! } //! ``` //! //! 3. If there's an error, emit the diagnostic as tokens: //! //! ```rust //! extern crate proc_macro; //! //! # use proc_macro2::TokenStream; //! # use proc_macro2_diagnostics::{SpanDiagnosticExt, Diagnostic}; //! # use syn::spanned::Spanned; //! # fn my_macro(input: TokenStream) -> Result { //! # Err(input.span().error("there's a problem here...")) //! # } //! # /* //! #[proc_macro] //! # */ //! pub fn real_macro(tokens: proc_macro::TokenStream) -> proc_macro::TokenStream { //! match my_macro(tokens.into()) { //! Ok(tokens) => tokens.into(), //! Err(diag) => diag.emit_as_expr_tokens().into() //! } //! } //! ``` //! //! This does the right thing on nightly _or_ stable. //! //! # Caveats //! //! On stable, due to limitations, any top-level, non-error diagnostics are //! emitted as errors. This will abort compilation. To avoid this, you may want //! to `cfg`-gate emitting non-error diagnostics to nightly. //! //! # Colors //! //! By default, error messages are colored on stable. To disable, disable //! default features: //! //! ```toml //! [dependencies] //! proc_macro2_diagnostics = { version = "0.10", default-features = false } //! ``` //! //! The compiler always colors diagnostics on nightly. extern crate proc_macro; mod ext; mod diagnostic; mod line; pub use diagnostic::{Diagnostic, Level}; pub use ext::SpanDiagnosticExt; // We stole this from proc_macro2. Checks whether nightly proc_macro things // _actually_ work by checking if calls to proc_macro::Span panic. #[cfg(nightly_diagnostics)] fn nightly_works() -> bool { use std::panic::{self, PanicInfo}; use std::sync::atomic::*; use std::sync::Once; static WORKS: AtomicUsize = AtomicUsize::new(0); static INIT: Once = Once::new(); match WORKS.load(Ordering::SeqCst) { 1 => return false, 2 => return true, _ => {} } // Swap in a null panic hook to avoid printing "thread panicked" to stderr, // then use catch_unwind to determine whether the compiler's proc_macro is // working. When proc-macro2 is used from outside of a procedural macro all // of the proc_macro crate's APIs currently panic. // // The Once is to prevent the possibility of this ordering: // // thread 1 calls take_hook, gets the user's original hook // thread 1 calls set_hook with the null hook // thread 2 calls take_hook, thinks null hook is the original hook // thread 2 calls set_hook with the null hook // thread 1 calls set_hook with the actual original hook // thread 2 calls set_hook with what it thinks is the original hook // // in which the user's hook has been lost. // // There is still a race condition where a panic in a different thread can // happen during the interval that the user's original panic hook is // unregistered such that their hook is incorrectly not called. This is // sufficiently unlikely and less bad than printing panic messages to stderr // on correct use of this crate. Maybe there is a libstd feature request // here. For now, if a user needs to guarantee that this failure mode does // not occur, they need to call e.g. `proc_macro2::Span::call_site()` from // the main thread before launching any other threads. INIT.call_once(|| { type PanicHook = dyn Fn(&PanicInfo) + Sync + Send + 'static; let null_hook: Box = Box::new(|_panic_info| { /* ignore */ }); let sanity_check = &*null_hook as *const PanicHook; let original_hook = panic::take_hook(); panic::set_hook(null_hook); let works = panic::catch_unwind(|| proc_macro::Span::call_site()).is_ok(); WORKS.store(works as usize + 1, Ordering::SeqCst); let hopefully_null_hook = panic::take_hook(); panic::set_hook(original_hook); if sanity_check != &*hopefully_null_hook { panic!("observed race condition in proc_macro2::nightly_works"); } }); nightly_works() } proc-macro2-diagnostics-0.10.1/src/line.rs000064400000000000000000000054471046102023000164320ustar 00000000000000use std::fmt; use std::borrow::Cow; use crate::Level; #[derive(Copy, Clone, PartialEq)] enum Kind { New, Joined, } impl Kind { fn raw_split(self) -> (Cow<'static, str>, Cow<'static, str>) { match self { Kind::New => ("[".into(), "] ".into()), Kind::Joined => ("= ".into(), ": ".into()), } } #[cfg(not(all(feature = "colors", not(nightly_diagnostics))))] fn split(self) -> (Cow<'static, str>, Cow<'static, str>) { self.raw_split() } #[cfg(all(feature = "colors", not(nightly_diagnostics)))] fn split(self) -> (Cow<'static, str>, Cow<'static, str>) { use yansi::Paint; let (prefix, suffix) = self.raw_split(); let (prefix, suffix) = match self { Kind::New => (prefix.blue().bold(), suffix.blue().bold()), Kind::Joined => (prefix.blue().bold(), suffix.primary()), }; (prefix.to_string().into(), suffix.to_string().into()) } } pub struct Line<'a> { pub level: Level, pub msg: &'a str, kind: Kind } impl<'a> Line<'a> { pub fn new(level: Level, msg: &'a str) -> Line<'a> { Line { kind: Kind::New, level, msg } } pub fn joined(level: Level, msg: &'a str) -> Line<'a> { Line { kind: Kind::Joined, level, msg } } pub fn is_new(&self) -> bool { self.kind == Kind::New } fn parse_kind(kind: Kind, string: &str) -> Option> { let string = string.trim_start(); let (prefix, suffix) = kind.split(); if !string.starts_with(&*prefix) { return None; } let end = string.find(&*suffix)?; let level: Level = string[prefix.len()..end].parse().ok()?; let msg = &string[end + suffix.len()..]; Some(Line { level, msg, kind }) } pub fn parse(string: &str) -> Option> { Line::parse_kind(Kind::Joined, string) .or_else(|| Line::parse_kind(Kind::New, string)) } } impl fmt::Display for Line<'_> { #[cfg(all(feature = "colors", not(nightly_diagnostics)))] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { use yansi::{Paint, Color}; let style = match self.level { Level::Error => Color::Red.bold(), Level::Warning => Color::Yellow.bold(), Level::Note => Color::Green.bold(), Level::Help => Color::Cyan.bold(), }; let ((prefix, suffix), msg) = (self.kind.split(), self.msg.primary()); write!(f, "{}{}{}{}", prefix, self.level.paint(style), suffix, msg.bold()) } #[cfg(not(all(feature = "colors", not(nightly_diagnostics))))] fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { let (prefix, suffix) = self.kind.split(); write!(f, "{}{}{}{}", prefix, self.level, suffix, self.msg) } } proc-macro2-diagnostics-0.10.1/tests/main.rs000064400000000000000000000003301046102023000167640ustar 00000000000000#[test] fn main() { let t = trybuild::TestCases::new(); #[cfg(not(nightly_diagnostics))] t.compile_fail("tests/stable/*.rs"); #[cfg(nightly_diagnostics)] t.compile_fail("tests/nightly/*.rs"); } proc-macro2-diagnostics-0.10.1/tests/nightly/errors.rs000064400000000000000000000021371046102023000210410ustar 00000000000000use diagnostic_example::{diagnostic_item, diagnostic_expr}; fn main() { diagnostic_item! { error: just an item error, _note: see an item, help: I can help with that, } diagnostic_expr! { error: just an expression error item context, _note: see an exp, _warning: kind of weird, help: I can help with that, } let x = diagnostic_expr! { error: just an expression error expr content, _warning: oh no, }; } diagnostic_item! { error: this is an item error message, } diagnostic_item! { error: this is an error message, _note: but it has a note, } diagnostic_item! { error: hello, warning: just wanted to warn you, note: just jotting things down, _help: please help on that note, _note: notes on notes, } diagnostic_item! { warning: hello not found, _note: just a note to say hi, _help: its a good idea to say hello, } diagnostic_item! { hello: hello, } diagnostic_item! { help: this is standalone help, _note: but we add things to it, _help: like more help, } proc-macro2-diagnostics-0.10.1/tests/nightly/errors.stderr000064400000000000000000000044111046102023000217150ustar 00000000000000error: just an item error --> $DIR/errors.rs:5:16 | 5 | error: just an item error, | ^^^^^^^^^^^^^^^^^^ | = note: see an item help: I can help with that --> $DIR/errors.rs:7:15 | 7 | help: I can help with that, | ^^^^^^^^^^^^^^^^^^^^ error: just an expression error item context --> $DIR/errors.rs:11:16 | 11 | error: just an expression error item context, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = note: see an exp = warning: kind of weird help: I can help with that --> $DIR/errors.rs:14:15 | 14 | help: I can help with that, | ^^^^^^^^^^^^^^^^^^^^ error: just an expression error expr content --> $DIR/errors.rs:18:16 | 18 | error: just an expression error expr content, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ | = warning: oh no error: this is an item error message --> $DIR/errors.rs:24:12 | 24 | error: this is an item error message, | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ error: this is an error message --> $DIR/errors.rs:28:12 | 28 | error: this is an error message, | ^^^^^^^^^^^^^^^^^^^^^^^^ | = note: but it has a note error: hello --> $DIR/errors.rs:33:12 | 33 | error: hello, | ^^^^^ | warning: just wanted to warn you --> $DIR/errors.rs:34:14 | 34 | warning: just wanted to warn you, | ^^^^^^^^^^^^^^^^^^^^^^^ note: just jotting things down --> $DIR/errors.rs:35:11 | 35 | note: just jotting things down, | ^^^^^^^^^^^^^^^^^^^^^^^^ = help: please help on that note = note: notes on notes warning: hello not found --> $DIR/errors.rs:41:14 | 41 | warning: hello not found, | ^^^^^^^^^^^^^^^ | = note: just a note to say hi = help: its a good idea to say hello error: unknown diagnostic kind --> $DIR/errors.rs:47:5 | 47 | hello: hello, | ^^^^^ | = help: expected one of: 'error', 'warning', 'note', 'help' = note: or their _ versions help: this is standalone help --> $DIR/errors.rs:51:11 | 51 | help: this is standalone help, | ^^^^^^^^^^^^^^^^^^^^^^^ | = note: but we add things to it = help: like more help proc-macro2-diagnostics-0.10.1/tests/stable/errors.rs000064400000000000000000000021371046102023000206350ustar 00000000000000use diagnostic_example::{diagnostic_item, diagnostic_expr}; fn main() { diagnostic_item! { error: just an item error, _note: see an item, help: I can help with that, } diagnostic_expr! { error: just an expression error item context, _note: see an exp, _warning: kind of weird, help: I can help with that, } let x = diagnostic_expr! { error: just an expression error expr content, _warning: oh no, }; } diagnostic_item! { error: this is an item error message, } diagnostic_item! { error: this is an error message, _note: but it has a note, } diagnostic_item! { error: hello, warning: just wanted to warn you, note: just jotting things down, _help: please help on that note, _note: notes on notes, } diagnostic_item! { warning: hello not found, _note: just a note to say hi, _help: its a good idea to say hello, } diagnostic_item! { hello: hello, } diagnostic_item! { help: this is standalone help, _note: but we add things to it, _help: like more help, } proc-macro2-diagnostics-0.10.1/tests/stable/errors.stderr000064400000000000000000000043141046102023000215130ustar 00000000000000error: just an item error = note: see an item --> tests/stable/errors.rs:5:16 | 5 | error: just an item error, | ^^^^ error: [help] I can help with that --> tests/stable/errors.rs:7:15 | 7 | help: I can help with that, | ^ error: just an expression error item context = note: see an exp = warning: kind of weird --> tests/stable/errors.rs:11:16 | 11 | error: just an expression error item context, | ^^^^ error: [help] I can help with that --> tests/stable/errors.rs:14:15 | 14 | help: I can help with that, | ^ error: just an expression error expr content = warning: oh no --> tests/stable/errors.rs:18:16 | 18 | error: just an expression error expr content, | ^^^^ error: this is an item error message --> tests/stable/errors.rs:24:12 | 24 | error: this is an item error message, | ^^^^ error: this is an error message = note: but it has a note --> tests/stable/errors.rs:28:12 | 28 | error: this is an error message, | ^^^^ error: hello --> tests/stable/errors.rs:33:12 | 33 | error: hello, | ^^^^^ error: [warning] just wanted to warn you --> tests/stable/errors.rs:34:14 | 34 | warning: just wanted to warn you, | ^^^^ error: [note] just jotting things down = help: please help on that note = note: notes on notes --> tests/stable/errors.rs:35:11 | 35 | note: just jotting things down, | ^^^^ error: [warning] hello not found = note: just a note to say hi = help: its a good idea to say hello --> tests/stable/errors.rs:41:14 | 41 | warning: hello not found, | ^^^^^ error: unknown diagnostic kind = help: expected one of: 'error', 'warning', 'note', 'help' = note: or their _ versions --> tests/stable/errors.rs:47:5 | 47 | hello: hello, | ^^^^^ error: [help] this is standalone help = note: but we add things to it = help: like more help --> tests/stable/errors.rs:51:11 | 51 | help: this is standalone help, | ^^^^