use rustc_ast::Safety;
use rustc_errors::{Diagnostic, MultiSpan};
use rustc_hir::AttrPath;
use rustc_lint_defs::builtin::UNSAFE_CODE;
use rustc_session::lint::LintId;
use rustc_session::lint::builtin::UNSAFE_ATTR_OUTSIDE_UNSAFE;
use rustc_span::Span;

use crate::attributes::AttributeSafety;
use crate::{AttributeParser, EmitAttribute, ShouldEmit, diagnostics};

impl<'sess> AttributeParser<'sess> {
    pub fn check_attribute_safety(
        &mut self,
        attr_path: &AttrPath,
        attr_span: Span,
        attr_safety: Safety,
        expected_safety: AttributeSafety,
        emit_lint: &mut impl FnMut(LintId, MultiSpan, EmitAttribute),
    ) {
        if matches!(self.should_emit, ShouldEmit::Nothing) {
            return;
        }

        // Check if expected & actual safety match
        match (expected_safety, attr_safety) {
            // - Unsafe builtin attribute
            // - User wrote `#[unsafe(..)]`, which is permitted on any edition
            (AttributeSafety::Unsafe { .. }, Safety::Unsafe(..)) => {
                // OK
            }

            // - Unsafe builtin attribute
            // - User did not write `#[unsafe(..)]`
            (AttributeSafety::Unsafe { unsafe_since, note: _ }, Safety::Default) => {
                let path_span = attr_path.span;

                // If the `attr_item`'s span is not from a macro, then just suggest
                // wrapping it in `unsafe(...)`. Otherwise, we suggest putting the
                // `unsafe(`, `)` right after and right before the opening and closing
                // square bracket respectively.
                let diag_span = attr_span;

                // Attributes can be safe in earlier editions, and become unsafe in later ones.
                //
                // Use the span of the attribute's name to determine the edition: the span of the
                // attribute as a whole may be inaccurate if it was emitted by a macro.
                //
                // See https://github.com/rust-lang/rust/issues/142182.
                let emit_error = match unsafe_since {
                    None => true,
                    Some(unsafe_since) => path_span.edition() >= unsafe_since,
                };

                let mut not_from_proc_macro = true;
                if diag_span.from_expansion()
                    && let Ok(mut snippet) = self.sess.source_map().span_to_snippet(diag_span)
                {
                    snippet.retain(|c| !c.is_whitespace());
                    if snippet.contains("!(") || snippet.starts_with("#[") && snippet.ends_with("]")
                    {
                        not_from_proc_macro = false;
                    }
                }

                if emit_error {
                    self.emit_err(crate::session_diagnostics::UnsafeAttrOutsideUnsafe {
                        span: path_span,
                        suggestion: not_from_proc_macro.then(|| {
                            crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion {
                                left: diag_span.shrink_to_lo(),
                                right: diag_span.shrink_to_hi(),
                            }
                        }),
                    });
                } else {
                    emit_lint(
                        LintId::of(UNSAFE_ATTR_OUTSIDE_UNSAFE),
                        path_span.into(),
                        EmitAttribute(Box::new(move |dcx, level, _| {
                            diagnostics::UnsafeAttrOutsideUnsafeLint {
                                span: path_span,
                                suggestion: not_from_proc_macro
                                    .then(|| (diag_span.shrink_to_lo(), diag_span.shrink_to_hi()))
                                    .map(|(left, right)| {
                                        crate::session_diagnostics::UnsafeAttrOutsideUnsafeSuggestion { left, right }
                                    }),
                            }
                            .into_diag(dcx, level)
                        })),
                    )
                }
            }

            // - Normal builtin attribute
            // - Writing `#[unsafe(..)]` is not permitted on normal builtin attributes
            (AttributeSafety::Normal, Safety::Unsafe(unsafe_span)) => {
                self.emit_err(crate::session_diagnostics::InvalidAttrUnsafe {
                    span: unsafe_span,
                    name: attr_path.clone(),
                });
            }

            // - Normal builtin attribute
            // - No explicit `#[unsafe(..)]` written.
            (AttributeSafety::Normal, Safety::Default) => {
                // OK
            }

            (_, Safety::Safe(..)) => {
                self.sess.dcx().span_delayed_bug(
                    attr_span,
                    "`check_attribute_safety` does not expect `Safety::Safe` on attributes",
                );
            }
        }

        // Emit `unsafe_code` lint
        if let AttributeSafety::Unsafe { note, .. } = expected_safety {
            let attr_path = attr_path.clone();
            emit_lint(
                LintId::of(UNSAFE_CODE),
                attr_span.into(),
                EmitAttribute(Box::new(move |dcx, level, _| {
                    diagnostics::UnsafeAttribute { attr_path, note }.into_diag(dcx, level)
                })),
            )
        }
    }
}
