1 use crate::utils::{match_def_path, span_help_and_lint};
2 use if_chain::if_chain;
3 use rustc::declare_lint_pass;
4 use rustc::lint::{LateContext, LateLintPass, LintArray, LintPass};
6 use rustc_hir::def_id::DefId;
8 use rustc_session::declare_tool_lint;
10 declare_clippy_lint! {
11 /// **What it does:** Checks for usage of invalid atomic
12 /// ordering in Atomic*::{load, store} calls.
14 /// **Why is this bad?** Using an invalid atomic ordering
15 /// will cause a panic at run-time.
17 /// **Known problems:** None.
21 /// # use std::sync::atomic::{AtomicBool, Ordering};
23 /// let x = AtomicBool::new(true);
25 /// let _ = x.load(Ordering::Release);
26 /// let _ = x.load(Ordering::AcqRel);
28 /// x.store(false, Ordering::Acquire);
29 /// x.store(false, Ordering::AcqRel);
31 pub INVALID_ATOMIC_ORDERING,
33 "usage of invalid atomic ordering in atomic load/store calls"
36 declare_lint_pass!(AtomicOrdering => [INVALID_ATOMIC_ORDERING]);
38 const ATOMIC_TYPES: [&str; 12] = [
53 fn type_is_atomic(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
54 if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.tables.expr_ty(expr).kind {
57 .any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty]))
63 fn match_ordering_def_path(cx: &LateContext<'_, '_>, did: DefId, orderings: &[&str]) -> bool {
66 .any(|ordering| match_def_path(cx, did, &["core", "sync", "atomic", "Ordering", ordering]))
69 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AtomicOrdering {
70 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
72 if let ExprKind::MethodCall(ref method_path, _, args) = &expr.kind;
73 let method = method_path.ident.name.as_str();
74 if type_is_atomic(cx, &args[0]);
75 if method == "load" || method == "store";
76 let ordering_arg = if method == "load" { &args[1] } else { &args[2] };
77 if let ExprKind::Path(ref ordering_qpath) = ordering_arg.kind;
78 if let Some(ordering_def_id) = cx.tables.qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id();
80 if method == "load" &&
81 match_ordering_def_path(cx, ordering_def_id, &["Release", "AcqRel"]) {
84 INVALID_ATOMIC_ORDERING,
86 "atomic loads cannot have `Release` and `AcqRel` ordering",
87 "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`"
89 } else if method == "store" &&
90 match_ordering_def_path(cx, ordering_def_id, &["Acquire", "AcqRel"]) {
93 INVALID_ATOMIC_ORDERING,
95 "atomic stores cannot have `Acquire` and `AcqRel` ordering",
96 "consider using ordering modes `Release`, `SeqCst` or `Relaxed`"