Skip to content

Commit

Permalink
feat(language-service): Implement go to definition for style and temp…
Browse files Browse the repository at this point in the history
…late urls (#39202)

This commit enables the Ivy Language Service to 'go to definition' of a
templateUrl or styleUrl, which would jump to the template/style file
itself.

PR Close #39202
  • Loading branch information
atscott authored and AndrewKushnir committed Oct 16, 2020
1 parent 087596b commit 563fb6c
Show file tree
Hide file tree
Showing 14 changed files with 166 additions and 57 deletions.
1 change: 0 additions & 1 deletion packages/language-service/common/BUILD.bazel
Expand Up @@ -6,7 +6,6 @@ ts_library(
name = "common",
srcs = glob(["*.ts"]),
deps = [
"@npm//@types/node",
"@npm//typescript",
],
)
39 changes: 26 additions & 13 deletions packages/language-service/common/definitions.ts
Expand Up @@ -6,24 +6,35 @@
* found in the LICENSE file at https://angular.io/license
*/

import * as path from 'path';
import * as ts from 'typescript';

import {findTightestNode, getClassDeclFromDecoratorProp, getPropertyAssignmentFromValue} from './ts_utils';

export interface ResourceResolver {
/**
* Resolve the url of a resource relative to the file that contains the reference to it.
*
* @param file The, possibly relative, url of the resource.
* @param basePath The path to the file that contains the URL of the resource.
* @returns A resolved url of resource.
* @throws An error if the resource cannot be resolved.
*/
resolve(file: string, basePath: string): string;
}

/**
* Gets an Angular-specific definition in a TypeScript source file.
*/
export function getTsDefinitionAndBoundSpan(
sf: ts.SourceFile, position: number,
tsLsHost: Pick<ts.LanguageServiceHost, 'fileExists'>): ts.DefinitionInfoAndBoundSpan|undefined {
resourceResolver: ResourceResolver): ts.DefinitionInfoAndBoundSpan|undefined {
const node = findTightestNode(sf, position);
if (!node) return;
switch (node.kind) {
case ts.SyntaxKind.StringLiteral:
case ts.SyntaxKind.NoSubstitutionTemplateLiteral:
// Attempt to extract definition of a URL in a property assignment.
return getUrlFromProperty(node as ts.StringLiteralLike, tsLsHost);
return getUrlFromProperty(node as ts.StringLiteralLike, resourceResolver);
default:
return undefined;
}
Expand All @@ -34,9 +45,8 @@ export function getTsDefinitionAndBoundSpan(
* directive decorator.
* Currently applies to `templateUrl` and `styleUrls` properties.
*/
function getUrlFromProperty(
urlNode: ts.StringLiteralLike,
tsLsHost: Pick<ts.LanguageServiceHost, 'fileExists'>): ts.DefinitionInfoAndBoundSpan|undefined {
function getUrlFromProperty(urlNode: ts.StringLiteralLike, resourceResolver: ResourceResolver):
ts.DefinitionInfoAndBoundSpan|undefined {
// Get the property assignment node corresponding to the `templateUrl` or `styleUrls` assignment.
// These assignments are specified differently; `templateUrl` is a string, and `styleUrls` is
// an array of strings:
Expand Down Expand Up @@ -65,20 +75,23 @@ function getUrlFromProperty(
}

const sf = urlNode.getSourceFile();
// Extract url path specified by the url node, which is relative to the TypeScript source file
// the url node is defined in.
const url = path.join(path.dirname(sf.fileName), urlNode.text);

// If the file does not exist, bail. It is possible that the TypeScript language service host
// does not have a `fileExists` method, in which case optimistically assume the file exists.
if (tsLsHost.fileExists && !tsLsHost.fileExists(url)) return;
let url: string;
try {
url = resourceResolver.resolve(urlNode.text, sf.fileName);
} catch {
// If the file does not exist, bail.
return;
}

const templateDefinitions: ts.DefinitionInfo[] = [{
kind: ts.ScriptElementKind.externalModuleName,
name: url,
containerKind: ts.ScriptElementKind.unknown,
containerName: '',
// Reading the template is expensive, so don't provide a preview.
// TODO(ayazhafiz): Consider providing an actual span:
// 1. We're likely to read the template anyway
// 2. We could show just the first 100 chars or so
textSpan: {start: 0, length: 0},
fileName: url,
}];
Expand Down
2 changes: 1 addition & 1 deletion packages/language-service/common/ts_utils.ts
Expand Up @@ -83,5 +83,5 @@ export function getClassDeclOfInlineTemplateNode(templateStringNode: ts.Node): t
if (!tmplAsgn) {
return;
}
return getClassDeclFromDecoratorProp(tmplAsgn)
return getClassDeclFromDecoratorProp(tmplAsgn);
}
1 change: 1 addition & 0 deletions packages/language-service/ivy/BUILD.bazel
Expand Up @@ -13,6 +13,7 @@ ts_library(
"//packages/compiler-cli/src/ngtsc/file_system",
"//packages/compiler-cli/src/ngtsc/incremental",
"//packages/compiler-cli/src/ngtsc/reflection",
"//packages/compiler-cli/src/ngtsc/resource",
"//packages/compiler-cli/src/ngtsc/shims",
"//packages/compiler-cli/src/ngtsc/typecheck",
"//packages/compiler-cli/src/ngtsc/typecheck/api",
Expand Down
3 changes: 2 additions & 1 deletion packages/language-service/ivy/compiler_factory.ts
Expand Up @@ -12,7 +12,8 @@ import {TrackedIncrementalBuildStrategy} from '@angular/compiler-cli/src/ngtsc/i
import {TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as ts from 'typescript/lib/tsserverlibrary';

import {isExternalTemplate, LanguageServiceAdapter} from './language_service_adapter';
import {LanguageServiceAdapter} from './language_service_adapter';
import {isExternalTemplate} from './utils';

export class CompilerFactory {
private readonly incrementalStrategy = new TrackedIncrementalBuildStrategy();
Expand Down
20 changes: 17 additions & 3 deletions packages/language-service/ivy/definitions.ts
Expand Up @@ -11,8 +11,10 @@ import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {DirectiveSymbol, DomBindingSymbol, ElementSymbol, ShimLocation, Symbol, SymbolKind, TemplateSymbol} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as ts from 'typescript';

import {getTsDefinitionAndBoundSpan, ResourceResolver} from '../common/definitions';

import {getPathToNodeAtPosition} from './hybrid_visitor';
import {flatMap, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateInfoAtPosition, getTextSpanOfNode, isDollarEvent, TemplateInfo, toTextSpan} from './utils';
import {flatMap, getDirectiveMatchesForAttribute, getDirectiveMatchesForElementTag, getTemplateInfoAtPosition, getTextSpanOfNode, isDollarEvent, isTypeScriptFile, TemplateInfo, toTextSpan} from './utils';

interface DefinitionMeta {
node: AST|TmplAstNode;
Expand All @@ -25,13 +27,25 @@ interface HasShimLocation {
}

export class DefinitionBuilder {
constructor(private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler) {}
constructor(
private readonly tsLS: ts.LanguageService, private readonly compiler: NgCompiler,
private readonly resourceResolver: ResourceResolver) {}

getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|undefined {
const templateInfo = getTemplateInfoAtPosition(fileName, position, this.compiler);
if (templateInfo === undefined) {
return;
// We were unable to get a template at the given position. If we are in a TS file, instead
// attempt to get an Angular definition at the location inside a TS file (examples of this
// would be templateUrl or a url in styleUrls).
if (!isTypeScriptFile(fileName)) {
return;
}
const sf = this.compiler.getNextProgram().getSourceFile(fileName);
if (!sf) {
return;
}
return getTsDefinitionAndBoundSpan(sf, position, this.resourceResolver);
}
const definitionMeta = this.getDefinitionMetaAtPosition(templateInfo, position);
// The `$event` of event handlers would point to the $event parameter in the shim file, as in
Expand Down
12 changes: 6 additions & 6 deletions packages/language-service/ivy/language_service.ts
Expand Up @@ -7,16 +7,16 @@
*/

import {CompilerOptions, createNgCompilerOptions} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
import {OptimizeFor, TypeCheckingProgramStrategy} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import * as ts from 'typescript/lib/tsserverlibrary';

import {CompilerFactory} from './compiler_factory';
import {DefinitionBuilder} from './definitions';
import {isExternalTemplate, isTypeScriptFile, LanguageServiceAdapter} from './language_service_adapter';
import {LanguageServiceAdapter} from './language_service_adapter';
import {QuickInfoBuilder} from './quick_info';
import {isTypeScriptFile} from './utils';

export class LanguageService {
private options: CompilerOptions;
Expand Down Expand Up @@ -57,17 +57,17 @@ export class LanguageService {
getDefinitionAndBoundSpan(fileName: string, position: number): ts.DefinitionInfoAndBoundSpan
|undefined {
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
const results =
new DefinitionBuilder(this.tsLS, compiler).getDefinitionAndBoundSpan(fileName, position);
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
.getDefinitionAndBoundSpan(fileName, position);
this.compilerFactory.registerLastKnownProgram();
return results;
}

getTypeDefinitionAtPosition(fileName: string, position: number):
readonly ts.DefinitionInfo[]|undefined {
const compiler = this.compilerFactory.getOrCreateWithChangedFile(fileName, this.options);
const results =
new DefinitionBuilder(this.tsLS, compiler).getTypeDefinitionsAtPosition(fileName, position);
const results = new DefinitionBuilder(this.tsLS, compiler, this.adapter)
.getTypeDefinitionsAtPosition(fileName, position);
this.compilerFactory.registerLastKnownProgram();
return results;
}
Expand Down
18 changes: 10 additions & 8 deletions packages/language-service/ivy/language_service_adapter.ts
Expand Up @@ -8,10 +8,15 @@

import {NgCompilerAdapter} from '@angular/compiler-cli/src/ngtsc/core/api';
import {absoluteFrom, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {AdapterResourceLoader} from '@angular/compiler-cli/src/ngtsc/resource';
import {isShim} from '@angular/compiler-cli/src/ngtsc/shims';
import * as ts from 'typescript/lib/tsserverlibrary';

export class LanguageServiceAdapter implements NgCompilerAdapter {
import {ResourceResolver} from '../common/definitions';

import {isTypeScriptFile} from './utils';

export class LanguageServiceAdapter implements NgCompilerAdapter, ResourceResolver {
readonly entryPoint = null;
readonly constructionDiagnostics: ts.Diagnostic[] = [];
readonly ignoreForEmit: Set<ts.SourceFile> = new Set();
Expand Down Expand Up @@ -75,12 +80,9 @@ export class LanguageServiceAdapter implements NgCompilerAdapter {
const latestVersion = this.project.getScriptVersion(fileName);
return lastVersion !== latestVersion;
}
}

export function isTypeScriptFile(fileName: string): boolean {
return fileName.endsWith('.ts');
}

export function isExternalTemplate(fileName: string): boolean {
return !isTypeScriptFile(fileName);
resolve(file: string, basePath: string): string {
const loader = new AdapterResourceLoader(this, this.project.getCompilationSettings());
return loader.resolve(file, basePath);
}
}
47 changes: 47 additions & 0 deletions packages/language-service/ivy/test/definitions_spec.ts
Expand Up @@ -448,6 +448,53 @@ describe('definitions', () => {
});
});

describe('external resources', () => {
it('should be able to find a template from a url', () => {
const {position, text} = service.overwrite(APP_COMPONENT, `
import {Component} from '@angular/core';
@Component({
templateUrl: './tes¦t.ng',
})
export class MyComponent {}`);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);

expect(result).toBeDefined();
const {textSpan, definitions} = result!;

expect(text.substring(textSpan.start, textSpan.start + textSpan.length)).toEqual('./test.ng');

expect(definitions).toBeDefined();
expect(definitions!.length).toBe(1);
const [def] = definitions!;
expect(def.fileName).toContain('/app/test.ng');
expect(def.textSpan).toEqual({start: 0, length: 0});
});

it('should be able to find a stylesheet from a url', () => {
const {position, text} = service.overwrite(APP_COMPONENT, `
import {Component} from '@angular/core';
@Component({
template: 'empty',
styleUrls: ['./te¦st.css']
})
export class MyComponent {}`);
const result = ngLS.getDefinitionAndBoundSpan(APP_COMPONENT, position);


expect(result).toBeDefined();
const {textSpan, definitions} = result!;

expect(text.substring(textSpan.start, textSpan.start + textSpan.length))
.toEqual('./test.css');

expect(definitions).toBeDefined();
expect(definitions!.length).toBe(1);
const [def] = definitions!;
expect(def.fileName).toContain('/app/test.css');
expect(def.textSpan).toEqual({start: 0, length: 0});
});
});

function getDefinitionsAndAssertBoundSpan(
{templateOverride, expectedSpanText}: {templateOverride: string, expectedSpanText: string}):
Array<{textSpan: string, contextSpan: string | undefined, fileName: string}> {
Expand Down
3 changes: 2 additions & 1 deletion packages/language-service/ivy/test/mock_host.ts
Expand Up @@ -8,7 +8,8 @@

import {join} from 'path';
import * as ts from 'typescript/lib/tsserverlibrary';
import {isTypeScriptFile} from '../language_service_adapter';

import {isTypeScriptFile} from '../utils';

const logger: ts.server.Logger = {
close(): void{},
Expand Down
48 changes: 29 additions & 19 deletions packages/language-service/ivy/utils.ts
Expand Up @@ -14,6 +14,7 @@ import * as t from '@angular/compiler/src/render3/r3_ast'; // t for temp
import * as ts from 'typescript';

import {ALIAS_NAME, SYMBOL_PUNC} from '../common/quick_info';
import {findTightestNode, getClassDeclOfInlineTemplateNode} from '../common/ts_utils';

export function getTextSpanOfNode(node: t.Node|e.AST): ts.TextSpan {
if (isTemplateNodeWithKeyAndValue(node)) {
Expand Down Expand Up @@ -70,8 +71,8 @@ export interface TemplateInfo {
*/
export function getTemplateInfoAtPosition(
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
if (fileName.endsWith('.ts')) {
return getInlineTemplateInfoAtPosition(fileName, position, compiler);
if (isTypeScriptFile(fileName)) {
return getTemplateInfoFromClassMeta(fileName, position, compiler);
} else {
return getFirstComponentForTemplateFile(fileName, compiler);
}
Expand Down Expand Up @@ -116,28 +117,29 @@ function getFirstComponentForTemplateFile(fileName: string, compiler: NgCompiler
/**
* Retrieves the `ts.ClassDeclaration` at a location along with its template nodes.
*/
function getInlineTemplateInfoAtPosition(
function getTemplateInfoFromClassMeta(
fileName: string, position: number, compiler: NgCompiler): TemplateInfo|undefined {
const sourceFile = compiler.getNextProgram().getSourceFile(fileName);
if (!sourceFile) {
return undefined;
const classDecl = getClassDeclForInlineTemplateAtPosition(fileName, position, compiler);
if (!classDecl || !classDecl.name) { // Does not handle anonymous class
return;
}
const template = compiler.getTemplateTypeChecker().getTemplate(classDecl);
if (template === null) {
return;
}

// We only support top level statements / class declarations
for (const statement of sourceFile.statements) {
if (!ts.isClassDeclaration(statement) || position < statement.pos || position > statement.end) {
continue;
}

const template = compiler.getTemplateTypeChecker().getTemplate(statement);
if (template === null) {
return undefined;
}
return {template, component: classDecl};
}

return {template, component: statement};
function getClassDeclForInlineTemplateAtPosition(
fileName: string, position: number, compiler: NgCompiler): ts.ClassDeclaration|undefined {
const sourceFile = compiler.getNextProgram().getSourceFile(fileName);
if (!sourceFile) {
return undefined;
}

return undefined;
const node = findTightestNode(sourceFile, position);
if (!node) return;
return getClassDeclOfInlineTemplateNode(node);
}

/**
Expand Down Expand Up @@ -291,3 +293,11 @@ export function flatMap<T, R>(items: T[]|readonly T[], f: (item: T) => R[] | rea
}
return results;
}

export function isTypeScriptFile(fileName: string): boolean {
return fileName.endsWith('.ts');
}

export function isExternalTemplate(fileName: string): boolean {
return !isTypeScriptFile(fileName);
}

0 comments on commit 563fb6c

Please sign in to comment.