no-this-before-super.js 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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("../util/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. *
  147. * @param {CodePath} codePath - A code path which was ended.
  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. };