curlyRule.js 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155
  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 OPTION_AS_NEEDED = "as-needed";
  24. var OPTION_IGNORE_SAME_LINE = "ignore-same-line";
  25. var Rule = /** @class */ (function (_super) {
  26. tslib_1.__extends(Rule, _super);
  27. function Rule() {
  28. return _super !== null && _super.apply(this, arguments) || this;
  29. }
  30. Rule.FAILURE_STRING_FACTORY = function (kind) {
  31. return kind + " statements must be braced";
  32. };
  33. Rule.prototype.apply = function (sourceFile) {
  34. if (this.ruleArguments.indexOf(OPTION_AS_NEEDED) !== -1) {
  35. return this.applyWithFunction(sourceFile, walkAsNeeded);
  36. }
  37. return this.applyWithWalker(new CurlyWalker(sourceFile, this.ruleName, {
  38. ignoreSameLine: this.ruleArguments.indexOf(OPTION_IGNORE_SAME_LINE) !== -1,
  39. }));
  40. };
  41. /* tslint:disable:object-literal-sort-keys */
  42. Rule.metadata = {
  43. ruleName: "curly",
  44. description: "Enforces braces for `if`/`for`/`do`/`while` statements.",
  45. 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, he 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, he forgot braces and \\`bar++\\` will be executed\n no matter what. This rule could prevent such a mistake."]))),
  46. 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),
  47. options: {
  48. type: "array",
  49. items: {
  50. type: "string",
  51. enum: [
  52. OPTION_AS_NEEDED,
  53. OPTION_IGNORE_SAME_LINE,
  54. ],
  55. },
  56. },
  57. optionExamples: [
  58. true,
  59. [true, OPTION_IGNORE_SAME_LINE],
  60. [true, OPTION_AS_NEEDED],
  61. ],
  62. type: "functionality",
  63. typescriptOnly: false,
  64. hasFix: true,
  65. };
  66. /* tslint:enable:object-literal-sort-keys */
  67. Rule.FAILURE_STRING_AS_NEEDED = "Block contains only one statement; remove the curly braces.";
  68. return Rule;
  69. }(Lint.Rules.AbstractRule));
  70. exports.Rule = Rule;
  71. function walkAsNeeded(ctx) {
  72. ts.forEachChild(ctx.sourceFile, function cb(node) {
  73. if (tsutils_1.isBlock(node) && isBlockUnnecessary(node)) {
  74. ctx.addFailureAt(node.statements.pos - 1, 1, Rule.FAILURE_STRING_AS_NEEDED);
  75. }
  76. ts.forEachChild(node, cb);
  77. });
  78. }
  79. function isBlockUnnecessary(node) {
  80. var parent = node.parent;
  81. if (node.statements.length !== 1) {
  82. return false;
  83. }
  84. var statement = node.statements[0];
  85. if (tsutils_1.isIterationStatement(parent)) {
  86. return true;
  87. }
  88. /*
  89. Watch out for this case:
  90. if (so) {
  91. if (also)
  92. foo();
  93. } else
  94. bar();
  95. */
  96. return tsutils_1.isIfStatement(parent) && !(tsutils_1.isIfStatement(statement)
  97. && statement.elseStatement === undefined
  98. && parent.thenStatement === node
  99. && parent.elseStatement !== undefined);
  100. }
  101. var CurlyWalker = /** @class */ (function (_super) {
  102. tslib_1.__extends(CurlyWalker, _super);
  103. function CurlyWalker() {
  104. return _super !== null && _super.apply(this, arguments) || this;
  105. }
  106. CurlyWalker.prototype.walk = function (sourceFile) {
  107. var _this = this;
  108. var cb = function (node) {
  109. if (tsutils_1.isIterationStatement(node)) {
  110. _this.checkStatement(node.statement, node, 0, node.end);
  111. }
  112. else if (tsutils_1.isIfStatement(node)) {
  113. _this.checkStatement(node.thenStatement, node, 0);
  114. if (node.elseStatement !== undefined && node.elseStatement.kind !== ts.SyntaxKind.IfStatement) {
  115. _this.checkStatement(node.elseStatement, node, 5);
  116. }
  117. }
  118. return ts.forEachChild(node, cb);
  119. };
  120. return ts.forEachChild(sourceFile, cb);
  121. };
  122. CurlyWalker.prototype.checkStatement = function (statement, node, childIndex, end) {
  123. if (end === void 0) { end = statement.end; }
  124. var sameLine = tsutils_1.isSameLine(this.sourceFile, statement.pos, statement.end);
  125. if (statement.kind !== ts.SyntaxKind.Block &&
  126. !(this.options.ignoreSameLine && sameLine)) {
  127. var token = node.getChildAt(childIndex, this.sourceFile);
  128. var tokenText = ts.tokenToString(token.kind);
  129. this.addFailure(token.end - tokenText.length, end, Rule.FAILURE_STRING_FACTORY(tokenText), this.createMissingBraceFix(statement, node, sameLine));
  130. }
  131. };
  132. /** Generate the necessary replacement to add braces to a statement that needs them. */
  133. CurlyWalker.prototype.createMissingBraceFix = function (statement, node, sameLine) {
  134. if (sameLine) {
  135. return [
  136. Lint.Replacement.appendText(statement.pos, " {"),
  137. Lint.Replacement.appendText(statement.end, " }"),
  138. ];
  139. }
  140. else {
  141. var match = /\n([\t ])/.exec(node.getFullText(this.sourceFile)); // determine which character to use (tab or space)
  142. var indentation = match === null ?
  143. "" :
  144. // indentation should match start of statement
  145. match[1].repeat(ts.getLineAndCharacterOfPosition(this.sourceFile, node.getStart(this.sourceFile)).character);
  146. var maybeCarriageReturn = this.sourceFile.text[this.sourceFile.getLineEndOfPosition(node.pos) - 1] === "\r" ? "\r" : "";
  147. return [
  148. Lint.Replacement.appendText(statement.pos, " {"),
  149. Lint.Replacement.appendText(statement.end, maybeCarriageReturn + "\n" + indentation + "}"),
  150. ];
  151. }
  152. };
  153. return CurlyWalker;
  154. }(Lint.AbstractWalker));
  155. var templateObject_1, templateObject_2;