Merge pull request #11737 from Microsoft/not_implemented

Add noop, notImplemented, and notYetImplemented helpers
This commit is contained in:
Andy
2016-10-20 10:43:49 -07:00
committed by GitHub
18 changed files with 88 additions and 100 deletions

View File

@@ -869,6 +869,14 @@ namespace ts {
return Array.isArray ? Array.isArray(value) : value instanceof Array;
}
/** Does nothing. */
export function noop(): void {}
/** Throws an error because a function is not implemented. */
export function notImplemented(): never {
throw new Error("Not implemented");
}
export function memoize<T>(callback: () => T): () => T {
let value: T;
return () => {

View File

@@ -63,7 +63,7 @@ namespace ts {
let isCurrentFileExternalModule: boolean;
let reportedDeclarationError = false;
let errorNameNode: DeclarationName;
const emitJsDocComments = compilerOptions.removeComments ? () => {} : writeJsDocComments;
const emitJsDocComments = compilerOptions.removeComments ? noop : writeJsDocComments;
const emit = compilerOptions.stripInternal ? stripInternal : emitNode;
let noDeclare: boolean;

View File

@@ -950,8 +950,7 @@ namespace ts {
return runWithCancellationToken(() => {
const resolver = getDiagnosticsProducingTypeChecker().getEmitResolver(sourceFile, cancellationToken);
// Don't actually write any files since we're just getting diagnostics.
const writeFile: WriteFileCallback = () => { };
return ts.getDeclarationDiagnostics(getEmitHost(writeFile), resolver, sourceFile);
return ts.getDeclarationDiagnostics(getEmitHost(noop), resolver, sourceFile);
});
}

View File

@@ -63,11 +63,11 @@ namespace ts {
// Completely ignore indentation for string writers. And map newlines to
// a single space.
writeLine: () => str += " ",
increaseIndent: () => { },
decreaseIndent: () => { },
increaseIndent: noop,
decreaseIndent: noop,
clear: () => str = "",
trackSymbol: () => { },
reportInaccessibleThisError: () => { }
trackSymbol: noop,
reportInaccessibleThisError: noop
};
}

View File

@@ -1331,18 +1331,18 @@ namespace ts {
export namespace Debug {
export const failNotOptional = shouldAssert(AssertionLevel.Normal)
? (message?: string) => assert(false, message || "Node not optional.")
: () => {};
: noop;
export const failBadSyntaxKind = shouldAssert(AssertionLevel.Normal)
? (node: Node, message?: string) => assert(false, message || "Unexpected node.", () => `Node ${formatSyntaxKind(node.kind)} was unexpected.`)
: () => {};
: noop;
export const assertNode = shouldAssert(AssertionLevel.Normal)
? (node: Node, test: (node: Node) => boolean, message?: string) => assert(
test === undefined || test(node),
message || "Unexpected node.",
() => `Node ${formatSyntaxKind(node.kind)} did not pass test '${getFunctionName(test)}'.`)
: () => {};
: noop;
function getFunctionName(func: Function) {
if (typeof func !== "function") {

View File

@@ -690,7 +690,7 @@ namespace Harness {
export const getCurrentDirectory = () => "";
export const args = () => <string[]>[];
export const getExecutingFilePath = () => "";
export const exit = () => { };
export const exit = ts.noop;
export const getDirectories = () => <string[]>[];
export let log = (s: string) => console.log(s);
@@ -1668,7 +1668,7 @@ namespace Harness {
// This does not need to exist strictly speaking, but many tests will need to be updated if it's removed
export function compileString(_code: string, _unitName: string, _callback: (result: CompilerResult) => void) {
// NEWTODO: Re-implement 'compileString'
throw new Error("compileString NYI");
return ts.notImplemented();
}
export interface GeneratedFile {

View File

@@ -313,14 +313,10 @@ namespace Harness.LanguageService {
getLocalizedDiagnosticMessages(): string { return JSON.stringify({}); }
readDirectory(_rootDir: string, _extension: string): string {
throw new Error("NYI");
}
readDirectoryNames(_path: string): string {
throw new Error("Not implemented.");
}
readFileNames(_path: string): string {
throw new Error("Not implemented.");
return ts.notImplemented();
}
readDirectoryNames = ts.notImplemented;
readFileNames = ts.notImplemented;
fileExists(fileName: string) { return this.getScriptInfo(fileName) !== undefined; }
readFile(fileName: string) {
const snapshot = this.nativeHost.getScriptSnapshot(fileName);
@@ -339,7 +335,7 @@ namespace Harness.LanguageService {
constructor(private shim: ts.ClassifierShim) {
}
getEncodedLexicalClassifications(_text: string, _lexState: ts.EndOfLineState, _classifyKeywordsInGenerics?: boolean): ts.Classifications {
throw new Error("NYI");
return ts.notImplemented();
}
getClassificationsForLine(text: string, lexState: ts.EndOfLineState, classifyKeywordsInGenerics?: boolean): ts.ClassificationResult {
const result = this.shim.getClassificationsForLine(text, lexState, classifyKeywordsInGenerics).split("\n");
@@ -648,7 +644,7 @@ namespace Harness.LanguageService {
}
createDirectory(_directoryName: string): void {
throw new Error("Not Implemented Yet.");
return ts.notImplemented();
}
getCurrentDirectory(): string {
@@ -664,15 +660,15 @@ namespace Harness.LanguageService {
}
readDirectory(_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] {
throw new Error("Not implemented Yet.");
return ts.notImplemented();
}
watchFile(): ts.FileWatcher {
return { close() { } };
return { close: ts.noop };
}
watchDirectory(): ts.FileWatcher {
return { close() { } };
return { close: ts.noop };
}
close(): void {

View File

@@ -222,5 +222,5 @@ else {
}
if (!runUnitTests) {
// patch `describe` to skip unit tests
describe = <any>(function () { });
describe = ts.noop as any;
}

View File

@@ -21,15 +21,15 @@ namespace ts {
args: <string[]>[],
newLine: "\r\n",
useCaseSensitiveFileNames: false,
write: () => { },
write: noop,
readFile: (path: string): string => {
return path in fileMap ? fileMap[path].content : undefined;
},
writeFile: (_path: string, _data: string, _writeByteOrderMark?: boolean) => {
throw new Error("NYI");
return ts.notImplemented();
},
resolvePath: (_path: string): string => {
throw new Error("NYI");
return ts.notImplemented();
},
fileExists: (path: string): boolean => {
return path in fileMap;
@@ -37,7 +37,7 @@ namespace ts {
directoryExists: (path: string): boolean => {
return existingDirectories[path] || false;
},
createDirectory: () => { },
createDirectory: noop,
getExecutingFilePath: (): string => {
return "";
},
@@ -47,14 +47,14 @@ namespace ts {
getDirectories: () => [],
getEnvironmentVariable: () => "",
readDirectory: (_path: string, _extension?: string[], _exclude?: string[], _include?: string[]): string[] => {
throw new Error("NYI");
return ts.notImplemented();
},
exit: () => { },
exit: noop,
watchFile: () => ({
close: () => { }
close: noop
}),
watchDirectory: () => ({
close: () => { }
close: noop
}),
setTimeout,
clearTimeout,
@@ -65,14 +65,14 @@ namespace ts {
function createProject(rootFile: string, serverHost: server.ServerHost): { project: server.Project, rootScriptInfo: server.ScriptInfo } {
const logger: server.Logger = {
close() { },
close: noop,
hasLevel: () => false,
loggingEnabled: () => false,
perftrc: () => { },
info: () => { },
startGroup: () => { },
endGroup: () => { },
msg: () => { },
perftrc: noop,
info: noop,
startGroup: noop,
endGroup: noop,
msg: noop,
getLogFileName: (): string => undefined
};
@@ -109,10 +109,7 @@ namespace ts {
const originalFileExists = serverHost.fileExists;
{
// patch fileExists to make sure that disk is not touched
serverHost.fileExists = (): boolean => {
assert.isTrue(false, "fileExists should not be called");
return false;
};
serverHost.fileExists = notImplemented;
const newContent = `import {x} from "f1"
var x: string = 1;`;

View File

@@ -290,7 +290,7 @@ namespace ts {
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (): void => { throw new Error("NotImplemented"); },
writeFile: notImplemented,
getCurrentDirectory: () => currentDirectory,
getDirectories: () => [],
getCanonicalFileName: fileName => fileName.toLowerCase(),
@@ -300,7 +300,7 @@ namespace ts {
const path = normalizePath(combinePaths(currentDirectory, fileName));
return path in files;
},
readFile: (): string => { throw new Error("NotImplemented"); }
readFile: notImplemented
};
const program = createProgram(rootFiles, options, host);
@@ -370,7 +370,7 @@ export = C;
return path in files ? createSourceFile(fileName, files[path], languageVersion) : undefined;
},
getDefaultLibFileName: () => "lib.d.ts",
writeFile: (): void => { throw new Error("NotImplemented"); },
writeFile: notImplemented,
getCurrentDirectory: () => currentDirectory,
getDirectories: () => [],
getCanonicalFileName,
@@ -380,7 +380,7 @@ export = C;
const path = getCanonicalFileName(normalizePath(combinePaths(currentDirectory, fileName)));
return path in files;
},
readFile: (): string => { throw new Error("NotImplemented"); }
readFile: notImplemented
};
const program = createProgram(rootFiles, options, host);
const diagnostics = sortAndDeduplicateDiagnostics(program.getSemanticDiagnostics().concat(program.getOptionsDiagnostics()));
@@ -911,15 +911,11 @@ import b = require("./moduleB");
});
});
function notImplemented(name: string): () => any {
return () => assert(`${name} is not implemented and should not be called`);
}
describe("ModuleResolutionHost.directoryExists", () => {
it("No 'fileExists' calls if containing directory is missing", () => {
const host: ModuleResolutionHost = {
readFile: notImplemented("readFile"),
fileExists: notImplemented("fileExists"),
readFile: notImplemented,
fileExists: notImplemented,
directoryExists: _ => false
};
@@ -1022,9 +1018,7 @@ import b = require("./moduleB");
fileExists : fileName => fileName in sourceFiles,
getSourceFile: fileName => sourceFiles[fileName],
getDefaultLibFileName: () => "lib.d.ts",
writeFile(_file, _text) {
throw new Error("NYI");
},
writeFile: notImplemented,
getCurrentDirectory: () => "/",
getDirectories: () => [],
getCanonicalFileName: f => f.toLowerCase(),

View File

@@ -111,9 +111,7 @@ namespace ts {
getDefaultLibFileName(): string {
return "lib.d.ts";
},
writeFile() {
throw new Error("NYI");
},
writeFile: notImplemented,
getCurrentDirectory(): string {
return "";
},
@@ -244,13 +242,13 @@ namespace ts {
it("fails if change affects type references", () => {
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
updateProgram(program_1, ["a.ts"], { types: ["b"] }, () => { });
updateProgram(program_1, ["a.ts"], { types: ["b"] }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("succeeds if change doesn't affect type references", () => {
const program_1 = newProgram(files, ["a.ts"], { types: ["a"] });
updateProgram(program_1, ["a.ts"], { types: ["a"] }, () => { });
updateProgram(program_1, ["a.ts"], { types: ["a"] }, noop);
assert.isTrue(program_1.structureIsReused);
});
@@ -276,19 +274,19 @@ namespace ts {
it("fails if module kind changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, () => { });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.AMD }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("fails if rootdir changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, () => { });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop);
assert.isTrue(!program_1.structureIsReused);
});
it("fails if config path changes", () => {
const program_1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/b/tsconfig.json" });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, () => { });
updateProgram(program_1, ["a.ts"], { target, module: ModuleKind.CommonJS, configFilePath: "/a/c/tsconfig.json" }, noop);
assert.isTrue(!program_1.structureIsReused);
});

View File

@@ -10,32 +10,32 @@ namespace ts.server {
useCaseSensitiveFileNames: true,
write(s): void { lastWrittenToHost = s; },
readFile(): string { return void 0; },
writeFile(): void {},
writeFile: noop,
resolvePath(): string { return void 0; },
fileExists: () => false,
directoryExists: () => false,
getDirectories: () => [],
createDirectory(): void {},
createDirectory: noop,
getExecutingFilePath(): string { return void 0; },
getCurrentDirectory(): string { return void 0; },
getEnvironmentVariable(): string { return ""; },
readDirectory(): string[] { return []; },
exit(): void { },
exit: noop,
setTimeout() { return 0; },
clearTimeout() { },
clearTimeout: noop,
setImmediate: () => 0,
clearImmediate() {}
clearImmediate: noop
};
const nullCancellationToken: HostCancellationToken = { isCancellationRequested: () => false };
const mockLogger: Logger = {
close(): void {},
close: noop,
hasLevel(): boolean { return false; },
loggingEnabled(): boolean { return false; },
perftrc(): void {},
info(): void {},
startGroup(): void {},
endGroup(): void {},
msg(): void {},
perftrc: noop,
info: noop,
startGroup: noop,
endGroup: noop,
msg: noop,
getLogFileName: (): string => undefined
};

View File

@@ -23,10 +23,6 @@ namespace ts.projectSystem {
readonly callback: TI.RequestCompletedAction;
}
export function notImplemented(): any {
throw new Error("Not yet implemented");
}
export const nullLogger: server.Logger = {
close: () => void 0,
hasLevel: () => void 0,

View File

@@ -242,7 +242,7 @@ namespace ts.server {
}
getCompletionEntrySymbol(_fileName: string, _position: number, _entryName: string): Symbol {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getNavigateToItems(searchValue: string): NavigateToItem[] {
@@ -415,7 +415,7 @@ namespace ts.server {
}
getEmitOutput(_fileName: string): EmitOutput {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getSyntacticDiagnostics(fileName: string): Diagnostic[] {
@@ -457,7 +457,7 @@ namespace ts.server {
}
getCompilerOptionsDiagnostics(): Diagnostic[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getRenameInfo(fileName: string, position: number, findInStrings?: boolean, findInComments?: boolean): RenameInfo {
@@ -562,11 +562,11 @@ namespace ts.server {
}
getNameOrDottedNameSpan(_fileName: string, _startPos: number, _endPos: number): TextSpan {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getBreakpointStatementAtPosition(_fileName: string, _position: number): TextSpan {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getSignatureHelpItems(fileName: string, position: number): SignatureHelpItems {
@@ -656,19 +656,19 @@ namespace ts.server {
}
getOutliningSpans(_fileName: string): OutliningSpan[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getTodoComments(_fileName: string, _descriptors: TodoCommentDescriptor[]): TodoComment[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getDocCommentTemplateAtPosition(_fileName: string, _position: number): TextInsertion {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
isValidBraceCompletionAtPosition(_fileName: string, _position: number, _openingBrace: number): boolean {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getCodeFixesAtPosition(fileName: string, start: number, end: number, errorCodes: number[]): CodeAction[] {
@@ -735,23 +735,23 @@ namespace ts.server {
}
getIndentationAtPosition(_fileName: string, _position: number, _options: EditorOptions): number {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getSyntacticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getSemanticClassifications(_fileName: string, _span: TextSpan): ClassifiedSpan[] {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getEncodedSyntacticClassifications(_fileName: string, _span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getEncodedSemanticClassifications(_fileName: string, _span: TextSpan): Classifications {
throw new Error("Not Implemented Yet.");
return notImplemented();
}
getProgram(): Program {

View File

@@ -9,9 +9,9 @@ namespace ts.server {
}
export const nullTypingsInstaller: ITypingsInstaller = {
enqueueInstallTypingsRequest: () => {},
attach: () => {},
onProjectClosed: () => {},
enqueueInstallTypingsRequest: noop,
attach: noop,
onProjectClosed: noop,
globalTypingsCacheLocation: undefined
};

View File

@@ -15,7 +15,7 @@ namespace ts.server.typingsInstaller {
const nullLog: Log = {
isEnabled: () => false,
writeLine: () => {}
writeLine: noop
};
function typingToFileName(cachePath: string, packageName: string, installTypingHost: InstallTypingHost): string {

View File

@@ -1051,7 +1051,7 @@ namespace ts {
useCaseSensitiveFileNames: () => useCaseSensitivefileNames,
getNewLine: () => getNewLineOrDefaultFromHost(host),
getDefaultLibFileName: (options) => host.getDefaultLibFileName(options),
writeFile: () => { },
writeFile: noop,
getCurrentDirectory: () => currentDirectory,
fileExists: (fileName): boolean => {
// stub missing host functionality

View File

@@ -1142,8 +1142,8 @@ namespace ts {
increaseIndent: () => { indent++; },
decreaseIndent: () => { indent--; },
clear: resetWriter,
trackSymbol: () => { },
reportInaccessibleThisError: () => { }
trackSymbol: noop,
reportInaccessibleThisError: noop
};
function writeIndent() {