Skip to content
Permalink
Browse files

Update: add int32Hint option to `no-bitwise` rule (fixes #4873)

  • Loading branch information...
zandaqo committed Jan 26, 2016
1 parent 6433b7b commit bcca69bc2933e70f67368b93aa31b69d14e8c98f
Showing with 31 additions and 3 deletions.
  1. +13 −1 docs/rules/no-bitwise.md
  2. +15 −1 lib/rules/no-bitwise.js
  3. +3 −1 tests/lib/rules/no-bitwise.js
@@ -58,10 +58,22 @@ var x = y < z;
x += y;
```

This rule takes one argument, an object with the `allow` property. This allows the listed bitwise operators to be used as exceptions to the rule. For example:
### Options

This rule supports the following options:

`allow`: The list of bitwise operators to be used as exceptions to the rule. For example:

```js
/*eslint no-bitwise: [2, { allow: ["~"] }] */
~[1,2,3].indexOf(1) === -1;
```

`int32Hint`: Allows the use of bitwise OR in `|0` pattern for type casting:

```js
/*eslint no-bitwise: [2, { int32Hint: true }] */
var b = a|0;
```
@@ -21,6 +21,7 @@ var BITWISE_OPERATORS = [
module.exports = function(context) {
var options = context.options[0] || {};
var allowed = options.allow || [];
var int32Hint = options.int32Hint === true;

/**
* Reports an unexpected use of a bitwise operator.
@@ -49,13 +50,23 @@ module.exports = function(context) {
return allowed.indexOf(node.operator) !== -1;
}

/**
* Checks if the given bitwise operator is used for integer typecasting, i.e. "|0"
* @param {ASTNode} node The node to check.
* @returns {boolean} whether the node is used in integer typecasting.
*/
function isInt32Hint(node) {
return int32Hint && node.operator === "|" && node.right &&
node.right.type === "Literal" && node.right.value === 0;
}

/**
* Report if the given node contains a bitwise operator.
* @param {ASTNode} node The node to check.
* @returns {void}
*/
function checkNodeForBitwiseOperator(node) {
if (hasBitwiseOperator(node) && !allowedOperator(node)) {
if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) {
report(node);
}
}
@@ -78,6 +89,9 @@ module.exports.schema = [
"enum": BITWISE_OPERATORS
},
"uniqueItems": true
},
"int32Hint": {
"type": "boolean"
}
},
"additionalProperties": false
@@ -24,7 +24,9 @@ ruleTester.run("no-bitwise", rule, {
"a += b",
{ code: "~[1, 2, 3].indexOf(1)", options: [{ allow: ["~"] }]},
{ code: "~1<<2 === -8", options: [{ allow: ["~", "<<"] }]},
{ code: "~1<<2 === -8", options: [{ allow: ["~", "<<"] }]}
{ code: "~1<<2 === -8", options: [{ allow: ["~", "<<"] }]},
{ code: "a|0", options: [{ int32Hint: true }]},
{ code: "a|0", options: [{ allow: ["|"], int32Hint: false }]}
],
invalid: [
{ code: "a ^ b", errors: [{ message: "Unexpected use of '^'.", type: "BinaryExpression"}] },

0 comments on commit bcca69b

Please sign in to comment.
You can’t perform that action at this time.