Merge branch 'master' into promisesAndUnderscores

This commit is contained in:
Benjamin Lichtman authored and GitHub committed 2018-09-17 16:43:08 -07:00
commit 0cb9fd62ba
69 files changed
+12798 -10428

No files matched your search

@@ -244,6 +244,20 @@ namespace ts {
}, [
combinePaths(basePath, "main.ts")
]);
it("adds extendedSourceFiles only once", () => {
const sourceFile = readJsonConfigFile("configs/fourth.json", (path) => host.readFile(path));
const dir = combinePaths(basePath, "configs");
const expected = [
combinePaths(dir, "third.json"),
combinePaths(dir, "second.json"),
combinePaths(dir, "base.json"),
];
parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json");
assert.deepEqual(sourceFile.extendedSourceFiles, expected);
parseJsonSourceFileConfigFileContent(sourceFile, host, dir, {}, "fourth.json");
assert.deepEqual(sourceFile.extendedSourceFiles, expected);
});
});
});
});
@@ -305,10 +305,10 @@ namespace ts {
assert.equal(program1.structureIsReused, StructureIsReused.Not);
});
it("fails if rootdir changes", () => {
it("succeeds if rootdir changes", () => {
const program1 = newProgram(files, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/b" });
updateProgram(program1, ["a.ts"], { target, module: ModuleKind.CommonJS, rootDir: "/a/c" }, noop);
assert.equal(program1.structureIsReused, StructureIsReused.Not);
assert.equal(program1.structureIsReused, StructureIsReused.Completely);
});
it("fails if config path changes", () => {
+107 -8
View File
@@ -34,6 +34,10 @@ namespace ts.tscWatch {
return `${projectPath(subProject)}/${baseFileName.toLowerCase()}`;
}
function projectFileName(subProject: SubProject, baseFileName: string) {
return `${projectPath(subProject)}/${baseFileName}`;
}
function projectFile(subProject: SubProject, baseFileName: string): File {
return {
path: projectFilePath(subProject, baseFileName),
@@ -94,6 +98,7 @@ namespace ts.tscWatch {
const ui = subProjectFiles(SubProject.ui);
const allFiles: ReadonlyArray<File> = [libFile, ...core, ...logic, ...tests, ...ui];
const testProjectExpectedWatchedFiles = [core[0], core[1], core[2], ...logic, ...tests].map(f => f.path);
const testProjectExpectedWatchedDirectoriesRecursive = [projectPath(SubProject.core), projectPath(SubProject.logic)];
function createSolutionInWatchMode(allFiles: ReadonlyArray<File>, defaultOptions?: BuildOptions, disableConsoleClears?: boolean) {
const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation });
@@ -110,7 +115,7 @@ namespace ts.tscWatch {
function verifyWatches(host: WatchedSystem) {
checkWatchedFiles(host, testProjectExpectedWatchedFiles);
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true);
checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true);
}
it("creates solution in watch mode", () => {
@@ -161,7 +166,7 @@ namespace ts.tscWatch {
function verifyWatches() {
checkWatchedFiles(host, additionalFiles ? testProjectExpectedWatchedFiles.concat(newFile.path) : testProjectExpectedWatchedFiles);
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true);
checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true);
}
}
@@ -347,7 +352,7 @@ function myFunc() { return 100; }`);
function verifyWatches() {
checkWatchedFiles(host, projectFiles.map(f => f.path));
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectories(host, [projectPath(SubProject.core), projectPath(SubProject.logic)], /*recursive*/ true);
checkWatchedDirectories(host, testProjectExpectedWatchedDirectoriesRecursive, /*recursive*/ true);
}
});
@@ -389,12 +394,106 @@ let x: string = 10;`);
});
});
it("tsc-watch works with project references", () => {
// Build the composite project
const host = createSolutionInWatchMode(allFiles);
describe("tsc-watch works with project references", () => {
const coreIndexDts = projectFileName(SubProject.core, "index.d.ts");
const coreAnotherModuleDts = projectFileName(SubProject.core, "anotherModule.d.ts");
const logicIndexDts = projectFileName(SubProject.logic, "index.d.ts");
const expectedWatchedFiles = [core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase()));
const expectedWatchedDirectoriesRecursive = projectSystem.getTypeRootsFromLocation(projectPath(SubProject.tests));
createWatchOfConfigFile(tests[0].path, host);
checkOutputErrorsInitial(host, emptyArray);
function createSolution() {
const host = createWatchedSystem(allFiles, { currentDirectory: projectsLocation });
const solutionBuilder = createSolutionBuilder(host, [`${project}/${SubProject.tests}`], {});
return { host, solutionBuilder };
}
function createBuiltSolution() {
const result = createSolution();
const { host, solutionBuilder } = result;
solutionBuilder.buildAllProjects();
const outputFileStamps = getOutputFileStamps(host);
for (const stamp of outputFileStamps) {
assert.isDefined(stamp[1], `${stamp[0]} expected to be present`);
}
return result;
}
function verifyWatches(host: WatchedSystem) {
checkWatchedFilesDetailed(host, expectedWatchedFiles, 1);
checkWatchedDirectories(host, emptyArray, /*recursive*/ false);
checkWatchedDirectoriesDetailed(host, expectedWatchedDirectoriesRecursive, 1, /*recursive*/ true);
}
function createSolutionAndWatchMode() {
// Build the composite project
const { host, solutionBuilder } = createBuiltSolution();
// Build in watch mode
const watch = createWatchOfConfigFileReturningBuilder(tests[0].path, host);
checkOutputErrorsInitial(host, emptyArray);
return { host, solutionBuilder, watch };
}
function verifyDependencies(watch: () => BuilderProgram, filePath: string, expected: ReadonlyArray<string>) {
checkArray(`${filePath} dependencies`, watch().getAllDependencies(watch().getSourceFile(filePath)!), expected);
}
describe("invoking when references are already built", () => {
it("verifies dependencies and watches", () => {
const { host, watch } = createSolutionAndWatchMode();
verifyWatches(host);
verifyDependencies(watch, coreIndexDts, [coreIndexDts]);
verifyDependencies(watch, coreAnotherModuleDts, [coreAnotherModuleDts]);
verifyDependencies(watch, logicIndexDts, [logicIndexDts, coreAnotherModuleDts]);
verifyDependencies(watch, tests[1].path, [tests[1].path, coreAnotherModuleDts, logicIndexDts, coreAnotherModuleDts]);
});
it("local edit in ts file, result in watch compilation because logic.d.ts is written", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[1].path, `${logic[1].content}
function foo() {
}`);
solutionBuilder.invalidateProject(`${project}/${SubProject.logic}`);
solutionBuilder.buildInvalidatedProject();
host.checkTimeoutQueueLengthAndRun(1); // not ideal, but currently because of d.ts but no new file is written
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]);
});
it("non local edit in ts file, rebuilds in watch compilation", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[1].path, `${logic[1].content}
export function gfoo() {
}`);
solutionBuilder.invalidateProject(logic[0].path);
solutionBuilder.buildInvalidatedProject();
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, emptyArray);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts]);
});
it("change in project reference config file builds correctly", () => {
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
host.writeFile(logic[0].path, JSON.stringify({
compilerOptions: { composite: true, declaration: true, declarationDir: "decls" },
references: [{ path: "../core" }]
}));
solutionBuilder.invalidateProject(logic[0].path, ConfigFileProgramReloadLevel.Full);
solutionBuilder.buildInvalidatedProject();
host.checkTimeoutQueueLengthAndRun(1);
checkOutputErrorsIncremental(host, [
// TODO: #26036
// The error is reported in d.ts file because it isnt resolved from ts file path, but is resolved from .d.ts file
"sample1/logic/decls/index.d.ts(2,22): error TS2307: Cannot find module '../core/anotherModule'.\n"
]);
checkProgramActualFiles(watch().getProgram(), [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]);
});
});
});
});
}
+39 -11
View File
@@ -20,6 +20,13 @@ namespace ts.tscWatch {
checkArray(`Program rootFileNames`, program.getRootFileNames(), expectedFiles);
}
export function createWatchOfConfigFileReturningBuilder(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) {
const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host);
compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation;
const watch = createWatchProgram(compilerHost);
return () => watch.getCurrentProgram();
}
export function createWatchOfConfigFile(configFileName: string, host: WatchedSystem, maxNumberOfFilesToIterateForInvalidation?: number) {
const compilerHost = createWatchCompilerHostOfConfigFile(configFileName, {}, host);
compilerHost.maxNumberOfFilesToIterateForInvalidation = maxNumberOfFilesToIterateForInvalidation;
@@ -443,6 +450,33 @@ namespace ts.tscWatch {
checkOutputErrorsIncremental(host, emptyArray);
});
it("Updates diagnostics when '--noUnusedLabels' changes", () => {
const aTs: File = { path: "/a.ts", content: "label: while (1) {}" };
const files = [libFile, aTs];
const paths = files.map(f => f.path);
const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`;
const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) };
const host = createWatchedSystem([...files, tsconfig]);
const watch = createWatchOfConfigFile(tsconfig.path, host);
checkProgramActualFiles(watch(), paths);
checkOutputErrorsInitial(host, emptyArray);
host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false));
host.checkTimeoutQueueLengthAndRun(1); // reload the configured project
checkProgramActualFiles(watch(), paths);
checkOutputErrorsIncremental(host, [
getDiagnosticOfFileFromProgram(watch(), aTs.path, 0, "label".length, Diagnostics.Unused_label),
]);
host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ true));
host.checkTimeoutQueueLengthAndRun(1); // reload the configured project
checkProgramActualFiles(watch(), paths);
checkOutputErrorsIncremental(host, emptyArray);
});
it("files explicitly excluded in config file", () => {
const configFile: File = {
path: "/a/b/tsconfig.json",
@@ -1190,7 +1224,7 @@ namespace ts.tscWatch {
host.reloadFS(files);
host.runQueuedTimeoutCallbacks();
checkProgramActualFiles(watch(), files.map(file => file.path));
checkOutputErrorsIncremental(host, []);
checkOutputErrorsIncremental(host, emptyArray);
});
it("watched files when file is deleted and new file is added as part of change", () => {
@@ -1322,12 +1356,10 @@ export class B
path: `${currentDirectory}/a.ts`,
content: `declare function foo(): null | { hello: any };
foo().hello`
};
const compilerOptions: CompilerOptions = {
};
const config: File = {
path: `${currentDirectory}/tsconfig.json`,
content: JSON.stringify({ compilerOptions })
content: JSON.stringify({ compilerOptions: {} })
};
const files = [aFile, config, libFile];
const host = createWatchedSystem(files, { currentDirectory });
@@ -1335,8 +1367,7 @@ foo().hello`
checkProgramActualFiles(watch(), [aFile.path, libFile.path]);
checkOutputErrorsInitial(host, emptyArray);
const modifiedTimeOfAJs = host.getModifiedTime(`${currentDirectory}/a.js`);
compilerOptions.strictNullChecks = true;
host.writeFile(config.path, JSON.stringify({ compilerOptions }));
host.writeFile(config.path, JSON.stringify({ compilerOptions: { strictNullChecks: true } }));
host.runQueuedTimeoutCallbacks();
const expectedStrictNullErrors = [
getDiagnosticOfFileFromProgram(watch(), aFile.path, aFile.content.lastIndexOf("foo()"), 5, Diagnostics.Object_is_possibly_null)
@@ -1344,15 +1375,12 @@ foo().hello`
checkOutputErrorsIncremental(host, expectedStrictNullErrors);
// File a need not be rewritten
assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs);
compilerOptions.strict = true;
delete (compilerOptions.strictNullChecks);
host.writeFile(config.path, JSON.stringify({ compilerOptions }));
host.writeFile(config.path, JSON.stringify({ compilerOptions: { strict: true, alwaysStrict: false } })); // Avoid changing 'alwaysStrict' or must re-bind
host.runQueuedTimeoutCallbacks();
checkOutputErrorsIncremental(host, expectedStrictNullErrors);
// File a need not be rewritten
assert.equal(host.getModifiedTime(`${currentDirectory}/a.js`), modifiedTimeOfAJs);
delete (compilerOptions.strict);
host.writeFile(config.path, JSON.stringify({ compilerOptions }));
host.writeFile(config.path, JSON.stringify({ compilerOptions: {} }));
host.runQueuedTimeoutCallbacks();
checkOutputErrorsIncremental(host, emptyArray);
// File a need not be rewritten
+107 -11
View File
@@ -456,7 +456,7 @@ namespace ts.projectSystem {
function protocolFileLocationFromSubstring(file: File, substring: string): protocol.FileLocationRequestArgs {
return { file: file.path, ...protocolLocationFromSubstring(file.content, substring) };
}
function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions) {
function protocolFileSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): protocol.FileSpan {
return { file: file.path, ...protocolTextSpanFromSubstring(file.content, substring, options) };
}
function documentSpanFromSubstring(file: File, substring: string, options?: SpanFromSubstringOptions): DocumentSpan {
@@ -3491,7 +3491,7 @@ namespace ts.projectSystem {
host.checkTimeoutQueueLength(2); // Update configured project and projects for open file
checkProjectActualFiles(services.configuredProjects.get(config.path)!, filesWithFileA.map(f => f.path));
// host.fileExists = originalFileExists;
// host.fileExists = originalFileExists;
openFile(fileSubA);
// This should create inferred project since fileSubA not on the disk
checkProjectActualFiles(services.configuredProjects.get(config.path)!, mapDefined(filesWithFileA, f => f === fileA ? undefined : f.path));
@@ -3672,7 +3672,7 @@ namespace ts.projectSystem {
path: `${projectRoot}/app1/tsconfig.json`,
content: JSON.stringify({
files: ["app.ts", "../core/core.ts"],
compilerOptions: { outFile : "build/output.js" },
compilerOptions: { outFile: "build/output.js" },
compileOnSave: true
})
};
@@ -6778,9 +6778,9 @@ namespace ts.projectSystem {
fileName: "/a.1.ts",
textChanges: [
{
start: { line: 0, offset: 0 },
end: { line: 0, offset: 0 },
newText: "export const a = 0;",
start: { line: 0, offset: 0 },
end: { line: 0, offset: 0 },
newText: "export const a = 0;",
},
],
}
@@ -8287,7 +8287,8 @@ namespace ts.projectSystem {
protocolTextSpanFromSubstring(aFile.content, "C"),
protocolTextSpanFromSubstring(aFile.content, "C", { index: 1 }),
];
const cLocs: protocol.TextSpan[] = [protocolTextSpanFromSubstring(cFile.content, "C")];
const span = protocolTextSpanFromSubstring(cFile.content, "C");
const cLocs: protocol.TextSpan[] = [span];
assert.deepEqual<protocol.RenameResponseBody | undefined>(response, {
info: {
canRename: true,
@@ -8296,6 +8297,7 @@ namespace ts.projectSystem {
kind: ScriptElementKind.constElement,
kindModifiers: ScriptElementKindModifier.exportedModifier,
localizedErrorMessage: undefined,
triggerSpan: span,
},
locs: [
{ file: aFc, locs: cLocs },
@@ -8672,7 +8674,7 @@ new C();`
}));
checkWatchedDirectories(host, [], /*recursive*/ false);
checkWatchedDirectories(host, arrayFrom(expectedRecursiveDirectories.keys()), /*recursive*/ true);
}
}
describe("from files in same folder", () => {
function getFiles(fileContent: string) {
@@ -9750,7 +9752,7 @@ declare class TestLib {
function verifyATsConfigOriginalProject(session: TestSession) {
checkNumberOfProjects(session.getProjectService(), { inferredProjects: 1, configuredProjects: 1 });
verifyInferredProjectUnchanged(session);
verifyATsConfigProject(session);
verifyATsConfigProject(session);
// Close user file should close all the projects
closeFilesForSession([userTs], session);
verifyOnlyOrphanInferredProject(session);
@@ -9900,11 +9902,12 @@ declare class TestLib {
verifyATsConfigWhenOpened(session);
});
interface ReferencesFullRequest extends protocol.FileLocationRequest { readonly command: protocol.CommandTypes.ReferencesFull; }
interface ReferencesFullResponse extends protocol.Response { readonly body: ReadonlyArray<ReferencedSymbol>; }
it("findAllReferencesFull", () => {
const session = makeSampleProjects();
interface ReferencesFullRequest extends protocol.FileLocationRequest { command: protocol.CommandTypes.ReferencesFull; }
interface ReferencesFullResponse extends protocol.Response { body: ReadonlyArray<ReferencedSymbol>; }
const responseFull = executeSessionRequest<ReferencesFullRequest, ReferencesFullResponse>(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(userTs, "fnA()"));
function fnAVoid(kind: SymbolDisplayPartKind): SymbolDisplayPart[] {
@@ -9961,6 +9964,67 @@ declare class TestLib {
verifyATsConfigOriginalProject(session);
});
it("findAllReferencesFull definition is in mapped file", () => {
const aTs: File = { path: "/a/a.ts", content: `function f() {}` };
const aTsconfig: File = {
path: "/a/tsconfig.json",
content: JSON.stringify({ compilerOptions: { declaration: true, declarationMap: true, outFile: "../bin/a.js" } }),
};
const bTs: File = { path: "/b/b.ts", content: `f();` };
const bTsconfig: File = { path: "/b/tsconfig.json", content: JSON.stringify({ references: [{ path: "../a" }] }) };
const aDts: File = { path: "/bin/a.d.ts", content: `declare function f(): void;\n//# sourceMappingURL=a.d.ts.map` };
const aDtsMap: File = {
path: "/bin/a.d.ts.map",
content: JSON.stringify({ version: 3, file: "a.d.ts", sourceRoot: "", sources: ["../a/a.ts"], names: [], mappings: "AAAA,iBAAS,CAAC,SAAK" }),
};
const session = createSession(createServerHost([aTs, aTsconfig, bTs, bTsconfig, aDts, aDtsMap]));
checkDeclarationFiles(aTs, session, [aDtsMap, aDts]);
openFilesForSession([bTs], session);
checkNumberOfProjects(session.getProjectService(), { configuredProjects: 1 });
const responseFull = executeSessionRequest<ReferencesFullRequest, ReferencesFullResponse>(session, protocol.CommandTypes.ReferencesFull, protocolFileLocationFromSubstring(bTs, "f()"));
assert.deepEqual<ReadonlyArray<ReferencedSymbol>>(responseFull, [
{
definition: {
containerKind: ScriptElementKind.unknown,
containerName: "",
displayParts: [
keywordPart(SyntaxKind.FunctionKeyword),
spacePart(),
displayPart("f", SymbolDisplayPartKind.functionName),
punctuationPart(SyntaxKind.OpenParenToken),
punctuationPart(SyntaxKind.CloseParenToken),
punctuationPart(SyntaxKind.ColonToken),
spacePart(),
keywordPart(SyntaxKind.VoidKeyword),
],
fileName: aTs.path,
kind: ScriptElementKind.functionElement,
name: "function f(): void",
textSpan: { start: 9, length: 1 },
},
references: [
{
fileName: bTs.path,
isDefinition: false,
isInString: undefined,
isWriteAccess: false,
textSpan: { start: 0, length: 1 },
},
{
fileName: aTs.path,
isDefinition: true,
isInString: undefined,
isWriteAccess: true,
textSpan: { start: 9, length: 1 },
},
],
}
]);
});
it("findAllReferences -- target does not exist", () => {
const session = makeSampleProjects();
@@ -10001,6 +10065,7 @@ declare class TestLib {
kind: ScriptElementKind.alias,
kindModifiers: ScriptElementKindModifier.none,
localizedErrorMessage: undefined,
triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnA", { index: 1 }),
},
locs: [renameUserTs(userTs), renameATs(aTs)],
});
@@ -10019,6 +10084,7 @@ declare class TestLib {
kind: ScriptElementKind.functionElement,
kindModifiers: ScriptElementKindModifier.exportedModifier,
localizedErrorMessage: undefined,
triggerSpan: protocolTextSpanFromSubstring(aTs.content, "fnA"),
},
locs: [renameATs(aTs), renameUserTs(userTs)],
});
@@ -10047,6 +10113,7 @@ declare class TestLib {
kind: ScriptElementKind.alias,
kindModifiers: ScriptElementKindModifier.none,
localizedErrorMessage: undefined,
triggerSpan: protocolTextSpanFromSubstring(userTs.content, "fnB", { index: 1 }),
},
locs: [
{
@@ -10180,6 +10247,35 @@ declare class TestLib {
});
});
describe("tsserverProjectSystem config file change", () => {
it("Updates diagnostics when '--noUnusedLabels' changes", () => {
const aTs: File = { path: "/a.ts", content: "label: while (1) {}" };
const options = (allowUnusedLabels: boolean) => `{ "compilerOptions": { "allowUnusedLabels": ${allowUnusedLabels} } }`;
const tsconfig: File = { path: "/tsconfig.json", content: options(/*allowUnusedLabels*/ true) };
const host = createServerHost([aTs, tsconfig]);
const session = createSession(host);
openFilesForSession([aTs], session);
host.modifyFile(tsconfig.path, options(/*allowUnusedLabels*/ false));
host.runQueuedTimeoutCallbacks();
const response = executeSessionRequest<protocol.SemanticDiagnosticsSyncRequest, protocol.SemanticDiagnosticsSyncResponse>(session, protocol.CommandTypes.SemanticDiagnosticsSync, { file: aTs.path }) as protocol.Diagnostic[] | undefined;
assert.deepEqual<protocol.Diagnostic[] | undefined>(response, [
{
start: { line: 1, offset: 1 },
end: { line: 1, offset: 1 + "label".length },
text: "Unused label.",
category: "error",
code: Diagnostics.Unused_label.code,
relatedInformation: undefined,
reportsUnnecessary: true,
source: undefined,
},
]);
});
});
function makeReferenceItem(file: File, isDefinition: boolean, text: string, lineText: string, options?: SpanFromSubstringOptions): protocol.ReferencesResponseItem {
return {
...protocolFileSpanFromSubstring(file, text, options),