curlyRule.js 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright 2013 Palantir Technologies, Inc.
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. Object.defineProperty(exports, "__esModule", { value: true });
  19. var tslib_1 = require("tslib");
  20. var tsutils_1 = require("tsutils");
  21. var ts = require("typescript");
  22. var Lint = require("../index");
  23. var curly_examples_1 = require("./code-examples/curly.examples");
  24. var OPTION_AS_NEEDED = "as-needed";
  25. var OPTION_IGNORE_SAME_LINE = "ignore-same-line";
  26. var Rule = /** @class */ (function (_super) {
  27. tslib_1.__extends(Rule, _super);
  28. function Rule() {
  29. return _super !== null && _super.apply(this, arguments) || this;
  30. }
  31. Rule.FAILURE_STRING_FACTORY = function (kind) {
  32. return kind + " statements must be braced";
  33. };
  34. Rule.prototype.apply = function (sourceFile) {
  35. if (this.ruleArguments.indexOf(OPTION_AS_NEEDED) !== -1) {
  36. return this.applyWithFunction(sourceFile, walkAsNeeded);
  37. }
  38. return this.applyWithWalker(new CurlyWalker(sourceFile, this.ruleName, {
  39. ignoreSameLine: this.ruleArguments.indexOf(OPTION_IGNORE_SAME_LINE) !== -1,
  40. }));
  41. };
  42. /* tslint:disable:object-literal-sort-keys */
  43. Rule.metadata = {
  44. ruleName: "curly",
  45. description: "Enforces braces for `if`/`for`/`do`/`while` statements.",
  46. rationale: Lint.Utils.dedent(templateObject_1 || (templateObject_1 = tslib_1.__makeTemplateObject(["\n ```ts\n if (foo === bar)\n foo++;\n bar++;\n ```\n\n In the code above, the author almost certainly meant for both `foo++` and `bar++`\n to be executed only if `foo === bar`. However, they forgot braces and `bar++` will be executed\n no matter what. This rule could prevent such a mistake."], ["\n \\`\\`\\`ts\n if (foo === bar)\n foo++;\n bar++;\n \\`\\`\\`\n\n In the code above, the author almost certainly meant for both \\`foo++\\` and \\`bar++\\`\n to be executed only if \\`foo === bar\\`. However, they forgot braces and \\`bar++\\` will be executed\n no matter what. This rule could prevent such a mistake."]))),
  47. optionsDescription: Lint.Utils.dedent(templateObject_2 || (templateObject_2 = tslib_1.__makeTemplateObject(["\n One of the following options may be provided:\n\n * `\"", "\"` forbids any unnecessary curly braces.\n * `\"", "\"` skips checking braces for control-flow statements\n that are on one line and start on the same line as their control-flow keyword\n "], ["\n One of the following options may be provided:\n\n * \\`\"", "\"\\` forbids any unnecessary curly braces.\n * \\`\"", "\"\\` skips checking braces for control-flow statements\n that are on one line and start on the same line as their control-flow keyword\n "])), OPTION_AS_NEEDED, OPTION_IGNORE_SAME_LINE),
  48. options: {
  49. type: "array",
  50. items: {
  51. type: "string",
  52. enum: [
  53. OPTION_AS_NEEDED,
  54. OPTION_IGNORE_SAME_LINE,
  55. ],
  56. },
  57. },
  58. optionExamples: [
  59. true,
  60. [true, OPTION_IGNORE_SAME_LINE],
  61. [true, OPTION_AS_NEEDED],
  62. ],
  63. type: "functionality",
  64. typescriptOnly: false,
  65. hasFix: true,
  66. codeExamples: curly_examples_1.codeExamples,
  67. };
  68. /* tslint:enable:object-literal-sort-keys */
  69. Rule.FAILURE_STRING_AS_NEEDED = "Block contains only one statement; remove the curly braces.";
  70. return Rule;
  71. }(Lint.Rules.AbstractRule));
  72. exports.Rule = Rule;
  73. function walkAsNeeded(ctx) {
  74. ts.forEachChild(ctx.sourceFile, function cb(node) {
  75. if (tsutils_1.isBlock(node) && isBlockUnnecessary(node)) {
  76. ctx.addFailureAt(node.statements.pos - 1, 1, Rule.FAILURE_STRING_AS_NEEDED);
  77. }
  78. ts.forEachChild(node, cb);
  79. });
  80. }
  81. function isBlockUnnecessary(node) {
  82. var parent = node.parent;
  83. if (node.statements.length !== 1) {
  84. return false;
  85. }
  86. var statement = node.statements[0];
  87. if (tsutils_1.isIterationStatement(parent)) {
  88. return true;
  89. }
  90. /*
  91. Watch out for this case:
  92. if (so) {
  93. if (also)
  94. foo();
  95. } else
  96. bar();
  97. */
  98. return tsutils_1.isIfStatement(parent) && !(tsutils_1.isIfStatement(statement)
  99. && statement.elseStatement === undefined
  100. && parent.thenStatement === node
  101. && parent.elseStatement !== undefined);
  102. }
  103. var CurlyWalker = /** @class */ (function (_super) {
  104. tslib_1.__extends(CurlyWalker, _super);
  105. function CurlyWalker() {
  106. return _super !== null && _super.apply(this, arguments) || this;
  107. }
  108. CurlyWalker.prototype.walk = function (sourceFile) {
  109. var _this = this;
  110. var cb = function (node) {
  111. if (tsutils_1.isIterationStatement(node)) {
  112. _this.checkStatement(node.statement, node, 0, node.end);
  113. }
  114. else if (tsutils_1.isIfStatement(node)) {
  115. _this.checkStatement(node.thenStatement, node, 0);
  116. if (node.elseStatement !== undefined && node.elseStatement.kind !== ts.SyntaxKind.IfStatement) {
  117. _this.checkStatement(node.elseStatement, node, 5);
  118. }
  119. }
  120. return ts.forEachChild(node, cb);
  121. };
  122. return ts.forEachChild(sourceFile, cb);
  123. };
  124. CurlyWalker.prototype.checkStatement = function (statement, node, childIndex, end) {
  125. if (end === void 0) { end = statement.end; }
  126. var sameLine = tsutils_1.isSameLine(this.sourceFile, statement.pos, statement.end);
  127. if (statement.kind !== ts.SyntaxKind.Block &&
  128. !(this.options.ignoreSameLine && sameLine)) {
  129. var token = node.getChildAt(childIndex, this.sourceFile);
  130. var tokenText = ts.tokenToString(token.kind);
  131. this.addFailure(token.end - tokenText.length, end, Rule.FAILURE_STRING_FACTORY(tokenText), this.createMissingBraceFix(statement, node, sameLine));
  132. }
  133. };
  134. /** Generate the necessary replacement to add braces to a statement that needs them. */
  135. CurlyWalker.prototype.createMissingBraceFix = function (statement, node, sameLine) {
  136. if (sameLine) {
  137. return [
  138. Lint.Replacement.appendText(statement.pos, " {"),
  139. Lint.Replacement.appendText(statement.end, " }"),
  140. ];
  141. }
  142. else {
  143. var match = /\n([\t ])/.exec(node.getFullText(this.sourceFile)); // determine which character to use (tab or space)
  144. var indentation = match === null ?
  145. "" :
  146. // indentation should match start of statement
  147. match[1].repeat(ts.getLineAndCharacterOfPosition(this.sourceFile, node.getStart(this.sourceFile)).character);
  148. var maybeCarriageReturn = this.sourceFile.text[this.sourceFile.getLineEndOfPosition(node.pos) - 1] === "\r" ? "\r" : "";
  149. return [
  150. Lint.Replacement.appendText(statement.pos, " {"),
  151. Lint.Replacement.appendText(statement.end, maybeCarriageReturn + "\n" + indentation + "}"),
  152. ];
  153. }
  154. };
  155. return CurlyWalker;
  156. }(Lint.AbstractWalker));
  157. var templateObject_1, templateObject_2;