Skip to main content

rustc_attr_parsing/
target_checking.rs

1use std::borrow::Cow;
2
3use rustc_ast::AttrStyle;
4use rustc_errors::{DiagArgValue, MultiSpan, StashKey};
5use rustc_feature::Features;
6use rustc_hir::attrs::AttributeKind;
7use rustc_hir::{AttrItem, Attribute, MethodKind, Target};
8use rustc_span::{BytePos, FileName, RemapPathScopeComponents, Span, Symbol, sym};
9
10use crate::context::AcceptContext;
11use crate::diagnostics::{
12    InvalidAttrAtCrateLevel, ItemFollowingInnerAttr, UnsupportedAttributesInWhere,
13};
14use crate::session_diagnostics::{InvalidTarget, InvalidTargetHelp};
15use crate::target_checking::Policy::Allow;
16use crate::{AttributeParser, ShouldEmit};
17
18#[derive(#[automatically_derived]
impl ::core::fmt::Debug for AllowedTargets {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            AllowedTargets::AllowList(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AllowList", &__self_0),
            AllowedTargets::AllowListWarnRest(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AllowListWarnRest", &__self_0),
            AllowedTargets::ManuallyChecked =>
                ::core::fmt::Formatter::write_str(f, "ManuallyChecked"),
        }
    }
}Debug)]
19pub(crate) enum AllowedTargets {
20    AllowList(&'static [Policy]),
21    AllowListWarnRest(&'static [Policy]),
22    /// This is useful for argument-dependent target checking.
23    /// If debug assertions are enabled,
24    /// this emits a delayed bug if the `cx.check_target(...)` method is not called during attribute parsing.
25    ManuallyChecked,
26}
27
28pub(crate) enum AllowedResult {
29    Allowed,
30    Warn,
31    Error,
32}
33
34impl AllowedTargets {
35    pub(crate) fn is_allowed(&self, target: Target) -> AllowedResult {
36        match self {
37            AllowedTargets::AllowList(list) => {
38                if list.contains(&Policy::Allow(target))
39                    || list.contains(&Policy::AllowSilent(target))
40                {
41                    AllowedResult::Allowed
42                } else if list.contains(&Policy::Warn(target)) {
43                    AllowedResult::Warn
44                } else {
45                    AllowedResult::Error
46                }
47            }
48            AllowedTargets::AllowListWarnRest(list) => {
49                if list.contains(&Policy::Allow(target))
50                    || list.contains(&Policy::AllowSilent(target))
51                {
52                    AllowedResult::Allowed
53                } else if list.contains(&Policy::Error(target)) {
54                    AllowedResult::Error
55                } else {
56                    AllowedResult::Warn
57                }
58            }
59            AllowedTargets::ManuallyChecked => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
60        }
61    }
62
63    pub(crate) fn allowed_targets(&self) -> Vec<Target> {
64        match self {
65            AllowedTargets::AllowList(list) => list,
66            AllowedTargets::AllowListWarnRest(list) => list,
67            AllowedTargets::ManuallyChecked => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
68        }
69        .iter()
70        .filter_map(|target| match target {
71            Policy::Allow(target) => Some(*target),
72            Policy::AllowSilent(_) => None, // Not listed in possible targets
73            Policy::Warn(_) => None,
74            Policy::Error(_) => None,
75        })
76        .collect()
77    }
78}
79
80/// This policy determines what diagnostics should be emitted based on the `Target` of the attribute.
81#[derive(#[automatically_derived]
impl ::core::fmt::Debug for Policy {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            Policy::Allow(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Allow",
                    &__self_0),
            Policy::AllowSilent(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f,
                    "AllowSilent", &__self_0),
            Policy::Warn(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Warn",
                    &__self_0),
            Policy::Error(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "Error",
                    &__self_0),
        }
    }
}Debug, #[automatically_derived]
impl ::core::cmp::Eq for Policy {
    #[inline]
    #[doc(hidden)]
    #[coverage(off)]
    fn assert_fields_are_eq(&self) {
        let _: ::core::cmp::AssertParamIsEq<Target>;
    }
}Eq, #[automatically_derived]
impl ::core::cmp::PartialEq for Policy {
    #[inline]
    fn eq(&self, other: &Policy) -> bool {
        let __self_discr = ::core::intrinsics::discriminant_value(self);
        let __arg1_discr = ::core::intrinsics::discriminant_value(other);
        __self_discr == __arg1_discr &&
            match (self, other) {
                (Policy::Allow(__self_0), Policy::Allow(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Policy::AllowSilent(__self_0), Policy::AllowSilent(__arg1_0))
                    => __self_0 == __arg1_0,
                (Policy::Warn(__self_0), Policy::Warn(__arg1_0)) =>
                    __self_0 == __arg1_0,
                (Policy::Error(__self_0), Policy::Error(__arg1_0)) =>
                    __self_0 == __arg1_0,
                _ => unsafe { ::core::intrinsics::unreachable() }
            }
    }
}PartialEq)]
82pub(crate) enum Policy {
83    /// A target that is allowed.
84    Allow(Target),
85    /// A target that is allowed and not listed in the possible targets.
86    /// This is useful if the target is checked elsewhere.
87    AllowSilent(Target),
88    /// Emits a FCW on this target.
89    /// This is useful if the target was previously allowed but should not be.
90    Warn(Target),
91    /// Emits an error on this target.
92    Error(Target),
93}
94
95impl<'sess> AttributeParser<'sess> {
96    pub(crate) fn check_target(
97        allowed_targets: &AllowedTargets,
98        attribute_args: &'static str,
99        cx: &mut AcceptContext<'_, 'sess>,
100    ) {
101        if #[allow(non_exhaustive_omitted_patterns)] match cx.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(cx.should_emit, ShouldEmit::Nothing) {
102            return;
103        }
104
105        if let AllowedTargets::ManuallyChecked = allowed_targets {
106            #[cfg(debug_assertions)]
107            if !cx.has_target_been_checked {
108                cx.dcx().delayed_bug("Attribute target has not been checked");
109            }
110
111            return;
112        }
113
114        // For crate-level attributes we emit a specific set of lints to warn
115        // people about accidentally not using them on the crate.
116        if let &AllowedTargets::AllowList(&[Allow(Target::Crate)]) = allowed_targets {
117            Self::check_crate_level(cx, false);
118            return;
119        }
120        if let &AllowedTargets::AllowListWarnRest(&[Allow(Target::Crate)]) = allowed_targets {
121            Self::check_crate_level(cx, true);
122            return;
123        }
124
125        let result = allowed_targets.is_allowed(cx.target);
126        if #[allow(non_exhaustive_omitted_patterns)] match result {
    AllowedResult::Allowed => true,
    _ => false,
}matches!(result, AllowedResult::Allowed) {
127            return;
128        }
129
130        let allowed_targets = allowed_targets.allowed_targets();
131        let (applied, only) = allowed_targets_applied(allowed_targets, cx.target, cx.features);
132        let diag = InvalidTarget {
133            span: cx.attr_span.clone(),
134            name: cx.attr_path.clone(),
135            target: cx.target.plural_name(),
136            only: if only { "only " } else { "" },
137            applied: DiagArgValue::StrListSepByAnd(applied.into_iter().map(Cow::Owned).collect()),
138            attribute_args,
139            help: Self::target_checking_help(attribute_args, cx),
140            previously_accepted: #[allow(non_exhaustive_omitted_patterns)] match result {
    AllowedResult::Warn => true,
    _ => false,
}matches!(result, AllowedResult::Warn),
141        };
142
143        match result {
144            AllowedResult::Allowed => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("Should have early returned above")));
}unreachable!("Should have early returned above"),
145            AllowedResult::Warn => {
146                let lint = if cx.attr_path.segments[0] == sym::deprecated
147                    && ![
148                        Target::Closure,
149                        Target::Expression,
150                        Target::Statement,
151                        Target::Arm,
152                        Target::MacroCall,
153                    ]
154                    .contains(&cx.target)
155                {
156                    rustc_session::lint::builtin::USELESS_DEPRECATED
157                } else {
158                    rustc_session::lint::builtin::UNUSED_ATTRIBUTES
159                };
160
161                let attr_span = cx.attr_span.clone();
162                cx.emit_lint(lint, diag, attr_span);
163            }
164            AllowedResult::Error => {
165                cx.dcx().emit_err(diag);
166            }
167        }
168    }
169
170    fn target_checking_help(
171        attribute_args: &'static str,
172        cx: &AcceptContext<'_, '_>,
173    ) -> Option<InvalidTargetHelp> {
174        match &*cx.attr_path.segments {
175            [sym::repr] if attribute_args == "(align(...))" => match cx.target {
176                Target::Fn | Target::Method(..) if cx.features().fn_align() => {
177                    Some(InvalidTargetHelp::UseRustcAlign)
178                }
179                Target::Static if cx.features().static_align() => {
180                    Some(InvalidTargetHelp::UseRustcAlignStatic)
181                }
182                _ => None,
183            },
184            _ => None,
185        }
186    }
187
188    pub(crate) fn check_crate_level(cx: &mut AcceptContext<'_, 'sess>, warn: bool) {
189        if cx.target == Target::Crate {
190            return;
191        }
192
193        let name = cx.attr_path.to_string();
194        let is_used_as_inner = cx.attr_style == AttrStyle::Inner;
195        let target_span = cx.target_span;
196        let attr_span = cx.attr_span;
197
198        let (show_crate_root_help, crate_root_path) = is_used_as_inner
199            .then(|| cx.cx.sess.local_crate_source_file())
200            .flatten()
201            .filter(|src| {
202                !#[allow(non_exhaustive_omitted_patterns)] match cx.cx.sess.source_map().span_to_filename(attr_span)
    {
    FileName::Real(ref name) if name == src => true,
    _ => false,
}matches!(
203                    cx.cx.sess.source_map().span_to_filename(attr_span),
204                    FileName::Real(ref name) if name == src
205                )
206            })
207            .map(|src| {
208                (true, src.path(RemapPathScopeComponents::DIAGNOSTICS).display().to_string())
209            })
210            .unwrap_or_default();
211
212        let diag = crate::diagnostics::InvalidAttrStyle {
213            name,
214            is_used_as_inner,
215            target_span: (!is_used_as_inner).then_some(target_span),
216            target: cx.target.name(),
217            crate_root_path,
218            show_crate_root_help,
219            span: attr_span,
220        };
221        if warn {
222            cx.emit_lint(rustc_session::lint::builtin::UNUSED_ATTRIBUTES, diag, attr_span);
223        } else {
224            cx.emit_err(diag);
225        }
226    }
227
228    // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
229    // from this check.
230    pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
231        // Check for builtin attributes at the crate level
232        // which were unsuccessfully resolved due to cannot determine
233        // resolution for the attribute macro error.
234        const ATTRS_TO_CHECK: &[Symbol] =
235            &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
236
237        // FIXME(jdonszelmann): all attrs should be combined here cleaning this up some day.
238        if let Some(name) = ATTRS_TO_CHECK.iter().find(|attr_to_check| #[allow(non_exhaustive_omitted_patterns)] match attr.path.segments.as_ref() {
    [segment] if segment == *attr_to_check => true,
    _ => false,
}matches!(attr.path.segments.as_ref(), [segment] if segment == *attr_to_check)) {
239            let span = attr.span;
240            let name = *name;
241
242            let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
243
244            let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
245                span,
246                pound_to_opening_bracket: span.until(inner_span),
247                name,
248                item,
249            });
250
251            self.dcx().try_steal_replace_and_emit_err(
252                attr.path.span,
253                StashKey::UndeterminedMacroResolution,
254                err,
255            );
256        }
257    }
258
259    fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
260        // We can't exactly call `tcx.hir_free_items()` here because it's too early and querying
261        // this would create a circular dependency. Instead, we resort to getting the original
262        // source code that follows `span` and find the next item from here.
263
264        self.sess()
265            .source_map()
266            .span_to_source(span, |content, _, span_end| {
267                let mut source = &content[span_end..];
268                let initial_source_len = source.len();
269                let span = try {
270                    loop {
271                        let first = source.chars().next()?;
272
273                        if first.is_whitespace() {
274                            let split_idx = source.find(|c: char| !c.is_whitespace())?;
275                            source = &source[split_idx..];
276                        } else if source.starts_with("//") {
277                            let line_idx = source.find('\n')?;
278                            source = &source[line_idx + '\n'.len_utf8()..];
279                        } else if source.starts_with("/*") {
280                            // FIXME: support nested comments.
281                            let close_idx = source.find("*/")?;
282                            source = &source[close_idx + "*/".len()..];
283                        } else if first == '#' {
284                            // FIXME: properly find the end of the attributes in order to accurately
285                            // skip them. This version just consumes the source code until the next
286                            // `]`.
287                            let close_idx = source.find(']')?;
288                            source = &source[close_idx + ']'.len_utf8()..];
289                        } else {
290                            let lo = span_end + initial_source_len - source.len();
291                            let last_line = source.split('\n').next().map(|s| s.trim_end())?;
292
293                            let hi = lo + last_line.len();
294                            let lo = BytePos(lo as u32);
295                            let hi = BytePos(hi as u32);
296                            let next_item_span = Span::new(lo, hi, span.ctxt(), None);
297
298                            break next_item_span;
299                        }
300                    }
301                };
302
303                Ok(span)
304            })
305            .ok()
306            .flatten()
307    }
308
309    pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
310        &self,
311        attrs: impl IntoIterator<Item = &'attr Attribute>,
312    ) {
313        // FIXME(where_clause_attrs): Currently, as the following check shows,
314        // only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
315        // if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
316        // in where clauses. After that, this function would become useless.
317        let spans = attrs
318            .into_iter()
319            .filter_map(|attr| {
320                match attr {
321                    Attribute::Parsed(AttributeKind::DocComment { span, .. }) => Some(*span),
322                    // FIXME: We shouldn't need to special-case `doc`!
323                    Attribute::Parsed(AttributeKind::Doc(attr)) => Some(attr.first_span),
324                    // Checked during attribute parsing target checking
325                    Attribute::Parsed(_) => None,
326                    Attribute::Unparsed(attr) => Some(attr.span),
327                }
328            })
329            .collect::<Vec<_>>();
330        if !spans.is_empty() {
331            self.dcx()
332                .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
333        }
334    }
335}
336
337/// Takes a list of `allowed_targets` for an attribute, and the `target` the attribute was applied to.
338/// Does some heuristic-based filtering to remove uninteresting targets, and formats the targets into a string
339pub(crate) fn allowed_targets_applied(
340    mut allowed_targets: Vec<Target>,
341    target: Target,
342    features: Option<&Features>,
343) -> (Vec<String>, bool) {
344    // Remove unstable targets from `allowed_targets` if their features are not enabled
345    if let Some(features) = features {
346        if !features.fn_delegation() {
347            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::Delegation { .. } => true,
    _ => false,
}matches!(t, Target::Delegation { .. }));
348        }
349        if !features.stmt_expr_attributes() {
350            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::Expression | Target::Statement => true,
    _ => false,
}matches!(t, Target::Expression | Target::Statement));
351        }
352        if !features.extern_types() {
353            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::ForeignTy => true,
    _ => false,
}matches!(t, Target::ForeignTy));
354        }
355    }
356
357    // We define groups of "similar" targets.
358    // If at least two of the targets are allowed, and the `target` is not in the group,
359    // we collapse the entire group to a single entry to simplify the target list
360    const FUNCTION_LIKE: &[Target] = &[
361        Target::Fn,
362        Target::Closure,
363        Target::ForeignFn,
364        Target::Method(MethodKind::Inherent),
365        Target::Method(MethodKind::Trait { body: false }),
366        Target::Method(MethodKind::Trait { body: true }),
367        Target::Method(MethodKind::TraitImpl),
368    ];
369    const FUNCTION_WITH_BODY_LIKE: &[Target] = &[
370        Target::Fn,
371        Target::Closure,
372        Target::Method(MethodKind::Inherent),
373        Target::Method(MethodKind::Trait { body: true }),
374        Target::Method(MethodKind::TraitImpl),
375    ];
376    const METHOD_LIKE: &[Target] = &[
377        Target::Method(MethodKind::Inherent),
378        Target::Method(MethodKind::Trait { body: false }),
379        Target::Method(MethodKind::Trait { body: true }),
380        Target::Method(MethodKind::TraitImpl),
381    ];
382    const IMPL_LIKE: &[Target] =
383        &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
384    const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
385
386    let mut added_fake_targets = Vec::new();
387    filter_targets(
388        &mut allowed_targets,
389        FUNCTION_LIKE,
390        "functions",
391        target,
392        &mut added_fake_targets,
393    );
394    filter_targets(
395        &mut allowed_targets,
396        FUNCTION_WITH_BODY_LIKE,
397        "functions with a body",
398        target,
399        &mut added_fake_targets,
400    );
401    filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
402    filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
403    filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
404
405    let mut target_strings: Vec<_> = added_fake_targets
406        .iter()
407        .copied()
408        .chain(allowed_targets.iter().map(|t| t.plural_name()))
409        .map(|i| i.to_string())
410        .collect();
411
412    // ensure a consistent order
413    target_strings.sort();
414
415    // If there is now only 1 target left, show that as the only possible target
416    let only_target = target_strings.len() == 1;
417
418    (target_strings, only_target)
419}
420
421fn filter_targets(
422    allowed_targets: &mut Vec<Target>,
423    target_group: &'static [Target],
424    target_group_name: &'static str,
425    target: Target,
426    added_fake_targets: &mut Vec<&'static str>,
427) {
428    if target_group.contains(&target) {
429        return;
430    }
431    if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
432        return;
433    }
434    allowed_targets.retain(|t| !target_group.contains(t));
435    added_fake_targets.push(target_group_name);
436}
437
438impl<'f, 'sess> AcceptContext<'f, 'sess> {
439    pub(crate) fn check_target(
440        &mut self,
441        attribute_args: &'static str,
442        allowed_targets: &AllowedTargets,
443    ) {
444        self.ignore_target_checks();
445        AttributeParser::check_target(allowed_targets, attribute_args, self);
446    }
447
448    pub(crate) fn ignore_target_checks(&mut self) {
449        #[cfg(debug_assertions)]
450        {
451            self.has_target_been_checked = true;
452        }
453    }
454}
455
456/// This is the list of all targets to which a attribute can be applied
457/// This is used for:
458/// - `rustc_dummy`, which can be applied to all targets
459/// - Attributes that are not parted to the new target system yet can use this list as a placeholder
460pub(crate) const ALL_TARGETS: &'static [Policy] = {
461    use Policy::Allow;
462    &[
463        Allow(Target::ExternCrate),
464        Allow(Target::Use),
465        Allow(Target::Static),
466        Allow(Target::Const),
467        Allow(Target::Fn),
468        Allow(Target::Closure),
469        Allow(Target::Mod),
470        Allow(Target::ForeignMod),
471        Allow(Target::GlobalAsm),
472        Allow(Target::TyAlias),
473        Allow(Target::Enum),
474        Allow(Target::Variant),
475        Allow(Target::Struct),
476        Allow(Target::Field),
477        Allow(Target::Union),
478        Allow(Target::Trait),
479        Allow(Target::TraitAlias),
480        Allow(Target::Impl { of_trait: false }),
481        Allow(Target::Impl { of_trait: true }),
482        Allow(Target::Expression),
483        Allow(Target::Statement),
484        Allow(Target::Arm),
485        Allow(Target::AssocConst),
486        Allow(Target::Method(MethodKind::Inherent)),
487        Allow(Target::Method(MethodKind::Trait { body: false })),
488        Allow(Target::Method(MethodKind::Trait { body: true })),
489        Allow(Target::Method(MethodKind::TraitImpl)),
490        Allow(Target::AssocTy),
491        Allow(Target::ForeignFn),
492        Allow(Target::ForeignStatic),
493        Allow(Target::ForeignTy),
494        Allow(Target::MacroDef),
495        Allow(Target::Param),
496        Allow(Target::PatField),
497        Allow(Target::ExprField),
498        Allow(Target::WherePredicate),
499        Allow(Target::MacroCall),
500        Allow(Target::Crate),
501        Allow(Target::Delegation { mac: false }),
502        Allow(Target::Delegation { mac: true }),
503        Allow(Target::GenericParam {
504            kind: rustc_hir::target::GenericParamKind::Const,
505            has_default: false,
506        }),
507        Allow(Target::GenericParam {
508            kind: rustc_hir::target::GenericParamKind::Const,
509            has_default: true,
510        }),
511        Allow(Target::GenericParam {
512            kind: rustc_hir::target::GenericParamKind::Lifetime,
513            has_default: false,
514        }),
515        Allow(Target::GenericParam {
516            kind: rustc_hir::target::GenericParamKind::Lifetime,
517            has_default: true,
518        }),
519        Allow(Target::GenericParam {
520            kind: rustc_hir::target::GenericParamKind::Type,
521            has_default: false,
522        }),
523        Allow(Target::GenericParam {
524            kind: rustc_hir::target::GenericParamKind::Type,
525            has_default: true,
526        }),
527        Allow(Target::Loop),
528        Allow(Target::ForLoop),
529        Allow(Target::While),
530    ]
531};