Skip to content

Commit

Permalink
feat(dev-infra):: add lint rule to enforce no-implicit-override abstr…
Browse files Browse the repository at this point in the history
…act members

TypeScript introduced a new flag called `noImplicitOverride` as part
of TypeScript v4.3. This flag introduces a new keyword called `override`
that can be applied to members which override declarations from a base
class. This helps with code health as TS will report an error if e.g.
the base class changes the method name but the override would still
have the old method name. Similarly, if the base class removes the method
completely, TS would complain that the memeber with `override` no longer
overrides any method.

A similar concept applies to abstract methods, with the exception that
TypeScript's builtin `noImplicitOverride` option does not flag members
which are implemented as part of an abstract class. We want to enforce
this as a best-practice in the repository as adding `override` to such
implemented members will cause TS to complain if an abstract member is
removed, but still implemented by derived classes.

More details: microsoft/TypeScript#44457.
  • Loading branch information
devversion committed Jul 8, 2021
1 parent 7f93e25 commit d778f46
Show file tree
Hide file tree
Showing 7 changed files with 206 additions and 4 deletions.
1 change: 1 addition & 0 deletions dev-infra/BUILD.bazel
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pkg_npm(
"//dev-infra/benchmark/driver-utilities",
"//dev-infra/commit-message",
"//dev-infra/ts-circular-dependencies",
"//dev-infra/tslint-rules",
],
)

Expand Down
13 changes: 13 additions & 0 deletions dev-infra/tslint-rules/BUILD.bazel
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
load("@npm//@bazel/typescript:index.bzl", "ts_library")

ts_library(
name = "tslint-rules",
srcs = glob(["*.ts"]),
module_name = "@angular/dev-infra-private/tslint-rules",
visibility = ["//dev-infra:__subpackages__"],
deps = [
"@npm//tslib",
"@npm//tslint",
"@npm//typescript",
],
)
145 changes: 145 additions & 0 deletions dev-infra/tslint-rules/noImplicitOverrideAbstractRule.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,145 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

import {Replacement, RuleFailure, WalkContext} from 'tslint/lib';
import {TypedRule} from 'tslint/lib/rules';
import * as ts from 'typescript';

const FAILURE_MESSAGE = 'Missing override modifier. Members implemented as part of ' +
'abstract classes must explicitly set the "override" modifier. ' +
'More details: https://github.com/microsoft/TypeScript/issues/44457#issuecomment-856202843.';

/**
* Rule which enforces that class members implementing abstract members
* from base classes explicitly specify the `override` modifier.
*
* This ensures we follow the best-practice of applying `override` for abstract-implemented
* members so that TypeScript creates diagnostics in both scenarios where either the abstract
* class member is removed, or renamed.
*
* More details can be found here: https://github.com/microsoft/TypeScript/issues/44457.
*/
export class Rule extends TypedRule {
override applyWithProgram(sourceFile: ts.SourceFile, program: ts.Program): RuleFailure[] {
return this.applyWithFunction(sourceFile, ctx => visitNode(sourceFile, ctx, program));
}
}

/**
* For a TypeScript AST node and each of its child nodes, check whether the node is a class
* element which implements an abstract member but does not have the `override` keyword.
*/
function visitNode(node: ts.Node, ctx: WalkContext, program: ts.Program) {
// If a class element implements an abstract member but does not have the
// `override` keyword, create a lint failure.
if (ts.isClassElement(node) && !hasOverrideModifier(node) &&
matchesParentAbstractElement(node, program)) {
ctx.addFailureAtNode(
node, FAILURE_MESSAGE, Replacement.appendText(node.getStart(), `override `));
}

ts.forEachChild(node, node => visitNode(node, ctx, program));
}

/**
* Checks if the specified class element matches a parent abstract class element. i.e.
* whether the specified member "implements" an abstract member from a base class.
*/
function matchesParentAbstractElement(node: ts.ClassElement, program: ts.Program): boolean {
const containingClass = node.parent as ts.ClassDeclaration;

// If the property we check does not have a property name, we cannot look for similarly-named
// members in parent classes and therefore return early.
if (node.name === undefined) {
return false;
}

const propertyName = getPropertyNameText(node.name);
const typeChecker = program.getTypeChecker();

// If the property we check does not have a statically-analyzable property name,
// we cannot look for similarly-named members in parent classes and return early.
if (propertyName === null) {
return false;
}

return checkClassForInheritedMatchingAbstractMember(containingClass, typeChecker, propertyName);
}

/** Checks if the given class inherits an abstract member with the specified name. */
function checkClassForInheritedMatchingAbstractMember(
clazz: ts.ClassDeclaration, typeChecker: ts.TypeChecker, searchMemberName: string): boolean {
const baseClass = getBaseClass(clazz, typeChecker);

// If the class is not `abstract`, then all parent abstract methods would need to
// be implemented, and there is never an abstract member within the class.
if (baseClass === null || !hasAbstractModifier(baseClass)) {
return false;
}

const matchingMember = baseClass.members.find(
m => m.name !== undefined && getPropertyNameText(m.name) === searchMemberName);

if (matchingMember !== undefined) {
return hasAbstractModifier(matchingMember);
}

return checkClassForInheritedMatchingAbstractMember(baseClass, typeChecker, searchMemberName);
}

/** Gets the base class for the given class declaration. */
function getBaseClass(node: ts.ClassDeclaration, typeChecker: ts.TypeChecker): ts.ClassDeclaration|
null {
const baseTypes = getExtendsHeritageExpressions(node);

if (baseTypes.length > 1) {
throw Error('Class unexpectedly extends from multiple types.');
}

const baseClass = typeChecker.getTypeAtLocation(baseTypes[0]).getSymbol();
const baseClassDecl = baseClass?.valueDeclaration ?? baseClass?.declarations?.[0];

if (baseClassDecl !== undefined && ts.isClassDeclaration(baseClassDecl)) {
return baseClassDecl;
}

return null;
}

/** Gets the `extends` base type expressions of the specified class. */
function getExtendsHeritageExpressions(classDecl: ts.ClassDeclaration):
ts.ExpressionWithTypeArguments[] {
if (classDecl.heritageClauses === undefined) {
return [];
}
const result: ts.ExpressionWithTypeArguments[] = [];
for (const clause of classDecl.heritageClauses) {
if (clause.token === ts.SyntaxKind.ExtendsKeyword) {
result.push(...clause.types);
}
}
return result;
}

/** Gets whether the specified node has the `abstract` modifier applied. */
function hasAbstractModifier(node: ts.Node): boolean {
return !!node.modifiers?.some(s => s.kind === ts.SyntaxKind.AbstractKeyword);
}

/** Gets whether the specified node has the `override` modifier applied. */
function hasOverrideModifier(node: ts.Node): boolean {
return !!node.modifiers?.some(s => s.kind === ts.SyntaxKind.OverrideKeyword);
}

/** Gets the property name text of the specified property name. */
function getPropertyNameText(name: ts.PropertyName): string|null {
if (ts.isComputedPropertyName(name)) {
return null;
}
return name.text;
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
"test-fixme-ivy-aot": "bazelisk test --config=ivy --build_tag_filters=-no-ivy-aot --test_tag_filters=-no-ivy-aot",
"list-fixme-ivy-targets": "bazelisk query --output=label 'attr(\"tags\", \"\\[.*fixme-ivy.*\\]\", //...) except kind(\"sh_binary\", //...) except kind(\"devmode_js_sources\", //...)' | sort",
"lint": "yarn -s tslint && yarn -s ng-dev format changed --check",
"tslint": "tsc -p tools/tsconfig.json && tslint -c tslint.json \"+(dev-infra|packages|modules|scripts|tools)/**/*.+(js|ts)\"",
"tslint": "tslint -c tslint.json --project tsconfig-tslint.json",
"public-api:check": "node goldens/public-api/manage.js test",
"public-api:update": "node goldens/public-api/manage.js accept",
"symbol-extractor:check": "node tools/symbol-extractor/run_all_symbols_extractor_tests.js test",
Expand Down
19 changes: 19 additions & 0 deletions tools/tslint/tsNodeLoaderRule.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/

const path = require('path');
const Lint = require('tslint');

// Custom rule that registers all of the custom rules, written in TypeScript, with ts-node.
// This is necessary, because `tslint` and IDEs won't execute any rules that aren't in a .js file.
require('ts-node').register();

// Add a noop rule so tslint doesn't complain.
exports.Rule = class Rule extends Lint.Rules.AbstractRule {
apply() {}
};
12 changes: 12 additions & 0 deletions tsconfig-tslint.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
{
"compilerOptions": {
"allowJs": true
},
"include": [
"dev-infra/**/*",
"packages/**/*",
"modules/**/*",
"tools/**/*",
"scripts/**/*"
]
}
18 changes: 15 additions & 3 deletions tslint.json
Original file line number Diff line number Diff line change
@@ -1,11 +1,19 @@
{
"rulesDirectory": [
"dist/tools/tslint",
"tools/tslint",
"dev-infra/tslint-rules",
"node_modules/vrsource-tslint-rules/rules",
"node_modules/tslint-eslint-rules/dist/rules",
"node_modules/tslint-no-toplevel-property-access/rules"
],
"rules": {
// The first rule needs to be `ts-node-loader` which sets up `ts-node` within TSLint so
// that rules written in TypeScript can be loaded without needing to be transpiled.
"ts-node-loader": true,
// Custom rules written in TypeScript.
"require-internal-with-underscore": true,
"no-implicit-override-abstract": true,

"eofline": true,
"file-header": [
true,
Expand All @@ -26,7 +34,6 @@
true,
"object"
],
"require-internal-with-underscore": true,
"no-toplevel-property-access": [
true,
"packages/animations/src/",
Expand Down Expand Up @@ -57,6 +64,12 @@
]
},
"jsRules": {
// The first rule needs to be `ts-node-loader` which sets up `ts-node` within TSLint so
// that rules written in TypeScript can be loaded without needing to be transpiled.
"ts-node-loader": true,
// Custom rules written in TypeScript.
"require-internal-with-underscore": true,

"eofline": true,
"file-header": [
true,
Expand All @@ -71,7 +84,6 @@
],
"no-duplicate-imports": true,
"no-duplicate-variable": true,
"require-internal-with-underscore": true,
"semicolon": [
true
],
Expand Down

0 comments on commit d778f46

Please sign in to comment.