forked from angular/angular
/
diagnostics.ts
261 lines (240 loc) · 8.48 KB
/
diagnostics.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
/**
* @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 {NgAnalyzedModules} from '@angular/compiler';
import {getTemplateExpressionDiagnostics} from '@angular/compiler-cli/src/language_services';
import * as path from 'path';
import * as ts from 'typescript';
import {AstResult} from './common';
import * as ng from './types';
import {TypeScriptServiceHost} from './typescript_host';
import {findPropertyValueOfType, findTightestNode, offsetSpan, spanOf} from './utils';
/**
* Return diagnostic information for the parsed AST of the template.
* @param ast contains HTML and template AST
*/
export function getTemplateDiagnostics(ast: AstResult): ng.Diagnostic[] {
const {parseErrors, templateAst, htmlAst, template} = ast;
if (parseErrors && parseErrors.length) {
return parseErrors.map(e => {
return {
kind: ng.DiagnosticKind.Error,
span: offsetSpan(spanOf(e.span), template.span.start),
message: e.msg,
};
});
}
return getTemplateExpressionDiagnostics({
templateAst: templateAst,
htmlAst: htmlAst,
offset: template.span.start,
query: template.query,
members: template.members,
});
}
/**
* Generate an error message that indicates a directive is not part of any
* NgModule.
* @param name class name
* @param isComponent true if directive is an Angular Component
*/
function missingDirective(name: string, isComponent: boolean) {
const type = isComponent ? 'Component' : 'Directive';
return `${type} '${name}' is not included in a module and will not be ` +
'available inside a template. Consider adding it to a NgModule declaration.';
}
/**
* Logs an error for an impossible state with a certain message.
*/
function logImpossibleState(message: string) {
console.error(`Impossible state: ${message}`);
}
/**
* Performs a variety diagnostics on directive declarations.
*
* @param declarations Angular directive declarations
* @param modules NgModules in the project
* @param host TypeScript service host used to perform TypeScript queries
* @return diagnosed errors, if any
*/
export function getDeclarationDiagnostics(
declarations: ng.Declaration[], modules: NgAnalyzedModules,
host: Readonly<TypeScriptServiceHost>): ng.Diagnostic[] {
const directives = new Set<ng.StaticSymbol>();
for (const ngModule of modules.ngModules) {
for (const directive of ngModule.declaredDirectives) {
directives.add(directive.reference);
}
}
const results: ng.Diagnostic[] = [];
for (const declaration of declarations) {
const {errors, metadata, type, declarationSpan} = declaration;
const sf = host.getSourceFile(type.filePath);
if (!sf) {
logImpossibleState(`directive ${type.name} exists but has no source file`);
return [];
}
// TypeScript identifier of the directive declaration annotation (e.g. "Component" or
// "Directive") on a directive class.
const directiveIdentifier = findTightestNode(sf, declarationSpan.start);
if (!directiveIdentifier) {
logImpossibleState(`directive ${type.name} exists but has no identifier`);
return [];
}
for (const error of errors) {
results.push({
kind: ng.DiagnosticKind.Error,
message: error.message,
span: error.span,
});
}
if (!metadata) {
continue; // declaration is not an Angular directive
}
if (metadata.isComponent) {
if (!modules.ngModuleByPipeOrDirective.has(declaration.type)) {
results.push({
kind: ng.DiagnosticKind.Error,
message: missingDirective(type.name, metadata.isComponent),
span: declarationSpan,
});
}
const {template, templateUrl, styleUrls} = metadata.template !;
if (template === null && !templateUrl) {
results.push({
kind: ng.DiagnosticKind.Error,
message: `Component '${type.name}' must have a template or templateUrl`,
span: declarationSpan,
});
} else if (templateUrl) {
if (template) {
results.push({
kind: ng.DiagnosticKind.Error,
message: `Component '${type.name}' must not have both template and templateUrl`,
span: declarationSpan,
});
}
// Find templateUrl value from the directive call expression, which is the parent of the
// directive identifier.
//
// TODO: We should create an enum of the various properties a directive can have to use
// instead of string literals. We can then perform a mass migration of all literal usages.
const templateUrlNode = findPropertyValueOfType(
directiveIdentifier.parent, 'templateUrl', ts.isLiteralExpression);
if (!templateUrlNode) {
logImpossibleState(`templateUrl ${templateUrl} exists but its TypeScript node doesn't`);
return [];
}
results.push(...validateUrls([templateUrlNode], host.tsLsHost));
}
if (styleUrls.length > 0) {
// Find styleUrls value from the directive call expression, which is the parent of the
// directive identifier.
const styleUrlsNode = findPropertyValueOfType(
directiveIdentifier.parent, 'styleUrls', ts.isArrayLiteralExpression);
if (!styleUrlsNode) {
logImpossibleState(`styleUrls property exists but its TypeScript node doesn't'`);
return [];
}
results.push(...validateUrls(styleUrlsNode.elements, host.tsLsHost));
}
} else if (!directives.has(declaration.type)) {
results.push({
kind: ng.DiagnosticKind.Error,
message: missingDirective(type.name, metadata.isComponent),
span: declarationSpan,
});
}
}
return results;
}
/**
* Checks that URLs on a directive point to a valid file.
* Note that this diagnostic check may require a filesystem hit, and thus may be slower than other
* checks.
*
* @param urls urls to check for validity
* @param tsLsHost TS LS host used for querying filesystem information
* @return diagnosed url errors, if any
*/
function validateUrls(
urls: ArrayLike<ts.Expression>, tsLsHost: Readonly<ts.LanguageServiceHost>): ng.Diagnostic[] {
if (!tsLsHost.fileExists) {
return [];
}
const allErrors: ng.Diagnostic[] = [];
// TODO(ayazhafiz): most of this logic can be unified with the logic in
// definitions.ts#getUrlFromProperty. Create a utility function to be used by both.
for (let i = 0; i < urls.length; ++i) {
const urlNode = urls[i];
if (!ts.isStringLiteralLike(urlNode)) {
// If a non-string value is assigned to a URL node (like `templateUrl`), a type error will be
// picked up by the TS Language Server.
continue;
}
const curPath = urlNode.getSourceFile().fileName;
const url = path.join(path.dirname(curPath), urlNode.text);
if (tsLsHost.fileExists(url)) continue;
allErrors.push({
kind: ng.DiagnosticKind.Error,
message: `URL does not point to a valid file`,
// Exclude opening and closing quotes in the url span.
span: {start: urlNode.getStart() + 1, end: urlNode.end - 1},
});
}
return allErrors;
}
/**
* Return a recursive data structure that chains diagnostic messages.
* @param chain
*/
function chainDiagnostics(chain: ng.DiagnosticMessageChain): ts.DiagnosticMessageChain {
return {
messageText: chain.message,
category: ts.DiagnosticCategory.Error,
code: 0,
next: chain.next ? chain.next.map(chainDiagnostics) : undefined
};
}
/**
* Convert ng.Diagnostic to ts.Diagnostic.
* @param d diagnostic
* @param file
*/
export function ngDiagnosticToTsDiagnostic(
d: ng.Diagnostic, file: ts.SourceFile | undefined): ts.Diagnostic {
return {
file,
start: d.span.start,
length: d.span.end - d.span.start,
messageText: typeof d.message === 'string' ? d.message : chainDiagnostics(d.message),
category: ts.DiagnosticCategory.Error,
code: 0,
source: 'ng',
};
}
/**
* Return elements filtered by unique span.
* @param elements
*/
export function uniqueBySpan<T extends{span: ng.Span}>(elements: T[]): T[] {
const result: T[] = [];
const map = new Map<number, Set<number>>();
for (const element of elements) {
const {span} = element;
let set = map.get(span.start);
if (!set) {
set = new Set();
map.set(span.start, set);
}
if (!set.has(span.end)) {
set.add(span.end);
result.push(element);
}
}
return result;
}