Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(compiler): allow selector-less directives as base classes #31379

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions packages/compiler-cli/test/ngc_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2283,4 +2283,28 @@ describe('ngc transformer command-line', () => {
let exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
});

describe('base directives', () => {
it('should allow directives with no selector that are not in NgModules', () => {
// first only generate .d.ts / .js / .metadata.json files
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["main.ts"]
}`);
write('main.ts', `
import {Directive} from '@angular/core';

@Directive({})
export class BaseDir {}

@Directive({})
export abstract class AbstractBaseDir {}

@Directive()
export abstract class EmptyDir {}
`);
let exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);
});
});
});
26 changes: 23 additions & 3 deletions packages/compiler/src/aot/compiler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -797,6 +797,7 @@ export interface NgAnalyzedFileWithInjectables {
export interface NgAnalyzedFile {
fileName: string;
directives: StaticSymbol[];
abstractDirectives: StaticSymbol[];
pipes: StaticSymbol[];
ngModules: CompileNgModuleMetadata[];
injectables: CompileInjectableMetadata[];
Expand Down Expand Up @@ -857,18 +858,20 @@ function _analyzeFilesIncludingNonProgramFiles(
export function analyzeFile(
host: NgAnalyzeModulesHost, staticSymbolResolver: StaticSymbolResolver,
metadataResolver: CompileMetadataResolver, fileName: string): NgAnalyzedFile {
const abstractDirectives: StaticSymbol[] = [];
const directives: StaticSymbol[] = [];
const pipes: StaticSymbol[] = [];
const injectables: CompileInjectableMetadata[] = [];
const ngModules: CompileNgModuleMetadata[] = [];
const hasDecorators = staticSymbolResolver.hasDecorators(fileName);
let exportsNonSourceFiles = false;
const isDeclarationFile = fileName.endsWith('.d.ts');
// Don't analyze .d.ts files that have no decorators as a shortcut
// to speed up the analysis. This prevents us from
// resolving the references in these files.
// Note: exportsNonSourceFiles is only needed when compiling with summaries,
// which is not the case when .d.ts files are treated as input files.
if (!fileName.endsWith('.d.ts') || hasDecorators) {
if (!isDeclarationFile || hasDecorators) {
staticSymbolResolver.getSymbolsOf(fileName).forEach((symbol) => {
const resolvedSymbol = staticSymbolResolver.resolveSymbol(symbol);
const symbolMeta = resolvedSymbol.metadata;
Expand All @@ -879,7 +882,23 @@ export function analyzeFile(
if (symbolMeta.__symbolic === 'class') {
if (metadataResolver.isDirective(symbol)) {
isNgSymbol = true;
directives.push(symbol);
if (!isDeclarationFile) {
// This directive either has a selector or doesn't. Selector-less directives get tracked
// in abstractDirectives, not directives. The compiler doesn't deal with selector-less
// directives at all, really, other than to persist their metadata. This is done so that
// apps will have an easier time migrating to Ivy, which requires the selector-less
// annotations to be applied.
if (!metadataResolver.isAbstractDirective(symbol)) {
// The directive is an ordinary directive.
directives.push(symbol);
} else {
// The directive has no selector and is an "abstract" directive, so track it
// accordingly.
abstractDirectives.push(symbol);
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: Can we flip the ternary so it's not "if-not/else" ?

           if (metadataResolver.isAbstractDirective(symbol)) {
              abstractDirectives.push(symbol);
            } else {
              directives.push(symbol);
            }

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The general rule I try to use in the compiler is that for simple if-else blocks, the common case is the first branch. So in this case, most directives are plain directives and flow through the if section, and the else section handles the occasional abstract directive. That does make the conditional a little trickier to parse, though.

I added some extra comments to clarify the two bodies here :)

} else {
directives.push(symbol);
}
} else if (metadataResolver.isPipe(symbol)) {
isNgSymbol = true;
pipes.push(symbol);
Expand All @@ -904,7 +923,8 @@ export function analyzeFile(
});
}
return {
fileName, directives, pipes, ngModules, injectables, exportsNonSourceFiles,
fileName, directives, abstractDirectives, pipes,
ngModules, injectables, exportsNonSourceFiles,
};
}

Expand Down
27 changes: 22 additions & 5 deletions packages/compiler/src/metadata_resolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -348,11 +348,7 @@ export class CompileMetadataResolver {
} else {
// Directive
if (!selector) {
this._reportError(
syntaxError(
`Directive ${stringifyType(directiveType)} has no selector, please add it!`),
directiveType);
selector = 'error';
selector = null !;
}
}

Expand Down Expand Up @@ -432,6 +428,21 @@ export class CompileMetadataResolver {
this._directiveResolver.isDirective(type);
}

isAbstractDirective(type: any): boolean {
const summary =
this._loadSummary(type, cpl.CompileSummaryKind.Directive) as cpl.CompileDirectiveSummary;
if (summary && !summary.isComponent) {
return !summary.selector;
}

const meta = this._directiveResolver.resolve(type, false);
if (meta && !createComponent.isTypeOf(meta)) {
return !meta.selector;
}

return false;
}

isPipe(type: any) {
return !!this._loadSummary(type, cpl.CompileSummaryKind.Pipe) ||
this._pipeResolver.isPipe(type);
Expand Down Expand Up @@ -607,6 +618,12 @@ export class CompileMetadataResolver {
}
const declaredIdentifier = this._getIdentifierMetadata(declaredType);
if (this.isDirective(declaredType)) {
if (this.isAbstractDirective(declaredType)) {
this._reportError(
syntaxError(
`Directive ${stringifyType(declaredType)} has no selector, please add it!`),
declaredType);
}
transitiveModule.addDirective(declaredIdentifier);
declaredDirectives.push(declaredIdentifier);
this._addTypeToModule(declaredType, moduleType);
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/metadata/directives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,12 +68,12 @@ export interface DirectiveDecorator {
*
* @Annotation
*/
(obj: Directive): TypeDecorator;
(obj?: Directive): TypeDecorator;

/**
* See the `Directive` decorator.
*/
new (obj: Directive): Directive;
new (obj?: Directive): Directive;
}

/**
Expand Down
4 changes: 2 additions & 2 deletions tools/public_api_guard/core/core.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -297,8 +297,8 @@ export interface Directive {
export declare const Directive: DirectiveDecorator;

export interface DirectiveDecorator {
(obj: Directive): TypeDecorator;
new (obj: Directive): Directive;
(obj?: Directive): TypeDecorator;
new (obj?: Directive): Directive;
}

export interface DoBootstrap {
Expand Down