All files noArrayMutationRule.ts

100% Statements 69/69
96.08% Branches 49/51
100% Functions 18/18
100% Lines 68/68
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 2811x   1x           1x               1x         1x         1x                               1x                   1x                                 1x             75x               1262x               1262x   33x     5x     7x             9x             145x     1063x                         33x 50x 97x           18x 18x   18x 16x     17x                     5x 5x 7x           3x 3x   3x 2x     3x                     7x 7x 10x 7x           4x 4x   4x 3x     4x                     9x 9x 13x 7x           5x 5x   5x 4x     5x                     145x 145x 144x 144x 972x                 45x   45x 36x       109x                       45x 36x 36x 36x 54x 36x         9x    
import * as ts from "typescript";
import * as Lint from "tslint";
import {
  createInvalidNode,
  CheckNodeResult,
  createCheckNodeTypedRule,
  InvalidNode
} from "./shared/check-node";
import * as Ignore from "./shared/ignore";
 
type Options = Ignore.IgnoreMutationFollowingAccessorOption &
  Ignore.IgnorePrefixOption;
 
type EntryAccessor = ts.ElementAccessExpression | ts.PropertyAccessExpression;
 
// tslint:disable-next-line:variable-name
export const Rule = createCheckNodeTypedRule(
  checkTypedNode,
  "Mutating an array is not allowed."
);
 
const arrPropAccessors: ReadonlyArray<ts.SyntaxKind> = [
  ts.SyntaxKind.ElementAccessExpression,
  ts.SyntaxKind.PropertyAccessExpression
];
 
const forbidArrPropOnLeftSideOf: ReadonlyArray<ts.SyntaxKind> = [
  ts.SyntaxKind.EqualsToken,
  ts.SyntaxKind.PlusEqualsToken,
  ts.SyntaxKind.MinusEqualsToken,
  ts.SyntaxKind.AsteriskEqualsToken,
  ts.SyntaxKind.AsteriskAsteriskEqualsToken,
  ts.SyntaxKind.SlashEqualsToken,
  ts.SyntaxKind.PercentEqualsToken,
  ts.SyntaxKind.LessThanLessThanEqualsToken,
  ts.SyntaxKind.GreaterThanGreaterThanEqualsToken,
  ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken,
  ts.SyntaxKind.AmpersandEqualsToken,
  ts.SyntaxKind.BarEqualsToken,
  ts.SyntaxKind.CaretEqualsToken
];
 
const forbidUnaryOps: ReadonlyArray<ts.SyntaxKind> = [
  ts.SyntaxKind.PlusPlusToken,
  ts.SyntaxKind.MinusMinusToken
];
 
/**
 * Methods that mutate an array.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods#Mutator_methods
 */
const mutatorMethods: ReadonlyArray<string> = [
  "copyWithin",
  "fill",
  "pop",
  "push",
  "reverse",
  "shift",
  "sort",
  "splice",
  "unshift"
];
 
/**
 * Methods that return a new array without mutating the original.
 *
 * @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype#Methods#Accessor_methods
 */
const accessorMethods: ReadonlyArray<string> = [
  "concat",
  "slice",
  "toSource" // TODO: This is a non standardized method, should it me including?
];
 
function isArrayType(type: ts.Type): boolean {
  return type.symbol !== undefined && type.symbol.name === "Array";
}
 
function checkTypedNode(
  node: ts.BinaryExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): CheckNodeResult {
  return { invalidNodes: getInvalidNodes(node, ctx, checker) };
}
 
function getInvalidNodes(
  node: ts.Node,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  switch (node.kind) {
    case ts.SyntaxKind.BinaryExpression:
      return checkBinaryExpression(node as ts.BinaryExpression, ctx, checker);
 
    case ts.SyntaxKind.DeleteExpression:
      return checkDeleteExpression(node as ts.DeleteExpression, ctx, checker);
 
    case ts.SyntaxKind.PrefixUnaryExpression:
      return checkPrefixUnaryExpression(
        node as ts.PrefixUnaryExpression,
        ctx,
        checker
      );
 
    case ts.SyntaxKind.PostfixUnaryExpression:
      return checkPostfixUnaryExpression(
        node as ts.PostfixUnaryExpression,
        ctx,
        checker
      );
 
    case ts.SyntaxKind.CallExpression:
      return checkCallExpression(node as ts.CallExpression, ctx, checker);
 
    default:
      return [];
  }
}
 
/**
 * No assignment with array[index] on the left.
 * No assignment with array.property on the left (e.g. array.length).
 */
function checkBinaryExpression(
  node: ts.BinaryExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  if (
    arrPropAccessors.some(k => k === node.left.kind) &&
    forbidArrPropOnLeftSideOf.some(k => k === node.operatorToken.kind) &&
    !Ignore.isIgnoredPrefix(
      node.getText(node.getSourceFile()),
      ctx.options.ignorePrefix
    )
  ) {
    const left = node.left as EntryAccessor;
    const leftExpressionType = checker.getTypeAtLocation(left.expression);
 
    if (isArrayType(leftExpressionType)) {
      return [createInvalidNode(node, [])];
    }
  }
  return [];
}
 
/**
 * No deleting array properties/values.
 */
function checkDeleteExpression(
  node: ts.DeleteExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  const delExp = node as ts.DeleteExpression;
  if (
    arrPropAccessors.some(k => k === delExp.expression.kind) &&
    !Ignore.isIgnoredPrefix(
      delExp.expression.getText(node.getSourceFile()),
      ctx.options.ignorePrefix
    )
  ) {
    const delExpExp = delExp.expression as EntryAccessor;
    const expressionType = checker.getTypeAtLocation(delExpExp.expression);
 
    if (isArrayType(expressionType)) {
      return [createInvalidNode(node, [])];
    }
  }
  return [];
}
 
/**
 * No prefix inc/dec.
 */
function checkPrefixUnaryExpression(
  node: ts.PrefixUnaryExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  const preExp = node as ts.PrefixUnaryExpression;
  if (
    arrPropAccessors.some(k => k === preExp.operand.kind) &&
    forbidUnaryOps.some(o => o === preExp.operator) &&
    !Ignore.isIgnoredPrefix(
      preExp.operand.getText(node.getSourceFile()),
      ctx.options.ignorePrefix
    )
  ) {
    const operand = preExp.operand as EntryAccessor;
    const operandExpressionType = checker.getTypeAtLocation(operand.expression);
 
    if (isArrayType(operandExpressionType)) {
      return [createInvalidNode(node, [])];
    }
  }
  return [];
}
 
/**
 * No postfix inc/dec.
 */
function checkPostfixUnaryExpression(
  node: ts.PostfixUnaryExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  const postExp = node as ts.PostfixUnaryExpression;
  if (
    arrPropAccessors.some(k => k === postExp.operand.kind) &&
    forbidUnaryOps.some(o => o === postExp.operator) &&
    !Ignore.isIgnoredPrefix(
      postExp.getText(node.getSourceFile()),
      ctx.options.ignorePrefix
    )
  ) {
    const operand = postExp.operand as EntryAccessor;
    const operandExpressionType = checker.getTypeAtLocation(operand.expression);
 
    if (isArrayType(operandExpressionType)) {
      return [createInvalidNode(node, [])];
    }
  }
  return [];
}
 
/**
 * No calls to array mutating methods.
 */
function checkCallExpression(
  node: ts.CallExpression,
  ctx: Lint.WalkContext<Options>,
  checker: ts.TypeChecker
): ReadonlyArray<InvalidNode> {
  const callExp = node as ts.CallExpression;
  if (ts.SyntaxKind.PropertyAccessExpression === callExp.expression.kind) {
    const propAccExp = callExp.expression as ts.PropertyAccessExpression;
    if (
      mutatorMethods.some(m => m === propAccExp.name.text) &&
      !Ignore.isIgnoredPrefix(
        callExp.getText(node.getSourceFile()),
        ctx.options.ignorePrefix
      ) &&
      (!ctx.options.ignoreMutationFollowingAccessor ||
        !isInChainCallAndFollowsAccessor(propAccExp))
    ) {
      // Do the type checking as late as possible (as it is expensive).
      const expressionType = checker.getTypeAtLocation(propAccExp.expression);
 
      if (isArrayType(expressionType)) {
        return [createInvalidNode(node, [])];
      }
    }
  }
  return [];
}
 
/**
 * Check if the given the given PropertyAccessExpression is part of a chain and
 * immediately follows an accessor method call.
 *
 * If this is the case, then the given PropertyAccessExpression is allowed to be a mutator method call.
 */
function isInChainCallAndFollowsAccessor(
  propAccExp: ts.PropertyAccessExpression
): boolean {
  if (ts.SyntaxKind.CallExpression === propAccExp.expression.kind) {
    const subCallExp = propAccExp.expression as ts.CallExpression;
    Eif (ts.SyntaxKind.PropertyAccessExpression === subCallExp.expression.kind) {
      const subPropAccExp = subCallExp.expression as ts.PropertyAccessExpression;
      Eif (accessorMethods.some(m => m === subPropAccExp.name.text)) {
        return true;
      }
    }
  }
 
  return false;
}