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(language-service): Implement outlining spans for control flow bl… #52062

Closed
wants to merge 1 commit 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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
5 changes: 5 additions & 0 deletions packages/compiler-cli/src/ngtsc/perf/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,6 +149,11 @@ export enum PerfPhase {
*/
LsSignatureHelp,

/**
* Time spent by the Angular Language Service calculating outlining spans.
*/
OutliningSpans,

/**
* Tracks the number of `PerfPhase`s, and must appear at the end of the list.
*/
Expand Down
14 changes: 7 additions & 7 deletions packages/compiler/src/render3/r3_ast.ts
Original file line number Diff line number Diff line change
Expand Up @@ -252,7 +252,7 @@ export class SwitchBlock implements Node {
export class SwitchBlockCase implements Node {
constructor(
public expression: AST|null, public children: Node[], public sourceSpan: ParseSourceSpan,
public startSourceSpan: ParseSourceSpan) {}
public startSourceSpan: ParseSourceSpan, public endSourceSpan: ParseSourceSpan|null) {}

visit<Result>(visitor: Visitor<Result>): Result {
return visitor.visitSwitchBlockCase(this);
Expand Down Expand Up @@ -445,10 +445,9 @@ export class RecursiveVisitor implements Visitor<void> {
visitAll(this, block.children);
}
visitForLoopBlock(block: ForLoopBlock): void {
block.item.visit(this);
visitAll(this, Object.values(block.contextVariables));
visitAll(this, block.children);
block.empty?.visit(this);
const blockItems = [block.item, ...Object.values(block.contextVariables), ...block.children];
block.empty && blockItems.push(block.empty);
visitAll(this, blockItems);
}
visitForLoopBlockEmpty(block: ForLoopBlockEmpty): void {
visitAll(this, block.children);
Expand All @@ -457,8 +456,9 @@ export class RecursiveVisitor implements Visitor<void> {
visitAll(this, block.branches);
}
visitIfBlockBranch(block: IfBlockBranch): void {
visitAll(this, block.children);
block.expressionAlias?.visit(this);
const blockItems = block.children;
block.expressionAlias && blockItems.push(block.expressionAlias);
visitAll(this, blockItems);
}
visitContent(content: Content): void {}
visitVariable(variable: Variable): void {}
Expand Down
2 changes: 1 addition & 1 deletion packages/compiler/src/render3/r3_control_flow.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,7 +175,7 @@ export function createSwitchBlock(
null;
const ast = new t.SwitchBlockCase(
expression, html.visitAll(visitor, node.children, node.children), node.sourceSpan,
node.startSourceSpan);
node.startSourceSpan, node.endSourceSpan);

if (expression === null) {
defaultCase = ast;
Expand Down
17 changes: 10 additions & 7 deletions packages/language-service/src/language_service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,31 +6,30 @@
* found in the LICENSE file at https://angular.io/license
*/

import {AbsoluteSourceSpan, AST, ParseSourceSpan, TmplAstBoundEvent, TmplAstNode} from '@angular/compiler';
import {AST, TmplAstNode} from '@angular/compiler';
import {CompilerOptions, ConfigurationHost, readConfiguration} from '@angular/compiler-cli';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {ErrorCode, ngErrorCode} from '@angular/compiler-cli/src/ngtsc/diagnostics';
import {absoluteFrom, absoluteFromSourceFile, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {absoluteFrom, AbsoluteFsPath} from '@angular/compiler-cli/src/ngtsc/file_system';
import {PerfPhase} from '@angular/compiler-cli/src/ngtsc/perf';
import {FileUpdate, ProgramDriver} from '@angular/compiler-cli/src/ngtsc/program_driver';
import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import {TypeCheckShimGenerator} from '@angular/compiler-cli/src/ngtsc/typecheck';
import {OptimizeFor} from '@angular/compiler-cli/src/ngtsc/typecheck/api';
import {findFirstMatchingNode} from '@angular/compiler-cli/src/ngtsc/typecheck/src/comments';
import ts from 'typescript/lib/tsserverlibrary';

import {GetComponentLocationsForTemplateResponse, GetTcbResponse, GetTemplateLocationForComponentResponse} from '../api';

import {LanguageServiceAdapter, LSParseConfigHost} from './adapters';
import {ALL_CODE_FIXES_METAS, CodeFixes} from './codefixes';
import {CompilerFactory} from './compiler_factory';
import {CompletionBuilder, CompletionNodeContext} from './completions';
import {CompletionBuilder} from './completions';
import {DefinitionBuilder} from './definitions';
import {getOutliningSpans} from './outlining_spans';
import {QuickInfoBuilder} from './quick_info';
import {ReferencesBuilder, RenameBuilder} from './references_and_rename';
import {createLocationKey} from './references_and_rename_utils';
import {getSignatureHelp} from './signature_help';
import {getTargetAtPosition, getTcbNodesOfTemplateAtPosition, TargetContext, TargetNodeKind} from './template_target';
import {getTargetAtPosition, getTcbNodesOfTemplateAtPosition, TargetNodeKind} from './template_target';
import {findTightestNode, getClassDeclFromDecoratorProp, getParentClassDeclaration, getPropertyAssignmentFromValue} from './ts_utils';
import {getTemplateInfoAtPosition, isTypeScriptFile} from './utils';

Expand Down Expand Up @@ -271,8 +270,12 @@ export class LanguageService {
}

return getSignatureHelp(compiler, this.tsLS, fileName, position, options);
});
}

return undefined;
getOutliningSpans(fileName: string): ts.OutliningSpan[] {
return this.withCompilerAndPerfTracing(PerfPhase.OutliningSpans, compiler => {
return getOutliningSpans(compiler, fileName);
});
}

Expand Down
89 changes: 89 additions & 0 deletions packages/language-service/src/outlining_spans.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
/**
* @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 {ParseLocation, ParseSourceSpan} from '@angular/compiler';
import {NgCompiler} from '@angular/compiler-cli/src/ngtsc/core';
import {isExternalResource} from '@angular/compiler-cli/src/ngtsc/metadata';
import {isNamedClassDeclaration} from '@angular/compiler-cli/src/ngtsc/reflection';
import * as t from '@angular/compiler/src/render3/r3_ast'; // t for template AST
import ts from 'typescript';

import {getFirstComponentForTemplateFile, isTypeScriptFile, toTextSpan} from './utils';

export function getOutliningSpans(compiler: NgCompiler, fileName: string): ts.OutliningSpan[] {
if (isTypeScriptFile(fileName)) {
const sf = compiler.getCurrentProgram().getSourceFile(fileName);
if (sf === undefined) {
return [];
}

const templatesInFile: Array<t.Node[]> = [];
for (const stmt of sf.statements) {
if (isNamedClassDeclaration(stmt)) {
const resources = compiler.getComponentResources(stmt);
if (resources === null || isExternalResource(resources.template)) {
continue;
}
const template = compiler.getTemplateTypeChecker().getTemplate(stmt);
if (template === null) {
continue;
}
templatesInFile.push(template);
}
}
return templatesInFile.map(template => BlockVisitor.getBlockSpans(template)).flat();
} else {
const templateInfo = getFirstComponentForTemplateFile(fileName, compiler);
if (templateInfo === undefined) {
return [];
}
const {template} = templateInfo;
return BlockVisitor.getBlockSpans(template);
}
}

class BlockVisitor extends t.RecursiveVisitor {
readonly blocks = [] as
Array<t.IfBlockBranch|t.ForLoopBlockEmpty|t.ForLoopBlock|t.SwitchBlockCase|t.SwitchBlock|
Copy link
Member

Choose a reason for hiding this comment

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

nit: should we have a type that includes all the blocks so we don't need to repeat this?

t.DeferredBlockError|t.DeferredBlockPlaceholder|t.DeferredBlockLoading>;

static getBlockSpans(templateNodes: t.Node[]): ts.OutliningSpan[] {
const visitor = new BlockVisitor();
t.visitAll(visitor, templateNodes);
const {blocks} = visitor;
return blocks.map(block => {
let mainBlockSpan = block.sourceSpan;
// The source span of for loops and deferred blocks contain all parts (ForLoopBlockEmpty,
// DeferredBlockLoading, etc.). The folding range should only include the main block span for
// these.
if (block instanceof t.ForLoopBlock || block instanceof t.DeferredBlock) {
mainBlockSpan = block.mainBlockSpan;
}
return {
// We move the end back 1 character so we do not consume the close brace of the block in the
// range.
textSpan: toTextSpan(
new ParseSourceSpan(block.startSourceSpan.end, mainBlockSpan.end.moveBy(-1))),
hintSpan: toTextSpan(block.startSourceSpan),
bannerText: '...',
autoCollapse: false,
kind: ts.OutliningSpanKind.Region,
};
});
}

visit(node: t.Node) {
if (node instanceof t.IfBlockBranch || node instanceof t.ForLoopBlockEmpty ||
node instanceof t.ForLoopBlock || node instanceof t.SwitchBlockCase ||
node instanceof t.SwitchBlock || node instanceof t.DeferredBlockError ||
node instanceof t.DeferredBlockPlaceholder || node instanceof t.DeferredBlockLoading ||
node instanceof t.DeferredBlock) {
this.blocks.push(node);
}
}
}
9 changes: 9 additions & 0 deletions packages/language-service/src/ts_plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,14 @@ export function create(info: ts.server.PluginCreateInfo): NgLanguageService {
}
}

function getOutliningSpans(fileName: string): ts.OutliningSpan[] {
if (angularOnly) {
return ngLS.getOutliningSpans(fileName);
} else {
return tsLS.getOutliningSpans(fileName) ?? ngLS.getOutliningSpans(fileName);
}
}

function getTcb(fileName: string, position: number): GetTcbResponse|undefined {
return ngLS.getTcb(fileName, position);
}
Expand Down Expand Up @@ -217,6 +225,7 @@ export function create(info: ts.server.PluginCreateInfo): NgLanguageService {
getCompilerOptionsDiagnostics,
getComponentLocationsForTemplate,
getSignatureHelpItems,
getOutliningSpans,
getTemplateLocationForComponent,
getCodeFixesAtPosition,
getCombinedCodeFix,
Expand Down
4 changes: 2 additions & 2 deletions packages/language-service/src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,8 +147,8 @@ function tsDeclarationSortComparator(a: DeclarationNode, b: DeclarationNode): nu
}
}

function getFirstComponentForTemplateFile(fileName: string, compiler: NgCompiler): TemplateInfo|
undefined {
export function getFirstComponentForTemplateFile(
fileName: string, compiler: NgCompiler): TemplateInfo|undefined {
const templateTypeChecker = compiler.getTemplateTypeChecker();
const components = compiler.getComponentsWithTemplateFile(fileName);
const sortedComponents = Array.from(components).sort(tsDeclarationSortComparator);
Expand Down