Skip to content

Commit 06090e8

Browse files
committed
Convert two rustc_middle::lint functions to Span methods.
`rustc_middle` is a huge crate and it's always good to move stuff out of it. There are lots of similar methods already on `Span`, so these two functions, `in_external_macro` and `is_from_async_await`, fit right in. The diff is big because `in_external_macro` is used a lot by clippy lints.
1 parent e08cd3c commit 06090e8

File tree

102 files changed

+179
-278
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

102 files changed

+179
-278
lines changed

compiler/rustc_hir_typeck/src/coercion.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,6 @@ use rustc_infer::traits::{
5050
IfExpressionCause, MatchExpressionArmCause, Obligation, PredicateObligation,
5151
PredicateObligations,
5252
};
53-
use rustc_middle::lint::in_external_macro;
5453
use rustc_middle::span_bug;
5554
use rustc_middle::traits::BuiltinImplSource;
5655
use rustc_middle::ty::adjustment::{
@@ -1937,7 +1936,7 @@ impl<'tcx, 'exprs, E: AsCoercionSite> CoerceMany<'tcx, 'exprs, E> {
19371936
cond_expr.span.desugaring_kind(),
19381937
None | Some(DesugaringKind::WhileLoop)
19391938
)
1940-
&& !in_external_macro(fcx.tcx.sess, cond_expr.span)
1939+
&& !cond_expr.span.in_external_macro(fcx.tcx.sess.source_map())
19411940
&& !matches!(
19421941
cond_expr.kind,
19431942
hir::ExprKind::Match(.., hir::MatchSource::TryDesugar(_))

compiler/rustc_hir_typeck/src/fn_ctxt/suggestions.rs

+4-6
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,6 @@ use rustc_hir::{
1414
};
1515
use rustc_hir_analysis::hir_ty_lowering::HirTyLowerer;
1616
use rustc_hir_analysis::suggest_impl_trait;
17-
use rustc_middle::lint::in_external_macro;
1817
use rustc_middle::middle::stability::EvalResult;
1918
use rustc_middle::span_bug;
2019
use rustc_middle::ty::print::with_no_trimmed_paths;
@@ -770,7 +769,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
770769
// If the expression is from an external macro, then do not suggest
771770
// adding a semicolon, because there's nowhere to put it.
772771
// See issue #81943.
773-
&& !in_external_macro(self.tcx.sess, expression.span) =>
772+
&& !expression.span.in_external_macro(self.tcx.sess.source_map()) =>
774773
{
775774
if needs_block {
776775
err.multipart_suggestion(
@@ -2265,7 +2264,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
22652264
expected: Ty<'tcx>,
22662265
expr_ty: Ty<'tcx>,
22672266
) -> bool {
2268-
if in_external_macro(self.tcx.sess, expr.span) {
2267+
if expr.span.in_external_macro(self.tcx.sess.source_map()) {
22692268
return false;
22702269
}
22712270
if let ty::Adt(expected_adt, args) = expected.kind() {
@@ -2593,14 +2592,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
25932592
)> {
25942593
let sess = self.sess();
25952594
let sp = expr.span;
2595+
let sm = sess.source_map();
25962596

25972597
// If the span is from an external macro, there's no suggestion we can make.
2598-
if in_external_macro(sess, sp) {
2598+
if sp.in_external_macro(sm) {
25992599
return None;
26002600
}
26012601

2602-
let sm = sess.source_map();
2603-
26042602
let replace_prefix = |s: &str, old: &str, new: &str| {
26052603
s.strip_prefix(old).map(|stripped| new.to_string() + stripped)
26062604
};

compiler/rustc_lint/src/builtin.rs

+1-2
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,6 @@ use rustc_hir::def_id::{CRATE_DEF_ID, DefId, LocalDefId};
2929
use rustc_hir::intravisit::FnKind as HirFnKind;
3030
use rustc_hir::{Body, FnDecl, GenericParamKind, PatKind, PredicateOrigin};
3131
use rustc_middle::bug;
32-
use rustc_middle::lint::in_external_macro;
3332
use rustc_middle::ty::layout::LayoutOf;
3433
use rustc_middle::ty::print::with_no_trimmed_paths;
3534
use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitableExt, Upcast, VariantDef};
@@ -2029,7 +2028,7 @@ impl ExplicitOutlivesRequirements {
20292028
}
20302029

20312030
let span = bound.span().find_ancestor_inside(predicate_span)?;
2032-
if in_external_macro(tcx.sess, span) {
2031+
if span.in_external_macro(tcx.sess.source_map()) {
20332032
return None;
20342033
}
20352034

compiler/rustc_lint/src/early/diagnostics/check_cfg.rs

+2-2
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,7 @@ pub(super) fn unexpected_cfg_name(
135135
};
136136

137137
let is_from_cargo = rustc_session::utils::was_invoked_from_cargo();
138-
let is_from_external_macro = rustc_middle::lint::in_external_macro(sess, name_span);
138+
let is_from_external_macro = name_span.in_external_macro(sess.source_map());
139139
let mut is_feature_cfg = name == sym::feature;
140140

141141
let code_sugg = if is_feature_cfg && is_from_cargo {
@@ -281,7 +281,7 @@ pub(super) fn unexpected_cfg_value(
281281
.collect();
282282

283283
let is_from_cargo = rustc_session::utils::was_invoked_from_cargo();
284-
let is_from_external_macro = rustc_middle::lint::in_external_macro(sess, name_span);
284+
let is_from_external_macro = name_span.in_external_macro(sess.source_map());
285285

286286
// Show the full list if all possible values for a given name, but don't do it
287287
// for names as the possibilities could be very long

compiler/rustc_lint/src/non_fmt_panic.rs

+5-5
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@ use rustc_ast as ast;
22
use rustc_errors::Applicability;
33
use rustc_hir::{self as hir, LangItem};
44
use rustc_infer::infer::TyCtxtInferExt;
5-
use rustc_middle::lint::in_external_macro;
65
use rustc_middle::{bug, ty};
76
use rustc_parse_format::{ParseMode, Parser, Piece};
87
use rustc_session::lint::FutureIncompatibilityReason;
@@ -100,7 +99,7 @@ fn check_panic<'tcx>(cx: &LateContext<'tcx>, f: &'tcx hir::Expr<'tcx>, arg: &'tc
10099

101100
let (span, panic, symbol) = panic_call(cx, f);
102101

103-
if in_external_macro(cx.sess(), span) {
102+
if span.in_external_macro(cx.sess().source_map()) {
104103
// Nothing that can be done about it in the current crate.
105104
return;
106105
}
@@ -229,14 +228,15 @@ fn check_panic_str<'tcx>(
229228

230229
let (span, _, _) = panic_call(cx, f);
231230

232-
if in_external_macro(cx.sess(), span) && in_external_macro(cx.sess(), arg.span) {
231+
let sm = cx.sess().source_map();
232+
if span.in_external_macro(sm) && arg.span.in_external_macro(sm) {
233233
// Nothing that can be done about it in the current crate.
234234
return;
235235
}
236236

237237
let fmt_span = arg.span.source_callsite();
238238

239-
let (snippet, style) = match cx.sess().psess.source_map().span_to_snippet(fmt_span) {
239+
let (snippet, style) = match sm.span_to_snippet(fmt_span) {
240240
Ok(snippet) => {
241241
// Count the number of `#`s between the `r` and `"`.
242242
let style = snippet.strip_prefix('r').and_then(|s| s.find('"'));
@@ -283,7 +283,7 @@ fn check_panic_str<'tcx>(
283283
/// Given the span of `some_macro!(args);`, gives the span of `(` and `)`,
284284
/// and the type of (opening) delimiter used.
285285
fn find_delimiters(cx: &LateContext<'_>, span: Span) -> Option<(Span, Span, char)> {
286-
let snippet = cx.sess().psess.source_map().span_to_snippet(span).ok()?;
286+
let snippet = cx.sess().source_map().span_to_snippet(span).ok()?;
287287
let (open, open_ch) = snippet.char_indices().find(|&(_, c)| "([{".contains(c))?;
288288
let close = snippet.rfind(|c| ")]}".contains(c))?;
289289
Some((

compiler/rustc_middle/src/lint.rs

+3-37
Original file line numberDiff line numberDiff line change
@@ -8,8 +8,7 @@ use rustc_macros::{Decodable, Encodable, HashStable};
88
use rustc_session::Session;
99
use rustc_session::lint::builtin::{self, FORBIDDEN_LINT_GROUPS};
1010
use rustc_session::lint::{FutureIncompatibilityReason, Level, Lint, LintExpectationId, LintId};
11-
use rustc_span::hygiene::{ExpnKind, MacroKind};
12-
use rustc_span::{DUMMY_SP, DesugaringKind, Span, Symbol, kw};
11+
use rustc_span::{DUMMY_SP, Span, Symbol, kw};
1312
use tracing::instrument;
1413

1514
use crate::ty::TyCtxt;
@@ -201,7 +200,7 @@ impl LintExpectation {
201200
}
202201
}
203202

204-
pub fn explain_lint_level_source(
203+
fn explain_lint_level_source(
205204
lint: &'static Lint,
206205
level: Level,
207206
src: LintLevelSource,
@@ -325,7 +324,7 @@ pub fn lint_level(
325324
// If this code originates in a foreign macro, aka something that this crate
326325
// did not itself author, then it's likely that there's nothing this crate
327326
// can do about it. We probably want to skip the lint entirely.
328-
if err.span.primary_spans().iter().any(|s| in_external_macro(sess, *s)) {
327+
if err.span.primary_spans().iter().any(|s| s.in_external_macro(sess.source_map())) {
329328
// Any suggestions made here are likely to be incorrect, so anything we
330329
// emit shouldn't be automatically fixed by rustfix.
331330
err.disable_suggestions();
@@ -422,36 +421,3 @@ pub fn lint_level(
422421
}
423422
lint_level_impl(sess, lint, level, src, span, Box::new(decorate))
424423
}
425-
426-
/// Returns whether `span` originates in a foreign crate's external macro.
427-
///
428-
/// This is used to test whether a lint should not even begin to figure out whether it should
429-
/// be reported on the current node.
430-
pub fn in_external_macro(sess: &Session, span: Span) -> bool {
431-
let expn_data = span.ctxt().outer_expn_data();
432-
match expn_data.kind {
433-
ExpnKind::Root
434-
| ExpnKind::Desugaring(
435-
DesugaringKind::ForLoop
436-
| DesugaringKind::WhileLoop
437-
| DesugaringKind::OpaqueTy
438-
| DesugaringKind::Async
439-
| DesugaringKind::Await,
440-
) => false,
441-
ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
442-
ExpnKind::Macro(MacroKind::Bang, _) => {
443-
// Dummy span for the `def_site` means it's an external macro.
444-
expn_data.def_site.is_dummy() || sess.source_map().is_imported(expn_data.def_site)
445-
}
446-
ExpnKind::Macro { .. } => true, // definitely a plugin
447-
}
448-
}
449-
450-
/// Return whether `span` is generated by `async` or `await`.
451-
pub fn is_from_async_await(span: Span) -> bool {
452-
let expn_data = span.ctxt().outer_expn_data();
453-
match expn_data.kind {
454-
ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await) => true,
455-
_ => false,
456-
}
457-
}

compiler/rustc_span/src/lib.rs

+32
Original file line numberDiff line numberDiff line change
@@ -600,11 +600,43 @@ impl Span {
600600
!self.is_dummy() && sm.is_span_accessible(self)
601601
}
602602

603+
/// Returns whether `span` originates in a foreign crate's external macro.
604+
///
605+
/// This is used to test whether a lint should not even begin to figure out whether it should
606+
/// be reported on the current node.
607+
pub fn in_external_macro(self, sm: &SourceMap) -> bool {
608+
let expn_data = self.ctxt().outer_expn_data();
609+
match expn_data.kind {
610+
ExpnKind::Root
611+
| ExpnKind::Desugaring(
612+
DesugaringKind::ForLoop
613+
| DesugaringKind::WhileLoop
614+
| DesugaringKind::OpaqueTy
615+
| DesugaringKind::Async
616+
| DesugaringKind::Await,
617+
) => false,
618+
ExpnKind::AstPass(_) | ExpnKind::Desugaring(_) => true, // well, it's "external"
619+
ExpnKind::Macro(MacroKind::Bang, _) => {
620+
// Dummy span for the `def_site` means it's an external macro.
621+
expn_data.def_site.is_dummy() || sm.is_imported(expn_data.def_site)
622+
}
623+
ExpnKind::Macro { .. } => true, // definitely a plugin
624+
}
625+
}
626+
603627
/// Returns `true` if `span` originates in a derive-macro's expansion.
604628
pub fn in_derive_expansion(self) -> bool {
605629
matches!(self.ctxt().outer_expn_data().kind, ExpnKind::Macro(MacroKind::Derive, _))
606630
}
607631

632+
/// Return whether `span` is generated by `async` or `await`.
633+
pub fn is_from_async_await(self) -> bool {
634+
matches!(
635+
self.ctxt().outer_expn_data().kind,
636+
ExpnKind::Desugaring(DesugaringKind::Async | DesugaringKind::Await),
637+
)
638+
}
639+
608640
/// Gate suggestions that would not be appropriate in a context the user didn't write.
609641
pub fn can_be_used_for_suggestions(self) -> bool {
610642
!self.from_expansion()

src/tools/clippy/book/src/development/adding_lints.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -788,7 +788,7 @@ don't hesitate to ask on [Zulip] or in the issue/PR.
788788
[`snippet`]: https://doc.rust-lang.org/nightly/nightly-rustc/clippy_utils/source/fn.snippet.html
789789
[let-chains]: https://github.com/rust-lang/rust/pull/94927
790790
[from_expansion]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html#method.from_expansion
791-
[in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_middle/lint/fn.in_external_macro.html
791+
[in_external_macro]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html#method.in_external_macro
792792
[span]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_span/struct.Span.html
793793
[applicability]: https://doc.rust-lang.org/nightly/nightly-rustc/rustc_errors/enum.Applicability.html
794794
[rustc-dev-guide]: https://rustc-dev-guide.rust-lang.org/

src/tools/clippy/book/src/development/common_tools_writing_lints.md

+2-4
Original file line numberDiff line numberDiff line change
@@ -218,7 +218,7 @@ functions to deal with macros:
218218
> context. And so just using `span.from_expansion()` is often good enough.
219219
220220

221-
- `in_external_macro(span)`: detect if the given span is from a macro defined in
221+
- `span.in_external_macro(sm)`: detect if the given span is from a macro defined in
222222
a foreign crate. If you want the lint to work with macro-generated code, this
223223
is the next line of defense to avoid macros not defined in the current crate.
224224
It doesn't make sense to lint code that the coder can't change.
@@ -227,15 +227,13 @@ functions to deal with macros:
227227
crates
228228

229229
```rust
230-
use rustc_middle::lint::in_external_macro;
231-
232230
use a_crate_with_macros::foo;
233231

234232
// `foo` is defined in `a_crate_with_macros`
235233
foo!("bar");
236234

237235
// if we lint the `match` of `foo` call and test its span
238-
assert_eq!(in_external_macro(cx.sess(), match_span), true);
236+
assert_eq!(match_span.in_external_macro(cx.sess().source_map()), true);
239237
```
240238

241239
- `span.ctxt()`: the span's context represents whether it is from expansion, and

src/tools/clippy/book/src/development/macro_expansions.md

+3-3
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,7 @@ assert_ne!(x_is_some_span.ctxt(), x_unwrap_span.ctxt());
120120

121121
### The `in_external_macro` function
122122

123-
`rustc_middle::lint` provides a function ([`in_external_macro`]) that can
123+
`Span` provides a method ([`in_external_macro`]) that can
124124
detect if the given span is from a macro defined in a foreign crate.
125125

126126
Therefore, if we really want a new lint to work with macro-generated code,
@@ -144,7 +144,7 @@ Also assume that we get the corresponding variable `foo_span` for the
144144
results in `true` (note that `cx` can be `EarlyContext` or `LateContext`):
145145

146146
```rust
147-
if in_external_macro(cx.sess(), foo_span) {
147+
if foo_span.in_external_macro(cx.sess().source_map()) {
148148
// We should ignore macro from a foreign crate.
149149
return;
150150
}
@@ -153,6 +153,6 @@ if in_external_macro(cx.sess(), foo_span) {
153153
[`ctxt`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_span/struct.Span.html#method.ctxt
154154
[expansion]: https://rustc-dev-guide.rust-lang.org/macro-expansion.html#expansion-and-ast-integration
155155
[`from_expansion`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_span/struct.Span.html#method.from_expansion
156-
[`in_external_macro`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_middle/lint/fn.in_external_macro.html
156+
[`in_external_macro`]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_span/struct.Span.html#method.in_external_macro
157157
[Span]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_span/struct.Span.html
158158
[SyntaxContext]: https://doc.rust-lang.org/stable/nightly-rustc/rustc_span/hygiene/struct.SyntaxContext.html

src/tools/clippy/clippy_lints/src/almost_complete_range.rs

+2-3
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use clippy_utils::source::{trim_span, walk_span_to_context};
55
use rustc_ast::ast::{Expr, ExprKind, LitKind, Pat, PatKind, RangeEnd, RangeLimits};
66
use rustc_errors::Applicability;
77
use rustc_lint::{EarlyContext, EarlyLintPass, LintContext};
8-
use rustc_middle::lint::in_external_macro;
98
use rustc_session::impl_lint_pass;
109

1110
declare_clippy_lint! {
@@ -45,7 +44,7 @@ impl EarlyLintPass for AlmostCompleteRange {
4544
fn check_expr(&mut self, cx: &EarlyContext<'_>, e: &Expr) {
4645
if let ExprKind::Range(Some(start), Some(end), RangeLimits::HalfOpen) = &e.kind
4746
&& is_incomplete_range(start, end)
48-
&& !in_external_macro(cx.sess(), e.span)
47+
&& !e.span.in_external_macro(cx.sess().source_map())
4948
{
5049
span_lint_and_then(
5150
cx,
@@ -74,7 +73,7 @@ impl EarlyLintPass for AlmostCompleteRange {
7473
if let PatKind::Range(Some(start), Some(end), kind) = &p.kind
7574
&& matches!(kind.node, RangeEnd::Excluded)
7675
&& is_incomplete_range(start, end)
77-
&& !in_external_macro(cx.sess(), p.span)
76+
&& !p.span.in_external_macro(cx.sess().source_map())
7877
{
7978
span_lint_and_then(
8079
cx,

src/tools/clippy/clippy_lints/src/arbitrary_source_item_ordering.rs

+5-6
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,6 @@ use rustc_hir::{
99
Variant, VariantData,
1010
};
1111
use rustc_lint::{LateContext, LateLintPass, LintContext};
12-
use rustc_middle::lint::in_external_macro;
1312
use rustc_session::impl_lint_pass;
1413

1514
declare_clippy_lint! {
@@ -248,7 +247,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
248247
ItemKind::Enum(enum_def, _generics) if self.enable_ordering_for_enum => {
249248
let mut cur_v: Option<&Variant<'_>> = None;
250249
for variant in enum_def.variants {
251-
if in_external_macro(cx.sess(), variant.span) {
250+
if variant.span.in_external_macro(cx.sess().source_map()) {
252251
continue;
253252
}
254253

@@ -263,7 +262,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
263262
ItemKind::Struct(VariantData::Struct { fields, .. }, _generics) if self.enable_ordering_for_struct => {
264263
let mut cur_f: Option<&FieldDef<'_>> = None;
265264
for field in *fields {
266-
if in_external_macro(cx.sess(), field.span) {
265+
if field.span.in_external_macro(cx.sess().source_map()) {
267266
continue;
268267
}
269268

@@ -281,7 +280,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
281280
let mut cur_t: Option<&TraitItemRef> = None;
282281

283282
for item in *item_ref {
284-
if in_external_macro(cx.sess(), item.span) {
283+
if item.span.in_external_macro(cx.sess().source_map()) {
285284
continue;
286285
}
287286

@@ -304,7 +303,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
304303
let mut cur_t: Option<&ImplItemRef> = None;
305304

306305
for item in trait_impl.items {
307-
if in_external_macro(cx.sess(), item.span) {
306+
if item.span.in_external_macro(cx.sess().source_map()) {
308307
continue;
309308
}
310309

@@ -348,7 +347,7 @@ impl<'tcx> LateLintPass<'tcx> for ArbitrarySourceItemOrdering {
348347
// as no sorting by source map/line of code has to be applied.
349348
//
350349
for item in items {
351-
if in_external_macro(cx.sess(), item.span) {
350+
if item.span.in_external_macro(cx.sess().source_map()) {
352351
continue;
353352
}
354353

0 commit comments

Comments
 (0)