forked from angular/angular
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locate_symbol.ts
341 lines (307 loc) · 13.3 KB
/
locate_symbol.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
/**
* @license
* Copyright Google Inc. 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 {AST, Attribute, BoundDirectivePropertyAst, CssSelector, DirectiveAst, ElementAst, EmbeddedTemplateAst, RecursiveTemplateAstVisitor, SelectorMatcher, StaticSymbol, TemplateAst, TemplateAstPath, VariableBinding, templateVisitAll, tokenReference} from '@angular/compiler';
import * as tss from 'typescript/lib/tsserverlibrary';
import {AstResult} from './common';
import {getExpressionScope} from './expression_diagnostics';
import {getExpressionSymbol} from './expressions';
import {Definition, DirectiveKind, Span, Symbol} from './types';
import {diagnosticInfoFromTemplateInfo, findOutputBinding, findTemplateAstAt, getPathToNodeAtPosition, inSpan, invertMap, isNarrower, offsetSpan, spanOf} from './utils';
export interface SymbolInfo {
symbol: Symbol;
span: tss.TextSpan;
staticSymbol?: StaticSymbol;
}
/**
* Traverses a template AST and locates symbol(s) at a specified position.
* @param info template AST information set
* @param position location to locate symbols at
*/
export function locateSymbols(info: AstResult, position: number): SymbolInfo[] {
const templatePosition = position - info.template.span.start;
// TODO: update `findTemplateAstAt` to use absolute positions.
const path = findTemplateAstAt(info.templateAst, templatePosition);
const attribute = findAttribute(info, position);
if (!path.tail) return [];
const narrowest = spanOf(path.tail);
const toVisit: TemplateAst[] = [];
for (let node: TemplateAst|undefined = path.tail;
node && isNarrower(spanOf(node.sourceSpan), narrowest); node = path.parentOf(node)) {
toVisit.push(node);
}
// For the structural directive, only care about the last template AST.
if (attribute?.name.startsWith('*')) {
toVisit.splice(0, toVisit.length - 1);
}
return toVisit.map(ast => locateSymbol(ast, path, info))
.filter((sym): sym is SymbolInfo => sym !== undefined);
}
/**
* Visits a template node and locates the symbol in that node at a path position.
* @param ast template AST node to visit
* @param path non-empty set of narrowing AST nodes at a position
* @param info template AST information set
*/
function locateSymbol(ast: TemplateAst, path: TemplateAstPath, info: AstResult): SymbolInfo|
undefined {
const templatePosition = path.position;
const position = templatePosition + info.template.span.start;
let symbol: Symbol|undefined;
let span: Span|undefined;
let staticSymbol: StaticSymbol|undefined;
const attributeValueSymbol = (ast: AST): boolean => {
const attribute = findAttribute(info, position);
if (attribute) {
if (inSpan(templatePosition, spanOf(attribute.valueSpan))) {
let result: {symbol: Symbol, span: Span}|undefined;
if (attribute.name.startsWith('*')) {
result = getSymbolInMicrosyntax(info, path, attribute);
} else {
const dinfo = diagnosticInfoFromTemplateInfo(info);
const scope = getExpressionScope(dinfo, path);
result = getExpressionSymbol(scope, ast, templatePosition, info.template);
}
if (result) {
symbol = result.symbol;
span = offsetSpan(result.span, attribute.valueSpan !.start.offset);
}
return true;
}
}
return false;
};
ast.visit(
{
visitNgContent(ast) {},
visitEmbeddedTemplate(ast) {},
visitElement(ast) {
const component = ast.directives.find(d => d.directive.isComponent);
if (component) {
// Need to cast because 'reference' is typed as any
staticSymbol = component.directive.type.reference as StaticSymbol;
symbol = info.template.query.getTypeSymbol(staticSymbol);
symbol = symbol && new OverrideKindSymbol(symbol, DirectiveKind.COMPONENT);
span = spanOf(ast);
} else {
// Find a directive that matches the element name
const directive = ast.directives.find(
d => d.directive.selector != null && d.directive.selector.indexOf(ast.name) >= 0);
if (directive) {
// Need to cast because 'reference' is typed as any
staticSymbol = directive.directive.type.reference as StaticSymbol;
symbol = info.template.query.getTypeSymbol(staticSymbol);
symbol = symbol && new OverrideKindSymbol(symbol, DirectiveKind.DIRECTIVE);
span = spanOf(ast);
}
}
},
visitReference(ast) {
symbol = ast.value && info.template.query.getTypeSymbol(tokenReference(ast.value));
span = spanOf(ast);
},
visitVariable(ast) {},
visitEvent(ast) {
if (!attributeValueSymbol(ast.handler)) {
symbol = findOutputBinding(ast, path, info.template.query);
symbol = symbol && new OverrideKindSymbol(symbol, DirectiveKind.EVENT);
span = spanOf(ast);
}
},
visitElementProperty(ast) { attributeValueSymbol(ast.value); },
visitAttr(ast) {
const element = path.first(ElementAst);
if (!element) return;
// Create a mapping of all directives applied to the element from their selectors.
const matcher = new SelectorMatcher<DirectiveAst>();
for (const dir of element.directives) {
if (!dir.directive.selector) continue;
matcher.addSelectables(CssSelector.parse(dir.directive.selector), dir);
}
// See if this attribute matches the selector of any directive on the element.
const attributeSelector = `[${ast.name}=${ast.value}]`;
const parsedAttribute = CssSelector.parse(attributeSelector);
if (!parsedAttribute.length) return;
matcher.match(parsedAttribute[0], (_, {directive}) => {
// Need to cast because 'reference' is typed as any
staticSymbol = directive.type.reference as StaticSymbol;
symbol = info.template.query.getTypeSymbol(staticSymbol);
symbol = symbol && new OverrideKindSymbol(symbol, DirectiveKind.DIRECTIVE);
span = spanOf(ast);
});
},
visitBoundText(ast) {
const expressionPosition = templatePosition - ast.sourceSpan.start.offset;
if (inSpan(expressionPosition, ast.value.span)) {
const dinfo = diagnosticInfoFromTemplateInfo(info);
const scope = getExpressionScope(dinfo, path);
const result = getExpressionSymbol(scope, ast.value, templatePosition, info.template);
if (result) {
symbol = result.symbol;
span = offsetSpan(result.span, ast.sourceSpan.start.offset);
}
}
},
visitText(ast) {},
visitDirective(ast) {
// Need to cast because 'reference' is typed as any
staticSymbol = ast.directive.type.reference as StaticSymbol;
symbol = info.template.query.getTypeSymbol(staticSymbol);
span = spanOf(ast);
},
visitDirectiveProperty(ast) {
if (!attributeValueSymbol(ast.value)) {
const directive = findParentOfBinding(info.templateAst, ast, templatePosition);
const attribute = findAttribute(info, position);
if (directive && attribute) {
if (attribute.name.startsWith('*')) {
const compileTypeSummary = directive.directive;
symbol = info.template.query.getTypeSymbol(compileTypeSummary.type.reference);
symbol = symbol && new OverrideKindSymbol(symbol, DirectiveKind.DIRECTIVE);
// Use 'attribute.sourceSpan' instead of the directive's,
// because the span of the directive is the whole opening tag of an element.
span = spanOf(attribute.sourceSpan);
} else {
symbol = findInputBinding(info, ast.templateName, directive);
span = spanOf(ast);
}
}
}
}
},
null);
if (symbol && span) {
const {start, end} = offsetSpan(span, info.template.span.start);
return {
symbol,
span: tss.createTextSpanFromBounds(start, end), staticSymbol,
};
}
}
// Get the symbol in microsyntax at template position.
function getSymbolInMicrosyntax(info: AstResult, path: TemplateAstPath, attribute: Attribute):
{symbol: Symbol, span: Span}|undefined {
if (!attribute.valueSpan) {
return;
}
const absValueOffset = attribute.valueSpan.start.offset;
let result: {symbol: Symbol, span: Span}|undefined;
const {templateBindings} = info.expressionParser.parseTemplateBindings(
attribute.name, attribute.value, attribute.sourceSpan.toString(),
attribute.sourceSpan.start.offset, attribute.valueSpan.start.offset);
// Find the symbol that contains the position.
for (const tb of templateBindings) {
if (tb instanceof VariableBinding) {
// TODO(kyliau): if binding is variable we should still look for the value
// of the key. For example, "let i=index" => "index" should point to
// NgForOfContext.index
continue;
}
if (inSpan(path.position, tb.value?.ast.sourceSpan)) {
const dinfo = diagnosticInfoFromTemplateInfo(info);
const scope = getExpressionScope(dinfo, path);
result = getExpressionSymbol(scope, tb.value !, path.position, info.template);
} else if (inSpan(path.position, tb.sourceSpan)) {
const template = path.first(EmbeddedTemplateAst);
if (template) {
// One element can only have one template binding.
const directiveAst = template.directives[0];
if (directiveAst) {
const symbol = findInputBinding(info, tb.key.source.substring(1), directiveAst);
if (symbol) {
result = {
symbol,
// the span here has to be relative to the start of the template
// value so deduct the absolute offset.
// TODO(kyliau): Use absolute source span throughout completions.
span: offsetSpan(tb.key.span, -absValueOffset),
};
}
}
}
}
}
return result;
}
function findAttribute(info: AstResult, position: number): Attribute|undefined {
const templatePosition = position - info.template.span.start;
const path = getPathToNodeAtPosition(info.htmlAst, templatePosition);
return path.first(Attribute);
}
// TODO: remove this function after the path includes 'DirectiveAst'.
// Find the directive that corresponds to the specified 'binding'
// at the specified 'position' in the 'ast'.
function findParentOfBinding(
ast: TemplateAst[], binding: BoundDirectivePropertyAst, position: number): DirectiveAst|
undefined {
let res: DirectiveAst|undefined;
const visitor = new class extends RecursiveTemplateAstVisitor {
visit(ast: TemplateAst): any {
const span = spanOf(ast);
if (!inSpan(position, span)) {
// Returning a value here will result in the children being skipped.
return true;
}
}
visitEmbeddedTemplate(ast: EmbeddedTemplateAst, context: any): any {
return this.visitChildren(context, visit => {
visit(ast.directives);
visit(ast.children);
});
}
visitElement(ast: ElementAst, context: any): any {
return this.visitChildren(context, visit => {
visit(ast.directives);
visit(ast.children);
});
}
visitDirective(ast: DirectiveAst) {
const result = this.visitChildren(ast, visit => { visit(ast.inputs); });
return result;
}
visitDirectiveProperty(ast: BoundDirectivePropertyAst, context: DirectiveAst) {
if (ast === binding) {
res = context;
}
}
};
templateVisitAll(visitor, ast);
return res;
}
// Find the symbol of input binding in 'directiveAst' by 'name'.
function findInputBinding(info: AstResult, name: string, directiveAst: DirectiveAst): Symbol|
undefined {
const invertedInput = invertMap(directiveAst.directive.inputs);
const fieldName = invertedInput[name];
if (fieldName) {
const classSymbol = info.template.query.getTypeSymbol(directiveAst.directive.type.reference);
if (classSymbol) {
return classSymbol.members().get(fieldName);
}
}
}
/**
* Wrap a symbol and change its kind to component.
*/
class OverrideKindSymbol implements Symbol {
public readonly kind: DirectiveKind;
constructor(private sym: Symbol, kindOverride: DirectiveKind) { this.kind = kindOverride; }
get name(): string { return this.sym.name; }
get language(): string { return this.sym.language; }
get type(): Symbol|undefined { return this.sym.type; }
get container(): Symbol|undefined { return this.sym.container; }
get public(): boolean { return this.sym.public; }
get callable(): boolean { return this.sym.callable; }
get nullable(): boolean { return this.sym.nullable; }
get definition(): Definition { return this.sym.definition; }
get documentation(): ts.SymbolDisplayPart[] { return this.sym.documentation; }
members() { return this.sym.members(); }
signatures() { return this.sym.signatures(); }
selectSignature(types: Symbol[]) { return this.sym.selectSignature(types); }
indexed(argument: Symbol) { return this.sym.indexed(argument); }
typeArguments(): Symbol[]|undefined { return this.sym.typeArguments(); }
}