constructor-super.js 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  1. /**
  2. * @fileoverview A rule to verify `super()` callings in constructor.
  3. * @author Toru Nagashima
  4. */
  5. "use strict";
  6. //------------------------------------------------------------------------------
  7. // Helpers
  8. //------------------------------------------------------------------------------
  9. /**
  10. * Checks whether a given code path segment is reachable or not.
  11. * @param {CodePathSegment} segment A code path segment to check.
  12. * @returns {boolean} `true` if the segment is reachable.
  13. */
  14. function isReachable(segment) {
  15. return segment.reachable;
  16. }
  17. /**
  18. * Checks whether or not a given node is a constructor.
  19. * @param {ASTNode} node A node to check. This node type is one of
  20. * `Program`, `FunctionDeclaration`, `FunctionExpression`, and
  21. * `ArrowFunctionExpression`.
  22. * @returns {boolean} `true` if the node is a constructor.
  23. */
  24. function isConstructorFunction(node) {
  25. return (
  26. node.type === "FunctionExpression" &&
  27. node.parent.type === "MethodDefinition" &&
  28. node.parent.kind === "constructor"
  29. );
  30. }
  31. /**
  32. * Checks whether a given node can be a constructor or not.
  33. * @param {ASTNode} node A node to check.
  34. * @returns {boolean} `true` if the node can be a constructor.
  35. */
  36. function isPossibleConstructor(node) {
  37. if (!node) {
  38. return false;
  39. }
  40. switch (node.type) {
  41. case "ClassExpression":
  42. case "FunctionExpression":
  43. case "ThisExpression":
  44. case "MemberExpression":
  45. case "CallExpression":
  46. case "NewExpression":
  47. case "YieldExpression":
  48. case "TaggedTemplateExpression":
  49. case "MetaProperty":
  50. return true;
  51. case "Identifier":
  52. return node.name !== "undefined";
  53. case "AssignmentExpression":
  54. return isPossibleConstructor(node.right);
  55. case "LogicalExpression":
  56. return (
  57. isPossibleConstructor(node.left) ||
  58. isPossibleConstructor(node.right)
  59. );
  60. case "ConditionalExpression":
  61. return (
  62. isPossibleConstructor(node.alternate) ||
  63. isPossibleConstructor(node.consequent)
  64. );
  65. case "SequenceExpression": {
  66. const lastExpression = node.expressions[node.expressions.length - 1];
  67. return isPossibleConstructor(lastExpression);
  68. }
  69. default:
  70. return false;
  71. }
  72. }
  73. //------------------------------------------------------------------------------
  74. // Rule Definition
  75. //------------------------------------------------------------------------------
  76. module.exports = {
  77. meta: {
  78. type: "problem",
  79. docs: {
  80. description: "require `super()` calls in constructors",
  81. category: "ECMAScript 6",
  82. recommended: true,
  83. url: "https://eslint.org/docs/rules/constructor-super"
  84. },
  85. schema: [],
  86. messages: {
  87. missingSome: "Lacked a call of 'super()' in some code paths.",
  88. missingAll: "Expected to call 'super()'.",
  89. duplicate: "Unexpected duplicate 'super()'.",
  90. badSuper: "Unexpected 'super()' because 'super' is not a constructor.",
  91. unexpected: "Unexpected 'super()'."
  92. }
  93. },
  94. create(context) {
  95. /*
  96. * {{hasExtends: boolean, scope: Scope, codePath: CodePath}[]}
  97. * Information for each constructor.
  98. * - upper: Information of the upper constructor.
  99. * - hasExtends: A flag which shows whether own class has a valid `extends`
  100. * part.
  101. * - scope: The scope of own class.
  102. * - codePath: The code path object of the constructor.
  103. */
  104. let funcInfo = null;
  105. /*
  106. * {Map<string, {calledInSomePaths: boolean, calledInEveryPaths: boolean}>}
  107. * Information for each code path segment.
  108. * - calledInSomePaths: A flag of be called `super()` in some code paths.
  109. * - calledInEveryPaths: A flag of be called `super()` in all code paths.
  110. * - validNodes:
  111. */
  112. let segInfoMap = Object.create(null);
  113. /**
  114. * Gets the flag which shows `super()` is called in some paths.
  115. * @param {CodePathSegment} segment A code path segment to get.
  116. * @returns {boolean} The flag which shows `super()` is called in some paths
  117. */
  118. function isCalledInSomePath(segment) {
  119. return segment.reachable && segInfoMap[segment.id].calledInSomePaths;
  120. }
  121. /**
  122. * Gets the flag which shows `super()` is called in all paths.
  123. * @param {CodePathSegment} segment A code path segment to get.
  124. * @returns {boolean} The flag which shows `super()` is called in all paths.
  125. */
  126. function isCalledInEveryPath(segment) {
  127. /*
  128. * If specific segment is the looped segment of the current segment,
  129. * skip the segment.
  130. * If not skipped, this never becomes true after a loop.
  131. */
  132. if (segment.nextSegments.length === 1 &&
  133. segment.nextSegments[0].isLoopedPrevSegment(segment)
  134. ) {
  135. return true;
  136. }
  137. return segment.reachable && segInfoMap[segment.id].calledInEveryPaths;
  138. }
  139. return {
  140. /**
  141. * Stacks a constructor information.
  142. * @param {CodePath} codePath A code path which was started.
  143. * @param {ASTNode} node The current node.
  144. * @returns {void}
  145. */
  146. onCodePathStart(codePath, node) {
  147. if (isConstructorFunction(node)) {
  148. // Class > ClassBody > MethodDefinition > FunctionExpression
  149. const classNode = node.parent.parent.parent;
  150. const superClass = classNode.superClass;
  151. funcInfo = {
  152. upper: funcInfo,
  153. isConstructor: true,
  154. hasExtends: Boolean(superClass),
  155. superIsConstructor: isPossibleConstructor(superClass),
  156. codePath
  157. };
  158. } else {
  159. funcInfo = {
  160. upper: funcInfo,
  161. isConstructor: false,
  162. hasExtends: false,
  163. superIsConstructor: false,
  164. codePath
  165. };
  166. }
  167. },
  168. /**
  169. * Pops a constructor information.
  170. * And reports if `super()` lacked.
  171. * @param {CodePath} codePath A code path which was ended.
  172. * @param {ASTNode} node The current node.
  173. * @returns {void}
  174. */
  175. onCodePathEnd(codePath, node) {
  176. const hasExtends = funcInfo.hasExtends;
  177. // Pop.
  178. funcInfo = funcInfo.upper;
  179. if (!hasExtends) {
  180. return;
  181. }
  182. // Reports if `super()` lacked.
  183. const segments = codePath.returnedSegments;
  184. const calledInEveryPaths = segments.every(isCalledInEveryPath);
  185. const calledInSomePaths = segments.some(isCalledInSomePath);
  186. if (!calledInEveryPaths) {
  187. context.report({
  188. messageId: calledInSomePaths
  189. ? "missingSome"
  190. : "missingAll",
  191. node: node.parent
  192. });
  193. }
  194. },
  195. /**
  196. * Initialize information of a given code path segment.
  197. * @param {CodePathSegment} segment A code path segment to initialize.
  198. * @returns {void}
  199. */
  200. onCodePathSegmentStart(segment) {
  201. if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
  202. return;
  203. }
  204. // Initialize info.
  205. const info = segInfoMap[segment.id] = {
  206. calledInSomePaths: false,
  207. calledInEveryPaths: false,
  208. validNodes: []
  209. };
  210. // When there are previous segments, aggregates these.
  211. const prevSegments = segment.prevSegments;
  212. if (prevSegments.length > 0) {
  213. info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
  214. info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath);
  215. }
  216. },
  217. /**
  218. * Update information of the code path segment when a code path was
  219. * looped.
  220. * @param {CodePathSegment} fromSegment The code path segment of the
  221. * end of a loop.
  222. * @param {CodePathSegment} toSegment A code path segment of the head
  223. * of a loop.
  224. * @returns {void}
  225. */
  226. onCodePathSegmentLoop(fromSegment, toSegment) {
  227. if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
  228. return;
  229. }
  230. // Update information inside of the loop.
  231. const isRealLoop = toSegment.prevSegments.length >= 2;
  232. funcInfo.codePath.traverseSegments(
  233. { first: toSegment, last: fromSegment },
  234. segment => {
  235. const info = segInfoMap[segment.id];
  236. const prevSegments = segment.prevSegments;
  237. // Updates flags.
  238. info.calledInSomePaths = prevSegments.some(isCalledInSomePath);
  239. info.calledInEveryPaths = prevSegments.every(isCalledInEveryPath);
  240. // If flags become true anew, reports the valid nodes.
  241. if (info.calledInSomePaths || isRealLoop) {
  242. const nodes = info.validNodes;
  243. info.validNodes = [];
  244. for (let i = 0; i < nodes.length; ++i) {
  245. const node = nodes[i];
  246. context.report({
  247. messageId: "duplicate",
  248. node
  249. });
  250. }
  251. }
  252. }
  253. );
  254. },
  255. /**
  256. * Checks for a call of `super()`.
  257. * @param {ASTNode} node A CallExpression node to check.
  258. * @returns {void}
  259. */
  260. "CallExpression:exit"(node) {
  261. if (!(funcInfo && funcInfo.isConstructor)) {
  262. return;
  263. }
  264. // Skips except `super()`.
  265. if (node.callee.type !== "Super") {
  266. return;
  267. }
  268. // Reports if needed.
  269. if (funcInfo.hasExtends) {
  270. const segments = funcInfo.codePath.currentSegments;
  271. let duplicate = false;
  272. let info = null;
  273. for (let i = 0; i < segments.length; ++i) {
  274. const segment = segments[i];
  275. if (segment.reachable) {
  276. info = segInfoMap[segment.id];
  277. duplicate = duplicate || info.calledInSomePaths;
  278. info.calledInSomePaths = info.calledInEveryPaths = true;
  279. }
  280. }
  281. if (info) {
  282. if (duplicate) {
  283. context.report({
  284. messageId: "duplicate",
  285. node
  286. });
  287. } else if (!funcInfo.superIsConstructor) {
  288. context.report({
  289. messageId: "badSuper",
  290. node
  291. });
  292. } else {
  293. info.validNodes.push(node);
  294. }
  295. }
  296. } else if (funcInfo.codePath.currentSegments.some(isReachable)) {
  297. context.report({
  298. messageId: "unexpected",
  299. node
  300. });
  301. }
  302. },
  303. /**
  304. * Set the mark to the returned path as `super()` was called.
  305. * @param {ASTNode} node A ReturnStatement node to check.
  306. * @returns {void}
  307. */
  308. ReturnStatement(node) {
  309. if (!(funcInfo && funcInfo.isConstructor && funcInfo.hasExtends)) {
  310. return;
  311. }
  312. // Skips if no argument.
  313. if (!node.argument) {
  314. return;
  315. }
  316. // Returning argument is a substitute of 'super()'.
  317. const segments = funcInfo.codePath.currentSegments;
  318. for (let i = 0; i < segments.length; ++i) {
  319. const segment = segments[i];
  320. if (segment.reachable) {
  321. const info = segInfoMap[segment.id];
  322. info.calledInSomePaths = info.calledInEveryPaths = true;
  323. }
  324. }
  325. },
  326. /**
  327. * Resets state.
  328. * @returns {void}
  329. */
  330. "Program:exit"() {
  331. segInfoMap = Object.create(null);
  332. }
  333. };
  334. }
  335. };