[clang] [clang][Sema] Warn when macro operator mixes with outer operand due to precedence (PR #184924)
Hans Wennborg via cfe-commits
cfe-commits at lists.llvm.org
Wed Mar 11 10:25:38 PDT 2026
================
@@ -0,0 +1,200 @@
+// RUN: %clang_cc1 -fsyntax-only -Wmacro-mixed-operator -verify %s
+
+// ------------------------------------------------------------
+// Basic macro body precedence problem
+// ------------------------------------------------------------
+#define FOO 2+3
+// 2+(3*4) == 14, not (2+3)*4 == 20
+int n = FOO*4; // expected-warning {{operator '+' in macro expansion has operand outside the macro; operator precedence may be different than expected}}
+
+// ------------------------------------------------------------
+// Macro argument precedence problem
+// ------------------------------------------------------------
+#define FOO_ARG(x) 2+x
+int m = FOO_ARG(3*4); // expected-warning {{operator '+' in macro expansion has operand outside the macro; operator precedence may be different than expected}}
+
+// ------------------------------------------------------------
+// Operator entirely outside macros (should NOT warn)
+// ------------------------------------------------------------
+int k = 2 + 3 * 4; // no-warning
+
+// ------------------------------------------------------------
+// Operator comes from macro argument only (should NOT warn)
+// ------------------------------------------------------------
+#define ID(x) x
+int p = ID(2+3)*4; // no-warning
----------------
zmodem wrote:
Don't we want to warn here actually? (The user probably expected p=20 rather than p=14).
Richard's suggested heuristic was:
> if the location of an operator is within a macro expansion, and an operand of that operator is not entirely within that same macro expansion, then warn
In this case the `+` operator is within the macro expansion, but the rhs operand (`3*4`) is partially (the `*4` part) outside of it.
https://github.com/llvm/llvm-project/pull/184924
More information about the cfe-commits
mailing list