Skip to main content

rustc_attr_parsing/
target_checking.rs

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