Skip to content
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
2 changes: 1 addition & 1 deletion integration/cli-hello-world-ivy/tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"angularCompilerOptions": {
"enableIvy": "ngtsc",
"enableIvy": true,
},
"compileOnSave": false,
"compilerOptions": {
Expand Down
2 changes: 1 addition & 1 deletion integration/ngcc/tsconfig-app.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,6 @@
"src/main.ts"
],
"angularCompilerOptions": {
"enableIvy": "ngtsc"
"enableIvy": true
}
}
2 changes: 1 addition & 1 deletion packages/bazel/src/ng_module.bzl
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def _enable_ivy_value(ctx):
if strategy == "legacy":
return False
elif strategy == "aot":
return "ngtsc"
return True
else:
fail("unreachable")

Expand Down
2 changes: 1 addition & 1 deletion packages/bazel/src/ngc-wrapped/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,7 @@ export function compile({allDepsCompiledWithBazel = true, compilerOpts, tsHost,
}

// Detect from compilerOpts whether the entrypoint is being invoked in Ivy mode.
const isInIvyMode = compilerOpts.enableIvy === 'ngtsc' || compilerOpts.enableIvy === 'tsc';
const isInIvyMode = compilerOpts.enableIvy === true || compilerOpts.enableIvy === 'tsc';

// Disable downleveling and Closure annotation if in Ivy mode.
if (isInIvyMode) {
Expand Down
4 changes: 2 additions & 2 deletions packages/compiler-cli/src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ export function mainDiagnosticsForTest(
}

function createEmitCallback(options: api.CompilerOptions): api.TsEmitCallback|undefined {
const transformDecorators = options.enableIvy !== 'ngtsc' && options.enableIvy !== 'tsc' &&
const transformDecorators = options.enableIvy !== true && options.enableIvy !== 'tsc' &&
options.annotationsAs !== 'decorators';
const transformTypesToClosure = options.annotateForClosureCompiler;
if (!transformDecorators && !transformTypesToClosure) {
Expand Down Expand Up @@ -173,7 +173,7 @@ function reportErrorsAndExit(
getCanonicalFileName: fileName => fileName,
getNewLine: () => ts.sys.newLine
};
if (options && (options.enableIvy === true || options.enableIvy === 'ngtsc')) {
if (options && options.enableIvy === true) {
const ngDiagnostics = errorsAndWarnings.filter(api.isNgDiagnostic);
const tsDiagnostics = errorsAndWarnings.filter(api.isTsDiagnostic);
consoleError(replaceTsWithNgInErrors(
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler-cli/src/transformers/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -192,7 +192,7 @@ export interface CompilerOptions extends ts.CompilerOptions {
*
* @publicApi
*/
enableIvy?: boolean|'ngtsc'|'tsc';
enableIvy?: boolean|'tsc';

/** @internal */
collectAllErrors?: boolean;
Expand Down
101 changes: 4 additions & 97 deletions packages/compiler-cli/src/transformers/program.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,18 +43,6 @@ const MAX_FILE_COUNT_FOR_SINGLE_FILE_EMIT = 20;
*/
const LOWER_FIELDS = ['useValue', 'useFactory', 'data', 'id', 'loadChildren'];

/**
* Fields to lower within metadata in render3 mode.
*/
const R3_LOWER_FIELDS = [...LOWER_FIELDS, 'providers', 'imports', 'exports'];

const R3_REIFIED_DECORATORS = [
'Component',
'Directive',
'Injectable',
'NgModule',
'Pipe',
];

const emptyModules: NgAnalyzedModules = {
ngModules: [],
Expand Down Expand Up @@ -110,7 +98,6 @@ class AngularCompilerProgram implements Program {
private _programWithStubs: ts.Program|undefined;
private _optionsDiagnostics: Diagnostic[] = [];
// TODO(issue/24571): remove '!'.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Remove this comment

private _reifiedDecorators !: Set<StaticSymbol>;

constructor(
rootNames: ReadonlyArray<string>, private options: CompilerOptions,
Expand Down Expand Up @@ -142,8 +129,7 @@ class AngularCompilerProgram implements Program {
}
}

this.loweringMetadataTransform =
new LowerMetadataTransform(options.enableIvy ? R3_LOWER_FIELDS : LOWER_FIELDS);
this.loweringMetadataTransform = new LowerMetadataTransform(LOWER_FIELDS);
this.metadataCache = this.createMetadataCache([this.loweringMetadataTransform]);
}

Expand Down Expand Up @@ -263,80 +249,10 @@ class AngularCompilerProgram implements Program {
emitCallback?: TsEmitCallback,
mergeEmitResultsCallback?: TsMergeEmitResultsCallback,
} = {}): ts.EmitResult {
if (this.options.enableIvy === 'ngtsc' || this.options.enableIvy === 'tsc') {
if (this.options.enableIvy === true || this.options.enableIvy === 'tsc') {
throw new Error('Cannot run legacy compiler in ngtsc mode');
}
return this.options.enableIvy === true ? this._emitRender3(parameters) :
this._emitRender2(parameters);
}

private _emitRender3(
{
emitFlags = EmitFlags.Default, cancellationToken, customTransformers,
emitCallback = defaultEmitCallback, mergeEmitResultsCallback = mergeEmitResults,
}: {
emitFlags?: EmitFlags,
cancellationToken?: ts.CancellationToken,
customTransformers?: CustomTransformers,
emitCallback?: TsEmitCallback,
mergeEmitResultsCallback?: TsMergeEmitResultsCallback,
} = {}): ts.EmitResult {
const emitStart = Date.now();
if ((emitFlags & (EmitFlags.JS | EmitFlags.DTS | EmitFlags.Metadata | EmitFlags.Codegen)) ===
0) {
return {emitSkipped: true, diagnostics: [], emittedFiles: []};
}

// analyzedModules and analyzedInjectables are created together. If one exists, so does the
// other.
const modules =
this.compiler.emitAllPartialModules(this.analyzedModules, this._analyzedInjectables !);

const writeTsFile: ts.WriteFileCallback =
(outFileName, outData, writeByteOrderMark, onError?, sourceFiles?) => {
const sourceFile = sourceFiles && sourceFiles.length == 1 ? sourceFiles[0] : null;
let genFile: GeneratedFile|undefined;
if (this.options.annotateForClosureCompiler && sourceFile &&
TS.test(sourceFile.fileName)) {
outData = nocollapseHack(outData);
}
this.writeFile(outFileName, outData, writeByteOrderMark, onError, undefined, sourceFiles);
};

const emitOnlyDtsFiles = (emitFlags & (EmitFlags.DTS | EmitFlags.JS)) == EmitFlags.DTS;

const tsCustomTransformers = this.calculateTransforms(
/* genFiles */ undefined, /* partialModules */ modules,
/* stripDecorators */ this.reifiedDecorators, customTransformers);


// Restore the original references before we emit so TypeScript doesn't emit
// a reference to the .d.ts file.
const augmentedReferences = new Map<ts.SourceFile, ReadonlyArray<ts.FileReference>>();
for (const sourceFile of this.tsProgram.getSourceFiles()) {
const originalReferences = getOriginalReferences(sourceFile);
if (originalReferences) {
augmentedReferences.set(sourceFile, sourceFile.referencedFiles);
sourceFile.referencedFiles = originalReferences;
}
}

try {
return emitCallback({
program: this.tsProgram,
host: this.host,
options: this.options,
writeFile: writeTsFile, emitOnlyDtsFiles,
customTransformers: tsCustomTransformers
});
} finally {
// Restore the references back to the augmented value to ensure that the
// checks that TypeScript makes for project structure reuse will succeed.
for (const [sourceFile, references] of Array.from(augmentedReferences)) {
// TODO(chuckj): Remove any cast after updating build to 2.6
(sourceFile as any).referencedFiles = references;
}
}
return this._emitRender2(parameters);
}

private _emitRender2(
Expand Down Expand Up @@ -557,15 +473,6 @@ class AngularCompilerProgram implements Program {
return this._tsProgram !;
}

private get reifiedDecorators(): Set<StaticSymbol> {
if (!this._reifiedDecorators) {
const reflector = this.compiler.reflector;
this._reifiedDecorators = new Set(
R3_REIFIED_DECORATORS.map(name => reflector.findDeclaration('@angular/core', name)));
}
return this._reifiedDecorators;
}

private calculateTransforms(
genFiles: Map<string, GeneratedFile>|undefined, partialModules: PartialModule[]|undefined,
stripDecorators: Set<StaticSymbol>|undefined,
Expand Down Expand Up @@ -899,7 +806,7 @@ export function createProgram({rootNames, options, host, oldProgram}: {
options: CompilerOptions,
host: CompilerHost, oldProgram?: Program
}): Program {
if (options.enableIvy === 'ngtsc') {
if (options.enableIvy === true) {
return new NgtscProgram(rootNames, options, host, oldProgram);
} else if (options.enableIvy === 'tsc') {
return new TscPassThroughProgram(rootNames, options, host, oldProgram);
Expand Down
86 changes: 0 additions & 86 deletions packages/compiler-cli/test/ngc_spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2307,92 +2307,6 @@ describe('ngc transformer command-line', () => {
});
});

describe('ngInjectorDef', () => {
it('is applied with lowered metadata', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["module.ts"],
"angularCompilerOptions": {
"enableIvy": true,
"skipTemplateCodegen": true
}
}`);
write('module.ts', `
import {Injectable, NgModule} from '@angular/core';

@Injectable()
export class ServiceA {}

@Injectable()
export class ServiceB {}

@NgModule()
export class Exported {}

@NgModule({
providers: [ServiceA]
})
export class Imported {
static forRoot() {
console.log('not statically analyzable');
return {
ngModule: Imported,
providers: [] as any,
};
}
}

@NgModule({
providers: [ServiceA, ServiceB],
imports: [Imported.forRoot()],
exports: [Exported],
})
export class Module {}
`);

const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);

const modulePath = path.resolve(outDir, 'module.js');
const moduleSource = fs.readFileSync(modulePath, 'utf8');
expect(moduleSource)
.toContain('var ɵ1 = [ServiceA, ServiceB], ɵ2 = [Imported.forRoot()], ɵ3 = [Exported];');
expect(moduleSource)
.toContain(
'Imported.ngInjectorDef = i0.defineInjector({ factory: function Imported_Factory() { return new Imported(); }, providers: ɵ0, imports: [] });');
expect(moduleSource)
.toContain(
'Module.ngInjectorDef = i0.defineInjector({ factory: function Module_Factory() { return new Module(); }, providers: ɵ1, imports: [ɵ2, ɵ3] });');
});

it('rewrites Injector to INJECTOR in Ivy factory functions ', () => {
writeConfig(`{
"extends": "./tsconfig-base.json",
"files": ["service.ts"],
"angularCompilerOptions": {
"enableIvy": true
}
}`);

write('service.ts', `
import {Injectable, Injector} from '@angular/core';

@Injectable()
export class Service {
constructor(private injector: Injector) {}
}
`);

const exitCode = main(['-p', path.join(basePath, 'tsconfig.json')], errorSpy);
expect(exitCode).toEqual(0);

const modulePath = path.resolve(outDir, 'service.js');
const moduleSource = fs.readFileSync(modulePath, 'utf8');
expect(moduleSource).not.toMatch(/inject\(i0\.Injector/);
expect(moduleSource).toMatch(/inject\(i0\.INJECTOR/);
});
});

it('libraries should not break strictMetadataEmit', () => {
// first only generate .d.ts / .js / .metadata.json files
writeConfig(`{
Expand Down
4 changes: 2 additions & 2 deletions packages/compiler-cli/test/ngtsc/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ export class NgtscTestEnvironment {
"typeRoots": ["node_modules/@types"]
},
"angularCompilerOptions": {
"enableIvy": "ngtsc"
"enableIvy": true
}
}`);

Expand Down Expand Up @@ -97,7 +97,7 @@ export class NgtscTestEnvironment {
write(fileName: string, content: string) { this.support.write(fileName, content); }

tsconfig(extraOpts: {[key: string]: string | boolean} = {}): void {
const opts = JSON.stringify({...extraOpts, 'enableIvy': 'ngtsc'});
const opts = JSON.stringify({...extraOpts, 'enableIvy': true});
const tsconfig: string =
`{"extends": "./tsconfig-base.json", "angularCompilerOptions": ${opts}}`;
this.write('tsconfig.json', tsconfig);
Expand Down
Loading