1 use crate::utils::{match_def_path, span_help_and_lint};
2 use if_chain::if_chain;
3 use rustc::lint::{LateContext, LateLintPass};
5 use rustc_hir::def_id::DefId;
7 use rustc_session::{declare_lint_pass, declare_tool_lint};
10 /// **What it does:** Checks for usage of invalid atomic
11 /// ordering in Atomic*::{load, store} calls.
13 /// **Why is this bad?** Using an invalid atomic ordering
14 /// will cause a panic at run-time.
16 /// **Known problems:** None.
20 /// # use std::sync::atomic::{AtomicBool, Ordering};
22 /// let x = AtomicBool::new(true);
24 /// let _ = x.load(Ordering::Release);
25 /// let _ = x.load(Ordering::AcqRel);
27 /// x.store(false, Ordering::Acquire);
28 /// x.store(false, Ordering::AcqRel);
30 pub INVALID_ATOMIC_ORDERING,
32 "usage of invalid atomic ordering in atomic load/store calls"
35 declare_lint_pass!(AtomicOrdering => [INVALID_ATOMIC_ORDERING]);
37 const ATOMIC_TYPES: [&str; 12] = [
52 fn type_is_atomic(cx: &LateContext<'_, '_>, expr: &Expr<'_>) -> bool {
53 if let ty::Adt(&ty::AdtDef { did, .. }, _) = cx.tables.expr_ty(expr).kind {
56 .any(|ty| match_def_path(cx, did, &["core", "sync", "atomic", ty]))
62 fn match_ordering_def_path(cx: &LateContext<'_, '_>, did: DefId, orderings: &[&str]) -> bool {
65 .any(|ordering| match_def_path(cx, did, &["core", "sync", "atomic", "Ordering", ordering]))
68 impl<'a, 'tcx> LateLintPass<'a, 'tcx> for AtomicOrdering {
69 fn check_expr(&mut self, cx: &LateContext<'a, 'tcx>, expr: &'tcx Expr<'_>) {
71 if let ExprKind::MethodCall(ref method_path, _, args) = &expr.kind;
72 let method = method_path.ident.name.as_str();
73 if type_is_atomic(cx, &args[0]);
74 if method == "load" || method == "store";
75 let ordering_arg = if method == "load" { &args[1] } else { &args[2] };
76 if let ExprKind::Path(ref ordering_qpath) = ordering_arg.kind;
77 if let Some(ordering_def_id) = cx.tables.qpath_res(ordering_qpath, ordering_arg.hir_id).opt_def_id();
79 if method == "load" &&
80 match_ordering_def_path(cx, ordering_def_id, &["Release", "AcqRel"]) {
83 INVALID_ATOMIC_ORDERING,
85 "atomic loads cannot have `Release` and `AcqRel` ordering",
86 "consider using ordering modes `Acquire`, `SeqCst` or `Relaxed`"
88 } else if method == "store" &&
89 match_ordering_def_path(cx, ordering_def_id, &["Acquire", "AcqRel"]) {
92 INVALID_ATOMIC_ORDERING,
94 "atomic stores cannot have `Acquire` and `AcqRel` ordering",
95 "consider using ordering modes `Release`, `SeqCst` or `Relaxed`"