constructor-signature-rule.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. "use strict";
  2. /**
  3. * @license
  4. * Copyright Google LLC All Rights Reserved.
  5. *
  6. * Use of this source code is governed by an MIT-style license that can be
  7. * found in the LICENSE file at https://angular.io/license
  8. */
  9. Object.defineProperty(exports, "__esModule", { value: true });
  10. const ts = require("typescript");
  11. const migration_rule_1 = require("../../update-tool/migration-rule");
  12. const version_changes_1 = require("../../update-tool/version-changes");
  13. /**
  14. * List of diagnostic codes that refer to pre-emit diagnostics which indicate invalid
  15. * new expression or super call signatures. See the list of diagnostics here:
  16. *
  17. * https://github.com/Microsoft/TypeScript/blob/master/src/compiler/diagnosticMessages.json
  18. */
  19. const signatureErrorDiagnostics = [
  20. // Type not assignable error diagnostic.
  21. 2345,
  22. // Constructor argument length invalid diagnostics
  23. 2554,
  24. 2555,
  25. 2556,
  26. 2557,
  27. ];
  28. /**
  29. * Rule that visits every TypeScript new expression or super call and checks if
  30. * the parameter type signature is invalid and needs to be updated manually.
  31. */
  32. class ConstructorSignatureRule extends migration_rule_1.MigrationRule {
  33. constructor() {
  34. super(...arguments);
  35. // Note that the data for this rule is not distinguished based on the target version because
  36. // we don't keep track of the new signature and don't want to update incrementally.
  37. // See: https://github.com/angular/components/pull/12970#issuecomment-418337566
  38. this.data = version_changes_1.getAllChanges(this.upgradeData.constructorChecks);
  39. // Only enable the migration rule if there is upgrade data.
  40. this.ruleEnabled = this.data.length !== 0;
  41. }
  42. visitNode(node) {
  43. if (ts.isSourceFile(node)) {
  44. this._visitSourceFile(node);
  45. }
  46. }
  47. /**
  48. * Method that will be called for each source file of the upgrade project. In order to
  49. * properly determine invalid constructor signatures, we take advantage of the pre-emit
  50. * diagnostics from TypeScript.
  51. *
  52. * By using the diagnostics, the migration can handle type assignability. Not using
  53. * diagnostics would mean that we need to use simple type equality checking which is
  54. * too strict. See related issue: https://github.com/Microsoft/TypeScript/issues/9879
  55. */
  56. _visitSourceFile(sourceFile) {
  57. // List of classes of which the constructor signature has changed.
  58. const diagnostics = ts.getPreEmitDiagnostics(this.program, sourceFile)
  59. .filter(diagnostic => signatureErrorDiagnostics.includes(diagnostic.code))
  60. .filter(diagnostic => diagnostic.start !== undefined);
  61. for (const diagnostic of diagnostics) {
  62. const node = findConstructorNode(diagnostic, sourceFile);
  63. if (!node) {
  64. continue;
  65. }
  66. const classType = this.typeChecker.getTypeAtLocation(node.expression);
  67. const className = classType.symbol && classType.symbol.name;
  68. const isNewExpression = ts.isNewExpression(node);
  69. // Determine the class names of the actual construct signatures because we cannot assume that
  70. // the diagnostic refers to a constructor of the actual expression. In case the constructor
  71. // is inherited, we need to detect that the owner-class of the constructor is added to the
  72. // constructor checks upgrade data. e.g. `class CustomCalendar extends MatCalendar {}`.
  73. const signatureClassNames = classType.getConstructSignatures()
  74. .map(signature => getClassDeclarationOfSignature(signature))
  75. .map(declaration => declaration && declaration.name ? declaration.name.text : null)
  76. .filter(Boolean);
  77. // Besides checking the signature class names, we need to check the actual class name because
  78. // there can be classes without an explicit constructor.
  79. if (!this.data.includes(className) &&
  80. !signatureClassNames.some(name => this.data.includes(name))) {
  81. continue;
  82. }
  83. const classSignatures = classType.getConstructSignatures().map(signature => getParameterTypesFromSignature(signature, this.typeChecker));
  84. const expressionName = isNewExpression ? `new ${className}` : 'super';
  85. const signatures = classSignatures.map(signature => signature.map(t => this.typeChecker.typeToString(t)))
  86. .map(signature => `${expressionName}(${signature.join(', ')})`)
  87. .join(' or ');
  88. this.createFailureAtNode(node, `Found "${className}" constructed with ` +
  89. `an invalid signature. Please manually update the ${expressionName} expression to ` +
  90. `match the new signature${classSignatures.length > 1 ? 's' : ''}: ${signatures}`);
  91. }
  92. }
  93. }
  94. exports.ConstructorSignatureRule = ConstructorSignatureRule;
  95. /** Resolves the type for each parameter in the specified signature. */
  96. function getParameterTypesFromSignature(signature, typeChecker) {
  97. return signature.getParameters().map(param => typeChecker.getTypeAtLocation(param.declarations[0]));
  98. }
  99. /**
  100. * Walks through each node of a source file in order to find a new-expression node or super-call
  101. * expression node that is captured by the specified diagnostic.
  102. */
  103. function findConstructorNode(diagnostic, sourceFile) {
  104. let resolvedNode = null;
  105. const _visitNode = (node) => {
  106. // Check whether the current node contains the diagnostic. If the node contains the diagnostic,
  107. // walk deeper in order to find all constructor expression nodes.
  108. if (node.getStart() <= diagnostic.start && node.getEnd() >= diagnostic.start) {
  109. if (ts.isNewExpression(node) ||
  110. (ts.isCallExpression(node) && node.expression.kind === ts.SyntaxKind.SuperKeyword)) {
  111. resolvedNode = node;
  112. }
  113. ts.forEachChild(node, _visitNode);
  114. }
  115. };
  116. ts.forEachChild(sourceFile, _visitNode);
  117. return resolvedNode;
  118. }
  119. /** Determines the class declaration of the specified construct signature. */
  120. function getClassDeclarationOfSignature(signature) {
  121. let node = signature.getDeclaration();
  122. // Handle signatures which don't have an actual declaration. This happens if a class
  123. // does not have an explicitly written constructor.
  124. if (!node) {
  125. return null;
  126. }
  127. while (!ts.isSourceFile(node = node.parent)) {
  128. if (ts.isClassDeclaration(node)) {
  129. return node;
  130. }
  131. }
  132. return null;
  133. }
  134. //# sourceMappingURL=constructor-signature-rule.js.map