2021-02-01 15:30:09 -06:00
|
|
|
use crate::{LateContext, LateLintPass, LintContext};
|
|
|
|
use rustc_ast as ast;
|
|
|
|
use rustc_errors::{pluralize, Applicability};
|
|
|
|
use rustc_hir as hir;
|
2021-08-16 10:25:35 -05:00
|
|
|
use rustc_infer::infer::TyCtxtInferExt;
|
2021-08-12 07:33:30 -05:00
|
|
|
use rustc_middle::lint::in_external_macro;
|
2021-02-01 15:30:09 -06:00
|
|
|
use rustc_middle::ty;
|
2021-08-16 10:25:35 -05:00
|
|
|
use rustc_middle::ty::subst::InternalSubsts;
|
2021-02-01 15:30:09 -06:00
|
|
|
use rustc_parse_format::{ParseMode, Parser, Piece};
|
2021-06-27 09:47:26 -05:00
|
|
|
use rustc_session::lint::FutureIncompatibilityReason;
|
|
|
|
use rustc_span::edition::Edition;
|
2021-12-14 15:32:21 -06:00
|
|
|
use rustc_span::{hygiene, sym, symbol::kw, InnerSpan, Span, Symbol};
|
2021-08-16 10:25:35 -05:00
|
|
|
use rustc_trait_selection::infer::InferCtxtExt;
|
2021-02-01 15:30:09 -06:00
|
|
|
|
|
|
|
declare_lint! {
|
2021-06-29 13:33:31 -05:00
|
|
|
/// The `non_fmt_panics` lint detects `panic!(..)` invocations where the first
|
2021-02-01 15:30:09 -06:00
|
|
|
/// argument is not a formatting string.
|
|
|
|
///
|
|
|
|
/// ### Example
|
|
|
|
///
|
2021-09-20 07:46:26 -05:00
|
|
|
/// ```rust,no_run,edition2018
|
2021-02-01 15:30:09 -06:00
|
|
|
/// panic!("{}");
|
|
|
|
/// panic!(123);
|
|
|
|
/// ```
|
|
|
|
///
|
|
|
|
/// {{produces}}
|
|
|
|
///
|
|
|
|
/// ### Explanation
|
|
|
|
///
|
|
|
|
/// In Rust 2018 and earlier, `panic!(x)` directly uses `x` as the message.
|
|
|
|
/// That means that `panic!("{}")` panics with the message `"{}"` instead
|
|
|
|
/// of using it as a formatting string, and `panic!(123)` will panic with
|
|
|
|
/// an `i32` as message.
|
|
|
|
///
|
|
|
|
/// Rust 2021 always interprets the first argument as format string.
|
2021-06-29 13:33:31 -05:00
|
|
|
NON_FMT_PANICS,
|
2021-02-01 15:30:09 -06:00
|
|
|
Warn,
|
|
|
|
"detect single-argument panic!() invocations in which the argument is not a format string",
|
2021-06-27 09:47:26 -05:00
|
|
|
@future_incompatible = FutureIncompatibleInfo {
|
|
|
|
reason: FutureIncompatibilityReason::EditionSemanticsChange(Edition::Edition2021),
|
|
|
|
explain_reason: false,
|
|
|
|
};
|
2021-02-01 15:30:09 -06:00
|
|
|
report_in_external_macro
|
|
|
|
}
|
|
|
|
|
2021-06-29 13:33:31 -05:00
|
|
|
declare_lint_pass!(NonPanicFmt => [NON_FMT_PANICS]);
|
2021-02-01 15:30:09 -06:00
|
|
|
|
|
|
|
impl<'tcx> LateLintPass<'tcx> for NonPanicFmt {
|
|
|
|
fn check_expr(&mut self, cx: &LateContext<'tcx>, expr: &'tcx hir::Expr<'tcx>) {
|
|
|
|
if let hir::ExprKind::Call(f, [arg]) = &expr.kind {
|
|
|
|
if let &ty::FnDef(def_id, _) = cx.typeck_results().expr_ty(f).kind() {
|
2022-01-23 07:57:49 -06:00
|
|
|
let f_diagnostic_name = cx.tcx.get_diagnostic_name(def_id);
|
|
|
|
|
2021-02-01 15:30:09 -06:00
|
|
|
if Some(def_id) == cx.tcx.lang_items().begin_panic_fn()
|
|
|
|
|| Some(def_id) == cx.tcx.lang_items().panic_fn()
|
2022-01-23 07:57:49 -06:00
|
|
|
|| f_diagnostic_name == Some(sym::panic_str)
|
2021-02-01 15:30:09 -06:00
|
|
|
{
|
|
|
|
if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
|
2021-10-04 16:11:22 -05:00
|
|
|
if matches!(
|
|
|
|
cx.tcx.get_diagnostic_name(id),
|
|
|
|
Some(sym::core_panic_2015_macro | sym::std_panic_2015_macro)
|
|
|
|
) {
|
2021-02-01 15:30:09 -06:00
|
|
|
check_panic(cx, f, arg);
|
|
|
|
}
|
|
|
|
}
|
2022-01-23 07:57:49 -06:00
|
|
|
} else if f_diagnostic_name == Some(sym::unreachable_display) {
|
|
|
|
if let Some(id) = f.span.ctxt().outer_expn_data().macro_def_id {
|
|
|
|
if cx.tcx.is_diagnostic_item(sym::unreachable_2015_macro, id) {
|
|
|
|
check_panic(
|
|
|
|
cx,
|
|
|
|
f,
|
|
|
|
// This is safe because we checked above that the callee is indeed
|
|
|
|
// unreachable_display
|
|
|
|
match &arg.kind {
|
|
|
|
// Get the borrowed arg not the borrow
|
|
|
|
hir::ExprKind::AddrOf(ast::BorrowKind::Ref, _, arg) => arg,
|
|
|
|
_ => bug!("call to unreachable_display without borrow"),
|
|
|
|
},
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|
2021-02-01 15:30:09 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tcx hir::Expr<'tcx>) {
|
|
|
|
if let hir::ExprKind::Lit(lit) = &arg.kind {
|
|
|
|
if let ast::LitKind::Str(sym, _) = lit.node {
|
|
|
|
// The argument is a string literal.
|
2021-12-14 21:39:23 -06:00
|
|
|
check_panic_str(cx, f, arg, sym.as_str());
|
2021-02-01 15:30:09 -06:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
// The argument is *not* a string literal.
|
|
|
|
|
2021-12-14 15:32:21 -06:00
|
|
|
let (span, panic, symbol) = panic_call(cx, f);
|
2021-02-01 15:30:09 -06:00
|
|
|
|
2021-08-12 07:33:30 -05:00
|
|
|
if in_external_macro(cx.sess(), span) {
|
|
|
|
// Nothing that can be done about it in the current crate.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2022-01-23 07:57:49 -06:00
|
|
|
// Find the span of the argument to `panic!()` or `unreachable!`, before expansion in the
|
|
|
|
// case of `panic!(some_macro!())` or `unreachable!(some_macro!())`.
|
2021-02-17 03:51:22 -06:00
|
|
|
// We don't use source_callsite(), because this `panic!(..)` might itself
|
|
|
|
// be expanded from another macro, in which case we want to stop at that
|
|
|
|
// expansion.
|
2021-02-14 11:14:23 -06:00
|
|
|
let mut arg_span = arg.span;
|
2021-02-14 11:52:47 -06:00
|
|
|
let mut arg_macro = None;
|
2021-02-14 11:14:23 -06:00
|
|
|
while !span.contains(arg_span) {
|
|
|
|
let expn = arg_span.ctxt().outer_expn_data();
|
|
|
|
if expn.is_root() {
|
|
|
|
break;
|
|
|
|
}
|
2021-02-14 11:52:47 -06:00
|
|
|
arg_macro = expn.macro_def_id;
|
2021-02-14 11:14:23 -06:00
|
|
|
arg_span = expn.call_site;
|
|
|
|
}
|
|
|
|
|
2021-06-29 13:33:31 -05:00
|
|
|
cx.struct_span_lint(NON_FMT_PANICS, arg_span, |lint| {
|
2021-02-01 15:30:09 -06:00
|
|
|
let mut l = lint.build("panic message is not a string literal");
|
2021-12-14 15:32:21 -06:00
|
|
|
l.note(&format!("this usage of {}!() is deprecated; it will be a hard error in Rust 2021", symbol));
|
2021-06-27 09:47:26 -05:00
|
|
|
l.note("for more information, see <https://doc.rust-lang.org/nightly/edition-guide/rust-2021/panic-macro-consistency.html>");
|
2021-08-12 07:56:41 -05:00
|
|
|
if !is_arg_inside_call(arg_span, span) {
|
2021-02-14 11:52:47 -06:00
|
|
|
// No clue where this argument is coming from.
|
|
|
|
l.emit();
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
if arg_macro.map_or(false, |id| cx.tcx.is_diagnostic_item(sym::format_macro, id)) {
|
|
|
|
// A case of `panic!(format!(..))`.
|
2021-12-14 15:32:21 -06:00
|
|
|
l.note(format!("the {}!() macro supports formatting, so there's no need for the format!() macro here", symbol).as_str());
|
2021-02-14 12:43:07 -06:00
|
|
|
if let Some((open, close, _)) = find_delimiters(cx, arg_span) {
|
2021-02-14 11:52:47 -06:00
|
|
|
l.multipart_suggestion(
|
|
|
|
"remove the `format!(..)` macro call",
|
|
|
|
vec![
|
2021-02-14 12:43:07 -06:00
|
|
|
(arg_span.until(open.shrink_to_hi()), "".into()),
|
|
|
|
(close.until(arg_span.shrink_to_hi()), "".into()),
|
2021-02-14 11:52:47 -06:00
|
|
|
],
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
} else {
|
2021-08-12 12:14:54 -05:00
|
|
|
let ty = cx.typeck_results().expr_ty(arg);
|
|
|
|
// If this is a &str or String, we can confidently give the `"{}", ` suggestion.
|
|
|
|
let is_str = matches!(
|
|
|
|
ty.kind(),
|
2021-08-12 12:21:46 -05:00
|
|
|
ty::Ref(_, r, _) if *r.kind() == ty::Str,
|
2021-08-12 12:14:54 -05:00
|
|
|
) || matches!(
|
2021-08-12 12:21:46 -05:00
|
|
|
ty.ty_adt_def(),
|
2022-03-04 14:28:41 -06:00
|
|
|
Some(ty_def) if cx.tcx.is_diagnostic_item(sym::String, ty_def.did()),
|
2021-08-12 12:14:54 -05:00
|
|
|
);
|
2021-08-16 10:25:35 -05:00
|
|
|
|
|
|
|
let (suggest_display, suggest_debug) = cx.tcx.infer_ctxt().enter(|infcx| {
|
2021-10-02 18:51:01 -05:00
|
|
|
let display = is_str || cx.tcx.get_diagnostic_item(sym::Display).map(|t| {
|
2021-08-16 10:25:35 -05:00
|
|
|
infcx.type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env).may_apply()
|
|
|
|
}) == Some(true);
|
2021-10-02 18:51:01 -05:00
|
|
|
let debug = !display && cx.tcx.get_diagnostic_item(sym::Debug).map(|t| {
|
2021-08-16 10:25:35 -05:00
|
|
|
infcx.type_implements_trait(t, ty, InternalSubsts::empty(), cx.param_env).may_apply()
|
|
|
|
}) == Some(true);
|
|
|
|
(display, debug)
|
|
|
|
});
|
|
|
|
|
|
|
|
let suggest_panic_any = !is_str && panic == sym::std_panic_macro;
|
|
|
|
|
|
|
|
let fmt_applicability = if suggest_panic_any {
|
|
|
|
// If we can use panic_any, use that as the MachineApplicable suggestion.
|
|
|
|
Applicability::MaybeIncorrect
|
|
|
|
} else {
|
|
|
|
// If we don't suggest panic_any, using a format string is our best bet.
|
|
|
|
Applicability::MachineApplicable
|
|
|
|
};
|
|
|
|
|
|
|
|
if suggest_display {
|
|
|
|
l.span_suggestion_verbose(
|
|
|
|
arg_span.shrink_to_lo(),
|
|
|
|
"add a \"{}\" format string to Display the message",
|
2022-04-26 00:17:33 -05:00
|
|
|
"\"{}\", ",
|
2021-08-16 10:25:35 -05:00
|
|
|
fmt_applicability,
|
|
|
|
);
|
|
|
|
} else if suggest_debug {
|
|
|
|
l.span_suggestion_verbose(
|
|
|
|
arg_span.shrink_to_lo(),
|
|
|
|
&format!(
|
|
|
|
"add a \"{{:?}}\" format string to use the Debug implementation of `{}`",
|
|
|
|
ty,
|
|
|
|
),
|
2022-04-26 00:17:33 -05:00
|
|
|
"\"{:?}\", ",
|
2021-08-16 10:25:35 -05:00
|
|
|
fmt_applicability,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
|
|
if suggest_panic_any {
|
2021-02-14 12:43:07 -06:00
|
|
|
if let Some((open, close, del)) = find_delimiters(cx, span) {
|
|
|
|
l.multipart_suggestion(
|
2021-08-16 10:25:35 -05:00
|
|
|
&format!(
|
|
|
|
"{}use std::panic::panic_any instead",
|
|
|
|
if suggest_display || suggest_debug {
|
|
|
|
"or "
|
|
|
|
} else {
|
|
|
|
""
|
|
|
|
},
|
|
|
|
),
|
2021-02-14 12:43:07 -06:00
|
|
|
if del == '(' {
|
|
|
|
vec![(span.until(open), "std::panic::panic_any".into())]
|
|
|
|
} else {
|
|
|
|
vec![
|
|
|
|
(span.until(open.shrink_to_hi()), "std::panic::panic_any(".into()),
|
|
|
|
(close, ")".into()),
|
|
|
|
]
|
|
|
|
},
|
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
2021-02-01 15:30:09 -06:00
|
|
|
}
|
|
|
|
}
|
|
|
|
l.emit();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
|
|
|
|
fn check_panic_str<'tcx>(
|
|
|
|
cx: &LateContext<'tcx>,
|
|
|
|
f: &'tcx hir::Expr<'tcx>,
|
|
|
|
arg: &'tcx hir::Expr<'tcx>,
|
|
|
|
fmt: &str,
|
|
|
|
) {
|
2021-12-02 20:06:36 -06:00
|
|
|
if !fmt.contains(&['{', '}']) {
|
2021-02-01 15:30:09 -06:00
|
|
|
// No brace, no problem.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-08-12 07:33:30 -05:00
|
|
|
let (span, _, _) = panic_call(cx, f);
|
|
|
|
|
|
|
|
if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
|
|
|
|
// Nothing that can be done about it in the current crate.
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2021-02-01 15:30:09 -06:00
|
|
|
let fmt_span = arg.span.source_callsite();
|
|
|
|
|
|
|
|
let (snippet, style) = match cx.sess().parse_sess.source_map().span_to_snippet(fmt_span) {
|
|
|
|
Ok(snippet) => {
|
|
|
|
// Count the number of `#`s between the `r` and `"`.
|
|
|
|
let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
|
|
|
|
(Some(snippet), style)
|
|
|
|
}
|
|
|
|
Err(_) => (None, None),
|
|
|
|
};
|
|
|
|
|
2021-10-07 16:18:39 -05:00
|
|
|
let mut fmt_parser = Parser::new(fmt, style, snippet.clone(), false, ParseMode::Format);
|
2021-02-01 15:30:09 -06:00
|
|
|
let n_arguments = (&mut fmt_parser).filter(|a| matches!(a, Piece::NextArgument(_))).count();
|
|
|
|
|
|
|
|
if n_arguments > 0 && fmt_parser.errors.is_empty() {
|
|
|
|
let arg_spans: Vec<_> = match &fmt_parser.arg_places[..] {
|
|
|
|
[] => vec![fmt_span],
|
2022-04-29 11:48:58 -05:00
|
|
|
v => v
|
|
|
|
.iter()
|
|
|
|
.map(|span| fmt_span.from_inner(InnerSpan::new(span.start, span.end)))
|
|
|
|
.collect(),
|
2021-02-01 15:30:09 -06:00
|
|
|
};
|
2021-06-29 13:33:31 -05:00
|
|
|
cx.struct_span_lint(NON_FMT_PANICS, arg_spans, |lint| {
|
2021-02-01 15:30:09 -06:00
|
|
|
let mut l = lint.build(match n_arguments {
|
|
|
|
1 => "panic message contains an unused formatting placeholder",
|
|
|
|
_ => "panic message contains unused formatting placeholders",
|
|
|
|
});
|
|
|
|
l.note("this message is not used as a format string when given without arguments, but will be in Rust 2021");
|
2021-08-12 07:56:41 -05:00
|
|
|
if is_arg_inside_call(arg.span, span) {
|
2021-02-01 15:30:09 -06:00
|
|
|
l.span_suggestion(
|
|
|
|
arg.span.shrink_to_hi(),
|
|
|
|
&format!("add the missing argument{}", pluralize!(n_arguments)),
|
2022-04-26 00:17:33 -05:00
|
|
|
", ...",
|
2021-02-01 15:30:09 -06:00
|
|
|
Applicability::HasPlaceholders,
|
|
|
|
);
|
|
|
|
l.span_suggestion(
|
|
|
|
arg.span.shrink_to_lo(),
|
|
|
|
"or add a \"{}\" format string to use the message literally",
|
2022-04-26 00:17:33 -05:00
|
|
|
"\"{}\", ",
|
2021-02-01 15:30:09 -06:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
l.emit();
|
|
|
|
});
|
|
|
|
} else {
|
|
|
|
let brace_spans: Option<Vec<_>> =
|
|
|
|
snippet.filter(|s| s.starts_with('"') || s.starts_with("r#")).map(|s| {
|
|
|
|
s.char_indices()
|
|
|
|
.filter(|&(_, c)| c == '{' || c == '}')
|
|
|
|
.map(|(i, _)| fmt_span.from_inner(InnerSpan { start: i, end: i + 1 }))
|
|
|
|
.collect()
|
|
|
|
});
|
|
|
|
let msg = match &brace_spans {
|
|
|
|
Some(v) if v.len() == 1 => "panic message contains a brace",
|
|
|
|
_ => "panic message contains braces",
|
|
|
|
};
|
2021-06-29 13:33:31 -05:00
|
|
|
cx.struct_span_lint(NON_FMT_PANICS, brace_spans.unwrap_or_else(|| vec![span]), |lint| {
|
2021-02-01 15:30:09 -06:00
|
|
|
let mut l = lint.build(msg);
|
|
|
|
l.note("this message is not used as a format string, but will be in Rust 2021");
|
2021-08-12 07:56:41 -05:00
|
|
|
if is_arg_inside_call(arg.span, span) {
|
2021-02-01 15:30:09 -06:00
|
|
|
l.span_suggestion(
|
|
|
|
arg.span.shrink_to_lo(),
|
|
|
|
"add a \"{}\" format string to use the message literally",
|
2022-04-26 00:17:33 -05:00
|
|
|
"\"{}\", ",
|
2021-02-01 15:30:09 -06:00
|
|
|
Applicability::MachineApplicable,
|
|
|
|
);
|
|
|
|
}
|
|
|
|
l.emit();
|
|
|
|
});
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-02-14 12:43:07 -06:00
|
|
|
/// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
|
|
|
|
/// and the type of (opening) delimiter used.
|
|
|
|
fn find_delimiters<'tcx>(cx: &LateContext<'tcx>, span: Span) -> Option<(Span, Span, char)> {
|
2021-02-14 11:52:47 -06:00
|
|
|
let snippet = cx.sess().parse_sess.source_map().span_to_snippet(span).ok()?;
|
2021-02-14 12:43:07 -06:00
|
|
|
let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
|
|
|
|
let close = snippet.rfind(|c| ")]}".contains(c))?;
|
|
|
|
Some((
|
2021-02-14 12:51:15 -06:00
|
|
|
span.from_inner(InnerSpan { start: open, end: open + 1 }),
|
|
|
|
span.from_inner(InnerSpan { start: close, end: close + 1 }),
|
2021-02-14 12:43:07 -06:00
|
|
|
open_ch,
|
|
|
|
))
|
2021-02-14 11:52:47 -06:00
|
|
|
}
|
|
|
|
|
2021-12-14 15:32:21 -06:00
|
|
|
fn panic_call<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>) -> (Span, Symbol, Symbol) {
|
2021-02-01 15:30:09 -06:00
|
|
|
let mut expn = f.span.ctxt().outer_expn_data();
|
|
|
|
|
|
|
|
let mut panic_macro = kw::Empty;
|
|
|
|
|
|
|
|
// Unwrap more levels of macro expansion, as panic_2015!()
|
|
|
|
// was likely expanded from panic!() and possibly from
|
|
|
|
// [debug_]assert!().
|
2021-11-16 13:12:38 -06:00
|
|
|
loop {
|
2021-02-01 15:30:09 -06:00
|
|
|
let parent = expn.call_site.ctxt().outer_expn_data();
|
2021-11-16 13:12:38 -06:00
|
|
|
let Some(id) = parent.macro_def_id else { break };
|
|
|
|
let Some(name) = cx.tcx.get_diagnostic_name(id) else { break };
|
|
|
|
if !matches!(
|
|
|
|
name,
|
|
|
|
sym::core_panic_macro
|
|
|
|
| sym::std_panic_macro
|
|
|
|
| sym::assert_macro
|
|
|
|
| sym::debug_assert_macro
|
2022-01-23 07:57:49 -06:00
|
|
|
| sym::unreachable_macro
|
2021-11-16 13:12:38 -06:00
|
|
|
) {
|
|
|
|
break;
|
2021-02-01 15:30:09 -06:00
|
|
|
}
|
2021-11-16 13:12:38 -06:00
|
|
|
expn = parent;
|
|
|
|
panic_macro = name;
|
2021-02-01 15:30:09 -06:00
|
|
|
}
|
|
|
|
|
Implement span quoting for proc-macros
This PR implements span quoting, allowing proc-macros to produce spans
pointing *into their own crate*. This is used by the unstable
`proc_macro::quote!` macro, allowing us to get error messages like this:
```
error[E0412]: cannot find type `MissingType` in this scope
--> $DIR/auxiliary/span-from-proc-macro.rs:37:20
|
LL | pub fn error_from_attribute(_args: TokenStream, _input: TokenStream) -> TokenStream {
| ----------------------------------------------------------------------------------- in this expansion of procedural macro `#[error_from_attribute]`
...
LL | field: MissingType
| ^^^^^^^^^^^ not found in this scope
|
::: $DIR/span-from-proc-macro.rs:8:1
|
LL | #[error_from_attribute]
| ----------------------- in this macro invocation
```
Here, `MissingType` occurs inside the implementation of the proc-macro
`#[error_from_attribute]`. Previosuly, this would always result in a
span pointing at `#[error_from_attribute]`
This will make many proc-macro-related error message much more useful -
when a proc-macro generates code containing an error, users will get an
error message pointing directly at that code (within the macro
definition), instead of always getting a span pointing at the macro
invocation site.
This is implemented as follows:
* When a proc-macro crate is being *compiled*, it causes the `quote!`
macro to get run. This saves all of the sapns in the input to `quote!`
into the metadata of *the proc-macro-crate* (which we are currently
compiling). The `quote!` macro then expands to a call to
`proc_macro::Span::recover_proc_macro_span(id)`, where `id` is an
opaque identifier for the span in the crate metadata.
* When the same proc-macro crate is *run* (e.g. it is loaded from disk
and invoked by some consumer crate), the call to
`proc_macro::Span::recover_proc_macro_span` causes us to load the span
from the proc-macro crate's metadata. The proc-macro then produces a
`TokenStream` containing a `Span` pointing into the proc-macro crate
itself.
The recursive nature of 'quote!' can be difficult to understand at
first. The file `src/test/ui/proc-macro/quote-debug.stdout` shows
the output of the `quote!` macro, which should make this eaier to
understand.
This PR also supports custom quoting spans in custom quote macros (e.g.
the `quote` crate). All span quoting goes through the
`proc_macro::quote_span` method, which can be called by a custom quote
macro to perform span quoting. An example of this usage is provided in
`src/test/ui/proc-macro/auxiliary/custom-quote.rs`
Custom quoting currently has a few limitations:
In order to quote a span, we need to generate a call to
`proc_macro::Span::recover_proc_macro_span`. However, proc-macros
support renaming the `proc_macro` crate, so we can't simply hardcode
this path. Previously, the `quote_span` method used the path
`crate::Span` - however, this only works when it is called by the
builtin `quote!` macro in the same crate. To support being called from
arbitrary crates, we need access to the name of the `proc_macro` crate
to generate a path. This PR adds an additional argument to `quote_span`
to specify the name of the `proc_macro` crate. Howver, this feels kind
of hacky, and we may want to change this before stabilizing anything
quote-related.
Additionally, using `quote_span` currently requires enabling the
`proc_macro_internals` feature. The builtin `quote!` macro
has an `#[allow_internal_unstable]` attribute, but this won't work for
custom quote implementations. This will likely require some additional
tricks to apply `allow_internal_unstable` to the span of
`proc_macro::Span::recover_proc_macro_span`.
2020-08-02 18:52:16 -05:00
|
|
|
let macro_symbol =
|
2021-07-10 14:14:52 -05:00
|
|
|
if let hygiene::ExpnKind::Macro(_, symbol) = expn.kind { symbol } else { sym::panic };
|
2021-12-14 15:32:21 -06:00
|
|
|
(expn.call_site, panic_macro, macro_symbol)
|
2021-02-01 15:30:09 -06:00
|
|
|
}
|
2021-08-12 07:56:41 -05:00
|
|
|
|
|
|
|
fn is_arg_inside_call(arg: Span, call: Span) -> bool {
|
|
|
|
// We only add suggestions if the argument we're looking at appears inside the
|
|
|
|
// panic call in the source file, to avoid invalid suggestions when macros are involved.
|
|
|
|
// We specifically check for the spans to not be identical, as that happens sometimes when
|
|
|
|
// proc_macros lie about spans and apply the same span to all the tokens they produce.
|
2022-01-27 01:17:13 -06:00
|
|
|
call.contains(arg) && !call.source_equal(arg)
|
2021-08-12 07:56:41 -05:00
|
|
|
}
|