[Issue 4077] Bugs caused by bitwise operator precedence

d-bugmail at puremagic.com d-bugmail at puremagic.com
Sun Apr 11 10:16:07 PDT 2010


http://d.puremagic.com/issues/show_bug.cgi?id=4077


Stewart Gordon <smjg at iname.com> changed:

           What    |Removed                     |Added
----------------------------------------------------------------------------
                 CC|                            |smjg at iname.com


--- Comment #5 from Stewart Gordon <smjg at iname.com> 2010-04-11 10:15:59 PDT ---
(In reply to comment #3)
> Yeah, when it bit me today, I wasn't thinking about it at all.  The 
> code looked like this:
> 
> assert( a|b <= max);
> 
> I meant (a|b) <= max, but the code ended up being a|(b <= max), 
> which was fairly useless.
> 
> I don't think bitwise being lower than comparison is useful, but we 
> have the difficulty here of maintaining C compatibility.  The best 
> fix we can get, if one is really needed*, is to call it an error to 
> have a bitwise operation next to anything that trumps it, unless 
> parenthesis are present.

The precedence of bitwise operators is indeed counter-intuitive.  Presumably
there's a reason C defined them this way.

It seems that, in most programming languages, operator precedence is a total
ordering.  The way to avoid problems like this is to change it into a partial
ordering.

At the moment, the precedence graph from && down to shifts looks like this:

shift
  .
 cmp
  .
  &
  .
  ^
  .
  |
  .
 &&

These changes in the grammar:

AndAndExpression:
    OrExpression
    AndAndExpression && OrExpression
    CmpExpression
    AndAndExpression && CmpExpression

AndExpression:
    ShiftExpression & ShiftExpression
    AndExpression & ShiftExpression


would change it to
 shift
 .  .
&    .
.    .
^   cmp
.    .
|    .
 .  .
  &&

By changing all occurrences of ShiftExpression in the definition of
AndExpression to something else, you can make the path divide higher up the
precedence chain.

This way, the bitwise operators would retain their precedence relative to each
other, but any attempt to mix them with comparison operators will cause an
error.

-- 
Configure issuemail: http://d.puremagic.com/issues/userprefs.cgi?tab=email
------- You are receiving this mail because: -------


More information about the Digitalmars-d-bugs mailing list