UNPKG

3.53 kBJavaScriptView Raw
1/**
2 * @fileoverview Rule to flag bitwise identifiers
3 * @author Nicholas C. Zakas
4 */
5
6"use strict";
7
8/*
9 *
10 * Set of bitwise operators.
11 *
12 */
13const BITWISE_OPERATORS = [
14 "^", "|", "&", "<<", ">>", ">>>",
15 "^=", "|=", "&=", "<<=", ">>=", ">>>=",
16 "~"
17];
18
19//------------------------------------------------------------------------------
20// Rule Definition
21//------------------------------------------------------------------------------
22
23module.exports = {
24 meta: {
25 docs: {
26 description: "disallow bitwise operators",
27 category: "Stylistic Issues",
28 recommended: false,
29 url: "https://eslint.org/docs/rules/no-bitwise"
30 },
31
32 schema: [
33 {
34 type: "object",
35 properties: {
36 allow: {
37 type: "array",
38 items: {
39 enum: BITWISE_OPERATORS
40 },
41 uniqueItems: true
42 },
43 int32Hint: {
44 type: "boolean"
45 }
46 },
47 additionalProperties: false
48 }
49 ],
50
51 messages: {
52 unexpected: "Unexpected use of '{{operator}}'."
53 }
54 },
55
56 create(context) {
57 const options = context.options[0] || {};
58 const allowed = options.allow || [];
59 const int32Hint = options.int32Hint === true;
60
61 /**
62 * Reports an unexpected use of a bitwise operator.
63 * @param {ASTNode} node Node which contains the bitwise operator.
64 * @returns {void}
65 */
66 function report(node) {
67 context.report({ node, messageId: "unexpected", data: { operator: node.operator } });
68 }
69
70 /**
71 * Checks if the given node has a bitwise operator.
72 * @param {ASTNode} node The node to check.
73 * @returns {boolean} Whether or not the node has a bitwise operator.
74 */
75 function hasBitwiseOperator(node) {
76 return BITWISE_OPERATORS.indexOf(node.operator) !== -1;
77 }
78
79 /**
80 * Checks if exceptions were provided, e.g. `{ allow: ['~', '|'] }`.
81 * @param {ASTNode} node The node to check.
82 * @returns {boolean} Whether or not the node has a bitwise operator.
83 */
84 function allowedOperator(node) {
85 return allowed.indexOf(node.operator) !== -1;
86 }
87
88 /**
89 * Checks if the given bitwise operator is used for integer typecasting, i.e. "|0"
90 * @param {ASTNode} node The node to check.
91 * @returns {boolean} whether the node is used in integer typecasting.
92 */
93 function isInt32Hint(node) {
94 return int32Hint && node.operator === "|" && node.right &&
95 node.right.type === "Literal" && node.right.value === 0;
96 }
97
98 /**
99 * Report if the given node contains a bitwise operator.
100 * @param {ASTNode} node The node to check.
101 * @returns {void}
102 */
103 function checkNodeForBitwiseOperator(node) {
104 if (hasBitwiseOperator(node) && !allowedOperator(node) && !isInt32Hint(node)) {
105 report(node);
106 }
107 }
108
109 return {
110 AssignmentExpression: checkNodeForBitwiseOperator,
111 BinaryExpression: checkNodeForBitwiseOperator,
112 UnaryExpression: checkNodeForBitwiseOperator
113 };
114
115 }
116};