Skip to content

Commit

Permalink
Detect expectError statements in nested blocks (#19)
Browse files Browse the repository at this point in the history
  • Loading branch information
BendingBender authored and SamVerschueren committed Mar 20, 2019
1 parent 94f9887 commit f97d462
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
35 changes: 24 additions & 11 deletions source/lib/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,14 @@
import * as path from 'path';
import {flattenDiagnosticMessageText, createProgram, SyntaxKind, Diagnostic as TSDiagnostic, Program, SourceFile} from 'typescript';
import {
flattenDiagnosticMessageText,
createProgram,
SyntaxKind,
Diagnostic as TSDiagnostic,
Program,
SourceFile,
Node,
forEachChild
} from 'typescript';
import {Diagnostic, DiagnosticCode, Context, Location} from './interfaces';

// List of diagnostic codes that should be ignored
Expand All @@ -21,26 +30,30 @@ const diagnosticCodesToIgnore = new Set<DiagnosticCode>([
const extractExpectErrorRanges = (program: Program) => {
const expectedErrors = new Map<Location, Pick<Diagnostic, 'fileName' | 'line' | 'column'>>();

for (const sourceFile of program.getSourceFiles()) {
for (const statement of sourceFile.statements) {
if (statement.kind !== SyntaxKind.ExpressionStatement || !statement.getText().startsWith('expectError')) {
continue;
}

function walkNodes(node: Node) {
if (node.kind === SyntaxKind.ExpressionStatement && node.getText().startsWith('expectError')) {
const location = {
fileName: statement.getSourceFile().fileName,
start: statement.getStart(),
end: statement.getEnd()
fileName: node.getSourceFile().fileName,
start: node.getStart(),
end: node.getEnd()
};

const pos = statement.getSourceFile().getLineAndCharacterOfPosition(statement.getStart());
const pos = node
.getSourceFile()
.getLineAndCharacterOfPosition(node.getStart());

expectedErrors.set(location, {
fileName: location.fileName,
line: pos.line + 1,
column: pos.character
});
}

forEachChild(node, walkNodes);
}

for (const sourceFile of program.getSourceFiles()) {
walkNodes(sourceFile);
}

return expectedErrors;
Expand Down
8 changes: 8 additions & 0 deletions source/test/fixtures/expect-error/values/index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,3 +9,11 @@ const foo: {readonly bar: string} = {

expectError(foo.bar = 'quux');
expectError(foo.quux);

// Ignore errors in deeply nested blocks too
try {
if (true) {
expectError(foo.bar = 'quux');
expectError(foo.quux);
}
} catch {}

0 comments on commit f97d462

Please sign in to comment.