Skip to main content

rustc_attr_parsing/
safety.rs

1use rustc_ast::Safety;
2use rustc_attr_ir::AttrPath;
3use rustc_errors::{Diagnostic, MultiSpan};
4use rustc_lint_defs::LintId;
5use rustc_lint_defs::builtin::{UNSAFE_ATTR_OUTSIDE_UNSAFE, UNSAFE_CODE};
6use rustc_span::Span;
7
8use crate::attributes::AttributeSafety;
9use crate::{AttributeParser, EmitAttribute, ShouldEmit, diagnostics};
10
11impl<'sess> AttributeParser<'sess> {
12    pub fn check_attribute_safety(
13        &mut self,
14        attr_path: &AttrPath,
15        attr_span: Span,
16        attr_safety: Safety,
17        expected_safety: AttributeSafety,
18        emit_lint: &mut impl FnMut(LintId, MultiSpan, EmitAttribute),
19    ) {
20        if #[allow(non_exhaustive_omitted_patterns)] match self.should_emit {
    ShouldEmit::Nothing => true,
    _ => false,
}matches!(self.should_emit, ShouldEmit::Nothing) {
21            return;
22        }
23
24        // Check if expected & actual safety match
25        match (expected_safety, attr_safety) {
26            // - An unsafe builtin attribute, where the user wrote `#[unsafe(..)]`,
27            // which is permitted on any edition
28            // - A normal builtin attribute, where no explicit `#[unsafe(..)]` was written.
29            (AttributeSafety::Unsafe { .. }, Safety::Unsafe(..))
30            | (AttributeSafety::Normal, Safety::Default) => {
31                // OK
32            }
33
34            // - Unsafe builtin attribute
35            // - User did not write `#[unsafe(..)]`
36            (AttributeSafety::Unsafe { unsafe_since, note: _ }, Safety::Default) => {
37                let path_span = attr_path.span;
38
39                // If the `attr_item`'s span is not from a macro, then just suggest
40                // wrapping it in `unsafe(...)`. Otherwise, we suggest putting the
41                // `unsafe(`, `)` right after and right before the opening and closing
42                // square bracket respectively.
43                let diag_span = attr_span;
44
45                // Attributes can be safe in earlier editions, and become unsafe in later ones.
46                //
47                // Use the span of the attribute's name to determine the edition: the span of the
48                // attribute as a whole may be inaccurate if it was emitted by a macro.
49                //
50                // See https://github.com/rust-lang/rust/issues/142182.
51                let emit_error = match unsafe_since {
52                    None => true,
53                    Some(unsafe_since) => path_span.edition() >= unsafe_since,
54                };
55
56                let mut not_from_proc_macro = true;
57                if diag_span.from_expansion()
58                    && let Ok(mut snippet) = self.sess.source_map().span_to_snippet(diag_span)
59                {
60                    snippet.retain(|c| !c.is_whitespace());
61                    if snippet.contains("!(") || snippet.starts_with("#[") && snippet.ends_with(']')
62                    {
63                        not_from_proc_macro = false;
64                    }
65                }
66
67                if emit_error {
68                    self.emit_err(crate::diagnostics::UnsafeAttrOutsideUnsafe {
69                        span: path_span,
70                        suggestion: not_from_proc_macro.then(|| {
71                            crate::diagnostics::UnsafeAttrOutsideUnsafeSuggestion {
72                                left: diag_span.shrink_to_lo(),
73                                right: diag_span.shrink_to_hi(),
74                            }
75                        }),
76                    });
77                } else {
78                    emit_lint(
79                        LintId::of(UNSAFE_ATTR_OUTSIDE_UNSAFE),
80                        path_span.into(),
81                        EmitAttribute(Box::new(move |dcx, level, _| {
82                            diagnostics::UnsafeAttrOutsideUnsafeLint {
83                                span: path_span,
84                                suggestion: not_from_proc_macro
85                                    .then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()))
86                                    .map(|(left, right)| {
87                                        crate::diagnostics::UnsafeAttrOutsideUnsafeSuggestion {
88                                            left,
89                                            right,
90                                        }
91                                    }),
92                            }
93                            .into_diag(dcx, level)
94                        })),
95                    )
96                }
97            }
98
99            // - Normal builtin attribute
100            // - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes
101            (AttributeSafety::Normal, Safety::Unsafe(unsafe_span)) => {
102                self.emit_err(crate::diagnostics::InvalidAttrUnsafe {
103                    span: unsafe_span,
104                    name: attr_path.clone(),
105                });
106            }
107
108            (_, Safety::Safe(..)) => {
109                self.sess.dcx().span_delayed_bug(
110                    attr_span,
111                    "`check_attribute_safety` does not expect `Safety::Safe` on attributes",
112                );
113            }
114        }
115
116        // Emit `unsafe_code` lint
117        if let AttributeSafety::Unsafe { note, .. } = expected_safety {
118            let attr_path = attr_path.clone();
119            emit_lint(
120                LintId::of(UNSAFE_CODE),
121                attr_span.into(),
122                EmitAttribute(Box::new(move |dcx, level, _| {
123                    diagnostics::UnsafeAttribute { attr_path, note }.into_diag(dcx, level)
124                })),
125            )
126        }
127    }
128}