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

Detect expectError statements in nested blocks #19

Merged
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions source/lib/compiler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import * as path from 'path';
import {flattenDiagnosticMessageText, createProgram, SyntaxKind, Diagnostic as TSDiagnostic, Program, SourceFile} from 'typescript';
import {
BendingBender marked this conversation as resolved.
Show resolved Hide resolved
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 @@ -22,25 +24,27 @@ 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;
}
walkNodes(sourceFile);
}

function walkNodes(node: Node) {
BendingBender marked this conversation as resolved.
Show resolved Hide resolved
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);
}

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 (e) {}