Vendor dependencies

This commit is contained in:
2026-08-01 16:11:49 +03:00
parent 7f139a0241
commit 6b5e7f0f8b
29706 changed files with 9575646 additions and 0 deletions
@@ -0,0 +1 @@
{"$comment":"This file only protects against accidental modifications. It is not a security mechanism and does not protect against malicious changes.","files":{".cargo_vcs_info.json":"c99ea6084731e40ea6235c83e01cffc239fcaa764e8dc4f9974c5b819c6a5a3c",".github/workflows/ci.yml":"c4f012297b0e0c7950b740857fbe952a804a6bbca96085c7ee366981ed450a9c","Cargo.toml":"d754d4a6cddf2768dc8df4ba5824d4c87a70afa486500d338bcb8ab462499048","Cargo.toml.orig":"fb2cfabc3b133a3a344a8622b2393a457d74616734ac4dbd19f4ad379c01c61f","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"38176bb6aad910a449a304967836091da15384cdb73c7477d805b1f6045d14d6","README.md":"5b7e1a364dfdeb70a043dbcf967f70ccbd2f651cbec1e9ea8fae2e2c04968634","build.rs":"66fcc487972086f42011c84a1949861799dc7cfde1e56201d22cf8e71b59b8b1","src/diagnostic.rs":"a4df111ff29b791590e459fc95b051a6076bb26443d661370f949dc3f50994f0","src/ext.rs":"1502116a76b25c17b5b4c063dc4fb742dc7266a564a75eec36a68a706089ea3e","src/lib.rs":"646691f94ccbb05346cebc0b5ac96ad754f32ac224ec20d2835256487554fdaa","src/line.rs":"d412c72e10f433982d94c9b2a4ff9569140b0de0e3be87e84a1112415b22fc1f","tests/main.rs":"cf0a5418ccc02f77f2b044159aca5ab4cacfa87c2088b8502ec72bb5cc5220a6","tests/nightly/errors.rs":"8fcc6e37003c9fa7b91a34e905e90cdd8e67e7e76b6f74593372b57a4cbf2cf0","tests/nightly/errors.stderr":"1264a26d81a8224241efcbf27f21c2a272e21ae6a628ede745939ce352efabf3","tests/stable/errors.rs":"8fcc6e37003c9fa7b91a34e905e90cdd8e67e7e76b6f74593372b57a4cbf2cf0","tests/stable/errors.stderr":"ecf4f58eb06064a7b7cdc79ea65d9c7b6877dbd6cdf4085d311ce6e7da8eb3b0"},"package":"af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8"}
@@ -0,0 +1,6 @@
{
"git": {
"sha1": "45fa2d68669d10daeaf0f9b664a96576626fae16"
},
"path_in_vcs": ""
}
@@ -0,0 +1,37 @@
name: 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
+45
View File
@@ -0,0 +1,45 @@
# 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 <sb@sergio.bz>"]
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"]
+28
View File
@@ -0,0 +1,28 @@
[package]
name = "proc-macro2-diagnostics"
version = "0.10.1"
authors = ["Sergio Benitez <sb@sergio.bz>"]
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/" }
@@ -0,0 +1,176 @@
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
@@ -0,0 +1,19 @@
The 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.
+70
View File
@@ -0,0 +1,70 @@
# proc-macro2-diagnostics &thinsp; [![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<TokenStream, Diagnostic> {
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)
+7
View File
@@ -0,0 +1,7 @@
fn 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");
}
}
}
@@ -0,0 +1,324 @@
use 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<Span>`.
fn into_spans(self) -> Vec<Span>;
}
impl MultiSpan for Span {
fn into_spans(self) -> Vec<Span> { vec![self] }
}
impl MultiSpan for Vec<Span> {
fn into_spans(self) -> Vec<Span> { self }
}
impl<'a> MultiSpan for &'a [Span] {
fn into_spans(self) -> Vec<Span> {
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<Self, Self::Err> {
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<Span>,
children: Vec<Diagnostic>
}
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<S, T>(self, spans: S, message: T) -> Diagnostic
where S: MultiSpan, T: Into<String>
{
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<T: Into<String>>(self, message: T) -> Diagnostic {
self.child($level, message)
}
)
}
impl Diagnostic {
/// Creates a new diagnostic with the given `level` and `message`.
pub fn new<T: Into<String>>(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<S, T>(spans: S, level: Level, message: T) -> Diagnostic
where S: MultiSpan, T: Into<String>
{
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<S, T>(mut self, spans: S, level: Level, message: T) -> Diagnostic
where S: MultiSpan, T: Into<String>
{
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<T: Into<String>>(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<Item=&Diagnostic> {
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<Diagnostic> 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<syn::Error> = 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<syn::parse::Error> for Diagnostic {
fn from(error: syn::parse::Error) -> Diagnostic {
let mut diag: Option<Diagnostic> = 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<Diagnostic> for proc_macro::Diagnostic {
fn from(diag: Diagnostic) -> proc_macro::Diagnostic {
fn spans_to_proc_macro_spans(spans: Vec<Span>) -> Vec<proc_macro::Span> {
spans.into_iter()
.map(|s| s.unstable())
.collect::<Vec<proc_macro::Span>>()
}
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
}
}
+53
View File
@@ -0,0 +1,53 @@
use 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<T: Into<String>>(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<T: Into<String>>(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);
}
+138
View File
@@ -0,0 +1,138 @@
#![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<TokenStream, Diagnostic> {
//! 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<TokenStream, Diagnostic> {
//! # 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<PanicHook> = 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()
}
@@ -0,0 +1,97 @@
use 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<Line<'_>> {
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<'_>> {
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)
}
}
@@ -0,0 +1,10 @@
#[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");
}
@@ -0,0 +1,54 @@
use 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,
}
@@ -0,0 +1,94 @@
error: 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
@@ -0,0 +1,54 @@
use 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,
}
@@ -0,0 +1,90 @@
error: 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,
| ^^^^