Skip to main content

cpp_code_analysis/sema/check/
assignment_in_condition.rs

1//! **`assignment-in-condition`**: `=` where the reader almost certainly meant `==`.
2//!
3//! ```cpp
4//! if (x = 1) { … }          // assigns, and the condition is then 1 — always true
5//! while (line = read()) { } // …and this one is deliberate, which is why the rule is about the *shape* below
6//! ```
7//!
8//! # The shape, and the one that is excused
9//!
10//! ```text
11//!   reported      `if (x = 1)`, `while (x = y)`, `for (; x = y;)`   an assignment directly in the condition
12//!   not reported  `if ((x = 1))`            the extra parentheses are the idiom that says "I meant this", and
13//!                                           every compiler warns about it in the same way — a second pair is a
14//!                                           deliberate choice rather than a typo
15//!   not reported  `if (x == 1)`             a comparison
16//!   not reported  `if (f(x = 1))`           the assignment is an argument, not the condition
17//!   not reported  `if (x = y, x > 0)`       the condition is the comma expression, whose *last* operand is what is
18//!                                           tested — and that operand is not an assignment
19//! ```
20//!
21//! # Read as text, and why that is the honest reading here
22//!
23//! The condition of an `if` is taken between its first `(` and the matching `)`, and the question is whether that
24//! text holds a top-level `=`. A tree walk would have to decide which of the recovered nodes is the condition —
25//! and a condition with a mismatched parenthesis is exactly where the grammar recovers hardest. The text is what
26//! the reader wrote, and the question is about what they wrote.
27
28use cpp_parser::{CppAstNode, CppAstToken};
29
30use super::{Check, CheckContext, DiagnosticCode};
31
32/// **`assignment-in-condition`** — see the module documentation.
33pub struct AssignmentInCondition;
34
35/// **The condition of an `if`/`while`, taken from the node and never from its text.**
36///
37/// This was a text scan — the first `(` and its match — and that is exactly how a real session got a false positive:
38/// `if (arg == "--port" && i + 1 < argc) { const auto message = readMessage(); … }` was reported as *an assignment
39/// in a condition*, with the body's own `=` in the message. Counting parentheses through text means deciding what a
40/// `<` is, and a `<` is a comparison far more often than it is a bracket.
41///
42/// A node's child is what the parser decided the condition is, and this takes **the one expression before the
43/// body**: no scanning, no ambiguity. A condition written as `(x = y)` arrives as a parenthesised expression, whose
44/// text is then trimmed — the trimming is safe because the node is already the whole condition.
45impl Check for AssignmentInCondition {
46    const CODES: &'static [DiagnosticCode] = &[DiagnosticCode::AssignmentInCondition];
47
48    fn check(context: &mut CheckContext<'_>) {
49        // **One walk of this file's own nodes**, dispatched by the sum type rather than by two kind comparisons: the
50        // two statements this check is about both hold their condition in a `CppParenExpr`, and asking for that is
51        // the parser's answer rather than this layer's guess. Collected before the loop because a finding needs
52        // `&mut context` while the iterator holds `&context`.
53        for node in context.own::<cpp_parser::CppAst>().collect::<Vec<_>>() {
54            let parenthesised = match &node {
55                cpp_parser::CppAst::Stat(cpp_parser::CppStat::IfStat(statement)) => {
56                    statement.children::<cpp_parser::CppParenExpr>().next()
57                }
58                cpp_parser::CppAst::Stat(cpp_parser::CppStat::WhileStat(statement)) => {
59                    statement.children::<cpp_parser::CppParenExpr>().next()
60                }
61                _ => None,
62            };
63            let Some(condition) = parenthesised.map(|p| p.syntax().clone()) else {
64                continue;
65            };
66            if !is_an_assignment(&condition) {
67                continue;
68            }
69            // **An assignment *compared against something* is the idiom**, not the mistake. `if ((op = queue.front()) != 0)`
70            // is written deliberately: the assignment is parenthesised, and its result is compared — which is exactly the
71            // shape the extra-parentheses rule exists for. The census found one such finding in 1191 files, in boost's
72            // `win_object_handle_service.ipp`, and it was this.
73            // **The inner expression decides, and it is typed.** `((op = queue->Peek()))` is a parenthesised expression
74            // whose child is the assignment; `((op = …) != 0)` is one whose child is a comparison *of* a parenthesised
75            // assignment, which is the idiom. The operator **token** on the inner binary says which — the previous form
76            // counted parentheses through text, which is how a `--port` comparison was once read as an assignment.
77            let is_a_comparison = cpp_parser::CppParenExpr::cast(condition.clone())
78                .and_then(|parenthesised| parenthesised.child::<cpp_parser::CppBinaryExpr>())
79                .and_then(|binary| binary.token::<cpp_parser::CppOperatorToken>())
80                .is_some_and(|operator| {
81                    matches!(
82                        operator.syntax().text().to_string().as_str(),
83                        "==" | "!=" | "<" | ">" | "<=" | ">="
84                    )
85                });
86            if is_a_comparison {
87                continue;
88            }
89            let text = context.node_text(&condition);
90            let text = text.trim();
91
92            context.add(
93                DiagnosticCode::AssignmentInCondition,
94                cpp_parser::source_range(condition.text_range()),
95                String::new(),
96                t!(
97                    "`%{text}` assigns rather than compares: `=` in a condition is almost always a `==`", text = text
98                ),
99            );
100        }
101    }
102}
103
104/// **Is this condition nothing but an assignment?**
105///
106/// Decided from the **tokens**, which is what makes it trustworthy: a string literal is one token, so an `=` in
107/// `if (s == "a=b")` cannot be seen at all, and a compound condition is refused before any `=` is looked for.
108///
109/// **The whole condition has to be the assignment.** A **compound** — `&&`, `||`, a comma — is not this rule's shape
110/// whatever it holds inside: `if (x = f() && ok)` is a rarer and different mistake than `if (x = f())`, and
111/// reporting the first as the second is what put a finding on a line whose condition is two comparisons.
112///
113/// # Why the kind alone was wrong, and the position is the fix
114///
115/// **The lexer splits `>=` into two tokens on purpose**, so that `>>` can collapse in `vector<vector<int>>`:
116///
117/// ```text
118/// CppTokenKind::GreaterEqual => {
119///     tokens.push(part(start, CppTokenKind::Greater));
120///     tokens.push(part(start + 1, CppTokenKind::Assign));   // ← the "=" of ">="
121/// }
122/// ```
123///
124/// So the `=` of a `>=` arrives as [`CppTokenKind::Assign`], exactly as a real assignment's does, and a test for the
125/// *kind* reported both. Measured on
126///
127/// ```cpp
128/// if (a >= b) { … }   →  Greater@32..33 ">"   Assign@33..34 "="
129/// if (a = b)  { … }   →                          Assign@74..75 "="
130/// ```
131///
132/// that was `if (a >= b) assigns rather than compares`, reported from an editor against real code. One `if (x >=
133/// size())` — the most ordinary bounds check there is — was a finding on every occurrence.
134///
135/// The distinction is **positional**, and it is the grammar's own: a real assignment's `=` is the operator of the
136/// expression, so it is the **first** token of the condition, while a split `>=` has its `>` before it. Asking for
137/// that asks the tree what the operator was rather than reading punctuation.
138fn is_an_assignment(condition: &cpp_parser::CppSyntaxNode) -> bool {
139    // **The condition arrives as the `ParenExpr`** — `(a = b)`, tokens `(`, `a`, `=`, `b`, `)` — so the leading and
140    // trailing parentheses are skipped and what is left is the expression. A condition that is *only* parentheses
141    // is not this shape.
142    let mut significant = condition
143        .descendants_with_tokens()
144        .filter_map(|element| element.into_token())
145        .filter(|token| !cpp_parser::is_trivia(cpp_parser::CppTokenKind::from(token.kind())))
146        .map(|token| cpp_parser::CppTokenKind::from(token.kind()))
147        .collect::<Vec<_>>();
148    while matches!(
149        significant.first(),
150        Some(cpp_parser::CppTokenKind::LeftParen)
151    ) {
152        significant.remove(0);
153    }
154    while matches!(
155        significant.last(),
156        Some(cpp_parser::CppTokenKind::RightParen)
157    ) {
158        significant.pop();
159    }
160
161    // **The token after the left operand is the operator**, which is where a binary expression puts it: `a = b` is
162    // `a`, `=` and `b`, and `a >= b` is `a`, `>` and `=` and `b`. The first is the operand in both, so asking for the
163    // *second* is the question — and asking for the kind anywhere in the range finds the split `=` of a `>=` just as
164    // readily as a real one, which is the defect this replaced.
165    let mut significant = significant.into_iter();
166    if significant.next().is_none() {
167        return false;
168    }
169    let is_the_operator = significant.next() == Some(cpp_parser::CppTokenKind::Assign);
170
171    is_the_operator
172    // **And a compound condition is not this question.** `if (x = f() && ok)` is a rarer and different mistake than
173    // `if (x = f())`; it is refused here rather than by the caller so that both halves of the rule are in one place.
174    && !condition
175        .descendants_with_tokens()
176        .filter_map(|element| element.into_token())
177        .any(|token| {
178            matches!(
179                cpp_parser::CppTokenKind::from(token.kind()),
180                cpp_parser::CppTokenKind::LogicalAnd
181                    | cpp_parser::CppTokenKind::LogicalOr
182                    | cpp_parser::CppTokenKind::Comma
183            )
184        })
185}