[CMake] math(EXPR) and unary operators

George Koehler xkernigh at netscape.net
Tue Mar 6 17:05:14 EST 2012


math(EXPR) rejects expressions with negative numbers. This is awful 
because math() can reject its own negative results. For example, this 
code fails:

  math(EXPR negative "1 - 2")
  math(EXPR sum "100 + ${negative}")

The second expression, "100 + -1", causes an error.

This contradicts cmake --help-command math, which claims, "Supported 
operators are + - * / % | & ^ ~ << >> * / %.  They have the same meaning 
as they do in c code."

I can write -2 or ~2 in C, but not in CMake. The ~ (bitwise not) seems 
impossible to use. My every attempt to use ~ in math() causes an error.

To fix this bug, I taught the grammar about unary operators:

diff --git a/Source/cmExprParser.y b/Source/cmExprParser.y
index 317b0ba..57820ec 100644
--- a/Source/cmExprParser.y
+++ b/Source/cmExprParser.y
@@ -150,6 +150,16 @@ term exp_MOD factor
  {$<Number>$ = $<Number>1 % $<Number>3;}

  factor:
+value
+{$<Number>$ = $<Number>1;}
+|
+exp_MINUS factor
+{$<Number>$ = -$<Number>2;}
+|
+exp_NOT factor
+{$<Number>$ = ~$<Number>2;}
+
+value:
  exp_NUMBER
  {$<Number>$ = $<Number>1;}
  |

I pasted this same patch at http://pastebin.com/7j5Pu3AL

After applying this patch, one must run the bison command from the 
comment in cmExprParser.y.

--George Koehler



More information about the CMake mailing list