style(compiler): reformat of codebase with new clang-format version (#36520)

This commit reformats the packages/compiler tree using the new version of
clang-format.

PR Close #36520
This commit is contained in:
Alex Rickabaugh
2020-04-08 10:14:18 -07:00
committed by atscott
parent d5aa6b5bd6
commit cbed582a1a
193 changed files with 5904 additions and 4574 deletions

View File

@ -13,7 +13,7 @@ import {extractSourceMap, originalPositionFor} from '@angular/compiler/testing/s
import {NodeFlags} from '@angular/core/src/view/index';
import * as ts from 'typescript';
import {EmittingCompilerHost, MockAotCompilerHost, MockCompilerHost, MockDirectory, MockMetadataBundlerHost, arrayToMockDir, compile, expectNoDiagnostics, isInBazel, settings, setup, toMockFileArray} from './test_util';
import {arrayToMockDir, compile, EmittingCompilerHost, expectNoDiagnostics, isInBazel, MockAotCompilerHost, MockCompilerHost, MockDirectory, MockMetadataBundlerHost, settings, setup, toMockFileArray} from './test_util';
describe('compiler (unbundled Angular)', () => {
let angularFiles = setup();
@ -53,11 +53,11 @@ describe('compiler (unbundled Angular)', () => {
function compileApp(): GeneratedFile {
const {genFiles} = compile([rootDir, angularFiles]);
return genFiles.find(
genFile => genFile.srcFileUrl === componentPath && genFile.genFileUrl.endsWith('.ts')) !;
genFile => genFile.srcFileUrl === componentPath && genFile.genFileUrl.endsWith('.ts'))!;
}
function findLineAndColumn(
file: string, token: string): {line: number | null, column: number | null} {
file: string, token: string): {line: number|null, column: number|null} {
const index = file.indexOf(token);
if (index === -1) {
return {line: null, column: null};
@ -84,7 +84,9 @@ describe('compiler (unbundled Angular)', () => {
describe('inline templates', () => {
const ngUrl = `${componentPath}.AppComponent.html`;
function templateDecorator(template: string) { return `template: \`${template}\`,`; }
function templateDecorator(template: string) {
return `template: \`${template}\`,`;
}
declareTests({ngUrl, templateDecorator});
});
@ -125,7 +127,7 @@ describe('compiler (unbundled Angular)', () => {
const genFile = compileApp();
const genSource = toTypeScript(genFile);
const sourceMap = extractSourceMap(genSource) !;
const sourceMap = extractSourceMap(genSource)!;
expect(sourceMap.file).toEqual(genFile.genFileUrl);
// Note: the generated file also contains code that is not mapped to
@ -146,7 +148,7 @@ describe('compiler (unbundled Angular)', () => {
const genFile = compileApp();
const genSource = toTypeScript(genFile);
const sourceMap = extractSourceMap(genSource) !;
const sourceMap = extractSourceMap(genSource)!;
expect(originalPositionFor(sourceMap, findLineAndColumn(genSource, `'span'`)))
.toEqual({line: 2, column: 3, source: ngUrl});
});
@ -158,7 +160,7 @@ describe('compiler (unbundled Angular)', () => {
const genFile = compileApp();
const genSource = toTypeScript(genFile);
const sourceMap = extractSourceMap(genSource) !;
const sourceMap = extractSourceMap(genSource)!;
expect(originalPositionFor(sourceMap, findLineAndColumn(genSource, `someMethod()`)))
.toEqual({line: 2, column: 9, source: ngUrl});
});
@ -170,7 +172,7 @@ describe('compiler (unbundled Angular)', () => {
const genFile = compileApp();
const genSource = toTypeScript(genFile);
const sourceMap = extractSourceMap(genSource) !;
const sourceMap = extractSourceMap(genSource)!;
expect(originalPositionFor(sourceMap, findLineAndColumn(genSource, `someMethod()`)))
.toEqual({line: 2, column: 9, source: ngUrl});
});
@ -180,7 +182,7 @@ describe('compiler (unbundled Angular)', () => {
const genFile = compileApp();
const genSource = toTypeScript(genFile);
const sourceMap = extractSourceMap(genSource) !;
const sourceMap = extractSourceMap(genSource)!;
expect(originalPositionFor(sourceMap, {line: 1, column: 0}))
.toEqual({line: 1, column: 0, source: ngFactoryPath});
});
@ -205,7 +207,6 @@ describe('compiler (unbundled Angular)', () => {
compile([FILES, angularFiles]);
expect(warnSpy).toHaveBeenCalledWith(
`Warning: Can't resolve all parameters for MyService in /app/app.ts: (?). This will become an error in Angular v6.x`);
});
it('should error if not all arguments of an @Injectable class can be resolved if strictInjectionParameters is true',
@ -279,7 +280,7 @@ describe('compiler (unbundled Angular)', () => {
};
compile([FILES, angularFiles], {
postCompile: program => {
const factorySource = program.getSourceFile('/app/app.ngfactory.ts') !;
const factorySource = program.getSourceFile('/app/app.ngfactory.ts')!;
expect(factorySource.text).not.toContain('\'/app/app.ngfactory\'');
}
});
@ -321,7 +322,7 @@ describe('compiler (unbundled Angular)', () => {
const genFilePreamble = '/* Hello world! */';
const {genFiles} = compile([FILES, angularFiles]);
const genFile =
genFiles.find(gf => gf.srcFileUrl === '/app/app.ts' && gf.genFileUrl.endsWith('.ts')) !;
genFiles.find(gf => gf.srcFileUrl === '/app/app.ts' && gf.genFileUrl.endsWith('.ts'))!;
const genSource = toTypeScript(genFile, genFilePreamble);
expect(genSource.startsWith(genFilePreamble)).toBe(true);
});
@ -445,9 +446,9 @@ describe('compiler (unbundled Angular)', () => {
}
};
const {genFiles} = compile([FILES, angularFiles]);
const genFile = genFiles.find(genFile => genFile.srcFileUrl === '/app/app.ts') !;
const genFile = genFiles.find(genFile => genFile.srcFileUrl === '/app/app.ts')!;
const genSource = toTypeScript(genFile);
const createComponentFactoryCall = /ɵccf\([^)]*\)/m.exec(genSource) ![0].replace(/\s*/g, '');
const createComponentFactoryCall = /ɵccf\([^)]*\)/m.exec(genSource)![0].replace(/\s*/g, '');
// selector
expect(createComponentFactoryCall).toContain('my-comp');
// inputs
@ -476,10 +477,9 @@ describe('compiler (unbundled Angular)', () => {
};
const {genFiles} = compile([FILES, angularFiles]);
const genFile =
genFiles.find(gf => gf.srcFileUrl === '/app/app.ts' && gf.genFileUrl.endsWith('.ts')) !;
genFiles.find(gf => gf.srcFileUrl === '/app/app.ts' && gf.genFileUrl.endsWith('.ts'))!;
const genSource = toTypeScript(genFile);
expect(genSource).not.toContain('check(');
});
});
@ -492,7 +492,6 @@ describe('compiler (unbundled Angular)', () => {
inheritanceWithSummariesSpecs(() => angularSummaryFiles);
describe('external symbol re-exports enabled', () => {
it('should not reexport type symbols mentioned in constructors', () => {
const libInput: MockDirectory = {
'lib': {
@ -520,7 +519,7 @@ describe('compiler (unbundled Angular)', () => {
const {genFiles: appGenFiles} = compile(
[appInput, libOutDir, angularSummaryFiles],
{useSummaries: true, createExternalSymbolFactoryReexports: true});
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts') !;
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts')!;
const appNgFactoryTs = toTypeScript(appNgFactory);
expect(appNgFactoryTs).not.toContain('AType');
expect(appNgFactoryTs).toContain('AValue');
@ -570,7 +569,7 @@ describe('compiler (unbundled Angular)', () => {
const {genFiles: appGenFiles} = compile(
[appInput, libOutDir, angularSummaryFiles],
{useSummaries: true, createExternalSymbolFactoryReexports: true});
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts') !;
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts')!;
const appNgFactoryTs = toTypeScript(appNgFactory);
// metadata of ctor calls is preserved, so we reexport the argument
@ -614,7 +613,7 @@ describe('compiler (unbundled Angular)', () => {
const {genFiles: appGenFiles} = compile(
[appInput, libOutDir, angularSummaryFiles],
{useSummaries: true, createExternalSymbolFactoryReexports: true});
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts') !;
const appNgFactory = appGenFiles.find((f) => f.genFileUrl === '/app/main.ngfactory.ts')!;
const appNgFactoryTs = toTypeScript(appNgFactory);
// we don't need to reexport exported symbols via the .ngfactory
@ -707,7 +706,7 @@ describe('compiler (unbundled Angular)', () => {
compile([libInput, getAngularSummaryFiles()], {useSummaries: true});
const {genFiles} =
compile([libOutDir, appInput, getAngularSummaryFiles()], {useSummaries: true});
const mainNgFactory = genFiles.find(gf => gf.srcFileUrl === '/app/main.ts') !;
const mainNgFactory = genFiles.find(gf => gf.srcFileUrl === '/app/main.ts')!;
const flags = NodeFlags.TypeDirective | NodeFlags.Component | NodeFlags.OnDestroy;
expect(toTypeScript(mainNgFactory))
.toContain(`${flags},(null as any),0,i1.Extends,[i2.AParam]`);
@ -761,7 +760,7 @@ describe('compiler (unbundled Angular)', () => {
const {genFiles} = compile(
[lib1OutDir, lib2OutDir, appInput, getAngularSummaryFiles()], {useSummaries: true});
const mainNgFactory = genFiles.find(gf => gf.srcFileUrl === '/app/main.ts') !;
const mainNgFactory = genFiles.find(gf => gf.srcFileUrl === '/app/main.ts')!;
const flags = NodeFlags.TypeDirective | NodeFlags.Component | NodeFlags.OnDestroy;
const mainNgFactorySource = toTypeScript(mainNgFactory);
expect(mainNgFactorySource).toContain(`import * as i2 from '/lib1/base';`);

View File

@ -8,7 +8,7 @@
import {AotCompiler, AotCompilerHost, AotCompilerOptions, CompileSummaryKind, GeneratedFile, toTypeScript} from '@angular/compiler';
import {MockDirectory, compile, setup} from './test_util';
import {compile, MockDirectory, setup} from './test_util';
describe('aot summaries for jit', () => {
let angularFiles = setup();
@ -19,7 +19,7 @@ describe('aot summaries for jit', () => {
});
function compileApp(
rootDir: MockDirectory, options: {useSummaries?: boolean}& AotCompilerOptions = {}):
rootDir: MockDirectory, options: {useSummaries?: boolean}&AotCompilerOptions = {}):
{genFiles: GeneratedFile[], outDir: MockDirectory} {
return compile(
[rootDir, options.useSummaries ? angularSummaryFiles : angularFiles],
@ -42,7 +42,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toContain(`import * as i0 from '/app/app.module'`);
@ -71,7 +71,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toContain(`import * as i0 from '/app/app.module'`);
@ -100,7 +100,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toContain(`import * as i0 from '/app/app.module'`);
@ -126,7 +126,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toContain(`import * as i0 from '/app/app.module'`);
@ -165,7 +165,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toMatch(/useClass:\{\s*reference:i1.MyService/);
@ -199,7 +199,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toMatch(/useClass:\{\s*reference:i1.MyService/);
@ -226,7 +226,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toMatch(
@ -248,7 +248,7 @@ describe('aot summaries for jit', () => {
const rootDir = {'app': appDir};
const genFile =
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts') !;
compileApp(rootDir).genFiles.find(f => f.genFileUrl === '/app/app.module.ngsummary.ts')!;
const genSource = toTypeScript(genFile);
expect(genSource).toMatch(
@ -301,10 +301,9 @@ describe('aot summaries for jit', () => {
createExternalSymbolFactoryReexports: true,
});
const lib2ModuleNgSummary =
lib2Gen.find(f => f.genFileUrl === '/lib2/module.ngsummary.ts') !;
const lib2ModuleNgSummary = lib2Gen.find(f => f.genFileUrl === '/lib2/module.ngsummary.ts')!;
const lib2ReexportNgSummary =
lib2Gen.find(f => f.genFileUrl === '/lib2/reexport.ngsummary.ts') !;
lib2Gen.find(f => f.genFileUrl === '/lib2/reexport.ngsummary.ts')!;
// ngsummaries should add reexports for imported NgModules from a direct dependency
expect(toTypeScript(lib2ModuleNgSummary))
@ -336,10 +335,9 @@ describe('aot summaries for jit', () => {
useSummaries: true,
createExternalSymbolFactoryReexports: true
}).genFiles;
const lib3ModuleNgSummary =
lib3Gen.find(f => f.genFileUrl === '/lib3/module.ngsummary.ts') !;
const lib3ModuleNgSummary = lib3Gen.find(f => f.genFileUrl === '/lib3/module.ngsummary.ts')!;
const lib3ReexportNgSummary =
lib3Gen.find(f => f.genFileUrl === '/lib3/reexport.ngsummary.ts') !;
lib3Gen.find(f => f.genFileUrl === '/lib3/reexport.ngsummary.ts')!;
// ngsummary.ts files should use the reexported values from direct and deep deps
const lib3ModuleNgSummarySource = toTypeScript(lib3ModuleNgSummary);
@ -398,9 +396,9 @@ describe('aot summaries for jit', () => {
const {outDir: lib2Out, genFiles: lib2Gen} = compileApp(lib2In, {useSummaries: true});
const lib2ModuleNgSummary = lib2Gen.find(f => f.genFileUrl === '/lib2/module.ngsummary.ts') !;
const lib2ModuleNgSummary = lib2Gen.find(f => f.genFileUrl === '/lib2/module.ngsummary.ts')!;
const lib2ReexportNgSummary =
lib2Gen.find(f => f.genFileUrl === '/lib2/reexport.ngsummary.ts') !;
lib2Gen.find(f => f.genFileUrl === '/lib2/reexport.ngsummary.ts')!;
// ngsummaries should not add reexports by default for imported NgModules from a direct
// dependency
@ -435,9 +433,9 @@ describe('aot summaries for jit', () => {
};
const lib3Gen = compileApp(lib3In, {useSummaries: true}).genFiles;
const lib3ModuleNgSummary = lib3Gen.find(f => f.genFileUrl === '/lib3/module.ngsummary.ts') !;
const lib3ModuleNgSummary = lib3Gen.find(f => f.genFileUrl === '/lib3/module.ngsummary.ts')!;
const lib3ReexportNgSummary =
lib3Gen.find(f => f.genFileUrl === '/lib3/reexport.ngsummary.ts') !;
lib3Gen.find(f => f.genFileUrl === '/lib3/reexport.ngsummary.ts')!;
// ngsummary.ts files should use the external symbols which are manually re-exported from
// "lib2" from their original symbol location. With re-exported external symbols this would

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {MockDirectory, compile, expectNoDiagnostics, setup} from './test_util';
import {compile, expectNoDiagnostics, MockDirectory, setup} from './test_util';
describe('regressions', () => {
let angularFiles = setup();

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, StaticSymbolResolverHost, core as compilerCore} from '@angular/compiler';
import {core as compilerCore, StaticReflector, StaticSymbol, StaticSymbolCache, StaticSymbolResolver, StaticSymbolResolverHost} from '@angular/compiler';
import {CollectorOptions, METADATA_VERSION} from '@angular/compiler-cli';
import {MockStaticSymbolResolverHost, MockSummaryResolver} from './static_symbol_resolver_spec';
@ -358,7 +358,7 @@ describe('StaticReflector', () => {
it('should record data about the error in the exception', () => {
let threw = false;
try {
const metadata = host.getMetadataFor('/tmp/src/invalid-metadata.ts') !;
const metadata = host.getMetadataFor('/tmp/src/invalid-metadata.ts')!;
expect(metadata).toBeDefined();
const moduleMetadata: any = metadata[0]['metadata'];
expect(moduleMetadata).toBeDefined();
@ -1334,10 +1334,9 @@ const DEFAULT_TEST_DATA: {[key: string]: any} = {
'decorators': [{
'__symbolic': 'call',
'expression': {'__symbolic': 'reference', 'name': 'Directive', 'module': '@angular/core'},
'arguments': [{
'selector': '[ngFor][ngForOf]',
'inputs': ['ngForTrackBy', 'ngForOf', 'ngForTemplate']
}]
'arguments': [
{'selector': '[ngFor][ngForOf]', 'inputs': ['ngForTrackBy', 'ngForOf', 'ngForTemplate']}
]
}],
'members': {
'__ctor__': [{
@ -1345,11 +1344,8 @@ const DEFAULT_TEST_DATA: {[key: string]: any} = {
'parameters': [
{'__symbolic': 'reference', 'module': '@angular/core', 'name': 'ViewContainerRef'},
{'__symbolic': 'reference', 'module': '@angular/core', 'name': 'TemplateRef'},
{'__symbolic': 'reference', 'module': '@angular/core', 'name': 'IterableDiffers'}, {
'__symbolic': 'reference',
'module': '@angular/core',
'name': 'ChangeDetectorRef'
}
{'__symbolic': 'reference', 'module': '@angular/core', 'name': 'IterableDiffers'},
{'__symbolic': 'reference', 'module': '@angular/core', 'name': 'ChangeDetectorRef'}
]
}]
}
@ -1387,8 +1383,7 @@ const DEFAULT_TEST_DATA: {[key: string]: any} = {
'__symbolic': 'property',
'decorators': [{
'__symbolic': 'call',
'expression':
{'__symbolic': 'reference', 'name': 'Input', 'module': '@angular/core'}
'expression': {'__symbolic': 'reference', 'name': 'Input', 'module': '@angular/core'}
}]
}],
'onMouseOver': [{

View File

@ -19,7 +19,9 @@ describe('StaticSymbolResolver', () => {
let symbolResolver: StaticSymbolResolver;
let symbolCache: StaticSymbolCache;
beforeEach(() => { symbolCache = new StaticSymbolCache(); });
beforeEach(() => {
symbolCache = new StaticSymbolCache();
});
function init(
testData: {[key: string]: any} = DEFAULT_TEST_DATA, summaries: Summary<StaticSymbol>[] = [],
@ -36,7 +38,8 @@ describe('StaticSymbolResolver', () => {
() => symbolResolver.resolveSymbol(
symbolResolver.getSymbolByModule('src/version-error', 'e')))
.toThrow(new Error(
`Metadata version mismatch for module /tmp/src/version-error.d.ts, found version 100, expected ${METADATA_VERSION}`));
`Metadata version mismatch for module /tmp/src/version-error.d.ts, found version 100, expected ${
METADATA_VERSION}`));
});
it('should throw an exception for version 2 metadata', () => {
@ -159,7 +162,6 @@ describe('StaticSymbolResolver', () => {
});
describe('importAs', () => {
it('should calculate importAs relationship for non source files without summaries', () => {
init(
{
@ -241,7 +243,6 @@ describe('StaticSymbolResolver', () => {
expect(symbolResolver.getImportAs(symbolCache.get('/test2.d.ts', 'a', ['someMember'])))
.toBe(symbolCache.get('/test3.d.ts', 'b', ['someMember']));
});
});
it('should replace references by StaticSymbols', () => {
@ -345,10 +346,9 @@ describe('StaticSymbolResolver', () => {
__symbolic: 'class',
arity: 1,
members: {
__ctor__: [{
__symbolic: 'constructor',
parameters: [symbolCache.get('/test.d.ts', 'AParam')]
}]
__ctor__: [
{__symbolic: 'constructor', parameters: [symbolCache.get('/test.d.ts', 'AParam')]}
]
}
}
}
@ -423,7 +423,6 @@ describe('StaticSymbolResolver', () => {
expect(symbol.name).toEqual('One');
expect(symbol.filePath).toEqual('/tmp/src/reexport/src/origin1.d.ts');
});
});
export class MockSummaryResolver implements SummaryResolver<StaticSymbol> {
@ -431,9 +430,11 @@ export class MockSummaryResolver implements SummaryResolver<StaticSymbol> {
symbol: StaticSymbol,
importAs: StaticSymbol
}[] = []) {}
addSummary(summary: Summary<StaticSymbol>) { this.summaries.push(summary); }
addSummary(summary: Summary<StaticSymbol>) {
this.summaries.push(summary);
}
resolveSummary(reference: StaticSymbol): Summary<StaticSymbol> {
return this.summaries.find(summary => summary.symbol === reference) !;
return this.summaries.find(summary => summary.symbol === reference)!;
}
getSymbolsOf(filePath: string): StaticSymbol[]|null {
const symbols = this.summaries.filter(summary => summary.symbol.filePath === filePath)
@ -442,12 +443,20 @@ export class MockSummaryResolver implements SummaryResolver<StaticSymbol> {
}
getImportAs(symbol: StaticSymbol): StaticSymbol {
const entry = this.importAs.find(entry => entry.symbol === symbol);
return entry ? entry.importAs : undefined !;
return entry ? entry.importAs : undefined!;
}
getKnownModuleName(fileName: string): string|null {
return null;
}
isLibraryFile(filePath: string): boolean {
return filePath.endsWith('.d.ts');
}
toSummaryFileName(filePath: string): string {
return filePath.replace(/(\.d)?\.ts$/, '.d.ts');
}
fromSummaryFileName(filePath: string): string {
return filePath;
}
getKnownModuleName(fileName: string): string|null { return null; }
isLibraryFile(filePath: string): boolean { return filePath.endsWith('.d.ts'); }
toSummaryFileName(filePath: string): string { return filePath.replace(/(\.d)?\.ts$/, '.d.ts'); }
fromSummaryFileName(filePath: string): string { return filePath; }
}
export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
@ -459,7 +468,9 @@ export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
// In tests, assume that symbols are not re-exported
moduleNameToFileName(modulePath: string, containingFile?: string): string {
function splitPath(path: string): string[] { return path.split(/\/|\\/g); }
function splitPath(path: string): string[] {
return path.split(/\/|\\/g);
}
function resolvePath(pathParts: string[]): string {
const result: string[] = [];
@ -490,7 +501,7 @@ export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
}
if (modulePath.indexOf('.') === 0) {
const baseName = pathTo(containingFile !, modulePath);
const baseName = pathTo(containingFile!, modulePath);
const tsName = baseName + '.ts';
if (this._getMetadataFor(tsName)) {
return tsName;
@ -498,14 +509,18 @@ export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
return baseName + '.d.ts';
}
if (modulePath == 'unresolved') {
return undefined !;
return undefined!;
}
return '/tmp/' + modulePath + '.d.ts';
}
getMetadataFor(moduleId: string): any { return this._getMetadataFor(moduleId); }
getMetadataFor(moduleId: string): any {
return this._getMetadataFor(moduleId);
}
getOutputName(filePath: string): string { return filePath; }
getOutputName(filePath: string): string {
return filePath;
}
private _getMetadataFor(filePath: string): any {
if (this.data[filePath] && filePath.match(TS_EXT)) {
@ -515,13 +530,13 @@ export class MockStaticSymbolResolverHost implements StaticSymbolResolverHost {
filePath, this.data[filePath], ts.ScriptTarget.ES5, /* setParentNodes */ true);
const diagnostics: ts.Diagnostic[] = (<any>sf).parseDiagnostics;
if (diagnostics && diagnostics.length) {
const errors =
diagnostics
.map(d => {
const {line, character} = ts.getLineAndCharacterOfPosition(d.file !, d.start !);
return `(${line}:${character}): ${d.messageText}`;
})
.join('\n');
const errors = diagnostics
.map(d => {
const {line, character} =
ts.getLineAndCharacterOfPosition(d.file!, d.start!);
return `(${line}:${character}): ${d.messageText}`;
})
.join('\n');
throw Error(`Error encountered during parse of file ${filePath}\n${errors}`);
}
return [this.collector.getMetadata(sf)];

View File

@ -23,7 +23,9 @@ const EXT = /(\.d)?\.ts$/;
let symbolCache: StaticSymbolCache;
let host: MockAotSummaryResolverHost;
beforeEach(() => { symbolCache = new StaticSymbolCache(); });
beforeEach(() => {
symbolCache = new StaticSymbolCache();
});
function init(summaries: {[filePath: string]: string} = {}) {
host = new MockAotSummaryResolverHost(summaries);
@ -121,11 +123,17 @@ export class MockAotSummaryResolverHost implements AotSummaryResolverHost {
return sourceFileName.replace(EXT, '') + '.d.ts';
}
fromSummaryFileName(filePath: string): string { return filePath; }
fromSummaryFileName(filePath: string): string {
return filePath;
}
isSourceFile(filePath: string) { return !filePath.endsWith('.d.ts'); }
isSourceFile(filePath: string) {
return !filePath.endsWith('.d.ts');
}
loadSummary(filePath: string): string { return this.summaries[filePath]; }
loadSummary(filePath: string): string {
return this.summaries[filePath];
}
}
export function createMockOutputContext(): OutputContext {

View File

@ -12,7 +12,7 @@ import {deserializeSummaries, serializeSummaries} from '@angular/compiler/src/ao
import {summaryFileName} from '@angular/compiler/src/aot/util';
import {MockStaticSymbolResolverHost} from './static_symbol_resolver_spec';
import {MockAotSummaryResolverHost, createMockOutputContext} from './summary_resolver_spec';
import {createMockOutputContext, MockAotSummaryResolverHost} from './summary_resolver_spec';
{
@ -22,7 +22,9 @@ import {MockAotSummaryResolverHost, createMockOutputContext} from './summary_res
let symbolCache: StaticSymbolCache;
let host: MockAotSummaryResolverHost;
beforeEach(() => { symbolCache = new StaticSymbolCache(); });
beforeEach(() => {
symbolCache = new StaticSymbolCache();
});
function init(
summaries: {[filePath: string]: string} = {}, metadata: {[key: string]: any} = {}) {
@ -101,7 +103,7 @@ import {MockAotSummaryResolverHost, createMockOutputContext} from './summary_res
members: {aMethod: {__symbolic: 'function'}},
statics: {aStatic: true}
});
expect(summaries[1].type !.type.reference)
expect(summaries[1].type!.type.reference)
.toBe(symbolCache.get('/tmp/some_service.d.ts', 'SomeService'));
});
@ -274,7 +276,7 @@ import {MockAotSummaryResolverHost, createMockOutputContext} from './summary_res
'/tmp/external_svc.d.ts', 'SomeService')]);
// SomService is a transitive dep, but should have been serialized as well.
expect(summaries[2].symbol).toBe(symbolCache.get('/tmp/external_svc.d.ts', 'SomeService'));
expect(summaries[2].type !.type.reference)
expect(summaries[2].type!.type.reference)
.toBe(symbolCache.get('/tmp/external_svc.d.ts', 'SomeService'));
// there was no summary for non_summary, but it should have
// been serialized as well.
@ -387,7 +389,6 @@ import {MockAotSummaryResolverHost, createMockOutputContext} from './summary_res
describe('symbol re-exports enabled', () => {
it('should not create "importAs" names for ctor arguments which are types of reexported classes in libraries',
() => {
init();

View File

@ -6,7 +6,7 @@
* found in the LICENSE file at https://angular.io/license
*/
import {AotCompilerHost, AotCompilerOptions, GeneratedFile, createAotCompiler, toTypeScript} from '@angular/compiler';
import {AotCompilerHost, AotCompilerOptions, createAotCompiler, GeneratedFile, toTypeScript} from '@angular/compiler';
import {MetadataBundlerHost} from '@angular/compiler-cli/src/metadata/bundler';
import {MetadataCollector} from '@angular/compiler-cli/src/metadata/collector';
import {ModuleMetadata} from '@angular/compiler-cli/src/metadata/index';
@ -15,7 +15,9 @@ import * as fs from 'fs';
import * as path from 'path';
import * as ts from 'typescript';
export interface MetadataProvider { getMetadata(source: ts.SourceFile): ModuleMetadata|undefined; }
export interface MetadataProvider {
getMetadata(source: ts.SourceFile): ModuleMetadata|undefined;
}
let nodeModulesPath: string;
let angularSourcePath: string;
@ -23,13 +25,13 @@ let rootPath: string;
calcPathsOnDisc();
export type MockFileOrDirectory = string | MockDirectory;
export type MockFileOrDirectory = string|MockDirectory;
export type MockDirectory = {
[name: string]: MockFileOrDirectory | undefined;
[name: string]: MockFileOrDirectory|undefined;
};
export function isDirectory(data: MockFileOrDirectory | undefined): data is MockDirectory {
export function isDirectory(data: MockFileOrDirectory|undefined): data is MockDirectory {
return typeof data !== 'string';
}
@ -119,9 +121,13 @@ export class EmittingCompilerHost implements ts.CompilerHost {
return Array.from(this.writtenFiles).map(f => ({name: f[0], content: f[1]}));
}
public get scripts(): string[] { return this.scriptNames; }
public get scripts(): string[] {
return this.scriptNames;
}
public get written(): Map<string, string> { return this.writtenFiles; }
public get written(): Map<string, string> {
return this.writtenFiles;
}
public effectiveName(fileName: string): string {
const prefix = '@angular/';
@ -154,7 +160,9 @@ export class EmittingCompilerHost implements ts.CompilerHost {
(fs.existsSync(directoryName) && fs.statSync(directoryName).isDirectory());
}
getCurrentDirectory(): string { return this.root; }
getCurrentDirectory(): string {
return this.root;
}
getDirectories(dir: string): string[] {
const result = open(dir, this.options.mockData);
@ -179,7 +187,9 @@ export class EmittingCompilerHost implements ts.CompilerHost {
throw new Error(`File not found '${fileName}'.`);
}
getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; }
getDefaultLibFileName(options: ts.CompilerOptions): string {
return 'lib.d.ts';
}
writeFile: ts.WriteFileCallback =
(fileName: string, data: string, writeByteOrderMark: boolean,
@ -197,8 +207,12 @@ export class EmittingCompilerHost implements ts.CompilerHost {
getCanonicalFileName(fileName: string): string {
return fileName;
}
useCaseSensitiveFileNames(): boolean { return false; }
getNewLine(): string { return '\n'; }
useCaseSensitiveFileNames(): boolean {
return false;
}
getNewLine(): string {
return '\n';
}
private getAddedDirectories(): Set<string> {
let result = this.cachedAddedDirectories;
@ -247,7 +261,9 @@ export class MockCompilerHost implements ts.CompilerHost {
this.sourceFiles.delete(fileName);
}
assumeFileExists(fileName: string) { this.assumeExists.add(fileName); }
assumeFileExists(fileName: string) {
this.assumeExists.add(fileName);
}
remove(files: string[]) {
// Remove the files from the list of scripts.
@ -274,11 +290,17 @@ export class MockCompilerHost implements ts.CompilerHost {
return false;
}
readFile(fileName: string): string { return this.getFileContent(fileName) !; }
readFile(fileName: string): string {
return this.getFileContent(fileName)!;
}
trace(s: string): void { this.traces.push(s); }
trace(s: string): void {
this.traces.push(s);
}
getCurrentDirectory(): string { return '/'; }
getCurrentDirectory(): string {
return '/';
}
getDirectories(dir: string): string[] {
const effectiveName = this.getEffectiveName(dir);
@ -303,10 +325,12 @@ export class MockCompilerHost implements ts.CompilerHost {
this.sourceFiles.set(fileName, result);
}
}
return result !;
return result!;
}
getDefaultLibFileName(options: ts.CompilerOptions): string { return 'lib.d.ts'; }
getDefaultLibFileName(options: ts.CompilerOptions): string {
return 'lib.d.ts';
}
writeFile: ts.WriteFileCallback =
(fileName: string, data: string, writeByteOrderMark: boolean) => {
@ -317,8 +341,12 @@ export class MockCompilerHost implements ts.CompilerHost {
getCanonicalFileName(fileName: string): string {
return fileName;
}
useCaseSensitiveFileNames(): boolean { return false; }
getNewLine(): string { return '\n'; }
useCaseSensitiveFileNames(): boolean {
return false;
}
getNewLine(): string {
return '\n';
}
// Private methods
private getFileContent(fileName: string): string|undefined {
@ -373,9 +401,13 @@ export class MockAotCompilerHost implements AotCompilerHost {
};
}
hideMetadata() { this.metadataVisible = false; }
hideMetadata() {
this.metadataVisible = false;
}
tsFilesOnly() { this.dtsAreSource = false; }
tsFilesOnly() {
this.dtsAreSource = false;
}
// StaticSymbolResolverHost
getMetadataFor(modulePath: string): {[key: string]: any}[]|undefined {
@ -414,7 +446,9 @@ export class MockAotCompilerHost implements AotCompilerHost {
return resolved ? resolved.resolvedFileName : null;
}
getOutputName(filePath: string) { return filePath; }
getOutputName(filePath: string) {
return filePath;
}
resourceNameToFileName(resourceName: string, containingFile: string) {
// Note: we convert package paths into relative paths to be compatible with the the
@ -428,16 +462,22 @@ export class MockAotCompilerHost implements AotCompilerHost {
}
// AotSummaryResolverHost
loadSummary(filePath: string): string|null { return this.tsHost.readFile(filePath); }
loadSummary(filePath: string): string|null {
return this.tsHost.readFile(filePath);
}
isSourceFile(sourceFilePath: string): boolean {
return !GENERATED_FILES.test(sourceFilePath) &&
(this.dtsAreSource || !DTS.test(sourceFilePath));
}
toSummaryFileName(filePath: string): string { return filePath.replace(EXT, '') + '.d.ts'; }
toSummaryFileName(filePath: string): string {
return filePath.replace(EXT, '') + '.d.ts';
}
fromSummaryFileName(filePath: string): string { return filePath; }
fromSummaryFileName(filePath: string): string {
return filePath;
}
// AotCompilerHost
fileNameToModuleName(importedFile: string, containingFile: string): string {
@ -464,7 +504,7 @@ export class MockMetadataBundlerHost implements MetadataBundlerHost {
}
}
function find(fileName: string, data: MockFileOrDirectory | undefined): MockFileOrDirectory|
function find(fileName: string, data: MockFileOrDirectory|undefined): MockFileOrDirectory|
undefined {
if (!data) return undefined;
const names = fileName.split('/');
@ -479,7 +519,7 @@ function find(fileName: string, data: MockFileOrDirectory | undefined): MockFile
return current;
}
function open(fileName: string, data: MockFileOrDirectory | undefined): string|undefined {
function open(fileName: string, data: MockFileOrDirectory|undefined): string|undefined {
let result = find(fileName, data);
if (typeof result === 'string') {
return result;
@ -487,7 +527,7 @@ function open(fileName: string, data: MockFileOrDirectory | undefined): string|u
return undefined;
}
function directoryExists(dirname: string, data: MockFileOrDirectory | undefined): boolean {
function directoryExists(dirname: string, data: MockFileOrDirectory|undefined): boolean {
let result = find(dirname, data);
return !!result && typeof result !== 'string';
}
@ -497,7 +537,7 @@ export type MockFileArray = {
content: string
}[];
export type MockData = MockDirectory | Map<string, string>| (MockDirectory | Map<string, string>)[];
export type MockData = MockDirectory|Map<string, string>|(MockDirectory|Map<string, string>)[];
export function toMockFileArray(data: MockData, target: MockFileArray = []): MockFileArray {
if (data instanceof Map) {
@ -512,7 +552,7 @@ export function toMockFileArray(data: MockData, target: MockFileArray = []): Moc
function mockDirToFileArray(dir: MockDirectory, path: string, target: MockFileArray) {
Object.keys(dir).forEach((localFileName) => {
const value = dir[localFileName] !;
const value = dir[localFileName]!;
const fileName = `${path}/${localFileName}`;
if (typeof value === 'string') {
target.push({fileName, content: value});
@ -523,12 +563,16 @@ function mockDirToFileArray(dir: MockDirectory, path: string, target: MockFileAr
}
function mapToMockFileArray(files: Map<string, string>, target: MockFileArray) {
files.forEach((content, fileName) => { target.push({fileName, content}); });
files.forEach((content, fileName) => {
target.push({fileName, content});
});
}
export function arrayToMockMap(arr: MockFileArray): Map<string, string> {
const map = new Map<string, string>();
arr.forEach(({fileName, content}) => { map.set(fileName, content); });
arr.forEach(({fileName, content}) => {
map.set(fileName, content);
});
return map;
}
@ -594,8 +638,8 @@ function readBazelWrittenFilesFrom(
map.set(path.posix.join('/node_modules/@angular', packageName, 'index.d.ts'), content);
}
} catch (e) {
console.error(
`Consider adding //packages/${packageName} as a data dependency in the BUILD.bazel rule for the failing test`);
console.error(`Consider adding //packages/${
packageName} as a data dependency in the BUILD.bazel rule for the failing test`);
throw e;
}
}
@ -606,8 +650,8 @@ export function isInBazel(): boolean {
export function setup(options: {
compileAngular: boolean,
compileFakeCore?: boolean,
compileAnimations: boolean, compileCommon?: boolean
compileFakeCore?: boolean, compileAnimations: boolean,
compileCommon?: boolean
} = {
compileAngular: true,
compileAnimations: true,
@ -687,7 +731,9 @@ export function expectNoDiagnostics(program: ts.Program) {
return '';
}
function chars(len: number, ch: string): string { return newArray(len, ch).join(''); }
function chars(len: number, ch: string): string {
return newArray(len, ch).join('');
}
function lineNoOf(offset: number, text: string): number {
let result = 1;
@ -699,8 +745,8 @@ export function expectNoDiagnostics(program: ts.Program) {
function lineInfo(diagnostic: ts.Diagnostic): string {
if (diagnostic.file) {
const start = diagnostic.start !;
let end = diagnostic.start ! + diagnostic.length !;
const start = diagnostic.start!;
let end = diagnostic.start! + diagnostic.length!;
const source = diagnostic.file.text;
let lineStart = start;
let lineEnd = end;
@ -726,8 +772,8 @@ export function expectNoDiagnostics(program: ts.Program) {
'Errors from TypeScript:\n' +
diagnostics
.map(
d =>
`${fileInfo(d)}${ts.flattenDiagnosticMessageText(d.messageText, '\n')}${lineInfo(d)}`)
d => `${fileInfo(d)}${ts.flattenDiagnosticMessageText(d.messageText, '\n')}${
lineInfo(d)}`)
.join(' \n'));
}
}
@ -758,7 +804,7 @@ export function compile(
useSummaries?: boolean,
preCompile?: (program: ts.Program) => void,
postCompile?: (program: ts.Program) => void,
}& AotCompilerOptions = {},
}&AotCompilerOptions = {},
tsOptions: ts.CompilerOptions = {}): {genFiles: GeneratedFile[], outDir: MockDirectory} {
// when using summaries, always emit so the next step can use the results.
const emit = options.emit || options.useSummaries;
@ -777,7 +823,9 @@ export function compile(
const tsSettings = {...settings, ...tsOptions};
const program = ts.createProgram([...host.scriptNames], tsSettings, host);
preCompile(program);
const {compiler, reflector} = createAotCompiler(aotHost, options, (err) => { throw err; });
const {compiler, reflector} = createAotCompiler(aotHost, options, (err) => {
throw err;
});
const analyzedModules =
compiler.analyzeModulesSync(program.getSourceFiles().map(sf => sf.fileName));
const genFiles = compiler.emitAllImpls(analyzedModules);