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