constructor-super.js 14 KB

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