diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-18 02:49:42 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-05-18 02:49:42 +0000 |
commit | 837b550238aa671a591ccf282dddeab29cadb206 (patch) | |
tree | 914b6b8862bace72bd3245ca184d374b08d8a672 /compiler/rustc_expand | |
parent | Adding debian version 1.70.0+dfsg2-1. (diff) | |
download | rustc-837b550238aa671a591ccf282dddeab29cadb206.tar.xz rustc-837b550238aa671a591ccf282dddeab29cadb206.zip |
Merging upstream version 1.71.1+dfsg1.
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'compiler/rustc_expand')
-rw-r--r-- | compiler/rustc_expand/Cargo.toml | 1 | ||||
-rw-r--r-- | compiler/rustc_expand/messages.ftl | 176 | ||||
-rw-r--r-- | compiler/rustc_expand/src/base.rs | 31 | ||||
-rw-r--r-- | compiler/rustc_expand/src/errors.rs | 10 | ||||
-rw-r--r-- | compiler/rustc_expand/src/expand.rs | 19 | ||||
-rw-r--r-- | compiler/rustc_expand/src/lib.rs | 2 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/diagnostics.rs | 4 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/macro_check.rs | 19 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/macro_parser.rs | 23 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/macro_rules.rs | 19 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/metavar_expr.rs | 6 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/quoted.rs | 8 | ||||
-rw-r--r-- | compiler/rustc_expand/src/mbe/transcribe.rs | 2 | ||||
-rw-r--r-- | compiler/rustc_expand/src/placeholders.rs | 1 | ||||
-rw-r--r-- | compiler/rustc_expand/src/proc_macro.rs | 4 | ||||
-rw-r--r-- | compiler/rustc_expand/src/proc_macro_server.rs | 17 | ||||
-rw-r--r-- | compiler/rustc_expand/src/tests.rs | 4 |
17 files changed, 189 insertions, 157 deletions
diff --git a/compiler/rustc_expand/Cargo.toml b/compiler/rustc_expand/Cargo.toml index c971714e0..2dae0e3f5 100644 --- a/compiler/rustc_expand/Cargo.toml +++ b/compiler/rustc_expand/Cargo.toml @@ -16,6 +16,7 @@ rustc_attr = { path = "../rustc_attr" } rustc_data_structures = { path = "../rustc_data_structures" } rustc_errors = { path = "../rustc_errors" } rustc_feature = { path = "../rustc_feature" } +rustc_fluent_macro = { path = "../rustc_fluent_macro" } rustc_lexer = { path = "../rustc_lexer" } rustc_lint_defs = { path = "../rustc_lint_defs" } rustc_macros = { path = "../rustc_macros" } diff --git a/compiler/rustc_expand/messages.ftl b/compiler/rustc_expand/messages.ftl index 5d999d0db..6c7e68246 100644 --- a/compiler/rustc_expand/messages.ftl +++ b/compiler/rustc_expand/messages.ftl @@ -1,138 +1,142 @@ -expand_explain_doc_comment_outer = - outer doc comments expand to `#[doc = "..."]`, which is what this macro attempted to match - -expand_explain_doc_comment_inner = - inner doc comments expand to `#![doc = "..."]`, which is what this macro attempted to match - -expand_expr_repeat_no_syntax_vars = - attempted to repeat an expression containing no syntax variables matched as repeating at this depth - -expand_must_repeat_once = - this must repeat at least once - -expand_count_repetition_misplaced = - `count` can not be placed inside the inner-most repetition - -expand_meta_var_expr_unrecognized_var = - variable `{$key}` is not recognized in meta-variable expression - -expand_var_still_repeating = - variable '{$ident}' is still repeating at this depth - -expand_meta_var_dif_seq_matchers = {$msg} - -expand_macro_const_stability = - macros cannot have const stability attributes - .label = invalid const stability attribute - .label2 = const stability attribute affects this macro - -expand_macro_body_stability = - macros cannot have body stability attributes - .label = invalid body stability attribute - .label2 = body stability attribute affects this macro - -expand_resolve_relative_path = - cannot resolve relative path in non-file source `{$path}` +expand_arg_not_attributes = + second argument must be `attributes` expand_attr_no_arguments = attribute must have either one or two arguments -expand_not_a_meta_item = - not a meta item - -expand_only_one_word = - must only be one word - -expand_cannot_be_name_of_macro = - `{$trait_ident}` cannot be a name of {$macro_type} macro +expand_attribute_meta_item = + attribute must be a meta item, not a literal -expand_arg_not_attributes = - second argument must be `attributes` +expand_attribute_single_word = + attribute must only be a single word expand_attributes_wrong_form = attribute must be of form: `attributes(foo, bar)` -expand_attribute_meta_item = - attribute must be a meta item, not a literal +expand_cannot_be_name_of_macro = + `{$trait_ident}` cannot be a name of {$macro_type} macro -expand_attribute_single_word = - attribute must only be a single word +expand_count_repetition_misplaced = + `count` can not be placed inside the inner-most repetition -expand_helper_attribute_name_invalid = - `{$name}` cannot be a name of derive helper attribute +expand_duplicate_matcher_binding = duplicate matcher binding + .label = duplicate binding + .label2 = previous binding expand_expected_comma_in_list = expected token: `,` -expand_only_one_argument = - {$name} takes 1 argument +expand_explain_doc_comment_inner = + inner doc comments expand to `#![doc = "..."]`, which is what this macro attempted to match -expand_takes_no_arguments = - {$name} takes no arguments +expand_explain_doc_comment_outer = + outer doc comments expand to `#[doc = "..."]`, which is what this macro attempted to match + +expand_expr_repeat_no_syntax_vars = + attempted to repeat an expression containing no syntax variables matched as repeating at this depth expand_feature_included_in_edition = the feature `{$feature}` is included in the Rust {$edition} edition +expand_feature_not_allowed = + the feature `{$name}` is not in the list of allowed features + expand_feature_removed = feature has been removed .label = feature has been removed .reason = {$reason} -expand_feature_not_allowed = - the feature `{$name}` is not in the list of allowed features - -expand_recursion_limit_reached = - recursion limit reached while expanding `{$descr}` - .help = consider increasing the recursion limit by adding a `#![recursion_limit = "{$suggested_limit}"]` attribute to your crate (`{$crate_name}`) +expand_helper_attribute_name_invalid = + `{$name}` cannot be a name of derive helper attribute -expand_malformed_feature_attribute = - malformed `feature` attribute input - .expected = expected just one word +expand_incomplete_parse = + macro expansion ignores token `{$token}` and any following + .label = caused by the macro expansion here + .note = the usage of `{$macro_path}!` is likely invalid in {$kind_name} context + .suggestion_add_semi = you might be missing a semicolon here -expand_remove_expr_not_supported = - removing an expression is not supported in this position +expand_invalid_cfg_expected_syntax = expected syntax is +expand_invalid_cfg_multiple_predicates = multiple `cfg` predicates are specified expand_invalid_cfg_no_parens = `cfg` is not followed by parentheses expand_invalid_cfg_no_predicate = `cfg` predicate is not specified -expand_invalid_cfg_multiple_predicates = multiple `cfg` predicates are specified expand_invalid_cfg_predicate_literal = `cfg` predicate key cannot be a literal -expand_invalid_cfg_expected_syntax = expected syntax is +expand_macro_body_stability = + macros cannot have body stability attributes + .label = invalid body stability attribute + .label2 = body stability attribute affects this macro -expand_wrong_fragment_kind = - non-{$kind} macro in {$kind} position: {$name} +expand_macro_const_stability = + macros cannot have const stability attributes + .label = invalid const stability attribute + .label2 = const stability attribute affects this macro -expand_unsupported_key_value = - key-value macro attributes are not supported +expand_malformed_feature_attribute = + malformed `feature` attribute input + .expected = expected just one word -expand_incomplete_parse = - macro expansion ignores token `{$token}` and any following - .label = caused by the macro expansion here - .note = the usage of `{$macro_path}!` is likely invalid in {$kind_name} context - .suggestion_add_semi = you might be missing a semicolon here +expand_meta_var_dif_seq_matchers = {$msg} -expand_remove_node_not_supported = - removing {$descr} is not supported in this position +expand_meta_var_expr_unrecognized_var = + variable `{$key}` is not recognized in meta-variable expression expand_module_circular = circular modules: {$modules} -expand_module_in_block = - cannot declare a non-inline module inside a block unless it has a path attribute - .note = maybe `use` the module `{$name}` instead of redeclaring it - expand_module_file_not_found = file not found for module `{$name}` .help = to create the module `{$name}`, create file "{$default_path}" or "{$secondary_path}" +expand_module_in_block = + cannot declare a non-inline module inside a block unless it has a path attribute + .note = maybe `use` the module `{$name}` instead of redeclaring it + expand_module_multiple_candidates = file for module `{$name}` found at both "{$default_path}" and "{$secondary_path}" .help = delete or rename one of them to remove the ambiguity -expand_trace_macro = trace_macro +expand_must_repeat_once = + this must repeat at least once + +expand_not_a_meta_item = + not a meta item + +expand_only_one_argument = + {$name} takes 1 argument + +expand_only_one_word = + must only be one word + +expand_proc_macro_derive_tokens = + proc-macro derive produced unparsable tokens expand_proc_macro_panicked = proc macro panicked .help = message: {$message} -expand_proc_macro_derive_tokens = - proc-macro derive produced unparsable tokens +expand_recursion_limit_reached = + recursion limit reached while expanding `{$descr}` + .help = consider increasing the recursion limit by adding a `#![recursion_limit = "{$suggested_limit}"]` attribute to your crate (`{$crate_name}`) + +expand_remove_expr_not_supported = + removing an expression is not supported in this position + +expand_remove_node_not_supported = + removing {$descr} is not supported in this position + +expand_resolve_relative_path = + cannot resolve relative path in non-file source `{$path}` + +expand_takes_no_arguments = + {$name} takes no arguments + +expand_trace_macro = trace_macro + +expand_unsupported_key_value = + key-value macro attributes are not supported + +expand_var_still_repeating = + variable '{$ident}' is still repeating at this depth + +expand_wrong_fragment_kind = + non-{$kind} macro in {$kind} position: {$name} diff --git a/compiler/rustc_expand/src/base.rs b/compiler/rustc_expand/src/base.rs index caa2a201c..4671adccc 100644 --- a/compiler/rustc_expand/src/base.rs +++ b/compiler/rustc_expand/src/base.rs @@ -15,7 +15,8 @@ use rustc_attr::{self as attr, Deprecation, Stability}; use rustc_data_structures::fx::FxIndexMap; use rustc_data_structures::sync::{self, Lrc}; use rustc_errors::{ - Applicability, DiagnosticBuilder, ErrorGuaranteed, IntoDiagnostic, MultiSpan, PResult, + Applicability, DiagnosticBuilder, DiagnosticMessage, ErrorGuaranteed, IntoDiagnostic, + MultiSpan, PResult, }; use rustc_lint_defs::builtin::PROC_MACRO_BACK_COMPAT; use rustc_lint_defs::{BufferedEarlyLint, BuiltinLintDiagnostics, RegisteredTools}; @@ -653,13 +654,13 @@ pub enum SyntaxExtensionKind { /// A token-based function-like macro. Bang( /// An expander with signature TokenStream -> TokenStream. - Box<dyn BangProcMacro + sync::Sync + sync::Send>, + Box<dyn BangProcMacro + sync::DynSync + sync::DynSend>, ), /// An AST-based function-like macro. LegacyBang( /// An expander with signature TokenStream -> AST. - Box<dyn TTMacroExpander + sync::Sync + sync::Send>, + Box<dyn TTMacroExpander + sync::DynSync + sync::DynSend>, ), /// A token-based attribute macro. @@ -667,7 +668,7 @@ pub enum SyntaxExtensionKind { /// An expander with signature (TokenStream, TokenStream) -> TokenStream. /// The first TokenSteam is the attribute itself, the second is the annotated item. /// The produced TokenSteam replaces the input TokenSteam. - Box<dyn AttrProcMacro + sync::Sync + sync::Send>, + Box<dyn AttrProcMacro + sync::DynSync + sync::DynSend>, ), /// An AST-based attribute macro. @@ -675,7 +676,7 @@ pub enum SyntaxExtensionKind { /// An expander with signature (AST, AST) -> AST. /// The first AST fragment is the attribute itself, the second is the annotated item. /// The produced AST fragment replaces the input AST fragment. - Box<dyn MultiItemModifier + sync::Sync + sync::Send>, + Box<dyn MultiItemModifier + sync::DynSync + sync::DynSend>, ), /// A trivial attribute "macro" that does nothing, @@ -692,14 +693,14 @@ pub enum SyntaxExtensionKind { /// is handled identically to `LegacyDerive`. It should be migrated to /// a token-based representation like `Bang` and `Attr`, instead of /// using `MultiItemModifier`. - Box<dyn MultiItemModifier + sync::Sync + sync::Send>, + Box<dyn MultiItemModifier + sync::DynSync + sync::DynSend>, ), /// An AST-based derive macro. LegacyDerive( /// An expander with signature AST -> AST. /// The produced AST fragment is appended to the input AST fragment. - Box<dyn MultiItemModifier + sync::Sync + sync::Send>, + Box<dyn MultiItemModifier + sync::DynSync + sync::DynSend>, ), } @@ -779,7 +780,7 @@ impl SyntaxExtension { let allow_internal_unsafe = attr::contains_name(attrs, sym::allow_internal_unsafe); let local_inner_macros = attr::find_by_name(attrs, sym::macro_export) .and_then(|macro_export| macro_export.meta_item_list()) - .map_or(false, |l| attr::list_contains_name(&l, sym::local_inner_macros)); + .is_some_and(|l| attr::list_contains_name(&l, sym::local_inner_macros)); let collapse_debuginfo = attr::contains_name(attrs, sym::collapse_debuginfo); tracing::debug!(?local_inner_macros, ?collapse_debuginfo, ?allow_internal_unsafe); @@ -992,7 +993,6 @@ pub struct ExpansionData { pub depth: usize, pub module: Rc<ModuleData>, pub dir_ownership: DirOwnership, - pub prior_type_ascription: Option<(Span, bool)>, /// Some parent node that is close to this macro call pub lint_node_id: NodeId, pub is_trailing_mac: bool, @@ -1043,7 +1043,6 @@ impl<'a> ExtCtxt<'a> { depth: 0, module: Default::default(), dir_ownership: DirOwnership::Owned { relative: None }, - prior_type_ascription: None, lint_node_id: ast::CRATE_NODE_ID, is_trailing_mac: false, }, @@ -1112,7 +1111,7 @@ impl<'a> ExtCtxt<'a> { pub fn struct_span_err<S: Into<MultiSpan>>( &self, sp: S, - msg: &str, + msg: impl Into<DiagnosticMessage>, ) -> DiagnosticBuilder<'a, ErrorGuaranteed> { self.sess.parse_sess.span_diagnostic.struct_span_err(sp, msg) } @@ -1134,21 +1133,21 @@ impl<'a> ExtCtxt<'a> { /// Compilation will be stopped in the near future (at the end of /// the macro expansion phase). #[rustc_lint_diagnostics] - pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + pub fn span_err<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) { self.sess.parse_sess.span_diagnostic.span_err(sp, msg); } #[rustc_lint_diagnostics] - pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: &str) { + pub fn span_warn<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) { self.sess.parse_sess.span_diagnostic.span_warn(sp, msg); } - pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: &str) -> ! { + pub fn span_bug<S: Into<MultiSpan>>(&self, sp: S, msg: impl Into<DiagnosticMessage>) -> ! { self.sess.parse_sess.span_diagnostic.span_bug(sp, msg); } pub fn trace_macros_diag(&mut self) { for (span, notes) in self.expansions.iter() { let mut db = self.sess.parse_sess.create_note(errors::TraceMacro { span: *span }); for note in notes { - db.note(note); + db.note(note.clone()); } db.emit(); } @@ -1450,7 +1449,7 @@ fn pretty_printing_compatibility_hack(item: &Item, sess: &ParseSess) -> bool { && version .next() .and_then(|c| c.parse::<u32>().ok()) - .map_or(false, |v| v < 6) + .is_some_and(|v| v < 6) }; if crate_matches { diff --git a/compiler/rustc_expand/src/errors.rs b/compiler/rustc_expand/src/errors.rs index e5102a952..e3a0ae357 100644 --- a/compiler/rustc_expand/src/errors.rs +++ b/compiler/rustc_expand/src/errors.rs @@ -397,3 +397,13 @@ pub struct ProcMacroDeriveTokens { #[primary_span] pub span: Span, } + +#[derive(Diagnostic)] +#[diag(expand_duplicate_matcher_binding)] +pub struct DuplicateMatcherBinding { + #[primary_span] + #[label] + pub span: Span, + #[label(expand_label2)] + pub prev: Span, +} diff --git a/compiler/rustc_expand/src/expand.rs b/compiler/rustc_expand/src/expand.rs index ec4091154..ce0093c7d 100644 --- a/compiler/rustc_expand/src/expand.rs +++ b/compiler/rustc_expand/src/expand.rs @@ -657,8 +657,6 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.parse_ast_fragment(tok_result, fragment_kind, &mac.path, span) } SyntaxExtensionKind::LegacyBang(expander) => { - let prev = self.cx.current_expansion.prior_type_ascription; - self.cx.current_expansion.prior_type_ascription = mac.prior_type_ascription; let tok_result = expander.expand(self.cx, span, mac.args.tokens.clone()); let result = if let Some(result) = fragment_kind.make_from(tok_result) { result @@ -666,7 +664,6 @@ impl<'a, 'b> MacroExpander<'a, 'b> { self.error_wrong_fragment_kind(fragment_kind, &mac, span); fragment_kind.dummy(span) }; - self.cx.current_expansion.prior_type_ascription = prev; result } _ => unreachable!(), @@ -725,7 +722,11 @@ impl<'a, 'b> MacroExpander<'a, 'b> { }); } }; - if fragment_kind == AstFragmentKind::Expr && items.is_empty() { + if matches!( + fragment_kind, + AstFragmentKind::Expr | AstFragmentKind::MethodReceiverExpr + ) && items.is_empty() + { self.cx.emit_err(RemoveExprNotSupported { span }); fragment_kind.dummy(span) } else { @@ -800,7 +801,7 @@ impl<'a, 'b> MacroExpander<'a, 'b> { &self.cx.sess.parse_sess, sym::proc_macro_hygiene, span, - &format!("custom attributes cannot be applied to {}", kind), + format!("custom attributes cannot be applied to {}", kind), ) .emit(); } @@ -1598,7 +1599,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { cfg_pos = Some(pos); // a cfg attr found, no need to search anymore break; } else if attr_pos.is_none() - && !name.map_or(false, rustc_feature::is_builtin_attr_name) + && !name.is_some_and(rustc_feature::is_builtin_attr_name) { attr_pos = Some(pos); // a non-cfg attr found, still may find a cfg attr } @@ -1646,7 +1647,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { let current_span = if let Some(sp) = span { sp.to(attr.span) } else { attr.span }; span = Some(current_span); - if attrs.peek().map_or(false, |next_attr| next_attr.doc_str().is_some()) { + if attrs.peek().is_some_and(|next_attr| next_attr.doc_str().is_some()) { continue; } @@ -1667,7 +1668,7 @@ impl<'a, 'b> InvocationCollector<'a, 'b> { &UNUSED_ATTRIBUTES, attr.span, self.cx.current_expansion.lint_node_id, - &format!("unused attribute `{}`", attr_name), + format!("unused attribute `{}`", attr_name), BuiltinLintDiagnostics::UnusedBuiltinAttribute { attr_name, macro_name: pprust::path_to_string(&call.path), @@ -1949,6 +1950,6 @@ impl<'feat> ExpansionConfig<'feat> { } fn proc_macro_hygiene(&self) -> bool { - self.features.map_or(false, |features| features.proc_macro_hygiene) + self.features.is_some_and(|features| features.proc_macro_hygiene) } } diff --git a/compiler/rustc_expand/src/lib.rs b/compiler/rustc_expand/src/lib.rs index ced7531c3..83a5043b0 100644 --- a/compiler/rustc_expand/src/lib.rs +++ b/compiler/rustc_expand/src/lib.rs @@ -21,7 +21,7 @@ extern crate tracing; extern crate proc_macro as pm; use rustc_errors::{DiagnosticMessage, SubdiagnosticMessage}; -use rustc_macros::fluent_messages; +use rustc_fluent_macro::fluent_messages; mod placeholders; mod proc_macro_server; diff --git a/compiler/rustc_expand/src/mbe/diagnostics.rs b/compiler/rustc_expand/src/mbe/diagnostics.rs index 355722922..cb8b4899e 100644 --- a/compiler/rustc_expand/src/mbe/diagnostics.rs +++ b/compiler/rustc_expand/src/mbe/diagnostics.rs @@ -48,7 +48,7 @@ pub(super) fn failed_to_match_macro<'cx>( let span = token.span.substitute_dummy(sp); - let mut err = cx.struct_span_err(span, &parse_failure_msg(&token)); + let mut err = cx.struct_span_err(span, parse_failure_msg(&token)); err.span_label(span, label); if !def_span.is_dummy() && !cx.source_map().is_imported(def_span) { err.span_label(cx.source_map().guess_head_span(def_span), "when calling this macro"); @@ -170,7 +170,7 @@ impl<'a, 'cx, 'matcher> Tracker<'matcher> for CollectTrackerAndEmitter<'a, 'cx, } Error(err_sp, msg) => { let span = err_sp.substitute_dummy(self.root_span); - self.cx.struct_span_err(span, msg).emit(); + self.cx.struct_span_err(span, msg.as_str()).emit(); self.result = Some(DummyResult::any(span)); } ErrorReported(_) => self.result = Some(DummyResult::any(self.root_span)), diff --git a/compiler/rustc_expand/src/mbe/macro_check.rs b/compiler/rustc_expand/src/mbe/macro_check.rs index 5be134f4e..34f998274 100644 --- a/compiler/rustc_expand/src/mbe/macro_check.rs +++ b/compiler/rustc_expand/src/mbe/macro_check.rs @@ -104,12 +104,13 @@ //! Kleene operators under which a meta-variable is repeating is the concatenation of the stacks //! stored when entering a macro definition starting from the state in which the meta-variable is //! bound. +use crate::errors; use crate::mbe::{KleeneToken, TokenTree}; use rustc_ast::token::{Delimiter, Token, TokenKind}; use rustc_ast::{NodeId, DUMMY_NODE_ID}; use rustc_data_structures::fx::FxHashMap; -use rustc_errors::MultiSpan; +use rustc_errors::{DiagnosticMessage, MultiSpan}; use rustc_session::lint::builtin::{META_VARIABLE_MISUSE, MISSING_FRAGMENT_SPECIFIER}; use rustc_session::parse::ParseSess; use rustc_span::symbol::kw; @@ -281,10 +282,7 @@ fn check_binders( // Duplicate binders at the top-level macro definition are errors. The lint is only // for nested macro definitions. sess.span_diagnostic - .struct_span_err(span, "duplicate matcher binding") - .span_label(span, "duplicate binding") - .span_label(prev_info.span, "previous binding") - .emit(); + .emit_err(errors::DuplicateMatcherBinding { span, prev: prev_info.span }); *valid = false; } else { binders.insert(name, BinderInfo { span, ops: ops.into() }); @@ -595,7 +593,7 @@ fn check_ops_is_prefix( return; } } - buffer_lint(sess, span.into(), node_id, &format!("unknown macro variable `{}`", name)); + buffer_lint(sess, span.into(), node_id, format!("unknown macro variable `{}`", name)); } /// Returns whether `binder_ops` is a prefix of `occurrence_ops`. @@ -628,7 +626,7 @@ fn ops_is_prefix( if i >= occurrence_ops.len() { let mut span = MultiSpan::from_span(span); span.push_span_label(binder.span, "expected repetition"); - let message = &format!("variable '{}' is still repeating at this depth", name); + let message = format!("variable '{}' is still repeating at this depth", name); buffer_lint(sess, span, node_id, message); return; } @@ -644,7 +642,12 @@ fn ops_is_prefix( } } -fn buffer_lint(sess: &ParseSess, span: MultiSpan, node_id: NodeId, message: &str) { +fn buffer_lint( + sess: &ParseSess, + span: MultiSpan, + node_id: NodeId, + message: impl Into<DiagnosticMessage>, +) { // Macros loaded from other crates have dummy node ids. if node_id != DUMMY_NODE_ID { sess.buffer_lint(&META_VARIABLE_MISUSE, span, node_id, message); diff --git a/compiler/rustc_expand/src/mbe/macro_parser.rs b/compiler/rustc_expand/src/mbe/macro_parser.rs index 283e68a68..1c222fb4a 100644 --- a/compiler/rustc_expand/src/mbe/macro_parser.rs +++ b/compiler/rustc_expand/src/mbe/macro_parser.rs @@ -88,6 +88,7 @@ use rustc_span::Span; use std::borrow::Cow; use std::collections::hash_map::Entry::{Occupied, Vacant}; use std::fmt::Display; +use std::rc::Rc; /// A unit within a matcher that a `MatcherPos` can refer to. Similar to (and derived from) /// `mbe::TokenTree`, but designed specifically for fast and easy traversal during matching. @@ -257,10 +258,10 @@ struct MatcherPos { /// against the relevant metavar by the black box parser. An element will be a `MatchedSeq` if /// the corresponding metavar decl is within a sequence. /// - /// It is critical to performance that this is an `Lrc`, because it gets cloned frequently when + /// It is critical to performance that this is an `Rc`, because it gets cloned frequently when /// processing sequences. Mostly for sequence-ending possibilities that must be tried but end /// up failing. - matches: Lrc<Vec<NamedMatch>>, + matches: Rc<Vec<NamedMatch>>, } // This type is used a lot. Make sure it doesn't unintentionally get bigger. @@ -272,7 +273,7 @@ impl MatcherPos { /// and both are hot enough to be always worth inlining. #[inline(always)] fn push_match(&mut self, metavar_idx: usize, seq_depth: usize, m: NamedMatch) { - let matches = Lrc::make_mut(&mut self.matches); + let matches = Rc::make_mut(&mut self.matches); match seq_depth { 0 => { // We are not within a sequence. Just append `m`. @@ -427,7 +428,7 @@ pub struct TtParser { /// Pre-allocate an empty match array, so it can be cloned cheaply for macros with many rules /// that have no metavars. - empty_matches: Lrc<Vec<NamedMatch>>, + empty_matches: Rc<Vec<NamedMatch>>, } impl TtParser { @@ -437,7 +438,7 @@ impl TtParser { cur_mps: vec![], next_mps: vec![], bb_mps: vec![], - empty_matches: Lrc::new(vec![]), + empty_matches: Rc::new(vec![]), } } @@ -507,7 +508,7 @@ impl TtParser { // Try zero matches of this sequence, by skipping over it. self.cur_mps.push(MatcherPos { idx: idx_first_after, - matches: Lrc::clone(&mp.matches), + matches: Rc::clone(&mp.matches), }); } @@ -521,7 +522,7 @@ impl TtParser { // processed next time around the loop. let ending_mp = MatcherPos { idx: mp.idx + 1, // +1 skips the Kleene op - matches: Lrc::clone(&mp.matches), + matches: Rc::clone(&mp.matches), }; self.cur_mps.push(ending_mp); @@ -537,7 +538,7 @@ impl TtParser { // will fail quietly when it is processed next time around the loop. let ending_mp = MatcherPos { idx: mp.idx + 2, // +2 skips the separator and the Kleene op - matches: Lrc::clone(&mp.matches), + matches: Rc::clone(&mp.matches), }; self.cur_mps.push(ending_mp); @@ -587,9 +588,9 @@ impl TtParser { if *token == token::Eof { Some(match eof_mps { EofMatcherPositions::One(mut eof_mp) => { - // Need to take ownership of the matches from within the `Lrc`. - Lrc::make_mut(&mut eof_mp.matches); - let matches = Lrc::try_unwrap(eof_mp.matches).unwrap().into_iter(); + // Need to take ownership of the matches from within the `Rc`. + Rc::make_mut(&mut eof_mp.matches); + let matches = Rc::try_unwrap(eof_mp.matches).unwrap().into_iter(); self.nameize(matcher, matches) } EofMatcherPositions::Multiple => { diff --git a/compiler/rustc_expand/src/mbe/macro_rules.rs b/compiler/rustc_expand/src/mbe/macro_rules.rs index 5679cdcbb..e4c65a204 100644 --- a/compiler/rustc_expand/src/mbe/macro_rules.rs +++ b/compiler/rustc_expand/src/mbe/macro_rules.rs @@ -250,8 +250,7 @@ fn expand_macro<'cx>( trace_macros_note(&mut cx.expansions, sp, msg); } - let mut p = Parser::new(sess, tts, false, None); - p.last_type_ascription = cx.current_expansion.prior_type_ascription; + let p = Parser::new(sess, tts, false, None); if is_local { cx.resolver.record_macro_rule_usage(node_id, i); @@ -341,7 +340,7 @@ pub(super) fn try_match_macro<'matcher, T: Tracker<'matcher>>( Success(named_matches) => { debug!("Parsed arm successfully"); // The matcher was `Success(..)`ful. - // Merge the gated spans from parsing the matcher with the pre-existing ones. + // Merge the gated spans from parsing the matcher with the preexisting ones. sess.gated_spans.merge(gated_spans_snapshot); return Ok((i, named_matches)); @@ -475,7 +474,7 @@ pub fn compile_declarative_macro( let s = parse_failure_msg(&token); let sp = token.span.substitute_dummy(def.span); - let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, &s); + let mut err = sess.parse_sess.span_diagnostic.struct_span_err(sp, s); err.span_label(sp, msg); annotate_doc_comment(&mut err, sess.source_map(), sp); err.emit(); @@ -484,7 +483,7 @@ pub fn compile_declarative_macro( Error(sp, msg) => { sess.parse_sess .span_diagnostic - .struct_span_err(sp.substitute_dummy(def.span), &msg) + .struct_span_err(sp.substitute_dummy(def.span), msg) .emit(); return dummy_syn_ext(); } @@ -556,7 +555,7 @@ pub fn compile_declarative_macro( let (transparency, transparency_error) = attr::find_transparency(&def.attrs, macro_rules); match transparency_error { Some(TransparencyError::UnknownTransparency(value, span)) => { - diag.span_err(span, &format!("unknown macro transparency: `{}`", value)); + diag.span_err(span, format!("unknown macro transparency: `{}`", value)); } Some(TransparencyError::MultipleTransparencyAttrs(old_span, new_span)) => { diag.span_err(vec![old_span, new_span], "multiple macro transparency attributes"); @@ -873,7 +872,7 @@ impl<'tt> FirstSets<'tt> { } } -// Most `mbe::TokenTree`s are pre-existing in the matcher, but some are defined +// Most `mbe::TokenTree`s are preexisting in the matcher, but some are defined // implicitly, such as opening/closing delimiters and sequence repetition ops. // This type encapsulates both kinds. It implements `Clone` while avoiding the // need for `mbe::TokenTree` to implement `Clone`. @@ -1165,7 +1164,7 @@ fn check_matcher_core<'tt>( let sp = next_token.span(); let mut err = sess.span_diagnostic.struct_span_err( sp, - &format!( + format!( "`${name}:{frag}` {may_be} followed by `{next}`, which \ is not allowed for `{frag}` fragments", name = name, @@ -1197,13 +1196,13 @@ fn check_matcher_core<'tt>( match possible { &[] => {} &[t] => { - err.note(&format!( + err.note(format!( "only {} is allowed after `{}` fragments", t, kind, )); } ts => { - err.note(&format!( + err.note(format!( "{}{} or {}", msg, ts[..ts.len() - 1].to_vec().join(", "), diff --git a/compiler/rustc_expand/src/mbe/metavar_expr.rs b/compiler/rustc_expand/src/mbe/metavar_expr.rs index fb3a00d86..6e9196150 100644 --- a/compiler/rustc_expand/src/mbe/metavar_expr.rs +++ b/compiler/rustc_expand/src/mbe/metavar_expr.rs @@ -78,7 +78,7 @@ fn check_trailing_token<'sess>( if let Some(tt) = iter.next() { let mut diag = sess .span_diagnostic - .struct_span_err(tt.span(), &format!("unexpected token: {}", pprust::tt_to_string(tt))); + .struct_span_err(tt.span(), format!("unexpected token: {}", pprust::tt_to_string(tt))); diag.span_note(tt.span(), "meta-variable expression must not have trailing tokens"); Err(diag) } else { @@ -137,11 +137,11 @@ fn parse_ident<'sess>( let token_str = pprust::token_to_string(token); let mut err = sess.span_diagnostic.struct_span_err( span, - &format!("expected identifier, found `{}`", &token_str) + format!("expected identifier, found `{}`", &token_str) ); err.span_suggestion( token.span, - &format!("try removing `{}`", &token_str), + format!("try removing `{}`", &token_str), "", Applicability::MaybeIncorrect, ); diff --git a/compiler/rustc_expand/src/mbe/quoted.rs b/compiler/rustc_expand/src/mbe/quoted.rs index bc298b0ad..b2bdf9c7e 100644 --- a/compiler/rustc_expand/src/mbe/quoted.rs +++ b/compiler/rustc_expand/src/mbe/quoted.rs @@ -85,7 +85,7 @@ pub(super) fn parse( frag.name ); sess.span_diagnostic - .struct_span_err(span, &msg) + .struct_span_err(span, msg) .help(VALID_FRAGMENT_NAMES_MSG) .emit(); token::NonterminalKind::Ident @@ -195,7 +195,7 @@ fn parse_tree( _ => { let tok = pprust::token_kind_to_string(&token::OpenDelim(delim)); let msg = format!("expected `(` or `{{`, found `{}`", tok); - sess.span_diagnostic.span_err(delim_span.entire(), &msg); + sess.span_diagnostic.span_err(delim_span.entire(), msg); } } } @@ -246,7 +246,7 @@ fn parse_tree( "expected identifier, found `{}`", pprust::token_to_string(&token), ); - sess.span_diagnostic.span_err(token.span, &msg); + sess.span_diagnostic.span_err(token.span, msg); TokenTree::MetaVar(token.span, Ident::empty()) } @@ -358,7 +358,7 @@ fn parse_sep_and_kleene_op( // For example, `macro_rules! foo { ( ${length()} ) => {} }` fn span_dollar_dollar_or_metavar_in_the_lhs_err(sess: &ParseSess, token: &Token) { sess.span_diagnostic - .span_err(token.span, &format!("unexpected token: {}", pprust::token_to_string(token))); + .span_err(token.span, format!("unexpected token: {}", pprust::token_to_string(token))); sess.span_diagnostic.span_note_without_error( token.span, "`$$` and meta-variable expressions are not allowed inside macro parameter definitions", diff --git a/compiler/rustc_expand/src/mbe/transcribe.rs b/compiler/rustc_expand/src/mbe/transcribe.rs index a07cb6517..d523d3eac 100644 --- a/compiler/rustc_expand/src/mbe/transcribe.rs +++ b/compiler/rustc_expand/src/mbe/transcribe.rs @@ -510,7 +510,7 @@ fn out_of_bounds_err<'a>( must be less than {max}" ) }; - cx.struct_span_err(span, &msg) + cx.struct_span_err(span, msg) } fn transcribe_metavar_expr<'a>( diff --git a/compiler/rustc_expand/src/placeholders.rs b/compiler/rustc_expand/src/placeholders.rs index 03bb5c1df..e9af688ee 100644 --- a/compiler/rustc_expand/src/placeholders.rs +++ b/compiler/rustc_expand/src/placeholders.rs @@ -21,7 +21,6 @@ pub fn placeholder( delim: ast::MacDelimiter::Parenthesis, tokens: ast::tokenstream::TokenStream::new(Vec::new()), }), - prior_type_ascription: None, }) } diff --git a/compiler/rustc_expand/src/proc_macro.rs b/compiler/rustc_expand/src/proc_macro.rs index 26bc216f6..41b24407f 100644 --- a/compiler/rustc_expand/src/proc_macro.rs +++ b/compiler/rustc_expand/src/proc_macro.rs @@ -95,7 +95,7 @@ impl base::AttrProcMacro for AttrProcMacro { |e| { let mut err = ecx.struct_span_err(span, "custom attribute panicked"); if let Some(s) = e.as_str() { - err.help(&format!("message: {}", s)); + err.help(format!("message: {}", s)); } err.emit() }, @@ -148,7 +148,7 @@ impl MultiItemModifier for DeriveProcMacro { Err(e) => { let mut err = ecx.struct_span_err(span, "proc-macro derive panicked"); if let Some(s) = e.as_str() { - err.help(&format!("message: {}", s)); + err.help(format!("message: {}", s)); } err.emit(); return ExpandResult::Ready(vec![]); diff --git a/compiler/rustc_expand/src/proc_macro_server.rs b/compiler/rustc_expand/src/proc_macro_server.rs index 341ae1854..891e84a2f 100644 --- a/compiler/rustc_expand/src/proc_macro_server.rs +++ b/compiler/rustc_expand/src/proc_macro_server.rs @@ -18,7 +18,7 @@ use rustc_span::def_id::CrateNum; use rustc_span::symbol::{self, sym, Symbol}; use rustc_span::{BytePos, FileName, Pos, SourceFile, Span}; use smallvec::{smallvec, SmallVec}; -use std::ops::Bound; +use std::ops::{Bound, Range}; trait FromInternal<T> { fn from_internal(x: T) -> Self; @@ -61,6 +61,8 @@ impl FromInternal<token::LitKind> for LitKind { token::StrRaw(n) => LitKind::StrRaw(n), token::ByteStr => LitKind::ByteStr, token::ByteStrRaw(n) => LitKind::ByteStrRaw(n), + token::CStr => LitKind::CStr, + token::CStrRaw(n) => LitKind::CStrRaw(n), token::Err => LitKind::Err, token::Bool => unreachable!(), } @@ -78,6 +80,8 @@ impl ToInternal<token::LitKind> for LitKind { LitKind::StrRaw(n) => token::StrRaw(n), LitKind::ByteStr => token::ByteStr, LitKind::ByteStrRaw(n) => token::ByteStrRaw(n), + LitKind::CStr => token::CStr, + LitKind::CStrRaw(n) => token::CStrRaw(n), LitKind::Err => token::Err, } } @@ -436,6 +440,8 @@ impl server::FreeFunctions for Rustc<'_, '_> { | token::LitKind::StrRaw(_) | token::LitKind::ByteStr | token::LitKind::ByteStrRaw(_) + | token::LitKind::CStr + | token::LitKind::CStrRaw(_) | token::LitKind::Err => return Err(()), token::LitKind::Integer | token::LitKind::Float => {} } @@ -634,6 +640,15 @@ impl server::Span for Rustc<'_, '_> { span.source_callsite() } + fn byte_range(&mut self, span: Self::Span) -> Range<usize> { + let source_map = self.sess().source_map(); + + let relative_start_pos = source_map.lookup_byte_offset(span.lo()).pos; + let relative_end_pos = source_map.lookup_byte_offset(span.hi()).pos; + + Range { start: relative_start_pos.0 as usize, end: relative_end_pos.0 as usize } + } + fn start(&mut self, span: Self::Span) -> LineColumn { let loc = self.sess().source_map().lookup_char_pos(span.lo()); LineColumn { line: loc.line, column: loc.col.to_usize() } diff --git a/compiler/rustc_expand/src/tests.rs b/compiler/rustc_expand/src/tests.rs index 480d95b77..8a5e09475 100644 --- a/compiler/rustc_expand/src/tests.rs +++ b/compiler/rustc_expand/src/tests.rs @@ -513,7 +513,7 @@ error: foo } #[test] -fn non_overlaping() { +fn non_overlapping() { test_harness( r#" fn foo() { @@ -552,7 +552,7 @@ error: foo } #[test] -fn overlaping_start_and_end() { +fn overlapping_start_and_end() { test_harness( r#" fn foo() { |