feat(compiler-cli): improve error messages produced during structural errors (#20459)
The errors produced when error were encountered while interpreting the content of a directive was often incomprehencible. With this change these kind of error messages should be easier to understand and diagnose. PR Close #20459
This commit is contained in:

committed by
Miško Hevery

parent
1366762d12
commit
8ecda94899
@ -20,7 +20,6 @@ import {GENERATED_FILES} from './transformers/util';
|
||||
|
||||
import {exitCodeFromResult, performCompilation, readConfiguration, formatDiagnostics, Diagnostics, ParsedConfiguration, PerformCompilationResult, filterErrorsAndWarnings} from './perform_compile';
|
||||
import {performWatchCompilation, createPerformWatchHost} from './perform_watch';
|
||||
import {isSyntaxError} from '@angular/compiler';
|
||||
|
||||
export function main(
|
||||
args: string[], consoleError: (s: string) => void = console.error,
|
||||
|
@ -8,8 +8,8 @@
|
||||
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {Evaluator, errorSymbol} from './evaluator';
|
||||
import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata} from './schema';
|
||||
import {Evaluator, errorSymbol, recordMapEntry} from './evaluator';
|
||||
import {ClassMetadata, ConstructorMetadata, FunctionMetadata, InterfaceMetadata, METADATA_VERSION, MemberMetadata, MetadataEntry, MetadataError, MetadataMap, MetadataSymbolicBinaryExpression, MetadataSymbolicCallExpression, MetadataSymbolicExpression, MetadataSymbolicIfExpression, MetadataSymbolicIndexExpression, MetadataSymbolicPrefixExpression, MetadataSymbolicReferenceExpression, MetadataSymbolicSelectExpression, MetadataSymbolicSpreadExpression, MetadataValue, MethodMetadata, ModuleExportMetadata, ModuleMetadata, isClassMetadata, isConstructorMetadata, isFunctionMetadata, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataSymbolicExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSelectExpression, isMethodMetadata} from './schema';
|
||||
import {Symbols} from './symbols';
|
||||
|
||||
const isStatic = (node: ts.Node) => ts.getCombinedModifierFlags(node) & ts.ModifierFlags.Static;
|
||||
@ -76,8 +76,7 @@ export class MetadataCollector {
|
||||
}
|
||||
|
||||
function recordEntry<T extends MetadataEntry>(entry: T, node: ts.Node): T {
|
||||
nodeMap.set(entry, node);
|
||||
return entry;
|
||||
return recordMapEntry(entry, node, nodeMap, sourceFile);
|
||||
}
|
||||
|
||||
function errorSym(
|
||||
|
@ -9,10 +9,11 @@
|
||||
import * as ts from 'typescript';
|
||||
|
||||
import {CollectorOptions} from './collector';
|
||||
import {MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSymbolicCallExpression, MetadataValue, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression} from './schema';
|
||||
import {ClassMetadata, FunctionMetadata, InterfaceMetadata, MetadataEntry, MetadataError, MetadataImportedSymbolReferenceExpression, MetadataSourceLocationInfo, MetadataSymbolicCallExpression, MetadataValue, isMetadataError, isMetadataGlobalReferenceExpression, isMetadataImportDefaultReference, isMetadataImportedSymbolReferenceExpression, isMetadataModuleReferenceExpression, isMetadataSymbolicReferenceExpression, isMetadataSymbolicSpreadExpression} from './schema';
|
||||
import {Symbols} from './symbols';
|
||||
|
||||
|
||||
|
||||
// In TypeScript 2.1 the spread element kind was renamed.
|
||||
const spreadElementSyntaxKind: ts.SyntaxKind =
|
||||
(ts.SyntaxKind as any).SpreadElement || (ts.SyntaxKind as any).SpreadElementExpression;
|
||||
@ -38,6 +39,24 @@ function isCallOf(callExpression: ts.CallExpression, ident: string): boolean {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function recordMapEntry<T extends MetadataEntry>(
|
||||
entry: T, node: ts.Node,
|
||||
nodeMap: Map<MetadataValue|ClassMetadata|InterfaceMetadata|FunctionMetadata, ts.Node>,
|
||||
sourceFile?: ts.SourceFile) {
|
||||
if (!nodeMap.has(entry)) {
|
||||
nodeMap.set(entry, node);
|
||||
if (node && (isMetadataImportedSymbolReferenceExpression(entry) ||
|
||||
isMetadataImportDefaultReference(entry)) &&
|
||||
entry.line == null) {
|
||||
const info = sourceInfo(node, sourceFile);
|
||||
if (info.line != null) entry.line = info.line;
|
||||
if (info.character != null) entry.character = info.character;
|
||||
}
|
||||
}
|
||||
return entry;
|
||||
}
|
||||
|
||||
/**
|
||||
* ts.forEachChild stops iterating children when the callback return a truthy value.
|
||||
* This method inverts this to implement an `every` style iterator. It will return
|
||||
@ -77,21 +96,22 @@ function getSourceFileOfNode(node: ts.Node | undefined): ts.SourceFile {
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function errorSymbol(
|
||||
message: string, node?: ts.Node, context?: {[name: string]: string},
|
||||
sourceFile?: ts.SourceFile): MetadataError {
|
||||
let result: MetadataError|undefined = undefined;
|
||||
export function sourceInfo(
|
||||
node: ts.Node | undefined, sourceFile: ts.SourceFile | undefined): MetadataSourceLocationInfo {
|
||||
if (node) {
|
||||
sourceFile = sourceFile || getSourceFileOfNode(node);
|
||||
if (sourceFile) {
|
||||
const {line, character} =
|
||||
ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile));
|
||||
result = {__symbolic: 'error', message, line, character};
|
||||
return ts.getLineAndCharacterOfPosition(sourceFile, node.getStart(sourceFile));
|
||||
}
|
||||
}
|
||||
if (!result) {
|
||||
result = {__symbolic: 'error', message};
|
||||
}
|
||||
return {};
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export function errorSymbol(
|
||||
message: string, node?: ts.Node, context?: {[name: string]: string},
|
||||
sourceFile?: ts.SourceFile): MetadataError {
|
||||
const result: MetadataError = {__symbolic: 'error', message, ...sourceInfo(node, sourceFile)};
|
||||
if (context) {
|
||||
result.context = context;
|
||||
}
|
||||
@ -242,8 +262,7 @@ export class Evaluator {
|
||||
}
|
||||
entry = newEntry;
|
||||
}
|
||||
t.nodeMap.set(entry, node);
|
||||
return entry;
|
||||
return recordMapEntry(entry, node, t.nodeMap);
|
||||
}
|
||||
|
||||
function isFoldableError(value: any): value is MetadataError {
|
||||
@ -256,6 +275,9 @@ export class Evaluator {
|
||||
// Encode as a global reference. StaticReflector will check the reference.
|
||||
return recordEntry({__symbolic: 'reference', name}, node);
|
||||
}
|
||||
if (reference && isMetadataSymbolicReferenceExpression(reference)) {
|
||||
return recordEntry({...reference}, node);
|
||||
}
|
||||
return reference;
|
||||
};
|
||||
|
||||
@ -628,7 +650,7 @@ export class Evaluator {
|
||||
return recordEntry({__symbolic: 'if', condition, thenExpression, elseExpression}, node);
|
||||
case ts.SyntaxKind.FunctionExpression:
|
||||
case ts.SyntaxKind.ArrowFunction:
|
||||
return recordEntry(errorSymbol('Function call not supported', node), node);
|
||||
return recordEntry(errorSymbol('Lambda not supported', node), node);
|
||||
case ts.SyntaxKind.TaggedTemplateExpression:
|
||||
return recordEntry(
|
||||
errorSymbol('Tagged template expressions are not supported in metadata', node), node);
|
||||
|
@ -178,7 +178,20 @@ export function isMetadataSymbolicIfExpression(value: any): value is MetadataSym
|
||||
return value && value.__symbolic === 'if';
|
||||
}
|
||||
|
||||
export interface MetadataGlobalReferenceExpression extends MetadataSymbolicExpression {
|
||||
export interface MetadataSourceLocationInfo {
|
||||
/**
|
||||
* The line number of the error in the .ts file the metadata was created for.
|
||||
*/
|
||||
line?: number;
|
||||
|
||||
/**
|
||||
* The number of utf8 code-units from the beginning of the file of the error.
|
||||
*/
|
||||
character?: number;
|
||||
}
|
||||
|
||||
export interface MetadataGlobalReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
__symbolic: 'reference';
|
||||
name: string;
|
||||
arguments?: MetadataValue[];
|
||||
@ -188,7 +201,8 @@ export function isMetadataGlobalReferenceExpression(value: any):
|
||||
return value && value.name && !value.module && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataModuleReferenceExpression extends MetadataSymbolicExpression {
|
||||
export interface MetadataModuleReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
}
|
||||
@ -198,7 +212,8 @@ export function isMetadataModuleReferenceExpression(value: any):
|
||||
isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataImportedSymbolReferenceExpression extends MetadataSymbolicExpression {
|
||||
export interface MetadataImportedSymbolReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
name: string;
|
||||
@ -209,7 +224,8 @@ export function isMetadataImportedSymbolReferenceExpression(value: any):
|
||||
return value && value.module && !!value.name && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export interface MetadataImportedDefaultReferenceExpression extends MetadataSymbolicExpression {
|
||||
export interface MetadataImportedDefaultReferenceExpression extends MetadataSymbolicExpression,
|
||||
MetadataSourceLocationInfo {
|
||||
__symbolic: 'reference';
|
||||
module: string;
|
||||
default:
|
||||
@ -218,7 +234,7 @@ export interface MetadataImportedDefaultReferenceExpression extends MetadataSymb
|
||||
}
|
||||
export function isMetadataImportDefaultReference(value: any):
|
||||
value is MetadataImportedDefaultReferenceExpression {
|
||||
return value.module && value.default && isMetadataSymbolicReferenceExpression(value);
|
||||
return value && value.module && value.default && isMetadataSymbolicReferenceExpression(value);
|
||||
}
|
||||
|
||||
export type MetadataSymbolicReferenceExpression = MetadataGlobalReferenceExpression |
|
||||
@ -248,7 +264,7 @@ export function isMetadataSymbolicSpreadExpression(value: any):
|
||||
return value && value.__symbolic === 'spread';
|
||||
}
|
||||
|
||||
export interface MetadataError {
|
||||
export interface MetadataError extends MetadataSourceLocationInfo {
|
||||
__symbolic: 'error';
|
||||
|
||||
/**
|
||||
@ -259,16 +275,6 @@ export interface MetadataError {
|
||||
*/
|
||||
message: string;
|
||||
|
||||
/**
|
||||
* The line number of the error in the .ts file the metadata was created for.
|
||||
*/
|
||||
line?: number;
|
||||
|
||||
/**
|
||||
* The number of utf8 code-units from the beginning of the file of the error.
|
||||
*/
|
||||
character?: number;
|
||||
|
||||
/**
|
||||
* The module of the error (only used in bundled metadata)
|
||||
*/
|
||||
@ -280,6 +286,7 @@ export interface MetadataError {
|
||||
*/
|
||||
context?: {[name: string]: string};
|
||||
}
|
||||
|
||||
export function isMetadataError(value: any): value is MetadataError {
|
||||
return value && value.__symbolic === 'error';
|
||||
}
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {isSyntaxError, syntaxError} from '@angular/compiler';
|
||||
import {Position, isSyntaxError, syntaxError} from '@angular/compiler';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
@ -29,30 +29,76 @@ const defaultFormatHost: ts.FormatDiagnosticsHost = {
|
||||
getNewLine: () => ts.sys.newLine
|
||||
};
|
||||
|
||||
function displayFileName(fileName: string, host: ts.FormatDiagnosticsHost): string {
|
||||
return path.relative(host.getCurrentDirectory(), host.getCanonicalFileName(fileName));
|
||||
}
|
||||
|
||||
export function formatDiagnosticPosition(
|
||||
position: Position, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
return `${displayFileName(position.fileName, host)}(${position.line + 1},${position.column+1})`;
|
||||
}
|
||||
|
||||
export function flattenDiagnosticMessageChain(
|
||||
chain: api.DiagnosticMessageChain, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
let result = chain.messageText;
|
||||
let indent = 1;
|
||||
let current = chain.next;
|
||||
const newLine = host.getNewLine();
|
||||
while (current) {
|
||||
result += newLine;
|
||||
for (let i = 0; i < indent; i++) {
|
||||
result += ' ';
|
||||
}
|
||||
result += current.messageText;
|
||||
const position = current.position;
|
||||
if (position) {
|
||||
result += ` at ${formatDiagnosticPosition(position, host)}`;
|
||||
}
|
||||
current = current.next;
|
||||
indent++;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatDiagnostic(
|
||||
diagnostic: api.Diagnostic, host: ts.FormatDiagnosticsHost = defaultFormatHost) {
|
||||
let result = '';
|
||||
const newLine = host.getNewLine();
|
||||
const span = diagnostic.span;
|
||||
if (span) {
|
||||
result += `${formatDiagnosticPosition({
|
||||
fileName: span.start.file.url,
|
||||
line: span.start.line,
|
||||
column: span.start.col
|
||||
}, host)}: `;
|
||||
} else if (diagnostic.position) {
|
||||
result += `${formatDiagnosticPosition(diagnostic.position, host)}: `;
|
||||
}
|
||||
if (diagnostic.span && diagnostic.span.details) {
|
||||
result += `: ${diagnostic.span.details}, ${diagnostic.messageText}${newLine}`;
|
||||
} else if (diagnostic.chain) {
|
||||
result += `${flattenDiagnosticMessageChain(diagnostic.chain, host)}.${newLine}`;
|
||||
} else {
|
||||
result += `: ${diagnostic.messageText}${newLine}`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
export function formatDiagnostics(
|
||||
diags: Diagnostics, tsFormatHost: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
diags: Diagnostics, host: ts.FormatDiagnosticsHost = defaultFormatHost): string {
|
||||
if (diags && diags.length) {
|
||||
return diags
|
||||
.map(d => {
|
||||
if (api.isTsDiagnostic(d)) {
|
||||
return ts.formatDiagnostics([d], tsFormatHost);
|
||||
.map(diagnostic => {
|
||||
if (api.isTsDiagnostic(diagnostic)) {
|
||||
return ts.formatDiagnostics([diagnostic], host);
|
||||
} else {
|
||||
let res = ts.DiagnosticCategory[d.category];
|
||||
if (d.span) {
|
||||
res +=
|
||||
` at ${d.span.start.file.url}(${d.span.start.line + 1},${d.span.start.col + 1})`;
|
||||
}
|
||||
if (d.span && d.span.details) {
|
||||
res += `: ${d.span.details}, ${d.messageText}\n`;
|
||||
} else {
|
||||
res += `: ${d.messageText}\n`;
|
||||
}
|
||||
return res;
|
||||
return formatDiagnostic(diagnostic, host);
|
||||
}
|
||||
})
|
||||
.join('');
|
||||
} else
|
||||
} else {
|
||||
return '';
|
||||
}
|
||||
}
|
||||
|
||||
export interface ParsedConfiguration {
|
||||
|
@ -6,16 +6,24 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {GeneratedFile, ParseSourceSpan} from '@angular/compiler';
|
||||
import {GeneratedFile, ParseSourceSpan, Position} from '@angular/compiler';
|
||||
import * as ts from 'typescript';
|
||||
|
||||
export const DEFAULT_ERROR_CODE = 100;
|
||||
export const UNKNOWN_ERROR_CODE = 500;
|
||||
export const SOURCE = 'angular' as 'angular';
|
||||
|
||||
export interface DiagnosticMessageChain {
|
||||
messageText: string;
|
||||
position?: Position;
|
||||
next?: DiagnosticMessageChain;
|
||||
}
|
||||
|
||||
export interface Diagnostic {
|
||||
messageText: string;
|
||||
span?: ParseSourceSpan;
|
||||
position?: Position;
|
||||
chain?: DiagnosticMessageChain;
|
||||
category: ts.DiagnosticCategory;
|
||||
code: number;
|
||||
source: 'angular';
|
||||
|
@ -6,7 +6,7 @@
|
||||
* found in the LICENSE file at https://angular.io/license
|
||||
*/
|
||||
|
||||
import {AotCompiler, AotCompilerHost, AotCompilerOptions, EmitterVisitorContext, GeneratedFile, MessageBundle, NgAnalyzedFile, NgAnalyzedModules, ParseSourceSpan, Serializer, TypeScriptEmitter, Xliff, Xliff2, Xmb, core, createAotCompiler, getParseErrors, isSyntaxError} from '@angular/compiler';
|
||||
import {AotCompiler, AotCompilerHost, AotCompilerOptions, EmitterVisitorContext, FormattedMessageChain, GeneratedFile, MessageBundle, NgAnalyzedFile, NgAnalyzedModules, ParseSourceSpan, Position, Serializer, TypeScriptEmitter, Xliff, Xliff2, Xmb, core, createAotCompiler, getParseErrors, isFormattedError, isSyntaxError} from '@angular/compiler';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import * as ts from 'typescript';
|
||||
@ -14,14 +14,13 @@ import * as ts from 'typescript';
|
||||
import {TypeCheckHost, translateDiagnostics} from '../diagnostics/translate_diagnostics';
|
||||
import {ModuleMetadata, createBundleIndexHost} from '../metadata/index';
|
||||
|
||||
import {CompilerHost, CompilerOptions, CustomTransformers, DEFAULT_ERROR_CODE, Diagnostic, EmitFlags, LazyRoute, LibrarySummary, Program, SOURCE, TsEmitArguments, TsEmitCallback} from './api';
|
||||
import {CompilerHost, CompilerOptions, CustomTransformers, DEFAULT_ERROR_CODE, Diagnostic, DiagnosticMessageChain, EmitFlags, LazyRoute, LibrarySummary, Program, SOURCE, TsEmitArguments, TsEmitCallback} from './api';
|
||||
import {CodeGenerator, TsCompilerAotCompilerTypeCheckHostAdapter, getOriginalReferences} from './compiler_host';
|
||||
import {LowerMetadataCache, getExpressionLoweringTransformFactory} from './lower_expressions';
|
||||
import {getAngularEmitterTransformFactory} from './node_emitter_transform';
|
||||
import {GENERATED_FILES, StructureIsReused, createMessageDiagnostic, isInRootDir, ngToTsDiagnostic, tsStructureIsReused} from './util';
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* Maximum number of files that are emitable via calling ts.Program.emit
|
||||
* passing individual targetSourceFiles.
|
||||
@ -378,10 +377,12 @@ class AngularCompilerProgram implements Program {
|
||||
}
|
||||
|
||||
private get structuralDiagnostics(): Diagnostic[] {
|
||||
if (!this._structuralDiagnostics) {
|
||||
let diagnostics = this._structuralDiagnostics;
|
||||
if (!diagnostics) {
|
||||
this.initSync();
|
||||
diagnostics = (this._structuralDiagnostics = this._structuralDiagnostics || []);
|
||||
}
|
||||
return this._structuralDiagnostics !;
|
||||
return diagnostics;
|
||||
}
|
||||
|
||||
private get tsProgram(): ts.Program {
|
||||
@ -430,16 +431,9 @@ class AngularCompilerProgram implements Program {
|
||||
this.rootNames, this.options, this.host, this.metadataCache, codegen,
|
||||
this.oldProgramLibrarySummaries);
|
||||
const aotOptions = getAotCompilerOptions(this.options);
|
||||
this._structuralDiagnostics = [];
|
||||
const errorCollector =
|
||||
(this.options.collectAllErrors || this.options.fullTemplateTypeCheck) ? (err: any) => {
|
||||
this._structuralDiagnostics !.push({
|
||||
messageText: err.toString(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
});
|
||||
} : undefined;
|
||||
const errorCollector = (this.options.collectAllErrors || this.options.fullTemplateTypeCheck) ?
|
||||
(err: any) => this._addStructuralDiagnostics(err) :
|
||||
undefined;
|
||||
this._compiler = createAotCompiler(this._hostAdapter, aotOptions, errorCollector).compiler;
|
||||
}
|
||||
|
||||
@ -522,33 +516,26 @@ class AngularCompilerProgram implements Program {
|
||||
this._hostAdapter.isSourceFile = () => false;
|
||||
this._tsProgram = ts.createProgram(this.rootNames, this.options, this.hostAdapter);
|
||||
if (isSyntaxError(e)) {
|
||||
const parserErrors = getParseErrors(e);
|
||||
if (parserErrors && parserErrors.length) {
|
||||
this._structuralDiagnostics = [
|
||||
...(this._structuralDiagnostics || []),
|
||||
...parserErrors.map<Diagnostic>(e => ({
|
||||
messageText: e.contextualMessage(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
span: e.span,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}))
|
||||
];
|
||||
} else {
|
||||
this._structuralDiagnostics = [
|
||||
...(this._structuralDiagnostics || []), {
|
||||
messageText: e.message,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}
|
||||
];
|
||||
}
|
||||
this._addStructuralDiagnostics(e);
|
||||
return;
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
|
||||
private _addStructuralDiagnostics(error: Error) {
|
||||
const diagnostics = this._structuralDiagnostics || (this._structuralDiagnostics = []);
|
||||
if (isSyntaxError(error)) {
|
||||
diagnostics.push(...syntaxErrorToDiagnostics(error));
|
||||
} else {
|
||||
diagnostics.push({
|
||||
messageText: error.toString(),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Note: this returns a ts.Diagnostic so that we
|
||||
// can return errors in a ts.EmitResult
|
||||
private generateFilesForEmit(emitFlags: EmitFlags):
|
||||
@ -843,3 +830,56 @@ function mergeEmitResults(emitResults: ts.EmitResult[]): ts.EmitResult {
|
||||
}
|
||||
return {diagnostics, emitSkipped, emittedFiles};
|
||||
}
|
||||
|
||||
function diagnosticSourceOfSpan(span: ParseSourceSpan): ts.SourceFile {
|
||||
// For diagnostics, TypeScript only uses the fileName and text properties.
|
||||
// The redundant '()' are here is to avoid having clang-format breaking the line incorrectly.
|
||||
return ({ fileName: span.start.file.url, text: span.start.file.content } as any);
|
||||
}
|
||||
|
||||
function diagnosticSourceOfFileName(fileName: string, program: ts.Program): ts.SourceFile {
|
||||
const sourceFile = program.getSourceFile(fileName);
|
||||
if (sourceFile) return sourceFile;
|
||||
|
||||
// If we are reporting diagnostics for a source file that is not in the project then we need
|
||||
// to fake a source file so the diagnostic formatting routines can emit the file name.
|
||||
// The redundant '()' are here is to avoid having clang-format breaking the line incorrectly.
|
||||
return ({ fileName, text: '' } as any);
|
||||
}
|
||||
|
||||
|
||||
function diagnosticChainFromFormattedDiagnosticChain(chain: FormattedMessageChain):
|
||||
DiagnosticMessageChain {
|
||||
return {
|
||||
messageText: chain.message,
|
||||
next: chain.next && diagnosticChainFromFormattedDiagnosticChain(chain.next),
|
||||
position: chain.position
|
||||
};
|
||||
}
|
||||
|
||||
function syntaxErrorToDiagnostics(error: Error): Diagnostic[] {
|
||||
const parserErrors = getParseErrors(error);
|
||||
if (parserErrors && parserErrors.length) {
|
||||
return parserErrors.map<Diagnostic>(e => ({
|
||||
messageText: e.contextualMessage(),
|
||||
file: diagnosticSourceOfSpan(e.span),
|
||||
start: e.span.start.offset,
|
||||
length: e.span.end.offset - e.span.start.offset,
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE
|
||||
}));
|
||||
} else {
|
||||
if (isFormattedError(error)) {
|
||||
return [{
|
||||
messageText: error.message,
|
||||
chain: error.chain && diagnosticChainFromFormattedDiagnosticChain(error.chain),
|
||||
category: ts.DiagnosticCategory.Error,
|
||||
source: SOURCE,
|
||||
code: DEFAULT_ERROR_CODE,
|
||||
position: error.position
|
||||
}];
|
||||
}
|
||||
}
|
||||
return [];
|
||||
}
|
Reference in New Issue
Block a user