lines-around-directive.js 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. /**
  2. * @fileoverview Require or disallow newlines around directives.
  3. * @author Kai Cataldo
  4. * @deprecated in ESLint v4.0.0
  5. */
  6. "use strict";
  7. const astUtils = require("./utils/ast-utils");
  8. //------------------------------------------------------------------------------
  9. // Rule Definition
  10. //------------------------------------------------------------------------------
  11. /** @type {import('../types').Rule.RuleModule} */
  12. module.exports = {
  13. meta: {
  14. type: "layout",
  15. docs: {
  16. description: "Require or disallow newlines around directives",
  17. recommended: false,
  18. url: "https://eslint.org/docs/latest/rules/lines-around-directive",
  19. },
  20. schema: [
  21. {
  22. oneOf: [
  23. {
  24. enum: ["always", "never"],
  25. },
  26. {
  27. type: "object",
  28. properties: {
  29. before: {
  30. enum: ["always", "never"],
  31. },
  32. after: {
  33. enum: ["always", "never"],
  34. },
  35. },
  36. additionalProperties: false,
  37. minProperties: 2,
  38. },
  39. ],
  40. },
  41. ],
  42. fixable: "whitespace",
  43. messages: {
  44. expected: 'Expected newline {{location}} "{{value}}" directive.',
  45. unexpected:
  46. 'Unexpected newline {{location}} "{{value}}" directive.',
  47. },
  48. deprecated: {
  49. message: "The rule was replaced with a more general rule.",
  50. url: "https://eslint.org/blog/2017/06/eslint-v4.0.0-released/",
  51. deprecatedSince: "4.0.0",
  52. availableUntil: "11.0.0",
  53. replacedBy: [
  54. {
  55. message: "The new rule moved to a plugin.",
  56. url: "https://eslint.org/docs/latest/rules/padding-line-between-statements#examples",
  57. plugin: {
  58. name: "@stylistic/eslint-plugin",
  59. url: "https://eslint.style",
  60. },
  61. rule: {
  62. name: "padding-line-between-statements",
  63. url: "https://eslint.style/rules/padding-line-between-statements",
  64. },
  65. },
  66. ],
  67. },
  68. },
  69. create(context) {
  70. const sourceCode = context.sourceCode;
  71. const config = context.options[0] || "always";
  72. const expectLineBefore =
  73. typeof config === "string" ? config : config.before;
  74. const expectLineAfter =
  75. typeof config === "string" ? config : config.after;
  76. //--------------------------------------------------------------------------
  77. // Helpers
  78. //--------------------------------------------------------------------------
  79. /**
  80. * Check if node is preceded by a blank newline.
  81. * @param {ASTNode} node Node to check.
  82. * @returns {boolean} Whether or not the passed in node is preceded by a blank newline.
  83. */
  84. function hasNewlineBefore(node) {
  85. const tokenBefore = sourceCode.getTokenBefore(node, {
  86. includeComments: true,
  87. });
  88. const tokenLineBefore = tokenBefore ? tokenBefore.loc.end.line : 0;
  89. return node.loc.start.line - tokenLineBefore >= 2;
  90. }
  91. /**
  92. * Gets the last token of a node that is on the same line as the rest of the node.
  93. * This will usually be the last token of the node, but it will be the second-to-last token if the node has a trailing
  94. * semicolon on a different line.
  95. * @param {ASTNode} node A directive node
  96. * @returns {Token} The last token of the node on the line
  97. */
  98. function getLastTokenOnLine(node) {
  99. const lastToken = sourceCode.getLastToken(node);
  100. const secondToLastToken = sourceCode.getTokenBefore(lastToken);
  101. return astUtils.isSemicolonToken(lastToken) &&
  102. lastToken.loc.start.line > secondToLastToken.loc.end.line
  103. ? secondToLastToken
  104. : lastToken;
  105. }
  106. /**
  107. * Check if node is followed by a blank newline.
  108. * @param {ASTNode} node Node to check.
  109. * @returns {boolean} Whether or not the passed in node is followed by a blank newline.
  110. */
  111. function hasNewlineAfter(node) {
  112. const lastToken = getLastTokenOnLine(node);
  113. const tokenAfter = sourceCode.getTokenAfter(lastToken, {
  114. includeComments: true,
  115. });
  116. return tokenAfter.loc.start.line - lastToken.loc.end.line >= 2;
  117. }
  118. /**
  119. * Report errors for newlines around directives.
  120. * @param {ASTNode} node Node to check.
  121. * @param {string} location Whether the error was found before or after the directive.
  122. * @param {boolean} expected Whether or not a newline was expected or unexpected.
  123. * @returns {void}
  124. */
  125. function reportError(node, location, expected) {
  126. context.report({
  127. node,
  128. messageId: expected ? "expected" : "unexpected",
  129. data: {
  130. value: node.expression.value,
  131. location,
  132. },
  133. fix(fixer) {
  134. const lastToken = getLastTokenOnLine(node);
  135. if (expected) {
  136. return location === "before"
  137. ? fixer.insertTextBefore(node, "\n")
  138. : fixer.insertTextAfter(lastToken, "\n");
  139. }
  140. return fixer.removeRange(
  141. location === "before"
  142. ? [node.range[0] - 1, node.range[0]]
  143. : [lastToken.range[1], lastToken.range[1] + 1],
  144. );
  145. },
  146. });
  147. }
  148. /**
  149. * Check lines around directives in node
  150. * @param {ASTNode} node node to check
  151. * @returns {void}
  152. */
  153. function checkDirectives(node) {
  154. const directives = astUtils.getDirectivePrologue(node);
  155. if (!directives.length) {
  156. return;
  157. }
  158. const firstDirective = directives[0];
  159. const leadingComments =
  160. sourceCode.getCommentsBefore(firstDirective);
  161. /*
  162. * Only check before the first directive if it is preceded by a comment or if it is at the top of
  163. * the file and expectLineBefore is set to "never". This is to not force a newline at the top of
  164. * the file if there are no comments as well as for compatibility with padded-blocks.
  165. */
  166. if (leadingComments.length) {
  167. if (
  168. expectLineBefore === "always" &&
  169. !hasNewlineBefore(firstDirective)
  170. ) {
  171. reportError(firstDirective, "before", true);
  172. }
  173. if (
  174. expectLineBefore === "never" &&
  175. hasNewlineBefore(firstDirective)
  176. ) {
  177. reportError(firstDirective, "before", false);
  178. }
  179. } else if (
  180. node.type === "Program" &&
  181. expectLineBefore === "never" &&
  182. !leadingComments.length &&
  183. hasNewlineBefore(firstDirective)
  184. ) {
  185. reportError(firstDirective, "before", false);
  186. }
  187. const lastDirective = directives.at(-1);
  188. const statements =
  189. node.type === "Program" ? node.body : node.body.body;
  190. /*
  191. * Do not check after the last directive if the body only
  192. * contains a directive prologue and isn't followed by a comment to ensure
  193. * this rule behaves well with padded-blocks.
  194. */
  195. if (
  196. lastDirective === statements.at(-1) &&
  197. !lastDirective.trailingComments
  198. ) {
  199. return;
  200. }
  201. if (
  202. expectLineAfter === "always" &&
  203. !hasNewlineAfter(lastDirective)
  204. ) {
  205. reportError(lastDirective, "after", true);
  206. }
  207. if (expectLineAfter === "never" && hasNewlineAfter(lastDirective)) {
  208. reportError(lastDirective, "after", false);
  209. }
  210. }
  211. //--------------------------------------------------------------------------
  212. // Public
  213. //--------------------------------------------------------------------------
  214. return {
  215. Program: checkDirectives,
  216. FunctionDeclaration: checkDirectives,
  217. FunctionExpression: checkDirectives,
  218. ArrowFunctionExpression: checkDirectives,
  219. };
  220. },
  221. };