2 * @fileoverview Rule to flag bitwise identifiers
3 * @author Nicholas C. Zakas
10 * Set of bitwise operators.
13 const BITWISE_OPERATORS = [
14 "^", "|", "&", "<<", ">>", ">>>",
15 "^=", "|=", "&=", "<<=", ">>=", ">>>=",
19 //------------------------------------------------------------------------------
21 //------------------------------------------------------------------------------
28 description: "disallow bitwise operators",
29 category: "Stylistic Issues",
31 url: "https://eslint.org/docs/rules/no-bitwise"
41 enum: BITWISE_OPERATORS
50 additionalProperties: false
55 unexpected: "Unexpected use of '{{operator}}'."
60 const options = context.options[0] || {};
61 const allowed = options.allow || [];
62 const int32Hint = options.int32Hint === true;
65 * Reports an unexpected use of a bitwise operator.
66 * @param {ASTNode} node Node which contains the bitwise operator.
69 function report(node) {
70 context.report({ node, messageId: "unexpected", data: { operator: node.operator } });
74 * Checks if the given node has a bitwise operator.
75 * @param {ASTNode} node The node to check.
76 * @returns {boolean} Whether or not the node has a bitwise operator.
78 function hasBitwiseOperator(node) {
79 return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
83 * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`.
84 * @param {ASTNode} node The node to check.
85 * @returns {boolean} Whether or not the node has a bitwise operator.
87 function allowedOperator(node) {
88 return allowed.indexOf(node.operator) !== -1;
92 * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0"
93 * @param {ASTNode} node The node to check.
94 * @returns {boolean} whether the node is used in integer typecasting.
96 function isInt32Hint(node) {
97 return int32Hint && node.operator === "|" && node.right &&
98 node.right.type === "Literal" && node.right.value === 0;
102 * Report if the given node contains a bitwise operator.
103 * @param {ASTNode} node The node to check.
106 function checkNodeForBitwiseOperator(node) {
107 if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) {
113 AssignmentExpression: checkNodeForBitwiseOperator,
114 BinaryExpression: checkNodeForBitwiseOperator,
115 UnaryExpression: checkNodeForBitwiseOperator