no-this-before-super.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. /**
  2. * @fileoverview A rule to disallow using `this`/`super` before `super()`.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Requirements
  8. //------------------------------------------------------------------------------
  9. const astUtils = require("../ast-utils");
  10. //------------------------------------------------------------------------------
  11. // Helpers
  12. //------------------------------------------------------------------------------
  13. /**
  14. * Checks whether or not a given node is a constructor.
  15. * @param {ASTNode} node - A node to check. This node type is one of
  16. * `Program`, `FunctionDeclaration`, `FunctionExpression`, and
  17. * `ArrowFunctionExpression`.
  18. * @returns {boolean} `true` if the node is a constructor.
  19. */
  20. function isConstructorFunction(node) {
  21. return (
  22. node.type === "FunctionExpression" &&
  23. node.parent.type === "MethodDefinition" &&
  24. node.parent.kind === "constructor"
  25. );
  26. }
  27. //------------------------------------------------------------------------------
  28. // Rule Definition
  29. //------------------------------------------------------------------------------
  30. module.exports = {
  31. meta: {
  32. docs: {
  33. description: "disallow `this`/`super` before calling `super()` in constructors",
  34. category: "ECMAScript 6",
  35. recommended: true,
  36. url: "https://eslint.org/docs/rules/no-this-before-super"
  37. },
  38. schema: []
  39. },
  40. create(context) {
  41. /*
  42. * Information for each constructor.
  43. * - upper: Information of the upper constructor.
  44. * - hasExtends: A flag which shows whether the owner class has a valid
  45. * `extends` part.
  46. * - scope: The scope of the owner class.
  47. * - codePath: The code path of this constructor.
  48. */
  49. let funcInfo = null;
  50. /*
  51. * Information for each code path segment.
  52. * Each key is the id of a code path segment.
  53. * Each value is an object:
  54. * - superCalled: The flag which shows `super()` called in all code paths.
  55. * - invalidNodes: The array of invalid ThisExpression and Super nodes.
  56. */
  57. let segInfoMap = Object.create(null);
  58. /**
  59. * Gets whether or not `super()` is called in a given code path segment.
  60. * @param {CodePathSegment} segment - A code path segment to get.
  61. * @returns {boolean} `true` if `super()` is called.
  62. */
  63. function isCalled(segment) {
  64. return !segment.reachable || segInfoMap[segment.id].superCalled;
  65. }
  66. /**
  67. * Checks whether or not this is in a constructor.
  68. * @returns {boolean} `true` if this is in a constructor.
  69. */
  70. function isInConstructorOfDerivedClass() {
  71. return Boolean(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends);
  72. }
  73. /**
  74. * Checks whether or not this is before `super()` is called.
  75. * @returns {boolean} `true` if this is before `super()` is called.
  76. */
  77. function isBeforeCallOfSuper() {
  78. return (
  79. isInConstructorOfDerivedClass() &&
  80. !funcInfo.codePath.currentSegments.every(isCalled)
  81. );
  82. }
  83. /**
  84. * Sets a given node as invalid.
  85. * @param {ASTNode} node - A node to set as invalid. This is one of
  86. * a ThisExpression and a Super.
  87. * @returns {void}
  88. */
  89. function setInvalid(node) {
  90. const segments = funcInfo.codePath.currentSegments;
  91. for (let i = 0; i < segments.length; ++i) {
  92. const segment = segments[i];
  93. if (segment.reachable) {
  94. segInfoMap[segment.id].invalidNodes.push(node);
  95. }
  96. }
  97. }
  98. /**
  99. * Sets the current segment as `super` was called.
  100. * @returns {void}
  101. */
  102. function setSuperCalled() {
  103. const segments = funcInfo.codePath.currentSegments;
  104. for (let i = 0; i < segments.length; ++i) {
  105. const segment = segments[i];
  106. if (segment.reachable) {
  107. segInfoMap[segment.id].superCalled = true;
  108. }
  109. }
  110. }
  111. return {
  112. /**
  113. * Adds information of a constructor into the stack.
  114. * @param {CodePath} codePath - A code path which was started.
  115. * @param {ASTNode} node - The current node.
  116. * @returns {void}
  117. */
  118. onCodePathStart(codePath, node) {
  119. if (isConstructorFunction(node)) {
  120. // Class > ClassBody > MethodDefinition > FunctionExpression
  121. const classNode = node.parent.parent.parent;
  122. funcInfo = {
  123. upper: funcInfo,
  124. isConstructor: true,
  125. hasExtends: Boolean(
  126. classNode.superClass &&
  127. !astUtils.isNullOrUndefined(classNode.superClass)
  128. ),
  129. codePath
  130. };
  131. } else {
  132. funcInfo = {
  133. upper: funcInfo,
  134. isConstructor: false,
  135. hasExtends: false,
  136. codePath
  137. };
  138. }
  139. },
  140. /**
  141. * Removes the top of stack item.
  142. *
  143. * And this treverses all segments of this code path then reports every
  144. * invalid node.
  145. *
  146. * @param {CodePath} codePath - A code path which was ended.
  147. * @param {ASTNode} node - The current node.
  148. * @returns {void}
  149. */
  150. onCodePathEnd(codePath) {
  151. const isDerivedClass = funcInfo.hasExtends;
  152. funcInfo = funcInfo.upper;
  153. if (!isDerivedClass) {
  154. return;
  155. }
  156. codePath.traverseSegments((segment, controller) => {
  157. const info = segInfoMap[segment.id];
  158. for (let i = 0; i < info.invalidNodes.length; ++i) {
  159. const invalidNode = info.invalidNodes[i];
  160. context.report({
  161. message: "'{{kind}}' is not allowed before 'super()'.",
  162. node: invalidNode,
  163. data: {
  164. kind: invalidNode.type === "Super" ? "super" : "this"
  165. }
  166. });
  167. }
  168. if (info.superCalled) {
  169. controller.skip();
  170. }
  171. });
  172. },
  173. /**
  174. * Initialize information of a given code path segment.
  175. * @param {CodePathSegment} segment - A code path segment to initialize.
  176. * @returns {void}
  177. */
  178. onCodePathSegmentStart(segment) {
  179. if (!isInConstructorOfDerivedClass()) {
  180. return;
  181. }
  182. // Initialize info.
  183. segInfoMap[segment.id] = {
  184. superCalled: (
  185. segment.prevSegments.length > 0 &&
  186. segment.prevSegments.every(isCalled)
  187. ),
  188. invalidNodes: []
  189. };
  190. },
  191. /**
  192. * Update information of the code path segment when a code path was
  193. * looped.
  194. * @param {CodePathSegment} fromSegment - The code path segment of the
  195. * end of a loop.
  196. * @param {CodePathSegment} toSegment - A code path segment of the head
  197. * of a loop.
  198. * @returns {void}
  199. */
  200. onCodePathSegmentLoop(fromSegment, toSegment) {
  201. if (!isInConstructorOfDerivedClass()) {
  202. return;
  203. }
  204. // Update information inside of the loop.
  205. funcInfo.codePath.traverseSegments(
  206. { first: toSegment, last: fromSegment },
  207. (segment, controller) => {
  208. const info = segInfoMap[segment.id];
  209. if (info.superCalled) {
  210. info.invalidNodes = [];
  211. controller.skip();
  212. } else if (
  213. segment.prevSegments.length > 0 &&
  214. segment.prevSegments.every(isCalled)
  215. ) {
  216. info.superCalled = true;
  217. info.invalidNodes = [];
  218. }
  219. }
  220. );
  221. },
  222. /**
  223. * Reports if this is before `super()`.
  224. * @param {ASTNode} node - A target node.
  225. * @returns {void}
  226. */
  227. ThisExpression(node) {
  228. if (isBeforeCallOfSuper()) {
  229. setInvalid(node);
  230. }
  231. },
  232. /**
  233. * Reports if this is before `super()`.
  234. * @param {ASTNode} node - A target node.
  235. * @returns {void}
  236. */
  237. Super(node) {
  238. if (!astUtils.isCallee(node) && isBeforeCallOfSuper()) {
  239. setInvalid(node);
  240. }
  241. },
  242. /**
  243. * Marks `super()` called.
  244. * @param {ASTNode} node - A target node.
  245. * @returns {void}
  246. */
  247. "CallExpression:exit"(node) {
  248. if (node.callee.type === "Super" && isBeforeCallOfSuper()) {
  249. setSuperCalled();
  250. }
  251. },
  252. /**
  253. * Resets state.
  254. * @returns {void}
  255. */
  256. "Program:exit"() {
  257. segInfoMap = Object.create(null);
  258. }
  259. };
  260. }
  261. };