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, Stage};
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, S: Stage> AttributeParser<'sess, S> {
91    pub(crate) fn check_target(
92        allowed_targets: &AllowedTargets,
93        target: Target,
94        cx: &mut AcceptContext<'_, 'sess, S>,
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_dyn_lint(
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, S>) {
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_dyn_lint(
190            rustc_session::lint::builtin::UNUSED_ATTRIBUTES,
191            move |dcx, level| {
192                crate::errors::InvalidAttrStyle {
193                    name: &name,
194                    is_used_as_inner,
195                    target_span: (!is_used_as_inner).then_some(target_span),
196                    target: target.name(),
197                }
198                .into_diag(dcx, level)
199            },
200            attr_span,
201        );
202    }
203
204    // FIXME: Fix "Cannot determine resolution" error and remove built-in macros
205    // from this check.
206    pub(crate) fn check_invalid_crate_level_attr_item(&self, attr: &AttrItem, inner_span: Span) {
207        // Check for builtin attributes at the crate level
208        // which were unsuccessfully resolved due to cannot determine
209        // resolution for the attribute macro error.
210        const ATTRS_TO_CHECK: &[Symbol] =
211            &[sym::derive, sym::test, sym::test_case, sym::global_allocator, sym::bench];
212
213        // FIXME(jdonszelmann): all attrs should be combined here cleaning this up some day.
214        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)) {
215            let span = attr.span;
216            let name = *name;
217
218            let item = self.first_line_of_next_item(span).map(|span| ItemFollowingInnerAttr { span });
219
220            let err = self.dcx().create_err(InvalidAttrAtCrateLevel {
221                span,
222                pound_to_opening_bracket: span.until(inner_span),
223                name,
224                item,
225            });
226
227            self.dcx().try_steal_replace_and_emit_err(
228                attr.path.span,
229                StashKey::UndeterminedMacroResolution,
230                err,
231            );
232        }
233    }
234
235    fn first_line_of_next_item(&self, span: Span) -> Option<Span> {
236        // We can't exactly call `tcx.hir_free_items()` here because it's too early and querying
237        // this would create a circular dependency. Instead, we resort to getting the original
238        // source code that follows `span` and find the next item from here.
239
240        self.sess()
241            .source_map()
242            .span_to_source(span, |content, _, span_end| {
243                let mut source = &content[span_end..];
244                let initial_source_len = source.len();
245                let span = try {
246                    loop {
247                        let first = source.chars().next()?;
248
249                        if first.is_whitespace() {
250                            let split_idx = source.find(|c: char| !c.is_whitespace())?;
251                            source = &source[split_idx..];
252                        } else if source.starts_with("//") {
253                            let line_idx = source.find('\n')?;
254                            source = &source[line_idx + '\n'.len_utf8()..];
255                        } else if source.starts_with("/*") {
256                            // FIXME: support nested comments.
257                            let close_idx = source.find("*/")?;
258                            source = &source[close_idx + "*/".len()..];
259                        } else if first == '#' {
260                            // FIXME: properly find the end of the attributes in order to accurately
261                            // skip them. This version just consumes the source code until the next
262                            // `]`.
263                            let close_idx = source.find(']')?;
264                            source = &source[close_idx + ']'.len_utf8()..];
265                        } else {
266                            let lo = span_end + initial_source_len - source.len();
267                            let last_line = source.split('\n').next().map(|s| s.trim_end())?;
268
269                            let hi = lo + last_line.len();
270                            let lo = BytePos(lo as u32);
271                            let hi = BytePos(hi as u32);
272                            let next_item_span = Span::new(lo, hi, span.ctxt(), None);
273
274                            break next_item_span;
275                        }
276                    }
277                };
278
279                Ok(span)
280            })
281            .ok()
282            .flatten()
283    }
284
285    pub(crate) fn check_invalid_where_predicate_attrs<'attr>(
286        &self,
287        attrs: impl IntoIterator<Item = &'attr Attribute>,
288    ) {
289        // FIXME(where_clause_attrs): Currently, as the following check shows,
290        // only `#[cfg]` and `#[cfg_attr]` are allowed, but it should be removed
291        // if we allow more attributes (e.g., tool attributes and `allow/deny/warn`)
292        // in where clauses. After that, this function would become useless.
293        let spans = attrs
294            .into_iter()
295            // FIXME: We shouldn't need to special-case `doc`!
296            .filter(|attr| {
297                #[allow(non_exhaustive_omitted_patterns)] match attr {
    Attribute::Parsed(AttributeKind::DocComment { .. } |
        AttributeKind::Doc(_)) | Attribute::Unparsed(_) => true,
    _ => false,
}matches!(
298                    attr,
299                    Attribute::Parsed(AttributeKind::DocComment { .. } | AttributeKind::Doc(_))
300                        | Attribute::Unparsed(_)
301                )
302            })
303            .map(|attr| attr.span())
304            .collect::<Vec<_>>();
305        if !spans.is_empty() {
306            self.dcx()
307                .emit_err(UnsupportedAttributesInWhere { span: MultiSpan::from_spans(spans) });
308        }
309    }
310}
311
312/// Takes a list of `allowed_targets` for an attribute, and the `target` the attribute was applied to.
313/// Does some heuristic-based filtering to remove uninteresting targets, and formats the targets into a string
314pub(crate) fn allowed_targets_applied(
315    mut allowed_targets: Vec<Target>,
316    target: Target,
317    features: Option<&Features>,
318) -> (Vec<String>, bool) {
319    // Remove unstable targets from `allowed_targets` if their features are not enabled
320    if let Some(features) = features {
321        if !features.fn_delegation() {
322            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::Delegation { .. } => true,
    _ => false,
}matches!(t, Target::Delegation { .. }));
323        }
324        if !features.stmt_expr_attributes() {
325            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::Expression | Target::Statement => true,
    _ => false,
}matches!(t, Target::Expression | Target::Statement));
326        }
327        if !features.extern_types() {
328            allowed_targets.retain(|t| !#[allow(non_exhaustive_omitted_patterns)] match t {
    Target::ForeignTy => true,
    _ => false,
}matches!(t, Target::ForeignTy));
329        }
330    }
331
332    // We define groups of "similar" targets.
333    // If at least two of the targets are allowed, and the `target` is not in the group,
334    // we collapse the entire group to a single entry to simplify the target list
335    const FUNCTION_LIKE: &[Target] = &[
336        Target::Fn,
337        Target::Closure,
338        Target::ForeignFn,
339        Target::Method(MethodKind::Inherent),
340        Target::Method(MethodKind::Trait { body: false }),
341        Target::Method(MethodKind::Trait { body: true }),
342        Target::Method(MethodKind::TraitImpl),
343    ];
344    const METHOD_LIKE: &[Target] = &[
345        Target::Method(MethodKind::Inherent),
346        Target::Method(MethodKind::Trait { body: false }),
347        Target::Method(MethodKind::Trait { body: true }),
348        Target::Method(MethodKind::TraitImpl),
349    ];
350    const IMPL_LIKE: &[Target] =
351        &[Target::Impl { of_trait: false }, Target::Impl { of_trait: true }];
352    const ADT_LIKE: &[Target] = &[Target::Struct, Target::Enum, Target::Union];
353
354    let mut added_fake_targets = Vec::new();
355    filter_targets(
356        &mut allowed_targets,
357        FUNCTION_LIKE,
358        "functions",
359        target,
360        &mut added_fake_targets,
361    );
362    filter_targets(&mut allowed_targets, METHOD_LIKE, "methods", target, &mut added_fake_targets);
363    filter_targets(&mut allowed_targets, IMPL_LIKE, "impl blocks", target, &mut added_fake_targets);
364    filter_targets(&mut allowed_targets, ADT_LIKE, "data types", target, &mut added_fake_targets);
365
366    let mut target_strings: Vec<_> = added_fake_targets
367        .iter()
368        .copied()
369        .chain(allowed_targets.iter().map(|t| t.plural_name()))
370        .map(|i| i.to_string())
371        .collect();
372
373    // ensure a consistent order
374    target_strings.sort();
375
376    // If there is now only 1 target left, show that as the only possible target
377    let only_target = target_strings.len() == 1;
378
379    (target_strings, only_target)
380}
381
382fn filter_targets(
383    allowed_targets: &mut Vec<Target>,
384    target_group: &'static [Target],
385    target_group_name: &'static str,
386    target: Target,
387    added_fake_targets: &mut Vec<&'static str>,
388) {
389    if target_group.contains(&target) {
390        return;
391    }
392    if allowed_targets.iter().filter(|at| target_group.contains(at)).count() < 2 {
393        return;
394    }
395    allowed_targets.retain(|t| !target_group.contains(t));
396    added_fake_targets.push(target_group_name);
397}
398
399/// This is the list of all targets to which a attribute can be applied
400/// This is used for:
401/// - `rustc_dummy`, which can be applied to all targets
402/// - Attributes that are not parted to the new target system yet can use this list as a placeholder
403pub(crate) const ALL_TARGETS: &'static [Policy] = {
404    use Policy::Allow;
405    &[
406        Allow(Target::ExternCrate),
407        Allow(Target::Use),
408        Allow(Target::Static),
409        Allow(Target::Const),
410        Allow(Target::Fn),
411        Allow(Target::Closure),
412        Allow(Target::Mod),
413        Allow(Target::ForeignMod),
414        Allow(Target::GlobalAsm),
415        Allow(Target::TyAlias),
416        Allow(Target::Enum),
417        Allow(Target::Variant),
418        Allow(Target::Struct),
419        Allow(Target::Field),
420        Allow(Target::Union),
421        Allow(Target::Trait),
422        Allow(Target::TraitAlias),
423        Allow(Target::Impl { of_trait: false }),
424        Allow(Target::Impl { of_trait: true }),
425        Allow(Target::Expression),
426        Allow(Target::Statement),
427        Allow(Target::Arm),
428        Allow(Target::AssocConst),
429        Allow(Target::Method(MethodKind::Inherent)),
430        Allow(Target::Method(MethodKind::Trait { body: false })),
431        Allow(Target::Method(MethodKind::Trait { body: true })),
432        Allow(Target::Method(MethodKind::TraitImpl)),
433        Allow(Target::AssocTy),
434        Allow(Target::ForeignFn),
435        Allow(Target::ForeignStatic),
436        Allow(Target::ForeignTy),
437        Allow(Target::MacroDef),
438        Allow(Target::Param),
439        Allow(Target::PatField),
440        Allow(Target::ExprField),
441        Allow(Target::WherePredicate),
442        Allow(Target::MacroCall),
443        Allow(Target::Crate),
444        Allow(Target::Delegation { mac: false }),
445        Allow(Target::Delegation { mac: true }),
446        Allow(Target::GenericParam {
447            kind: rustc_hir::target::GenericParamKind::Const,
448            has_default: false,
449        }),
450        Allow(Target::GenericParam {
451            kind: rustc_hir::target::GenericParamKind::Const,
452            has_default: true,
453        }),
454        Allow(Target::GenericParam {
455            kind: rustc_hir::target::GenericParamKind::Lifetime,
456            has_default: false,
457        }),
458        Allow(Target::GenericParam {
459            kind: rustc_hir::target::GenericParamKind::Lifetime,
460            has_default: true,
461        }),
462        Allow(Target::GenericParam {
463            kind: rustc_hir::target::GenericParamKind::Type,
464            has_default: false,
465        }),
466        Allow(Target::GenericParam {
467            kind: rustc_hir::target::GenericParamKind::Type,
468            has_default: true,
469        }),
470    ]
471};