about summary refs log tree commit diff
path: root/src/libsyntax
diff options
context:
space:
mode:
authorMark Rousskov <mark.simulacrum@gmail.com>2019-09-03 21:15:18 -0400
committerMark Rousskov <mark.simulacrum@gmail.com>2019-09-05 12:35:15 -0400
commitb437240ceefaad3cdf92ad7e9d1255b8da88dbb3 (patch)
treead724c143dc6cf6b20b214fa00e4572571e87399 /src/libsyntax
parent74563b41666228e46f892e795108e06306b2b514 (diff)
downloadrust-b437240ceefaad3cdf92ad7e9d1255b8da88dbb3.tar.gz
rust-b437240ceefaad3cdf92ad7e9d1255b8da88dbb3.zip
Replace diagnostic plugins with macro_rules
Diffstat (limited to 'src/libsyntax')
-rw-r--r--src/libsyntax/diagnostics/macros.rs55
-rw-r--r--src/libsyntax/diagnostics/plugin.rs185
-rw-r--r--src/libsyntax/error_codes.rs5
-rw-r--r--src/libsyntax/lib.rs5
-rw-r--r--src/libsyntax/parse/mod.rs4
5 files changed, 31 insertions, 223 deletions
diff --git a/src/libsyntax/diagnostics/macros.rs b/src/libsyntax/diagnostics/macros.rs
index b754d083376..c95c5bd5d02 100644
--- a/src/libsyntax/diagnostics/macros.rs
+++ b/src/libsyntax/diagnostics/macros.rs
@@ -1,13 +1,14 @@
 #[macro_export]
-macro_rules! register_diagnostic {
-    ($code:tt, $description:tt) => (__register_diagnostic! { $code, $description });
-    ($code:tt) => (__register_diagnostic! { $code })
+macro_rules! diagnostic_used {
+    ($code:ident) => (
+        let _ = crate::error_codes::$code;
+    )
 }
 
 #[macro_export]
 macro_rules! span_fatal {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.span_fatal_with_code(
             $span,
             &format!($($message)*),
@@ -19,7 +20,7 @@ macro_rules! span_fatal {
 #[macro_export]
 macro_rules! span_err {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.span_err_with_code(
             $span,
             &format!($($message)*),
@@ -31,7 +32,7 @@ macro_rules! span_err {
 #[macro_export]
 macro_rules! span_warn {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.span_warn_with_code(
             $span,
             &format!($($message)*),
@@ -43,7 +44,7 @@ macro_rules! span_warn {
 #[macro_export]
 macro_rules! struct_err {
     ($session:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.struct_err_with_code(
             &format!($($message)*),
             $crate::errors::DiagnosticId::Error(stringify!($code).to_owned()),
@@ -54,7 +55,7 @@ macro_rules! struct_err {
 #[macro_export]
 macro_rules! span_err_or_warn {
     ($is_warning:expr, $session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         if $is_warning {
             $session.span_warn_with_code(
                 $span,
@@ -74,7 +75,7 @@ macro_rules! span_err_or_warn {
 #[macro_export]
 macro_rules! struct_span_fatal {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.struct_span_fatal_with_code(
             $span,
             &format!($($message)*),
@@ -86,7 +87,7 @@ macro_rules! struct_span_fatal {
 #[macro_export]
 macro_rules! struct_span_err {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.struct_span_err_with_code(
             $span,
             &format!($($message)*),
@@ -98,7 +99,7 @@ macro_rules! struct_span_err {
 #[macro_export]
 macro_rules! stringify_error_code {
     ($code:ident) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $crate::errors::DiagnosticId::Error(stringify!($code).to_owned())
     })
 }
@@ -117,7 +118,7 @@ macro_rules! type_error_struct {
 #[macro_export]
 macro_rules! struct_span_warn {
     ($session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         $session.struct_span_warn_with_code(
             $span,
             &format!($($message)*),
@@ -129,7 +130,7 @@ macro_rules! struct_span_warn {
 #[macro_export]
 macro_rules! struct_span_err_or_warn {
     ($is_warning:expr, $session:expr, $span:expr, $code:ident, $($message:tt)*) => ({
-        __diagnostic_used!($code);
+        $crate::diagnostic_used!($code);
         if $is_warning {
             $session.struct_span_warn_with_code(
                 $span,
@@ -169,20 +170,22 @@ macro_rules! help {
 
 #[macro_export]
 macro_rules! register_diagnostics {
-    ($($code:tt),*) => (
-        $($crate::register_diagnostic! { $code })*
+    ($($ecode:ident: $message:expr,)*) => (
+        $crate::register_diagnostics!{$($ecode:$message,)* ;}
     );
-    ($($code:tt),*,) => (
-        $($crate::register_diagnostic! { $code })*
-    )
-}
 
-#[macro_export]
-macro_rules! register_long_diagnostics {
-    ($($code:tt: $description:tt),*) => (
-        $($crate::register_diagnostic! { $code, $description })*
-    );
-    ($($code:tt: $description:tt),*,) => (
-        $($crate::register_diagnostic! { $code, $description })*
+    ($($ecode:ident: $message:expr,)* ; $($code:ident,)*) => (
+        pub static DIAGNOSTICS: &[(&str, &str)] = &[
+            $( (stringify!($ecode), $message), )*
+        ];
+
+        $(
+            #[deny(unused)]
+            pub(crate) const $ecode: &str = $message;
+        )*
+        $(
+            #[deny(unused)]
+            pub(crate) const $code: () = ();
+        )*
     )
 }
diff --git a/src/libsyntax/diagnostics/plugin.rs b/src/libsyntax/diagnostics/plugin.rs
deleted file mode 100644
index 5de39c8d14d..00000000000
--- a/src/libsyntax/diagnostics/plugin.rs
+++ /dev/null
@@ -1,185 +0,0 @@
-use std::collections::BTreeMap;
-
-use crate::ast::{self, Ident, Name};
-use crate::source_map;
-use crate::ext::base::{ExtCtxt, MacEager, MacResult};
-use crate::parse::token::{self, Token};
-use crate::ptr::P;
-use crate::symbol::kw;
-use crate::tokenstream::{TokenTree, TokenStream};
-
-use smallvec::smallvec;
-use syntax_pos::Span;
-
-pub use errors::*;
-
-// Maximum width of any line in an extended error description (inclusive).
-const MAX_DESCRIPTION_WIDTH: usize = 80;
-
-/// Error information type.
-pub struct ErrorInfo {
-    pub description: Option<Name>,
-    pub use_site: Option<Span>
-}
-
-/// Mapping from error codes to metadata.
-pub type ErrorMap = BTreeMap<Name, ErrorInfo>;
-
-pub fn expand_diagnostic_used<'cx>(ecx: &'cx mut ExtCtxt<'_>,
-                                   span: Span,
-                                   tts: TokenStream)
-                                   -> Box<dyn MacResult+'cx> {
-    assert_eq!(tts.len(), 1);
-    let code = match tts.into_trees().next() {
-        Some(TokenTree::Token(Token { kind: token::Ident(code, _), .. })) => code,
-        _ => unreachable!()
-    };
-
-    ecx.parse_sess.registered_diagnostics.with_lock(|diagnostics| {
-        match diagnostics.get_mut(&code) {
-            // Previously used errors.
-            Some(&mut ErrorInfo { description: _, use_site: Some(previous_span) }) => {
-                ecx.struct_span_warn(span, &format!(
-                    "diagnostic code {} already used", code
-                )).span_note(previous_span, "previous invocation")
-                  .emit();
-            }
-            // Newly used errors.
-            Some(ref mut info) => {
-                info.use_site = Some(span);
-            }
-            // Unregistered errors.
-            None => {
-                ecx.span_err(span, &format!(
-                    "used diagnostic code {} not registered", code
-                ));
-            }
-        }
-    });
-    MacEager::expr(ecx.expr_tuple(span, Vec::new()))
-}
-
-pub fn expand_register_diagnostic<'cx>(ecx: &'cx mut ExtCtxt<'_>,
-                                       span: Span,
-                                       tts: TokenStream)
-                                       -> Box<dyn MacResult+'cx> {
-    assert!(tts.len() == 1 || tts.len() == 3);
-    let mut cursor = tts.into_trees();
-    let code = match cursor.next() {
-        Some(TokenTree::Token(Token { kind: token::Ident(code, _), .. })) => code,
-        _ => unreachable!()
-    };
-    let description = match  (cursor.next(), cursor.next()) {
-        (None, None) => None,
-        (
-            Some(TokenTree::Token(Token { kind: token::Comma, .. })),
-            Some(TokenTree::Token(Token { kind: token::Literal(token::Lit { symbol, .. }), ..}))
-        ) => {
-            Some(symbol)
-        },
-        _ => unreachable!()
-    };
-
-    // Check that the description starts and ends with a newline and doesn't
-    // overflow the maximum line width.
-    description.map(|raw_msg| {
-        let msg = raw_msg.as_str();
-        if !msg.starts_with("\n") || !msg.ends_with("\n") {
-            ecx.span_err(span, &format!(
-                "description for error code {} doesn't start and end with a newline",
-                code
-            ));
-        }
-
-        // URLs can be unavoidably longer than the line limit, so we allow them.
-        // Allowed format is: `[name]: https://www.rust-lang.org/`
-        let is_url = |l: &str| l.starts_with("[") && l.contains("]:") && l.contains("http");
-
-        if msg.lines().any(|line| line.len() > MAX_DESCRIPTION_WIDTH && !is_url(line)) {
-            ecx.span_err(span, &format!(
-                "description for error code {} contains a line longer than {} characters.\n\
-                 if you're inserting a long URL use the footnote style to bypass this check.",
-                code, MAX_DESCRIPTION_WIDTH
-            ));
-        }
-    });
-    // Add the error to the map.
-    ecx.parse_sess.registered_diagnostics.with_lock(|diagnostics| {
-        let info = ErrorInfo {
-            description,
-            use_site: None
-        };
-        if diagnostics.insert(code, info).is_some() {
-            ecx.span_err(span, &format!(
-                "diagnostic code {} already registered", code
-            ));
-        }
-    });
-
-    MacEager::items(smallvec![])
-}
-
-pub fn expand_build_diagnostic_array<'cx>(ecx: &'cx mut ExtCtxt<'_>,
-                                          span: Span,
-                                          tts: TokenStream)
-                                          -> Box<dyn MacResult+'cx> {
-    assert_eq!(tts.len(), 3);
-    let ident = match tts.into_trees().nth(2) {
-        // DIAGNOSTICS ident.
-        Some(TokenTree::Token(Token { kind: token::Ident(name, _), span }))
-        => Ident::new(name, span),
-        _ => unreachable!()
-    };
-
-    // Construct the output expression.
-    let (count, expr) =
-        ecx.parse_sess.registered_diagnostics.with_lock(|diagnostics| {
-            let descriptions: Vec<P<ast::Expr>> =
-                diagnostics.iter().filter_map(|(&code, info)| {
-                    info.description.map(|description| {
-                        ecx.expr_tuple(span, vec![
-                            ecx.expr_str(span, code),
-                            ecx.expr_str(span, description)
-                        ])
-                    })
-                }).collect();
-            (descriptions.len(), ecx.expr_vec(span, descriptions))
-        });
-
-    let static_ = ecx.lifetime(span, Ident::with_dummy_span(kw::StaticLifetime));
-    let ty_str = ecx.ty_rptr(
-        span,
-        ecx.ty_ident(span, ecx.ident_of("str")),
-        Some(static_),
-        ast::Mutability::Immutable,
-    );
-
-    let ty = ecx.ty(
-        span,
-        ast::TyKind::Array(
-            ecx.ty(
-                span,
-                ast::TyKind::Tup(vec![ty_str.clone(), ty_str])
-            ),
-            ast::AnonConst {
-                id: ast::DUMMY_NODE_ID,
-                value: ecx.expr_usize(span, count),
-            },
-        ),
-    );
-
-    MacEager::items(smallvec![
-        P(ast::Item {
-            ident,
-            attrs: Vec::new(),
-            id: ast::DUMMY_NODE_ID,
-            node: ast::ItemKind::Const(
-                ty,
-                expr,
-            ),
-            vis: source_map::respan(span.shrink_to_lo(), ast::VisibilityKind::Public),
-            span,
-            tokens: None,
-        })
-    ])
-}
diff --git a/src/libsyntax/error_codes.rs b/src/libsyntax/error_codes.rs
index 76b2575bfd6..9925dd8ada0 100644
--- a/src/libsyntax/error_codes.rs
+++ b/src/libsyntax/error_codes.rs
@@ -421,9 +421,8 @@ Delete the offending feature attribute, or add it to the list of allowed
 features in the `-Z allow_features` flag.
 "##,
 
-}
+;
 
-register_diagnostics! {
     E0539, // incorrect meta item
     E0540, // multiple rustc_deprecated attributes
     E0542, // missing 'since'
@@ -447,7 +446,7 @@ register_diagnostics! {
     // attribute
     E0630,
     E0693, // incorrect `repr(align)` attribute format
-    E0694, // an unknown tool name found in scoped attributes
+//  E0694, // an unknown tool name found in scoped attributes
     E0703, // invalid ABI
     E0717, // rustc_promotable without stability attribute
 }
diff --git a/src/libsyntax/lib.rs b/src/libsyntax/lib.rs
index 1741932c1b8..75ce306df80 100644
--- a/src/libsyntax/lib.rs
+++ b/src/libsyntax/lib.rs
@@ -123,11 +123,8 @@ scoped_tls::scoped_thread_local!(pub static GLOBALS: Globals);
 pub mod diagnostics {
     #[macro_use]
     pub mod macros;
-    pub mod plugin;
 }
 
-// N.B., this module needs to be declared first so diagnostics are
-// registered before they are used.
 pub mod error_codes;
 
 pub mod util {
@@ -182,5 +179,3 @@ pub mod ext {
 }
 
 pub mod early_buffered_lints;
-
-__build_diagnostic_array! { libsyntax, DIAGNOSTICS }
diff --git a/src/libsyntax/parse/mod.rs b/src/libsyntax/parse/mod.rs
index b1af4806e2d..981f5f1f7b0 100644
--- a/src/libsyntax/parse/mod.rs
+++ b/src/libsyntax/parse/mod.rs
@@ -8,7 +8,6 @@ use crate::parse::parser::Parser;
 use crate::parse::parser::emit_unclosed_delims;
 use crate::parse::token::TokenKind;
 use crate::tokenstream::{TokenStream, TokenTree};
-use crate::diagnostics::plugin::ErrorMap;
 use crate::print::pprust;
 use crate::symbol::Symbol;
 
@@ -64,8 +63,6 @@ pub struct ParseSess {
     pub missing_fragment_specifiers: Lock<FxHashSet<Span>>,
     /// Places where raw identifiers were used. This is used for feature-gating raw identifiers.
     pub raw_identifier_spans: Lock<Vec<Span>>,
-    /// The registered diagnostics codes.
-    crate registered_diagnostics: Lock<ErrorMap>,
     /// Used to determine and report recursive module inclusions.
     included_mod_stack: Lock<Vec<PathBuf>>,
     source_map: Lrc<SourceMap>,
@@ -95,7 +92,6 @@ impl ParseSess {
             config: FxHashSet::default(),
             missing_fragment_specifiers: Lock::new(FxHashSet::default()),
             raw_identifier_spans: Lock::new(Vec::new()),
-            registered_diagnostics: Lock::new(ErrorMap::new()),
             included_mod_stack: Lock::new(vec![]),
             source_map,
             buffered_lints: Lock::new(vec![]),