mirror of
https://github.com/microsoft/TypeScript.git
synced 2026-11-18 20:11:14 +00:00
Merge branch 'baselining' into resolution
This commit is contained in:
commit
2b7ab891ad
236 files changed
+10815
-2401
No files matched your search
+39
-15
@@ -564,7 +564,7 @@ namespace ts {
|
||||
if (!isIIFE) {
|
||||
currentFlow = { flags: FlowFlags.Start };
|
||||
if (containerFlags & (ContainerFlags.IsFunctionExpression | ContainerFlags.IsObjectLiteralOrClassExpressionMethod)) {
|
||||
currentFlow.container = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
|
||||
currentFlow.node = <FunctionExpression | ArrowFunction | MethodDeclaration>node;
|
||||
}
|
||||
}
|
||||
// We create a return control flow graph for IIFEs and constructors. For constructors
|
||||
@@ -581,6 +581,7 @@ namespace ts {
|
||||
if (!(currentFlow.flags & FlowFlags.Unreachable) && containerFlags & ContainerFlags.IsFunctionLike && nodeIsPresent((<FunctionLikeDeclaration>node).body)) {
|
||||
node.flags |= NodeFlags.HasImplicitReturn;
|
||||
if (hasExplicitReturn) node.flags |= NodeFlags.HasExplicitReturn;
|
||||
(<FunctionLikeDeclaration>node).endFlowNode = currentFlow;
|
||||
}
|
||||
if (node.kind === SyntaxKind.SourceFile) {
|
||||
node.flags |= emitFlags;
|
||||
@@ -671,6 +672,9 @@ namespace ts {
|
||||
bindJSDoc(node);
|
||||
return;
|
||||
}
|
||||
if (node.kind >= SyntaxKind.FirstStatement && node.kind <= SyntaxKind.LastStatement && !options.allowUnreachableCode) {
|
||||
node.flowNode = currentFlow;
|
||||
}
|
||||
switch (node.kind) {
|
||||
case SyntaxKind.WhileStatement:
|
||||
bindWhileStatement(<WhileStatement>node);
|
||||
@@ -708,6 +712,9 @@ namespace ts {
|
||||
case SyntaxKind.CaseClause:
|
||||
bindCaseClause(<CaseClause>node);
|
||||
break;
|
||||
case SyntaxKind.ExpressionStatement:
|
||||
bindExpressionStatement(<ExpressionStatement>node);
|
||||
break;
|
||||
case SyntaxKind.LabeledStatement:
|
||||
bindLabeledStatement(<LabeledStatement>node);
|
||||
break;
|
||||
@@ -845,17 +852,11 @@ namespace ts {
|
||||
}
|
||||
|
||||
function createBranchLabel(): FlowLabel {
|
||||
return {
|
||||
flags: FlowFlags.BranchLabel,
|
||||
antecedents: undefined
|
||||
};
|
||||
return { flags: FlowFlags.BranchLabel, antecedents: undefined };
|
||||
}
|
||||
|
||||
function createLoopLabel(): FlowLabel {
|
||||
return {
|
||||
flags: FlowFlags.LoopLabel,
|
||||
antecedents: undefined
|
||||
};
|
||||
return { flags: FlowFlags.LoopLabel, antecedents: undefined };
|
||||
}
|
||||
|
||||
function setFlowNodeReferenced(flow: FlowNode) {
|
||||
@@ -885,7 +886,7 @@ namespace ts {
|
||||
return antecedent;
|
||||
}
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return flowNodeCreated({ flags, expression, antecedent });
|
||||
return flowNodeCreated({ flags, antecedent, node: expression });
|
||||
}
|
||||
|
||||
function createFlowSwitchClause(antecedent: FlowNode, switchStatement: SwitchStatement, clauseStart: number, clauseEnd: number): FlowNode {
|
||||
@@ -893,7 +894,7 @@ namespace ts {
|
||||
return antecedent;
|
||||
}
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return flowNodeCreated({ flags: FlowFlags.SwitchClause, switchStatement, clauseStart, clauseEnd, antecedent });
|
||||
return flowNodeCreated({ flags: FlowFlags.SwitchClause, antecedent, switchStatement, clauseStart, clauseEnd });
|
||||
}
|
||||
|
||||
function createFlowAssignment(antecedent: FlowNode, node: Expression | VariableDeclaration | BindingElement): FlowNode {
|
||||
@@ -901,10 +902,14 @@ namespace ts {
|
||||
return flowNodeCreated({ flags: FlowFlags.Assignment, antecedent, node });
|
||||
}
|
||||
|
||||
function createFlowCall(antecedent: FlowNode, node: CallExpression): FlowNode {
|
||||
setFlowNodeReferenced(antecedent);
|
||||
return flowNodeCreated({ flags: FlowFlags.Call, antecedent, node });
|
||||
}
|
||||
|
||||
function createFlowArrayMutation(antecedent: FlowNode, node: CallExpression | BinaryExpression): FlowNode {
|
||||
setFlowNodeReferenced(antecedent);
|
||||
const res: FlowArrayMutation = flowNodeCreated({ flags: FlowFlags.ArrayMutation, antecedent, node });
|
||||
return res;
|
||||
return flowNodeCreated({ flags: FlowFlags.ArrayMutation, antecedent, node });
|
||||
}
|
||||
|
||||
function finishFlowLabel(flow: FlowLabel): FlowNode {
|
||||
@@ -1030,12 +1035,12 @@ namespace ts {
|
||||
function bindForInOrForOfStatement(node: ForInOrOfStatement): void {
|
||||
const preLoopLabel = createLoopLabel();
|
||||
const postLoopLabel = createBranchLabel();
|
||||
bind(node.expression);
|
||||
addAntecedent(preLoopLabel, currentFlow);
|
||||
currentFlow = preLoopLabel;
|
||||
if (node.kind === SyntaxKind.ForOfStatement) {
|
||||
bind(node.awaitModifier);
|
||||
}
|
||||
bind(node.expression);
|
||||
addAntecedent(postLoopLabel, currentFlow);
|
||||
bind(node.initializer);
|
||||
if (node.initializer.kind !== SyntaxKind.VariableDeclarationList) {
|
||||
@@ -1222,7 +1227,8 @@ namespace ts {
|
||||
addAntecedent(postSwitchLabel, currentFlow);
|
||||
const hasDefault = forEach(node.caseBlock.clauses, c => c.kind === SyntaxKind.DefaultClause);
|
||||
// We mark a switch statement as possibly exhaustive if it has no default clause and if all
|
||||
// case clauses have unreachable end points (e.g. they all return).
|
||||
// case clauses have unreachable end points (e.g. they all return). Note, we no longer need
|
||||
// this property in control flow analysis, it's there only for backwards compatibility.
|
||||
node.possiblyExhaustive = !hasDefault && !postSwitchLabel.antecedents;
|
||||
if (!hasDefault) {
|
||||
addAntecedent(postSwitchLabel, createFlowSwitchClause(preSwitchCaseFlow, node, 0, 0));
|
||||
@@ -1281,6 +1287,24 @@ namespace ts {
|
||||
activeLabels!.pop();
|
||||
}
|
||||
|
||||
function isDottedName(node: Expression): boolean {
|
||||
return node.kind === SyntaxKind.Identifier || node.kind === SyntaxKind.ThisKeyword ||
|
||||
node.kind === SyntaxKind.PropertyAccessExpression && isDottedName((<PropertyAccessExpression>node).expression) ||
|
||||
node.kind === SyntaxKind.ParenthesizedExpression && isDottedName((<ParenthesizedExpression>node).expression);
|
||||
}
|
||||
|
||||
function bindExpressionStatement(node: ExpressionStatement): void {
|
||||
bind(node.expression);
|
||||
// A top level call expression with a dotted function name and at least one argument
|
||||
// is potentially an assertion and is therefore included in the control flow.
|
||||
if (node.expression.kind === SyntaxKind.CallExpression) {
|
||||
const call = <CallExpression>node.expression;
|
||||
if (isDottedName(call.expression)) {
|
||||
currentFlow = createFlowCall(currentFlow, call);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function bindLabeledStatement(node: LabeledStatement): void {
|
||||
const preStatementLabel = createLoopLabel();
|
||||
const postStatementLabel = createBranchLabel();
|
||||
|
||||
@@ -425,7 +425,7 @@ namespace ts {
|
||||
const options = program.getCompilerOptions();
|
||||
forEach(program.getSourceFiles(), f =>
|
||||
program.isSourceFileDefaultLibrary(f) &&
|
||||
!skipTypeChecking(f, options) &&
|
||||
!skipTypeChecking(f, options, program) &&
|
||||
removeSemanticDiagnosticsOf(state, f.path)
|
||||
);
|
||||
}
|
||||
|
||||
+511
-193
File diff suppressed because it is too large.
Load diff
@@ -772,6 +772,12 @@ namespace ts {
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Disable_size_limitations_on_JavaScript_projects
|
||||
},
|
||||
{
|
||||
name: "disableSourceOfProjectReferenceRedirect",
|
||||
type: "boolean",
|
||||
category: Diagnostics.Advanced_Options,
|
||||
description: Diagnostics.Disable_use_of_source_files_instead_of_declaration_files_from_referenced_projects
|
||||
},
|
||||
{
|
||||
name: "noImplicitUseStrict",
|
||||
type: "boolean",
|
||||
|
||||
@@ -1040,6 +1040,35 @@
|
||||
"code": 1357
|
||||
},
|
||||
|
||||
"The types of '{0}' are incompatible between these types.": {
|
||||
"category": "Error",
|
||||
"code": 2200
|
||||
},
|
||||
"The types returned by '{0}' are incompatible between these types.": {
|
||||
"category": "Error",
|
||||
"code": 2201
|
||||
},
|
||||
"Call signature return types '{0}' and '{1}' are incompatible.": {
|
||||
"category": "Error",
|
||||
"code": 2202,
|
||||
"elidedInCompatabilityPyramid": true
|
||||
},
|
||||
"Construct signature return types '{0}' and '{1}' are incompatible.": {
|
||||
"category": "Error",
|
||||
"code": 2203,
|
||||
"elidedInCompatabilityPyramid": true
|
||||
},
|
||||
"Call signatures with no arguments have incompatible return types '{0}' and '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 2204,
|
||||
"elidedInCompatabilityPyramid": true
|
||||
},
|
||||
"Construct signatures with no arguments have incompatible return types '{0}' and '{1}'.": {
|
||||
"category": "Error",
|
||||
"code": 2205,
|
||||
"elidedInCompatabilityPyramid": true
|
||||
},
|
||||
|
||||
"Duplicate identifier '{0}'.": {
|
||||
"category": "Error",
|
||||
"code": 2300
|
||||
@@ -4007,6 +4036,10 @@
|
||||
"category": "Message",
|
||||
"code": 6220
|
||||
},
|
||||
"Disable use of source files instead of declaration files from referenced projects.": {
|
||||
"category": "Message",
|
||||
"code": 6221
|
||||
},
|
||||
|
||||
"Projects to reference": {
|
||||
"category": "Message",
|
||||
|
||||
+10
-4
@@ -1946,11 +1946,17 @@ namespace ts {
|
||||
//
|
||||
|
||||
function emitTypePredicate(node: TypePredicateNode) {
|
||||
if (node.assertsModifier) {
|
||||
emit(node.assertsModifier);
|
||||
writeSpace();
|
||||
}
|
||||
emit(node.parameterName);
|
||||
writeSpace();
|
||||
writeKeyword("is");
|
||||
writeSpace();
|
||||
emit(node.type);
|
||||
if (node.type) {
|
||||
writeSpace();
|
||||
writeKeyword("is");
|
||||
writeSpace();
|
||||
emit(node.type);
|
||||
}
|
||||
}
|
||||
|
||||
function emitTypeReference(node: TypeReferenceNode) {
|
||||
|
||||
+12
-2
@@ -669,16 +669,26 @@ namespace ts {
|
||||
}
|
||||
|
||||
export function createTypePredicateNode(parameterName: Identifier | ThisTypeNode | string, type: TypeNode) {
|
||||
return createTypePredicateNodeWithModifier(/*assertsModifier*/ undefined, parameterName, type);
|
||||
}
|
||||
|
||||
export function createTypePredicateNodeWithModifier(assertsModifier: AssertsToken | undefined, parameterName: Identifier | ThisTypeNode | string, type: TypeNode | undefined) {
|
||||
const node = createSynthesizedNode(SyntaxKind.TypePredicate) as TypePredicateNode;
|
||||
node.assertsModifier = assertsModifier;
|
||||
node.parameterName = asName(parameterName);
|
||||
node.type = type;
|
||||
return node;
|
||||
}
|
||||
|
||||
export function updateTypePredicateNode(node: TypePredicateNode, parameterName: Identifier | ThisTypeNode, type: TypeNode) {
|
||||
return node.parameterName !== parameterName
|
||||
return updateTypePredicateNodeWithModifier(node, node.assertsModifier, parameterName, type);
|
||||
}
|
||||
|
||||
export function updateTypePredicateNodeWithModifier(node: TypePredicateNode, assertsModifier: AssertsToken | undefined, parameterName: Identifier | ThisTypeNode, type: TypeNode | undefined) {
|
||||
return node.assertsModifier !== assertsModifier
|
||||
|| node.parameterName !== parameterName
|
||||
|| node.type !== type
|
||||
? updateNode(createTypePredicateNode(parameterName, type), node)
|
||||
? updateNode(createTypePredicateNodeWithModifier(assertsModifier, parameterName, type), node)
|
||||
: node;
|
||||
}
|
||||
|
||||
|
||||
+14
-1
@@ -165,7 +165,8 @@ namespace ts {
|
||||
return visitNode(cbNode, (<TypeReferenceNode>node).typeName) ||
|
||||
visitNodes(cbNode, cbNodes, (<TypeReferenceNode>node).typeArguments);
|
||||
case SyntaxKind.TypePredicate:
|
||||
return visitNode(cbNode, (<TypePredicateNode>node).parameterName) ||
|
||||
return visitNode(cbNode, (<TypePredicateNode>node).assertsModifier) ||
|
||||
visitNode(cbNode, (<TypePredicateNode>node).parameterName) ||
|
||||
visitNode(cbNode, (<TypePredicateNode>node).type);
|
||||
case SyntaxKind.TypeQuery:
|
||||
return visitNode(cbNode, (<TypeQueryNode>node).exprName);
|
||||
@@ -3041,6 +3042,8 @@ namespace ts {
|
||||
return parseParenthesizedType();
|
||||
case SyntaxKind.ImportKeyword:
|
||||
return parseImportType();
|
||||
case SyntaxKind.AssertsKeyword:
|
||||
return lookAhead(nextTokenIsIdentifierOrKeywordOnSameLine) ? parseAssertsTypePredicate() : parseTypeReference();
|
||||
default:
|
||||
return parseTypeReference();
|
||||
}
|
||||
@@ -3081,6 +3084,7 @@ namespace ts {
|
||||
case SyntaxKind.DotDotDotToken:
|
||||
case SyntaxKind.InferKeyword:
|
||||
case SyntaxKind.ImportKeyword:
|
||||
case SyntaxKind.AssertsKeyword:
|
||||
return true;
|
||||
case SyntaxKind.FunctionKeyword:
|
||||
return !inStartOfParameter;
|
||||
@@ -3257,6 +3261,7 @@ namespace ts {
|
||||
const type = parseType();
|
||||
if (typePredicateVariable) {
|
||||
const node = <TypePredicateNode>createNode(SyntaxKind.TypePredicate, typePredicateVariable.pos);
|
||||
node.assertsModifier = undefined;
|
||||
node.parameterName = typePredicateVariable;
|
||||
node.type = type;
|
||||
return finishNode(node);
|
||||
@@ -3274,6 +3279,14 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function parseAssertsTypePredicate(): TypeNode {
|
||||
const node = <TypePredicateNode>createNode(SyntaxKind.TypePredicate);
|
||||
node.assertsModifier = parseExpectedToken(SyntaxKind.AssertsKeyword);
|
||||
node.parameterName = token() === SyntaxKind.ThisKeyword ? parseThisTypeNode() : parseIdentifier();
|
||||
node.type = parseOptional(SyntaxKind.IsKeyword) ? parseType() : undefined;
|
||||
return finishNode(node);
|
||||
}
|
||||
|
||||
function parseType(): TypeNode {
|
||||
// The rules about 'yield' only apply to actual code/expression contexts. They don't
|
||||
// apply to 'type' contexts. So we disable these parameters here before moving on.
|
||||
|
||||
+87
-11
@@ -817,6 +817,8 @@ namespace ts {
|
||||
let resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined;
|
||||
let projectReferenceRedirects: Map<ResolvedProjectReference | false> | undefined;
|
||||
let mapFromFileToProjectReferenceRedirects: Map<Path> | undefined;
|
||||
let mapFromToProjectReferenceRedirectSource: Map<SourceOfProjectReferenceRedirect> | undefined;
|
||||
const useSourceOfProjectReferenceRedirect = !!host.useSourceOfProjectReferenceRedirect && host.useSourceOfProjectReferenceRedirect();
|
||||
|
||||
const shouldCreateNewSourceFile = shouldProgramCreateNewSourceFiles(oldProgram, options);
|
||||
// We set `structuralIsReused` to `undefined` because `tryReuseStructureFromOldProgram` calls `tryReuseStructureFromOldProgram` which checks
|
||||
@@ -831,17 +833,32 @@ namespace ts {
|
||||
if (!resolvedProjectReferences) {
|
||||
resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
|
||||
}
|
||||
if (host.setResolvedProjectReferenceCallbacks) {
|
||||
host.setResolvedProjectReferenceCallbacks({
|
||||
getSourceOfProjectReferenceRedirect,
|
||||
forEachResolvedProjectReference
|
||||
});
|
||||
}
|
||||
if (rootNames.length) {
|
||||
for (const parsedRef of resolvedProjectReferences) {
|
||||
if (!parsedRef) continue;
|
||||
const out = parsedRef.commandLine.options.outFile || parsedRef.commandLine.options.out;
|
||||
if (out) {
|
||||
processSourceFile(changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
if (useSourceOfProjectReferenceRedirect) {
|
||||
if (out || getEmitModuleKind(parsedRef.commandLine.options) === ModuleKind.None) {
|
||||
for (const fileName of parsedRef.commandLine.fileNames) {
|
||||
processSourceFile(fileName, /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (getEmitModuleKind(parsedRef.commandLine.options) === ModuleKind.None) {
|
||||
for (const fileName of parsedRef.commandLine.fileNames) {
|
||||
if (!fileExtensionIs(fileName, Extension.Dts) && hasTSFileExtension(fileName)) {
|
||||
processSourceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
else {
|
||||
if (out) {
|
||||
processSourceFile(changeExtension(out, ".d.ts"), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
}
|
||||
else if (getEmitModuleKind(parsedRef.commandLine.options) === ModuleKind.None) {
|
||||
for (const fileName of parsedRef.commandLine.fileNames) {
|
||||
if (!fileExtensionIs(fileName, Extension.Dts) && hasTSFileExtension(fileName)) {
|
||||
processSourceFile(getOutputDeclarationFileName(fileName, parsedRef.commandLine, !host.useCaseSensitiveFileNames()), /*isDefaultLib*/ false, /*ignoreNoDefaultLib*/ false, /*packageId*/ undefined);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -955,6 +972,7 @@ namespace ts {
|
||||
getResolvedProjectReferenceToRedirect,
|
||||
getResolvedProjectReferenceByPath,
|
||||
forEachResolvedProjectReference,
|
||||
isSourceOfProjectReferenceRedirect,
|
||||
emitBuildInfo
|
||||
};
|
||||
|
||||
@@ -987,9 +1005,15 @@ namespace ts {
|
||||
return ts.toPath(fileName, currentDirectory, getCanonicalFileName);
|
||||
}
|
||||
|
||||
function isValidSourceFileForEmit(file: SourceFile) {
|
||||
// source file is allowed to be emitted and its not source of project reference redirect
|
||||
return sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect) &&
|
||||
!isSourceOfProjectReferenceRedirect(file.fileName);
|
||||
}
|
||||
|
||||
function getCommonSourceDirectory() {
|
||||
if (commonSourceDirectory === undefined) {
|
||||
const emittedFiles = filter(files, file => sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect));
|
||||
const emittedFiles = filter(files, file => isValidSourceFileForEmit(file));
|
||||
if (options.rootDir && checkSourceFilesBelongToPath(emittedFiles, options.rootDir)) {
|
||||
// If a rootDir is specified use it as the commonSourceDirectory
|
||||
commonSourceDirectory = getNormalizedAbsolutePath(options.rootDir, currentDirectory);
|
||||
@@ -1220,6 +1244,12 @@ namespace ts {
|
||||
}
|
||||
if (projectReferences) {
|
||||
resolvedProjectReferences = projectReferences.map(parseProjectReferenceConfigFile);
|
||||
if (host.setResolvedProjectReferenceCallbacks) {
|
||||
host.setResolvedProjectReferenceCallbacks({
|
||||
getSourceOfProjectReferenceRedirect,
|
||||
forEachResolvedProjectReference
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// check if program source files has changed in the way that can affect structure of the program
|
||||
@@ -1403,6 +1433,13 @@ namespace ts {
|
||||
for (const newSourceFile of newSourceFiles) {
|
||||
const filePath = newSourceFile.path;
|
||||
addFileToFilesByName(newSourceFile, filePath, newSourceFile.resolvedPath);
|
||||
if (useSourceOfProjectReferenceRedirect) {
|
||||
const redirectProject = getProjectReferenceRedirectProject(newSourceFile.fileName);
|
||||
if (redirectProject && !(redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out)) {
|
||||
const redirect = getProjectReferenceOutputName(redirectProject, newSourceFile.fileName);
|
||||
addFileToFilesByName(newSourceFile, toPath(redirect), /*redirectedPath*/ undefined);
|
||||
}
|
||||
}
|
||||
// Set the file as found during node modules search if it was found that way in old progra,
|
||||
if (oldProgram.isSourceFileFromExternalLibrary(oldProgram.getSourceFileByPath(newSourceFile.resolvedPath)!)) {
|
||||
sourceFilesFoundSearchingNodeModules.set(filePath, true);
|
||||
@@ -1682,7 +1719,7 @@ namespace ts {
|
||||
|
||||
function getSemanticDiagnosticsForFileNoCache(sourceFile: SourceFile, cancellationToken: CancellationToken): Diagnostic[] | undefined {
|
||||
return runWithCancellationToken(() => {
|
||||
if (skipTypeChecking(sourceFile, options)) {
|
||||
if (skipTypeChecking(sourceFile, options, program)) {
|
||||
return emptyArray;
|
||||
}
|
||||
|
||||
@@ -2234,6 +2271,16 @@ namespace ts {
|
||||
|
||||
// Get source file from normalized fileName
|
||||
function findSourceFile(fileName: string, path: Path, isDefaultLib: boolean, ignoreNoDefaultLib: boolean, refFile: RefFile | undefined, packageId: PackageId | undefined): SourceFile | undefined {
|
||||
if (useSourceOfProjectReferenceRedirect) {
|
||||
const source = getSourceOfProjectReferenceRedirect(fileName);
|
||||
if (source) {
|
||||
const file = isString(source) ?
|
||||
findSourceFile(source, toPath(source), isDefaultLib, ignoreNoDefaultLib, refFile, packageId) :
|
||||
undefined;
|
||||
if (file) addFileToFilesByName(file, path, /*redirectedPath*/ undefined);
|
||||
return file;
|
||||
}
|
||||
}
|
||||
const originalFileName = fileName;
|
||||
if (filesByName.has(path)) {
|
||||
const file = filesByName.get(path);
|
||||
@@ -2282,7 +2329,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
let redirectedPath: Path | undefined;
|
||||
if (refFile) {
|
||||
if (refFile && !useSourceOfProjectReferenceRedirect) {
|
||||
const redirectProject = getProjectReferenceRedirectProject(fileName);
|
||||
if (redirectProject) {
|
||||
if (redirectProject.commandLine.options.outFile || redirectProject.commandLine.options.out) {
|
||||
@@ -2451,6 +2498,36 @@ namespace ts {
|
||||
});
|
||||
}
|
||||
|
||||
function getSourceOfProjectReferenceRedirect(file: string) {
|
||||
if (!isDeclarationFileName(file)) return undefined;
|
||||
if (mapFromToProjectReferenceRedirectSource === undefined) {
|
||||
mapFromToProjectReferenceRedirectSource = createMap();
|
||||
forEachResolvedProjectReference(resolvedRef => {
|
||||
if (resolvedRef) {
|
||||
const out = resolvedRef.commandLine.options.outFile || resolvedRef.commandLine.options.out;
|
||||
if (out) {
|
||||
// Dont know which source file it means so return true?
|
||||
const outputDts = changeExtension(out, Extension.Dts);
|
||||
mapFromToProjectReferenceRedirectSource!.set(toPath(outputDts), true);
|
||||
}
|
||||
else {
|
||||
forEach(resolvedRef.commandLine.fileNames, fileName => {
|
||||
if (!fileExtensionIs(fileName, Extension.Dts) && hasTSFileExtension(fileName)) {
|
||||
const outputDts = getOutputDeclarationFileName(fileName, resolvedRef.commandLine, host.useCaseSensitiveFileNames());
|
||||
mapFromToProjectReferenceRedirectSource!.set(toPath(outputDts), fileName);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
return mapFromToProjectReferenceRedirectSource.get(toPath(file));
|
||||
}
|
||||
|
||||
function isSourceOfProjectReferenceRedirect(fileName: string) {
|
||||
return useSourceOfProjectReferenceRedirect && !!getResolvedProjectReferenceToRedirect(fileName);
|
||||
}
|
||||
|
||||
function forEachProjectReference<T>(
|
||||
projectReferences: readonly ProjectReference[] | undefined,
|
||||
resolvedProjectReferences: readonly (ResolvedProjectReference | undefined)[] | undefined,
|
||||
@@ -2858,8 +2935,7 @@ namespace ts {
|
||||
const rootPaths = arrayToSet(rootNames, toPath);
|
||||
for (const file of files) {
|
||||
// Ignore file that is not emitted
|
||||
if (!sourceFileMayBeEmitted(file, options, isSourceFileFromExternalLibrary, getResolvedProjectReferenceToRedirect)) continue;
|
||||
if (!rootPaths.has(file.path)) {
|
||||
if (isValidSourceFileForEmit(file) && !rootPaths.has(file.path)) {
|
||||
addProgramDiagnosticAtRefPath(
|
||||
file,
|
||||
rootPaths,
|
||||
|
||||
@@ -66,6 +66,7 @@ namespace ts {
|
||||
abstract: SyntaxKind.AbstractKeyword,
|
||||
any: SyntaxKind.AnyKeyword,
|
||||
as: SyntaxKind.AsKeyword,
|
||||
asserts: SyntaxKind.AssertsKeyword,
|
||||
bigint: SyntaxKind.BigIntKeyword,
|
||||
boolean: SyntaxKind.BooleanKeyword,
|
||||
break: SyntaxKind.BreakKeyword,
|
||||
|
||||
+28
-19
@@ -522,6 +522,33 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function recursiveCreateDirectory(directoryPath: string, sys: System) {
|
||||
const basePath = getDirectoryPath(directoryPath);
|
||||
const shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath);
|
||||
if (shouldCreateParent) {
|
||||
recursiveCreateDirectory(basePath, sys);
|
||||
}
|
||||
if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
|
||||
sys.createDirectory(directoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* patch writefile to create folder before writing the file
|
||||
*/
|
||||
/*@internal*/
|
||||
export function patchWriteFileEnsuringDirectory(sys: System) {
|
||||
// patch writefile to create folder before writing the file
|
||||
const originalWriteFile = sys.writeFile;
|
||||
sys.writeFile = (path, data, writeBom) => {
|
||||
const directoryPath = getDirectoryPath(normalizeSlashes(path));
|
||||
if (directoryPath && !sys.directoryExists(directoryPath)) {
|
||||
recursiveCreateDirectory(directoryPath, sys);
|
||||
}
|
||||
originalWriteFile.call(sys, path, data, writeBom);
|
||||
};
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
export type BufferEncoding = "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex";
|
||||
|
||||
@@ -1367,17 +1394,6 @@ namespace ts {
|
||||
};
|
||||
}
|
||||
|
||||
function recursiveCreateDirectory(directoryPath: string, sys: System) {
|
||||
const basePath = getDirectoryPath(directoryPath);
|
||||
const shouldCreateParent = basePath !== "" && directoryPath !== basePath && !sys.directoryExists(basePath);
|
||||
if (shouldCreateParent) {
|
||||
recursiveCreateDirectory(basePath, sys);
|
||||
}
|
||||
if (shouldCreateParent || !sys.directoryExists(directoryPath)) {
|
||||
sys.createDirectory(directoryPath);
|
||||
}
|
||||
}
|
||||
|
||||
let sys: System | undefined;
|
||||
if (typeof ChakraHost !== "undefined") {
|
||||
sys = getChakraSystem();
|
||||
@@ -1389,14 +1405,7 @@ namespace ts {
|
||||
}
|
||||
if (sys) {
|
||||
// patch writefile to create folder before writing the file
|
||||
const originalWriteFile = sys.writeFile;
|
||||
sys.writeFile = (path, data, writeBom) => {
|
||||
const directoryPath = getDirectoryPath(normalizeSlashes(path));
|
||||
if (directoryPath && !sys!.directoryExists(directoryPath)) {
|
||||
recursiveCreateDirectory(directoryPath, sys!);
|
||||
}
|
||||
originalWriteFile.call(sys, path, data, writeBom);
|
||||
};
|
||||
patchWriteFileEnsuringDirectory(sys);
|
||||
}
|
||||
return sys!;
|
||||
})();
|
||||
|
||||
@@ -2871,7 +2871,7 @@ namespace ts {
|
||||
function tryEnterOrLeaveBlock(operationIndex: number): void {
|
||||
if (blocks) {
|
||||
for (; blockIndex < blockActions!.length && blockOffsets![blockIndex] <= operationIndex; blockIndex++) {
|
||||
const block = blocks[blockIndex];
|
||||
const block: CodeBlock = blocks[blockIndex];
|
||||
const blockAction = blockActions![blockIndex];
|
||||
switch (block.kind) {
|
||||
case CodeBlockKind.Exception:
|
||||
|
||||
+90
-25
@@ -32,6 +32,7 @@ namespace ts {
|
||||
| SyntaxKind.AbstractKeyword
|
||||
| SyntaxKind.AnyKeyword
|
||||
| SyntaxKind.AsKeyword
|
||||
| SyntaxKind.AssertsKeyword
|
||||
| SyntaxKind.BigIntKeyword
|
||||
| SyntaxKind.BooleanKeyword
|
||||
| SyntaxKind.BreakKeyword
|
||||
@@ -250,6 +251,7 @@ namespace ts {
|
||||
// Contextual keywords
|
||||
AbstractKeyword,
|
||||
AsKeyword,
|
||||
AssertsKeyword,
|
||||
AnyKeyword,
|
||||
AsyncKeyword,
|
||||
AwaitKeyword,
|
||||
@@ -361,8 +363,8 @@ namespace ts {
|
||||
SemicolonClassElement,
|
||||
// Element
|
||||
Block,
|
||||
VariableStatement,
|
||||
EmptyStatement,
|
||||
VariableStatement,
|
||||
ExpressionStatement,
|
||||
IfStatement,
|
||||
DoStatement,
|
||||
@@ -512,6 +514,8 @@ namespace ts {
|
||||
LastTemplateToken = TemplateTail,
|
||||
FirstBinaryOperator = LessThanToken,
|
||||
LastBinaryOperator = CaretEqualsToken,
|
||||
FirstStatement = VariableStatement,
|
||||
LastStatement = DebuggerStatement,
|
||||
FirstNode = QualifiedName,
|
||||
FirstJSDocNode = JSDocTypeExpression,
|
||||
LastJSDocNode = JSDocPropertyTag,
|
||||
@@ -614,9 +618,13 @@ namespace ts {
|
||||
|
||||
/* @internal */
|
||||
export const enum RelationComparisonResult {
|
||||
Succeeded = 1, // Should be truthy
|
||||
Failed = 2,
|
||||
FailedAndReported = 3
|
||||
Succeeded = 1 << 0, // Should be truthy
|
||||
Failed = 1 << 1,
|
||||
Reported = 1 << 2,
|
||||
|
||||
ReportsUnmeasurable = 1 << 3,
|
||||
ReportsUnreliable = 1 << 4,
|
||||
ReportsMask = ReportsUnmeasurable | ReportsUnreliable
|
||||
}
|
||||
|
||||
export interface Node extends TextRange {
|
||||
@@ -736,6 +744,7 @@ namespace ts {
|
||||
export type AwaitKeywordToken = Token<SyntaxKind.AwaitKeyword>;
|
||||
export type PlusToken = Token<SyntaxKind.PlusToken>;
|
||||
export type MinusToken = Token<SyntaxKind.MinusToken>;
|
||||
export type AssertsToken = Token<SyntaxKind.AssertsKeyword>;
|
||||
|
||||
export type Modifier
|
||||
= Token<SyntaxKind.AbstractKeyword>
|
||||
@@ -1037,6 +1046,7 @@ namespace ts {
|
||||
questionToken?: QuestionToken;
|
||||
exclamationToken?: ExclamationToken;
|
||||
body?: Block | Expression;
|
||||
/* @internal */ endFlowNode?: FlowNode;
|
||||
}
|
||||
|
||||
export type FunctionLikeDeclaration =
|
||||
@@ -1180,8 +1190,9 @@ namespace ts {
|
||||
export interface TypePredicateNode extends TypeNode {
|
||||
kind: SyntaxKind.TypePredicate;
|
||||
parent: SignatureDeclaration | JSDocTypeExpression;
|
||||
assertsModifier?: AssertsToken;
|
||||
parameterName: Identifier | ThisTypeNode;
|
||||
type: TypeNode;
|
||||
type?: TypeNode;
|
||||
}
|
||||
|
||||
export interface TypeQueryNode extends TypeNode {
|
||||
@@ -2570,16 +2581,33 @@ namespace ts {
|
||||
FalseCondition = 1 << 6, // Condition known to be false
|
||||
SwitchClause = 1 << 7, // Switch statement clause
|
||||
ArrayMutation = 1 << 8, // Potential array mutation
|
||||
Referenced = 1 << 9, // Referenced as antecedent once
|
||||
Shared = 1 << 10, // Referenced as antecedent more than once
|
||||
PreFinally = 1 << 11, // Injected edge that links pre-finally label and pre-try flow
|
||||
AfterFinally = 1 << 12, // Injected edge that links post-finally flow with the rest of the graph
|
||||
Call = 1 << 9, // Potential assertion call
|
||||
Referenced = 1 << 10, // Referenced as antecedent once
|
||||
Shared = 1 << 11, // Referenced as antecedent more than once
|
||||
PreFinally = 1 << 12, // Injected edge that links pre-finally label and pre-try flow
|
||||
AfterFinally = 1 << 13, // Injected edge that links post-finally flow with the rest of the graph
|
||||
/** @internal */
|
||||
Cached = 1 << 13, // Indicates that at least one cross-call cache entry exists for this node, even if not a loop participant
|
||||
Cached = 1 << 14, // Indicates that at least one cross-call cache entry exists for this node, even if not a loop participant
|
||||
Label = BranchLabel | LoopLabel,
|
||||
Condition = TrueCondition | FalseCondition
|
||||
}
|
||||
|
||||
export type FlowNode =
|
||||
| AfterFinallyFlow
|
||||
| PreFinallyFlow
|
||||
| FlowStart
|
||||
| FlowLabel
|
||||
| FlowAssignment
|
||||
| FlowCall
|
||||
| FlowCondition
|
||||
| FlowSwitchClause
|
||||
| FlowArrayMutation;
|
||||
|
||||
export interface FlowNodeBase {
|
||||
flags: FlowFlags;
|
||||
id?: number; // Node id used by flow type cache in checker
|
||||
}
|
||||
|
||||
export interface FlowLock {
|
||||
locked?: boolean;
|
||||
}
|
||||
@@ -2593,18 +2621,11 @@ namespace ts {
|
||||
lock: FlowLock;
|
||||
}
|
||||
|
||||
export type FlowNode =
|
||||
| AfterFinallyFlow | PreFinallyFlow | FlowStart | FlowLabel | FlowAssignment | FlowCondition | FlowSwitchClause | FlowArrayMutation;
|
||||
export interface FlowNodeBase {
|
||||
flags: FlowFlags;
|
||||
id?: number; // Node id used by flow type cache in checker
|
||||
}
|
||||
|
||||
// FlowStart represents the start of a control flow. For a function expression or arrow
|
||||
// function, the container property references the function (which in turn has a flowNode
|
||||
// function, the node property references the function (which in turn has a flowNode
|
||||
// property for the containing control flow).
|
||||
export interface FlowStart extends FlowNodeBase {
|
||||
container?: FunctionExpression | ArrowFunction | MethodDeclaration;
|
||||
node?: FunctionExpression | ArrowFunction | MethodDeclaration;
|
||||
}
|
||||
|
||||
// FlowLabel represents a junction with multiple possible preceding control flows.
|
||||
@@ -2619,10 +2640,15 @@ namespace ts {
|
||||
antecedent: FlowNode;
|
||||
}
|
||||
|
||||
export interface FlowCall extends FlowNodeBase {
|
||||
node: CallExpression;
|
||||
antecedent: FlowNode;
|
||||
}
|
||||
|
||||
// FlowCondition represents a condition that is known to be true or false at the
|
||||
// node's location in the control flow.
|
||||
export interface FlowCondition extends FlowNodeBase {
|
||||
expression: Expression;
|
||||
node: Expression;
|
||||
antecedent: FlowNode;
|
||||
}
|
||||
|
||||
@@ -3039,6 +3065,7 @@ namespace ts {
|
||||
/*@internal*/ getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined;
|
||||
/*@internal*/ forEachResolvedProjectReference<T>(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined;
|
||||
/*@internal*/ getResolvedProjectReferenceByPath(projectReferencePath: Path): ResolvedProjectReference | undefined;
|
||||
/*@internal*/ isSourceOfProjectReferenceRedirect(fileName: string): boolean;
|
||||
/*@internal*/ getProgramBuildInfo?(): ProgramBuildInfo | undefined;
|
||||
/*@internal*/ emitBuildInfo(writeFile?: WriteFileCallback, cancellationToken?: CancellationToken): EmitResult;
|
||||
}
|
||||
@@ -3139,6 +3166,7 @@ namespace ts {
|
||||
getSourceFile(fileName: string): SourceFile | undefined;
|
||||
getResolvedTypeReferenceDirectives(): ReadonlyMap<ResolvedTypeReferenceDirective | undefined>;
|
||||
getProjectReferenceRedirect(fileName: string): string | undefined;
|
||||
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
|
||||
|
||||
readonly redirectTargetsMap: RedirectTargetsMap;
|
||||
}
|
||||
@@ -3289,6 +3317,7 @@ namespace ts {
|
||||
/* @internal */ getElementTypeOfArrayType(arrayType: Type): Type | undefined;
|
||||
/* @internal */ createPromiseType(type: Type): Type;
|
||||
|
||||
/* @internal */ isTypeAssignableTo(source: Type, target: Type): boolean;
|
||||
/* @internal */ createAnonymousType(symbol: Symbol, members: SymbolTable, callSignatures: Signature[], constructSignatures: Signature[], stringIndexInfo: IndexInfo | undefined, numberIndexInfo: IndexInfo | undefined): Type;
|
||||
/* @internal */ createSignature(
|
||||
declaration: SignatureDeclaration,
|
||||
@@ -3527,25 +3556,45 @@ namespace ts {
|
||||
|
||||
export const enum TypePredicateKind {
|
||||
This,
|
||||
Identifier
|
||||
Identifier,
|
||||
AssertsThis,
|
||||
AssertsIdentifier
|
||||
}
|
||||
|
||||
export interface TypePredicateBase {
|
||||
kind: TypePredicateKind;
|
||||
type: Type;
|
||||
type: Type | undefined;
|
||||
}
|
||||
|
||||
export interface ThisTypePredicate extends TypePredicateBase {
|
||||
kind: TypePredicateKind.This;
|
||||
parameterName: undefined;
|
||||
parameterIndex: undefined;
|
||||
type: Type;
|
||||
}
|
||||
|
||||
export interface IdentifierTypePredicate extends TypePredicateBase {
|
||||
kind: TypePredicateKind.Identifier;
|
||||
parameterName: string;
|
||||
parameterIndex: number;
|
||||
type: Type;
|
||||
}
|
||||
|
||||
export type TypePredicate = IdentifierTypePredicate | ThisTypePredicate;
|
||||
export interface AssertsThisTypePredicate extends TypePredicateBase {
|
||||
kind: TypePredicateKind.AssertsThis;
|
||||
parameterName: undefined;
|
||||
parameterIndex: undefined;
|
||||
type: Type | undefined;
|
||||
}
|
||||
|
||||
export interface AssertsIdentifierTypePredicate extends TypePredicateBase {
|
||||
kind: TypePredicateKind.AssertsIdentifier;
|
||||
parameterName: string;
|
||||
parameterIndex: number;
|
||||
type: Type | undefined;
|
||||
}
|
||||
|
||||
export type TypePredicate = ThisTypePredicate | IdentifierTypePredicate | AssertsThisTypePredicate | AssertsIdentifierTypePredicate;
|
||||
|
||||
/* @internal */
|
||||
export type AnyImportSyntax = ImportDeclaration | ImportEqualsDeclaration;
|
||||
@@ -3963,7 +4012,7 @@ namespace ts {
|
||||
resolvedSignature?: Signature; // Cached signature of signature node or call expression
|
||||
resolvedSymbol?: Symbol; // Cached name resolution result
|
||||
resolvedIndexInfo?: IndexInfo; // Cached indexing info resolution result
|
||||
maybeTypePredicate?: boolean; // Cached check whether call expression might reference a type predicate
|
||||
effectsSignature?: Signature; // Signature with possible control flow effects
|
||||
enumMemberValue?: string | number; // Constant value of enum member
|
||||
isVisible?: boolean; // Is this node visible
|
||||
containsArgumentsReference?: boolean; // Whether a function-like declaration contains an 'arguments' reference
|
||||
@@ -3978,6 +4027,7 @@ namespace ts {
|
||||
contextFreeType?: Type; // Cached context-free type used by the first pass of inference; used when a function's return is partially contextually sensitive
|
||||
deferredNodes?: Map<Node>; // Set of nodes whose checking has been deferred
|
||||
capturedBlockScopeBindings?: Symbol[]; // Block-scoped bindings captured beneath this part of an IterationStatement
|
||||
isExhaustive?: boolean; // Is node an exhaustive switch statement
|
||||
}
|
||||
|
||||
export const enum TypeFlags {
|
||||
@@ -4202,7 +4252,7 @@ namespace ts {
|
||||
}
|
||||
|
||||
// Object type or intersection of object types
|
||||
export type BaseType = ObjectType | IntersectionType;
|
||||
export type BaseType = ObjectType | IntersectionType | TypeVariable; // Also `any` and `object`
|
||||
|
||||
export interface InterfaceTypeWithDeclaredMembers extends InterfaceType {
|
||||
declaredProperties: Symbol[]; // Declared members
|
||||
@@ -4631,6 +4681,8 @@ namespace ts {
|
||||
code: number;
|
||||
message: string;
|
||||
reportsUnnecessary?: {};
|
||||
/* @internal */
|
||||
elidedInCompatabilityPyramid?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -4725,6 +4777,7 @@ namespace ts {
|
||||
/* @internal */ diagnostics?: boolean;
|
||||
/* @internal */ extendedDiagnostics?: boolean;
|
||||
disableSizeLimit?: boolean;
|
||||
disableSourceOfProjectReferenceRedirect?: boolean;
|
||||
downlevelIteration?: boolean;
|
||||
emitBOM?: boolean;
|
||||
emitDecoratorMetadata?: boolean;
|
||||
@@ -5253,11 +5306,23 @@ namespace ts {
|
||||
/* @internal */ hasChangedAutomaticTypeDirectiveNames?: boolean;
|
||||
createHash?(data: string): string;
|
||||
getParsedCommandLine?(fileName: string): ParsedCommandLine | undefined;
|
||||
/* @internal */ setResolvedProjectReferenceCallbacks?(callbacks: ResolvedProjectReferenceCallbacks): void;
|
||||
/* @internal */ useSourceOfProjectReferenceRedirect?(): boolean;
|
||||
|
||||
// TODO: later handle this in better way in builder host instead once the api for tsbuild finalizes and doesn't use compilerHost as base
|
||||
/*@internal*/createDirectory?(directory: string): void;
|
||||
}
|
||||
|
||||
/** true if --out otherwise source file name */
|
||||
/*@internal*/
|
||||
export type SourceOfProjectReferenceRedirect = string | true;
|
||||
|
||||
/*@internal*/
|
||||
export interface ResolvedProjectReferenceCallbacks {
|
||||
getSourceOfProjectReferenceRedirect(fileName: string): SourceOfProjectReferenceRedirect | undefined;
|
||||
forEachResolvedProjectReference<T>(cb: (resolvedProjectReference: ResolvedProjectReference | undefined, resolvedProjectReferencePath: Path) => T | undefined): T | undefined;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
export const enum TransformFlags {
|
||||
None = 0,
|
||||
|
||||
@@ -8713,11 +8713,16 @@ namespace ts {
|
||||
return { pos: typeParameters.pos - 1, end: typeParameters.end + 1 };
|
||||
}
|
||||
|
||||
export function skipTypeChecking(sourceFile: SourceFile, options: CompilerOptions) {
|
||||
export interface HostWithIsSourceOfProjectReferenceRedirect {
|
||||
isSourceOfProjectReferenceRedirect(fileName: string): boolean;
|
||||
}
|
||||
export function skipTypeChecking(sourceFile: SourceFile, options: CompilerOptions, host: HostWithIsSourceOfProjectReferenceRedirect) {
|
||||
// If skipLibCheck is enabled, skip reporting errors if file is a declaration file.
|
||||
// If skipDefaultLibCheck is enabled, skip reporting errors if file contains a
|
||||
// '/// <reference no-default-lib="true"/>' directive.
|
||||
return options.skipLibCheck && sourceFile.isDeclarationFile || options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib;
|
||||
return (options.skipLibCheck && sourceFile.isDeclarationFile ||
|
||||
options.skipDefaultLibCheck && sourceFile.hasNoDefaultLib) ||
|
||||
host.isSourceOfProjectReferenceRedirect(sourceFile.fileName);
|
||||
}
|
||||
|
||||
export function isJsonEqual(a: unknown, b: unknown): boolean {
|
||||
|
||||
@@ -333,7 +333,8 @@ namespace ts {
|
||||
|
||||
// Types
|
||||
case SyntaxKind.TypePredicate:
|
||||
return updateTypePredicateNode(<TypePredicateNode>node,
|
||||
return updateTypePredicateNodeWithModifier(<TypePredicateNode>node,
|
||||
visitNode((<TypePredicateNode>node).assertsModifier, visitor),
|
||||
visitNode((<TypePredicateNode>node).parameterName, visitor),
|
||||
visitNode((<TypePredicateNode>node).type, visitor, isTypeNode));
|
||||
|
||||
|
||||
@@ -44,7 +44,10 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
|
||||
export function createServerHost(fileOrFolderList: readonly FileOrFolderOrSymLink[], params?: TestServerHostCreationParameters): TestServerHost {
|
||||
return new TestServerHost(/*withSafelist*/ true, fileOrFolderList, params);
|
||||
const host = new TestServerHost(/*withSafelist*/ true, fileOrFolderList, params);
|
||||
// Just like sys, patch the host to use writeFile
|
||||
patchWriteFileEnsuringDirectory(host);
|
||||
return host;
|
||||
}
|
||||
|
||||
export interface File {
|
||||
@@ -174,8 +177,8 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
}
|
||||
|
||||
export function checkWatchedFiles(host: TestServerHost, expectedFiles: string[]) {
|
||||
checkMapKeys("watchedFiles", host.watchedFiles, expectedFiles);
|
||||
export function checkWatchedFiles(host: TestServerHost, expectedFiles: string[], additionalInfo?: string) {
|
||||
checkMapKeys(`watchedFiles:: ${additionalInfo || ""}::`, host.watchedFiles, expectedFiles);
|
||||
}
|
||||
|
||||
export function checkWatchedFilesDetailed(host: TestServerHost, expectedFiles: ReadonlyMap<number>): void;
|
||||
@@ -1016,6 +1019,19 @@ interface Array<T> { length: number; [n: number]: T; }`
|
||||
}
|
||||
}
|
||||
|
||||
export type TestServerHostTrackingWrittenFiles = TestServerHost & { writtenFiles: Map<true>; };
|
||||
|
||||
export function changeToHostTrackingWrittenFiles(inputHost: TestServerHost) {
|
||||
const host = inputHost as TestServerHostTrackingWrittenFiles;
|
||||
const originalWriteFile = host.writeFile;
|
||||
host.writtenFiles = createMap<true>();
|
||||
host.writeFile = (fileName, content) => {
|
||||
originalWriteFile.call(host, fileName, content);
|
||||
const path = host.toFullPath(fileName);
|
||||
host.writtenFiles.set(path, true);
|
||||
};
|
||||
return host;
|
||||
}
|
||||
export const tsbuildProjectsLocation = "/user/username/projects";
|
||||
export function getTsBuildProjectFilePath(project: string, file: string) {
|
||||
return `${tsbuildProjectsLocation}/${project}/${file}`;
|
||||
|
||||
Vendored
+11
-11
@@ -18,7 +18,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>, T10 | PromiseLike<T10>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9, T10]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -26,7 +26,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8, T9>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>, T9 | PromiseLike<T9>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8, T9]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -34,7 +34,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
|
||||
all<T1, T2, T3, T4, T5, T6, T7, T8>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>, T8 | PromiseLike<T8>]): Promise<[T1, T2, T3, T4, T5, T6, T7, T8]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -42,7 +42,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6, T7>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
|
||||
all<T1, T2, T3, T4, T5, T6, T7>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>, T7 | PromiseLike<T7>]): Promise<[T1, T2, T3, T4, T5, T6, T7]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -50,7 +50,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5, T6>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
|
||||
all<T1, T2, T3, T4, T5, T6>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>, T6 | PromiseLike<T6>]): Promise<[T1, T2, T3, T4, T5, T6]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -58,7 +58,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4, T5>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
|
||||
all<T1, T2, T3, T4, T5>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>, T5 | PromiseLike<T5>]): Promise<[T1, T2, T3, T4, T5]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -66,7 +66,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3, T4>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
|
||||
all<T1, T2, T3, T4>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>, T4 | PromiseLike <T4>]): Promise<[T1, T2, T3, T4]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -74,7 +74,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2, T3>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
|
||||
all<T1, T2, T3>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>, T3 | PromiseLike<T3>]): Promise<[T1, T2, T3]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -82,7 +82,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T1, T2>(values: [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
|
||||
all<T1, T2>(values: readonly [T1 | PromiseLike<T1>, T2 | PromiseLike<T2>]): Promise<[T1, T2]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved with an array of results when all of the provided Promises
|
||||
@@ -90,7 +90,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
all<T>(values: (T | PromiseLike<T>)[]): Promise<T[]>;
|
||||
all<T>(values: readonly (T | PromiseLike<T>)[]): Promise<T[]>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
|
||||
@@ -98,7 +98,7 @@ interface PromiseConstructor {
|
||||
* @param values An array of Promises.
|
||||
* @returns A new Promise.
|
||||
*/
|
||||
race<T>(values: T[]): Promise<T extends PromiseLike<infer U> ? U : T>;
|
||||
race<T>(values: readonly T[]): Promise<T extends PromiseLike<infer U> ? U : T>;
|
||||
|
||||
/**
|
||||
* Creates a Promise that is resolved or rejected when any of the provided Promises are resolved
|
||||
|
||||
@@ -1777,6 +1777,12 @@ namespace ts.server {
|
||||
configFileErrors.push(...parsedCommandLine.errors);
|
||||
}
|
||||
|
||||
this.logger.info(`Config: ${configFilename} : ${JSON.stringify({
|
||||
rootNames: parsedCommandLine.fileNames,
|
||||
options: parsedCommandLine.options,
|
||||
projectReferences: parsedCommandLine.projectReferences
|
||||
}, /*replacer*/ undefined, " ")}`);
|
||||
|
||||
Debug.assert(!!parsedCommandLine.fileNames);
|
||||
const compilerOptions = parsedCommandLine.options;
|
||||
|
||||
@@ -1818,7 +1824,7 @@ namespace ts.server {
|
||||
let scriptInfo: ScriptInfo | NormalizedPath;
|
||||
let path: Path;
|
||||
// Use the project's fileExists so that it can use caching instead of reaching to disk for the query
|
||||
if (!isDynamic && !project.fileExists(newRootFile)) {
|
||||
if (!isDynamic && !project.fileExistsWithCache(newRootFile)) {
|
||||
path = normalizedPathToPath(normalizedPath, this.currentDirectory, this.toCanonicalFileName);
|
||||
const existingValue = projectRootFilesMap.get(path)!;
|
||||
if (isScriptInfo(existingValue)) {
|
||||
@@ -1851,7 +1857,7 @@ namespace ts.server {
|
||||
projectRootFilesMap.forEach((value, path) => {
|
||||
if (!newRootScriptInfoMap.has(path)) {
|
||||
if (isScriptInfo(value)) {
|
||||
project.removeFile(value, project.fileExists(path), /*detachFromProject*/ true);
|
||||
project.removeFile(value, project.fileExistsWithCache(path), /*detachFromProject*/ true);
|
||||
}
|
||||
else {
|
||||
projectRootFilesMap.delete(path);
|
||||
@@ -2584,7 +2590,9 @@ namespace ts.server {
|
||||
|
||||
/*@internal*/
|
||||
getOriginalLocationEnsuringConfiguredProject(project: Project, location: DocumentPosition): DocumentPosition | undefined {
|
||||
const originalLocation = project.getSourceMapper().tryGetSourcePosition(location);
|
||||
const originalLocation = project.isSourceOfProjectReferenceRedirect(location.fileName) ?
|
||||
location :
|
||||
project.getSourceMapper().tryGetSourcePosition(location);
|
||||
if (!originalLocation) return undefined;
|
||||
|
||||
const { fileName } = originalLocation;
|
||||
@@ -2595,7 +2603,8 @@ namespace ts.server {
|
||||
if (!configFileName) return undefined;
|
||||
|
||||
const configuredProject = this.findConfiguredProjectByProjectName(configFileName) ||
|
||||
this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName} for location: ${location.fileName}`);
|
||||
this.createAndLoadConfiguredProject(configFileName, `Creating project for original file: ${originalFileInfo.fileName}${location !== originalLocation ? " for location: " + location.fileName : ""}`);
|
||||
if (configuredProject === project) return originalLocation;
|
||||
updateProjectIfDirty(configuredProject);
|
||||
// Keep this configured project as referenced from project
|
||||
addOriginalConfiguredProject(configuredProject);
|
||||
|
||||
+90
-3
@@ -196,6 +196,11 @@ namespace ts.server {
|
||||
/*@internal*/
|
||||
originalConfiguredProjects: Map<true> | undefined;
|
||||
|
||||
/*@internal*/
|
||||
getResolvedProjectReferenceToRedirect(_fileName: string): ResolvedProjectReference | undefined {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
private readonly cancellationToken: ThrottledCancellationToken;
|
||||
|
||||
public isNonTsProject() {
|
||||
@@ -391,6 +396,11 @@ namespace ts.server {
|
||||
}
|
||||
|
||||
fileExists(file: string): boolean {
|
||||
return this.fileExistsWithCache(file);
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
fileExistsWithCache(file: string): boolean {
|
||||
// As an optimization, don't hit the disks for files we already know don't exist
|
||||
// (because we're watching for their creation).
|
||||
const path = this.toPath(file);
|
||||
@@ -527,8 +537,11 @@ namespace ts.server {
|
||||
return this.projectService.getSourceFileLike(fileName, this);
|
||||
}
|
||||
|
||||
private shouldEmitFile(scriptInfo: ScriptInfo) {
|
||||
return scriptInfo && !scriptInfo.isDynamicOrHasMixedContent();
|
||||
/*@internal*/
|
||||
shouldEmitFile(scriptInfo: ScriptInfo | undefined) {
|
||||
return scriptInfo &&
|
||||
!scriptInfo.isDynamicOrHasMixedContent() &&
|
||||
!this.program!.isSourceOfProjectReferenceRedirect(scriptInfo.path);
|
||||
}
|
||||
|
||||
getCompileOnSaveAffectedFileList(scriptInfo: ScriptInfo): string[] {
|
||||
@@ -538,7 +551,7 @@ namespace ts.server {
|
||||
updateProjectIfDirty(this);
|
||||
this.builderState = BuilderState.create(this.program!, this.projectService.toCanonicalFileName, this.builderState);
|
||||
return mapDefined(BuilderState.getFilesAffectedBy(this.builderState, this.program!, scriptInfo.path, this.cancellationToken, data => this.projectService.host.createHash!(data)), // TODO: GH#18217
|
||||
sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)!) ? sourceFile.fileName : undefined);
|
||||
sourceFile => this.shouldEmitFile(this.projectService.getScriptInfoForPath(sourceFile.path)) ? sourceFile.fileName : undefined);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -1223,6 +1236,11 @@ namespace ts.server {
|
||||
this.rootFilesMap.delete(info.path);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
isSourceOfProjectReferenceRedirect(fileName: string) {
|
||||
return !!this.program && this.program.isSourceOfProjectReferenceRedirect(fileName);
|
||||
}
|
||||
|
||||
protected enableGlobalPlugins(options: CompilerOptions, pluginConfigOverrides: Map<any> | undefined) {
|
||||
const host = this.projectService.host;
|
||||
|
||||
@@ -1475,6 +1493,8 @@ namespace ts.server {
|
||||
configFileWatcher: FileWatcher | undefined;
|
||||
private directoriesWatchedForWildcards: Map<WildcardDirectoryWatcher> | undefined;
|
||||
readonly canonicalConfigFilePath: NormalizedPath;
|
||||
private projectReferenceCallbacks: ResolvedProjectReferenceCallbacks | undefined;
|
||||
private mapOfDeclarationDirectories: Map<true> | undefined;
|
||||
|
||||
/* @internal */
|
||||
pendingReload: ConfigFileProgramReloadLevel | undefined;
|
||||
@@ -1520,6 +1540,63 @@ namespace ts.server {
|
||||
this.canonicalConfigFilePath = asNormalizedPath(projectService.toCanonicalFileName(configFileName));
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
setResolvedProjectReferenceCallbacks(projectReferenceCallbacks: ResolvedProjectReferenceCallbacks) {
|
||||
this.projectReferenceCallbacks = projectReferenceCallbacks;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
useSourceOfProjectReferenceRedirect = () => !!this.languageServiceEnabled &&
|
||||
!this.getCompilerOptions().disableSourceOfProjectReferenceRedirect;
|
||||
|
||||
/**
|
||||
* This implementation of fileExists checks if the file being requested is
|
||||
* .d.ts file for the referenced Project.
|
||||
* If it is it returns true irrespective of whether that file exists on host
|
||||
*/
|
||||
fileExists(file: string): boolean {
|
||||
// Project references go to source file instead of .d.ts file
|
||||
if (this.useSourceOfProjectReferenceRedirect() && this.projectReferenceCallbacks) {
|
||||
const source = this.projectReferenceCallbacks.getSourceOfProjectReferenceRedirect(file);
|
||||
if (source) return isString(source) ? super.fileExists(source) : true;
|
||||
}
|
||||
return super.fileExists(file);
|
||||
}
|
||||
|
||||
/**
|
||||
* This implementation of directoryExists checks if the directory being requested is
|
||||
* directory of .d.ts file for the referenced Project.
|
||||
* If it is it returns true irrespective of whether that directory exists on host
|
||||
*/
|
||||
directoryExists(path: string): boolean {
|
||||
if (super.directoryExists(path)) return true;
|
||||
if (!this.useSourceOfProjectReferenceRedirect() || !this.projectReferenceCallbacks) return false;
|
||||
|
||||
if (!this.mapOfDeclarationDirectories) {
|
||||
this.mapOfDeclarationDirectories = createMap();
|
||||
this.projectReferenceCallbacks.forEachResolvedProjectReference(ref => {
|
||||
if (!ref) return;
|
||||
const out = ref.commandLine.options.outFile || ref.commandLine.options.outDir;
|
||||
if (out) {
|
||||
this.mapOfDeclarationDirectories!.set(getDirectoryPath(this.toPath(out)), true);
|
||||
}
|
||||
else {
|
||||
// Set declaration's in different locations only, if they are next to source the directory present doesnt change
|
||||
const declarationDir = ref.commandLine.options.declarationDir || ref.commandLine.options.outDir;
|
||||
if (declarationDir) {
|
||||
this.mapOfDeclarationDirectories!.set(this.toPath(declarationDir), true);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
const dirPath = this.toPath(path);
|
||||
const dirPathWithTrailingDirectorySeparator = `${dirPath}${directorySeparator}`;
|
||||
return !!forEachKey(
|
||||
this.mapOfDeclarationDirectories,
|
||||
declDirPath => dirPath === declDirPath || startsWith(declDirPath, dirPathWithTrailingDirectorySeparator)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* If the project has reload from disk pending, it reloads (and then updates graph as part of that) instead of just updating the graph
|
||||
* @returns: true if set of files in the project stays the same and false - otherwise.
|
||||
@@ -1528,6 +1605,8 @@ namespace ts.server {
|
||||
this.isInitialLoadPending = returnFalse;
|
||||
const reloadLevel = this.pendingReload;
|
||||
this.pendingReload = ConfigFileProgramReloadLevel.None;
|
||||
this.projectReferenceCallbacks = undefined;
|
||||
this.mapOfDeclarationDirectories = undefined;
|
||||
let result: boolean;
|
||||
switch (reloadLevel) {
|
||||
case ConfigFileProgramReloadLevel.Partial:
|
||||
@@ -1570,6 +1649,12 @@ namespace ts.server {
|
||||
return program && program.forEachResolvedProjectReference(cb);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
getResolvedProjectReferenceToRedirect(fileName: string): ResolvedProjectReference | undefined {
|
||||
const program = this.getCurrentProgram();
|
||||
return program && program.getResolvedProjectReferenceToRedirect(fileName);
|
||||
}
|
||||
|
||||
/*@internal*/
|
||||
enablePluginsWithOptions(options: CompilerOptions, pluginConfigOverrides: Map<any> | undefined) {
|
||||
const host = this.projectService.host;
|
||||
@@ -1652,6 +1737,8 @@ namespace ts.server {
|
||||
this.stopWatchingWildCards();
|
||||
this.projectErrors = undefined;
|
||||
this.configFileSpecs = undefined;
|
||||
this.projectReferenceCallbacks = undefined;
|
||||
this.mapOfDeclarationDirectories = undefined;
|
||||
super.close();
|
||||
}
|
||||
|
||||
|
||||
@@ -495,15 +495,17 @@ namespace ts.server {
|
||||
// the default project; if no configured projects, the first external project should
|
||||
// be the default project; otherwise the first inferred project should be the default.
|
||||
let firstExternalProject;
|
||||
let firstConfiguredProject;
|
||||
for (const project of this.containingProjects) {
|
||||
if (project.projectKind === ProjectKind.Configured) {
|
||||
return project;
|
||||
if (!project.isSourceOfProjectReferenceRedirect(this.fileName)) return project;
|
||||
if (!firstConfiguredProject) firstConfiguredProject = project;
|
||||
}
|
||||
else if (project.projectKind === ProjectKind.External && !firstExternalProject) {
|
||||
firstExternalProject = project;
|
||||
}
|
||||
}
|
||||
return firstExternalProject || this.containingProjects[0];
|
||||
return firstConfiguredProject || firstExternalProject || this.containingProjects[0];
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -448,7 +448,9 @@ namespace ts.server {
|
||||
|
||||
function getDefinitionInProject(definition: DocumentPosition | undefined, definingProject: Project, project: Project): DocumentPosition | undefined {
|
||||
if (!definition || project.containsFile(toNormalizedPath(definition.fileName))) return definition;
|
||||
const mappedDefinition = definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition);
|
||||
const mappedDefinition = definingProject.isSourceOfProjectReferenceRedirect(definition.fileName) ?
|
||||
definition :
|
||||
definingProject.getLanguageService().getSourceMapper().tryGetGeneratedPosition(definition);
|
||||
return mappedDefinition && project.containsFile(toNormalizedPath(mappedDefinition.fileName)) ? mappedDefinition : undefined;
|
||||
}
|
||||
|
||||
@@ -477,7 +479,7 @@ namespace ts.server {
|
||||
for (const symlinkedProject of symlinkedProjects) addToTodo({ project: symlinkedProject, location: originalLocation as TLocation }, toDo!, seenProjects);
|
||||
});
|
||||
}
|
||||
return originalLocation;
|
||||
return originalLocation === location ? undefined : originalLocation;
|
||||
});
|
||||
return toDo;
|
||||
}
|
||||
@@ -1037,7 +1039,9 @@ namespace ts.server {
|
||||
|
||||
private getEmitOutput(args: protocol.FileRequestArgs): EmitOutput {
|
||||
const { file, project } = this.getFileAndProject(args);
|
||||
return project.getLanguageService().getEmitOutput(file);
|
||||
return project.shouldEmitFile(project.getScriptInfo(file)) ?
|
||||
project.getLanguageService().getEmitOutput(file) :
|
||||
{ emitSkipped: true, outputFiles: [] };
|
||||
}
|
||||
|
||||
private mapDefinitionInfo(definitions: readonly DefinitionInfo[], project: Project): readonly protocol.FileSpanWithContext[] {
|
||||
@@ -1672,10 +1676,10 @@ namespace ts.server {
|
||||
}
|
||||
}
|
||||
|
||||
private createCheckList(fileNames: string[], defaultProject?: Project): PendingErrorCheck[] {
|
||||
private createCheckList(fileNames: string[]): PendingErrorCheck[] {
|
||||
return mapDefined<string, PendingErrorCheck>(fileNames, uncheckedFileName => {
|
||||
const fileName = toNormalizedPath(uncheckedFileName);
|
||||
const project = defaultProject || this.projectService.tryGetDefaultProjectForFile(fileName);
|
||||
const project = this.projectService.tryGetDefaultProjectForFile(fileName);
|
||||
return project && { fileName, project };
|
||||
});
|
||||
}
|
||||
|
||||
@@ -393,6 +393,19 @@ namespace ts.codefix {
|
||||
|
||||
function inferTypeFromReferences(program: Program, references: readonly Identifier[], cancellationToken: CancellationToken) {
|
||||
const checker = program.getTypeChecker();
|
||||
const builtinConstructors: { [s: string]: (t: Type) => Type } = {
|
||||
string: () => checker.getStringType(),
|
||||
number: () => checker.getNumberType(),
|
||||
Array: t => checker.createArrayType(t),
|
||||
Promise: t => checker.createPromiseType(t),
|
||||
};
|
||||
const builtins = [
|
||||
checker.getStringType(),
|
||||
checker.getNumberType(),
|
||||
checker.createArrayType(checker.getAnyType()),
|
||||
checker.createPromiseType(checker.getAnyType()),
|
||||
];
|
||||
|
||||
return {
|
||||
single,
|
||||
parameters,
|
||||
@@ -401,26 +414,74 @@ namespace ts.codefix {
|
||||
|
||||
interface CallUsage {
|
||||
argumentTypes: Type[];
|
||||
returnType: Usage;
|
||||
return_: Usage;
|
||||
}
|
||||
|
||||
interface Usage {
|
||||
isNumber?: boolean;
|
||||
isString?: boolean;
|
||||
isNumber: boolean | undefined;
|
||||
isString: boolean | undefined;
|
||||
/** Used ambiguously, eg x + ___ or object[___]; results in string | number if no other evidence exists */
|
||||
isNumberOrString?: boolean;
|
||||
isNumberOrString: boolean | undefined;
|
||||
|
||||
candidateTypes?: Type[];
|
||||
properties?: UnderscoreEscapedMap<Usage>;
|
||||
calls?: CallUsage[];
|
||||
constructs?: CallUsage[];
|
||||
numberIndex?: Usage;
|
||||
stringIndex?: Usage;
|
||||
candidateThisTypes?: Type[];
|
||||
candidateTypes: Type[] | undefined;
|
||||
properties: UnderscoreEscapedMap<Usage> | undefined;
|
||||
calls: CallUsage[] | undefined;
|
||||
constructs: CallUsage[] | undefined;
|
||||
numberIndex: Usage | undefined;
|
||||
stringIndex: Usage | undefined;
|
||||
candidateThisTypes: Type[] | undefined;
|
||||
inferredTypes: Type[] | undefined;
|
||||
}
|
||||
|
||||
function createEmptyUsage(): Usage {
|
||||
return {
|
||||
isNumber: undefined,
|
||||
isString: undefined,
|
||||
isNumberOrString: undefined,
|
||||
candidateTypes: undefined,
|
||||
properties: undefined,
|
||||
calls: undefined,
|
||||
constructs: undefined,
|
||||
numberIndex: undefined,
|
||||
stringIndex: undefined,
|
||||
candidateThisTypes: undefined,
|
||||
inferredTypes: undefined,
|
||||
};
|
||||
}
|
||||
|
||||
function combineUsages(usages: Usage[]): Usage {
|
||||
const combinedProperties = createUnderscoreEscapedMap<Usage[]>();
|
||||
for (const u of usages) {
|
||||
if (u.properties) {
|
||||
u.properties.forEach((p, name) => {
|
||||
if (!combinedProperties.has(name)) {
|
||||
combinedProperties.set(name, []);
|
||||
}
|
||||
combinedProperties.get(name)!.push(p);
|
||||
});
|
||||
}
|
||||
}
|
||||
const properties = createUnderscoreEscapedMap<Usage>();
|
||||
combinedProperties.forEach((ps, name) => {
|
||||
properties.set(name, combineUsages(ps));
|
||||
});
|
||||
return {
|
||||
isNumber: usages.some(u => u.isNumber),
|
||||
isString: usages.some(u => u.isString),
|
||||
isNumberOrString: usages.some(u => u.isNumberOrString),
|
||||
candidateTypes: flatMap(usages, u => u.candidateTypes) as Type[],
|
||||
properties,
|
||||
calls: flatMap(usages, u => u.calls) as CallUsage[],
|
||||
constructs: flatMap(usages, u => u.constructs) as CallUsage[],
|
||||
numberIndex: forEach(usages, u => u.numberIndex),
|
||||
stringIndex: forEach(usages, u => u.stringIndex),
|
||||
candidateThisTypes: flatMap(usages, u => u.candidateThisTypes) as Type[],
|
||||
inferredTypes: undefined, // clear type cache
|
||||
};
|
||||
}
|
||||
|
||||
function single(): Type {
|
||||
return unifyFromUsage(inferTypesFromReferencesSingle(references));
|
||||
return combineTypes(inferTypesFromReferencesSingle(references));
|
||||
}
|
||||
|
||||
function parameters(declaration: FunctionLike): ParameterInference[] | undefined {
|
||||
@@ -428,7 +489,7 @@ namespace ts.codefix {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const usage: Usage = {};
|
||||
const usage = createEmptyUsage();
|
||||
for (const reference of references) {
|
||||
cancellationToken.throwIfCancellationRequested();
|
||||
calculateUsageOfNode(reference, usage);
|
||||
@@ -456,7 +517,7 @@ namespace ts.codefix {
|
||||
const inferred = inferTypesFromReferencesSingle(getReferences(parameter.name, program, cancellationToken));
|
||||
types.push(...(isRest ? mapDefined(inferred, checker.getElementTypeOfArrayType) : inferred));
|
||||
}
|
||||
const type = unifyFromUsage(types);
|
||||
const type = combineTypes(types);
|
||||
return {
|
||||
type: isRest ? checker.createArrayType(type) : type,
|
||||
isOptional: isOptional && !isRest,
|
||||
@@ -466,22 +527,22 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
function thisParameter() {
|
||||
const usage: Usage = {};
|
||||
const usage = createEmptyUsage();
|
||||
for (const reference of references) {
|
||||
cancellationToken.throwIfCancellationRequested();
|
||||
calculateUsageOfNode(reference, usage);
|
||||
}
|
||||
|
||||
return unifyFromUsage(usage.candidateThisTypes || emptyArray);
|
||||
return combineTypes(usage.candidateThisTypes || emptyArray);
|
||||
}
|
||||
|
||||
function inferTypesFromReferencesSingle(references: readonly Identifier[]): Type[] {
|
||||
const usage: Usage = {};
|
||||
const usage: Usage = createEmptyUsage();
|
||||
for (const reference of references) {
|
||||
cancellationToken.throwIfCancellationRequested();
|
||||
calculateUsageOfNode(reference, usage);
|
||||
}
|
||||
return inferFromUsage(usage);
|
||||
return inferTypes(usage);
|
||||
}
|
||||
|
||||
function calculateUsageOfNode(node: Expression, usage: Usage): void {
|
||||
@@ -490,6 +551,9 @@ namespace ts.codefix {
|
||||
}
|
||||
|
||||
switch (node.parent.kind) {
|
||||
case SyntaxKind.ExpressionStatement:
|
||||
addCandidateType(usage, checker.getVoidType());
|
||||
break;
|
||||
case SyntaxKind.PostfixUnaryExpression:
|
||||
usage.isNumber = true;
|
||||
break;
|
||||
@@ -632,6 +696,9 @@ namespace ts.codefix {
|
||||
else if (otherOperandType.flags & TypeFlags.StringLike) {
|
||||
usage.isString = true;
|
||||
}
|
||||
else if (otherOperandType.flags & TypeFlags.Any) {
|
||||
// do nothing, maybe we'll learn something elsewhere
|
||||
}
|
||||
else {
|
||||
usage.isNumberOrString = true;
|
||||
}
|
||||
@@ -677,7 +744,7 @@ namespace ts.codefix {
|
||||
function inferTypeFromCallExpression(parent: CallExpression | NewExpression, usage: Usage): void {
|
||||
const call: CallUsage = {
|
||||
argumentTypes: [],
|
||||
returnType: {}
|
||||
return_: createEmptyUsage()
|
||||
};
|
||||
|
||||
if (parent.arguments) {
|
||||
@@ -686,7 +753,7 @@ namespace ts.codefix {
|
||||
}
|
||||
}
|
||||
|
||||
calculateUsageOfNode(parent, call.returnType);
|
||||
calculateUsageOfNode(parent, call.return_);
|
||||
if (parent.kind === SyntaxKind.CallExpression) {
|
||||
(usage.calls || (usage.calls = [])).push(call);
|
||||
}
|
||||
@@ -700,7 +767,7 @@ namespace ts.codefix {
|
||||
if (!usage.properties) {
|
||||
usage.properties = createUnderscoreEscapedMap<Usage>();
|
||||
}
|
||||
const propertyUsage = usage.properties.get(name) || { };
|
||||
const propertyUsage = usage.properties.get(name) || createEmptyUsage();
|
||||
calculateUsageOfNode(parent, propertyUsage);
|
||||
usage.properties.set(name, propertyUsage);
|
||||
}
|
||||
@@ -712,7 +779,7 @@ namespace ts.codefix {
|
||||
}
|
||||
else {
|
||||
const indexType = checker.getTypeAtLocation(parent.argumentExpression);
|
||||
const indexUsage = {};
|
||||
const indexUsage = createEmptyUsage();
|
||||
calculateUsageOfNode(parent, indexUsage);
|
||||
if (indexType.flags & TypeFlags.NumberLike) {
|
||||
usage.numberIndex = indexUsage;
|
||||
@@ -752,8 +819,12 @@ namespace ts.codefix {
|
||||
return inferences.filter(i => toRemove.every(f => !f(i)));
|
||||
}
|
||||
|
||||
function unifyFromUsage(inferences: readonly Type[], fallback = checker.getAnyType()): Type {
|
||||
if (!inferences.length) return fallback;
|
||||
function combineFromUsage(usage: Usage) {
|
||||
return combineTypes(inferTypes(usage));
|
||||
}
|
||||
|
||||
function combineTypes(inferences: readonly Type[]): Type {
|
||||
if (!inferences.length) return checker.getAnyType();
|
||||
|
||||
// 1. string or number individually override string | number
|
||||
// 2. non-any, non-void overrides any or void
|
||||
@@ -776,12 +847,12 @@ namespace ts.codefix {
|
||||
const anons = good.filter(i => checker.getObjectFlags(i) & ObjectFlags.Anonymous) as AnonymousType[];
|
||||
if (anons.length) {
|
||||
good = good.filter(i => !(checker.getObjectFlags(i) & ObjectFlags.Anonymous));
|
||||
good.push(unifyAnonymousTypes(anons));
|
||||
good.push(combineAnonymousTypes(anons));
|
||||
}
|
||||
return checker.getWidenedType(checker.getUnionType(good));
|
||||
return checker.getWidenedType(checker.getUnionType(good.map(checker.getBaseTypeOfLiteralType), UnionReduction.Subtype));
|
||||
}
|
||||
|
||||
function unifyAnonymousTypes(anons: AnonymousType[]) {
|
||||
function combineAnonymousTypes(anons: AnonymousType[]) {
|
||||
if (anons.length === 1) {
|
||||
return anons[0];
|
||||
}
|
||||
@@ -822,7 +893,7 @@ namespace ts.codefix {
|
||||
numberIndices.length ? checker.createIndexInfo(checker.getUnionType(numberIndices), numberIndexReadonly) : undefined);
|
||||
}
|
||||
|
||||
function inferFromUsage(usage: Usage) {
|
||||
function inferTypes(usage: Usage): Type[] {
|
||||
const types = [];
|
||||
|
||||
if (usage.isNumber) {
|
||||
@@ -834,92 +905,155 @@ namespace ts.codefix {
|
||||
if (usage.isNumberOrString) {
|
||||
types.push(checker.getUnionType([checker.getStringType(), checker.getNumberType()]));
|
||||
}
|
||||
if (usage.numberIndex) {
|
||||
types.push(checker.createArrayType(combineFromUsage(usage.numberIndex)));
|
||||
}
|
||||
if (usage.properties && usage.properties.size
|
||||
|| usage.calls && usage.calls.length
|
||||
|| usage.constructs && usage.constructs.length
|
||||
|| usage.stringIndex) {
|
||||
types.push(inferStructuralType(usage));
|
||||
}
|
||||
|
||||
types.push(...(usage.candidateTypes || []).map(t => checker.getBaseTypeOfLiteralType(t)));
|
||||
types.push(...inferNamedTypesFromProperties(usage));
|
||||
|
||||
if (usage.properties && hasCalls(usage.properties.get("then" as __String))) {
|
||||
const paramType = getParameterTypeFromCalls(0, usage.properties.get("then" as __String)!.calls!, /*isRestParameter*/ false)!; // TODO: GH#18217
|
||||
const types = paramType.getCallSignatures().map(sig => sig.getReturnType());
|
||||
types.push(checker.createPromiseType(types.length ? checker.getUnionType(types, UnionReduction.Subtype) : checker.getAnyType()));
|
||||
}
|
||||
else if (usage.properties && hasCalls(usage.properties.get("push" as __String))) {
|
||||
types.push(checker.createArrayType(getParameterTypeFromCalls(0, usage.properties.get("push" as __String)!.calls!, /*isRestParameter*/ false)!));
|
||||
}
|
||||
|
||||
if (usage.numberIndex) {
|
||||
types.push(checker.createArrayType(recur(usage.numberIndex)));
|
||||
}
|
||||
else if (usage.properties || usage.calls || usage.constructs || usage.stringIndex) {
|
||||
const members = createUnderscoreEscapedMap<Symbol>();
|
||||
const callSignatures: Signature[] = [];
|
||||
const constructSignatures: Signature[] = [];
|
||||
let stringIndexInfo: IndexInfo | undefined;
|
||||
|
||||
if (usage.properties) {
|
||||
usage.properties.forEach((u, name) => {
|
||||
const symbol = checker.createSymbol(SymbolFlags.Property, name);
|
||||
symbol.type = recur(u);
|
||||
members.set(name, symbol);
|
||||
});
|
||||
}
|
||||
|
||||
if (usage.calls) {
|
||||
for (const call of usage.calls) {
|
||||
callSignatures.push(getSignatureFromCall(call));
|
||||
}
|
||||
}
|
||||
|
||||
if (usage.constructs) {
|
||||
for (const construct of usage.constructs) {
|
||||
constructSignatures.push(getSignatureFromCall(construct));
|
||||
}
|
||||
}
|
||||
|
||||
if (usage.stringIndex) {
|
||||
stringIndexInfo = checker.createIndexInfo(recur(usage.stringIndex), /*isReadonly*/ false);
|
||||
}
|
||||
|
||||
types.push(checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined)); // TODO: GH#18217
|
||||
}
|
||||
return types;
|
||||
|
||||
function recur(innerUsage: Usage): Type {
|
||||
return unifyFromUsage(inferFromUsage(innerUsage));
|
||||
}
|
||||
}
|
||||
|
||||
function getParameterTypeFromCalls(parameterIndex: number, calls: CallUsage[], isRestParameter: boolean) {
|
||||
let types: Type[] = [];
|
||||
if (calls) {
|
||||
for (const call of calls) {
|
||||
if (call.argumentTypes.length > parameterIndex) {
|
||||
if (isRestParameter) {
|
||||
types = concatenate(types, map(call.argumentTypes.slice(parameterIndex), a => checker.getBaseTypeOfLiteralType(a)));
|
||||
}
|
||||
else {
|
||||
types.push(checker.getBaseTypeOfLiteralType(call.argumentTypes[parameterIndex]));
|
||||
function inferStructuralType(usage: Usage) {
|
||||
const members = createUnderscoreEscapedMap<Symbol>();
|
||||
if (usage.properties) {
|
||||
usage.properties.forEach((u, name) => {
|
||||
const symbol = checker.createSymbol(SymbolFlags.Property, name);
|
||||
symbol.type = combineFromUsage(u);
|
||||
members.set(name, symbol);
|
||||
});
|
||||
}
|
||||
const callSignatures: Signature[] = usage.calls ? [getSignatureFromCalls(usage.calls)] : [];
|
||||
const constructSignatures: Signature[] = usage.constructs ? [getSignatureFromCalls(usage.constructs)] : [];
|
||||
const stringIndexInfo = usage.stringIndex && checker.createIndexInfo(combineFromUsage(usage.stringIndex), /*isReadonly*/ false);
|
||||
return checker.createAnonymousType(/*symbol*/ undefined!, members, callSignatures, constructSignatures, stringIndexInfo, /*numberIndexInfo*/ undefined); // TODO: GH#18217
|
||||
}
|
||||
|
||||
function inferNamedTypesFromProperties(usage: Usage): Type[] {
|
||||
if (!usage.properties || !usage.properties.size) return [];
|
||||
const types = builtins.filter(t => allPropertiesAreAssignableToUsage(t, usage));
|
||||
if (0 < types.length && types.length < 3) {
|
||||
return types.map(t => inferInstantiationFromUsage(t, usage));
|
||||
}
|
||||
return [];
|
||||
}
|
||||
|
||||
function allPropertiesAreAssignableToUsage(type: Type, usage: Usage) {
|
||||
if (!usage.properties) return false;
|
||||
return !forEachEntry(usage.properties, (propUsage, name) => {
|
||||
const source = checker.getTypeOfPropertyOfType(type, name as string);
|
||||
if (!source) {
|
||||
return true;
|
||||
}
|
||||
if (propUsage.calls) {
|
||||
const sigs = checker.getSignaturesOfType(source, SignatureKind.Call);
|
||||
return !sigs.length || !checker.isTypeAssignableTo(source, getFunctionFromCalls(propUsage.calls));
|
||||
}
|
||||
else {
|
||||
return !checker.isTypeAssignableTo(source, combineFromUsage(propUsage));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* inference is limited to
|
||||
* 1. generic types with a single parameter
|
||||
* 2. inference to/from calls with a single signature
|
||||
*/
|
||||
function inferInstantiationFromUsage(type: Type, usage: Usage) {
|
||||
if (!(getObjectFlags(type) & ObjectFlags.Reference) || !usage.properties) {
|
||||
return type;
|
||||
}
|
||||
const generic = (type as TypeReference).target;
|
||||
const singleTypeParameter = singleOrUndefined(generic.typeParameters);
|
||||
if (!singleTypeParameter) return type;
|
||||
|
||||
const types: Type[] = [];
|
||||
usage.properties.forEach((propUsage, name) => {
|
||||
const genericPropertyType = checker.getTypeOfPropertyOfType(generic, name as string);
|
||||
Debug.assert(!!genericPropertyType, "generic should have all the properties of its reference.");
|
||||
types.push(...inferTypeParameters(genericPropertyType!, combineFromUsage(propUsage), singleTypeParameter));
|
||||
});
|
||||
return builtinConstructors[type.symbol.escapedName as string](combineTypes(types));
|
||||
}
|
||||
|
||||
function inferTypeParameters(genericType: Type, usageType: Type, typeParameter: Type): readonly Type[] {
|
||||
if (genericType === typeParameter) {
|
||||
return [usageType];
|
||||
}
|
||||
else if (genericType.flags & TypeFlags.UnionOrIntersection) {
|
||||
return flatMap((genericType as UnionOrIntersectionType).types, t => inferTypeParameters(t, usageType, typeParameter));
|
||||
}
|
||||
else if (getObjectFlags(genericType) & ObjectFlags.Reference && getObjectFlags(usageType) & ObjectFlags.Reference) {
|
||||
// this is wrong because we need a reference to the targetType to, so we can check that it's also a reference
|
||||
const genericArgs = (genericType as TypeReference).typeArguments;
|
||||
const usageArgs = (usageType as TypeReference).typeArguments;
|
||||
const types = [];
|
||||
if (genericArgs && usageArgs) {
|
||||
for (let i = 0; i < genericArgs.length; i++) {
|
||||
if (usageArgs[i]) {
|
||||
types.push(...inferTypeParameters(genericArgs[i], usageArgs[i], typeParameter));
|
||||
}
|
||||
}
|
||||
}
|
||||
return types;
|
||||
}
|
||||
|
||||
if (types.length) {
|
||||
const type = checker.getWidenedType(checker.getUnionType(types, UnionReduction.Subtype));
|
||||
return isRestParameter ? checker.createArrayType(type) : type;
|
||||
const genericSigs = checker.getSignaturesOfType(genericType, SignatureKind.Call);
|
||||
const usageSigs = checker.getSignaturesOfType(usageType, SignatureKind.Call);
|
||||
if (genericSigs.length === 1 && usageSigs.length === 1) {
|
||||
return inferFromSignatures(genericSigs[0], usageSigs[0], typeParameter);
|
||||
}
|
||||
return undefined;
|
||||
return [];
|
||||
}
|
||||
|
||||
function getSignatureFromCall(call: CallUsage): Signature {
|
||||
function inferFromSignatures(genericSig: Signature, usageSig: Signature, typeParameter: Type) {
|
||||
const types = [];
|
||||
for (let i = 0; i < genericSig.parameters.length; i++) {
|
||||
const genericParam = genericSig.parameters[i];
|
||||
const usageParam = usageSig.parameters[i];
|
||||
const isRest = genericSig.declaration && isRestParameter(genericSig.declaration.parameters[i]);
|
||||
if (!usageParam) {
|
||||
break;
|
||||
}
|
||||
let genericParamType = checker.getTypeOfSymbolAtLocation(genericParam, genericParam.valueDeclaration);
|
||||
const elementType = isRest && checker.getElementTypeOfArrayType(genericParamType);
|
||||
if (elementType) {
|
||||
genericParamType = elementType;
|
||||
}
|
||||
const targetType = (usageParam as SymbolLinks).type || checker.getTypeOfSymbolAtLocation(usageParam, usageParam.valueDeclaration);
|
||||
types.push(...inferTypeParameters(genericParamType, targetType, typeParameter));
|
||||
}
|
||||
const genericReturn = checker.getReturnTypeOfSignature(genericSig);
|
||||
const usageReturn = checker.getReturnTypeOfSignature(usageSig);
|
||||
types.push(...inferTypeParameters(genericReturn, usageReturn, typeParameter));
|
||||
return types;
|
||||
}
|
||||
|
||||
function getFunctionFromCalls(calls: CallUsage[]) {
|
||||
return checker.createAnonymousType(undefined!, createSymbolTable(), [getSignatureFromCalls(calls)], emptyArray, /*stringIndexInfo*/ undefined, /*numberIndexInfo*/ undefined);
|
||||
}
|
||||
|
||||
function getSignatureFromCalls(calls: CallUsage[]): Signature {
|
||||
const parameters: Symbol[] = [];
|
||||
for (let i = 0; i < call.argumentTypes.length; i++) {
|
||||
const length = Math.max(...calls.map(c => c.argumentTypes.length));
|
||||
for (let i = 0; i < length; i++) {
|
||||
const symbol = checker.createSymbol(SymbolFlags.FunctionScopedVariable, escapeLeadingUnderscores(`arg${i}`));
|
||||
symbol.type = checker.getWidenedType(checker.getBaseTypeOfLiteralType(call.argumentTypes[i]));
|
||||
symbol.type = combineTypes(calls.map(call => call.argumentTypes[i] || checker.getUndefinedType()));
|
||||
if (calls.some(call => call.argumentTypes[i] === undefined)) {
|
||||
symbol.flags |= SymbolFlags.Optional;
|
||||
}
|
||||
parameters.push(symbol);
|
||||
}
|
||||
const returnType = unifyFromUsage(inferFromUsage(call.returnType), checker.getVoidType());
|
||||
const returnType = combineFromUsage(combineUsages(calls.map(call => call.return_)));
|
||||
// TODO: GH#18217
|
||||
return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, call.argumentTypes.length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
|
||||
return checker.createSignature(/*declaration*/ undefined!, /*typeParameters*/ undefined, /*thisParameter*/ undefined, parameters, returnType, /*typePredicate*/ undefined, length, /*hasRestParameter*/ false, /*hasLiteralTypes*/ false);
|
||||
}
|
||||
|
||||
function addCandidateType(usage: Usage, type: Type | undefined) {
|
||||
@@ -933,9 +1067,5 @@ namespace ts.codefix {
|
||||
(usage.candidateThisTypes || (usage.candidateThisTypes = [])).push(type);
|
||||
}
|
||||
}
|
||||
|
||||
function hasCalls(usage: Usage | undefined): boolean {
|
||||
return !!usage && !!usage.calls;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1149,10 +1149,10 @@ namespace ts {
|
||||
useCaseSensitiveFileNames: () => useCaseSensitiveFileNames,
|
||||
getCurrentDirectory: () => currentDirectory,
|
||||
getProgram,
|
||||
fileExists: host.fileExists && (f => host.fileExists!(f)),
|
||||
readFile: host.readFile && ((f, encoding) => host.readFile!(f, encoding)),
|
||||
getDocumentPositionMapper: host.getDocumentPositionMapper && ((generatedFileName, sourceFileName) => host.getDocumentPositionMapper!(generatedFileName, sourceFileName)),
|
||||
getSourceFileLike: host.getSourceFileLike && (f => host.getSourceFileLike!(f)),
|
||||
fileExists: maybeBind(host, host.fileExists),
|
||||
readFile: maybeBind(host, host.readFile),
|
||||
getDocumentPositionMapper: maybeBind(host, host.getDocumentPositionMapper),
|
||||
getSourceFileLike: maybeBind(host, host.getSourceFileLike),
|
||||
log
|
||||
});
|
||||
|
||||
@@ -1250,6 +1250,12 @@ namespace ts {
|
||||
if (host.resolveTypeReferenceDirectives) {
|
||||
compilerHost.resolveTypeReferenceDirectives = (...args) => host.resolveTypeReferenceDirectives!(...args);
|
||||
}
|
||||
if (host.setResolvedProjectReferenceCallbacks) {
|
||||
compilerHost.setResolvedProjectReferenceCallbacks = callbacks => host.setResolvedProjectReferenceCallbacks!(callbacks);
|
||||
}
|
||||
if (host.useSourceOfProjectReferenceRedirect) {
|
||||
compilerHost.useSourceOfProjectReferenceRedirect = () => host.useSourceOfProjectReferenceRedirect!();
|
||||
}
|
||||
|
||||
const documentRegistryBucketKey = documentRegistry.getKeyForCompilationSettings(newSettings);
|
||||
const options: CreateProgramOptions = {
|
||||
|
||||
@@ -70,6 +70,11 @@ namespace ts {
|
||||
if (!sourceFile) return undefined;
|
||||
|
||||
const program = host.getProgram()!;
|
||||
// If this is source file of project reference source (instead of redirect) there is no generated position
|
||||
if (program.isSourceOfProjectReferenceRedirect(sourceFile.fileName)) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const options = program.getCompilerOptions();
|
||||
const outPath = options.outFile || options.out;
|
||||
|
||||
|
||||
@@ -234,6 +234,10 @@ namespace ts {
|
||||
getDocumentPositionMapper?(generatedFileName: string, sourceFileName?: string): DocumentPositionMapper | undefined;
|
||||
/* @internal */
|
||||
getSourceFileLike?(fileName: string): SourceFileLike | undefined;
|
||||
/* @internal */
|
||||
setResolvedProjectReferenceCallbacks?(callbacks: ResolvedProjectReferenceCallbacks): void;
|
||||
/* @internal */
|
||||
useSourceOfProjectReferenceRedirect?(): boolean;
|
||||
}
|
||||
|
||||
/* @internal */
|
||||
|
||||
@@ -147,6 +147,8 @@
|
||||
"unittests/tsserver/occurences.ts",
|
||||
"unittests/tsserver/openFile.ts",
|
||||
"unittests/tsserver/projectErrors.ts",
|
||||
"unittests/tsserver/projectReferenceCompileOnSave.ts",
|
||||
"unittests/tsserver/projectReferenceErrors.ts",
|
||||
"unittests/tsserver/projectReferences.ts",
|
||||
"unittests/tsserver/projects.ts",
|
||||
"unittests/tsserver/refactors.ts",
|
||||
|
||||
@@ -2,18 +2,12 @@ namespace ts.tscWatch {
|
||||
import projectsLocation = TestFSWithWatch.tsbuildProjectsLocation;
|
||||
import getFilePathInProject = TestFSWithWatch.getTsBuildProjectFilePath;
|
||||
import getFileFromProject = TestFSWithWatch.getTsBuildProjectFile;
|
||||
type TsBuildWatchSystem = WatchedSystem & { writtenFiles: Map<true>; };
|
||||
type TsBuildWatchSystem = TestFSWithWatch.TestServerHostTrackingWrittenFiles;
|
||||
|
||||
function createTsBuildWatchSystem(fileOrFolderList: readonly TestFSWithWatch.FileOrFolderOrSymLink[], params?: TestFSWithWatch.TestServerHostCreationParameters) {
|
||||
const host = createWatchedSystem(fileOrFolderList, params) as TsBuildWatchSystem;
|
||||
const originalWriteFile = host.writeFile;
|
||||
host.writtenFiles = createMap<true>();
|
||||
host.writeFile = (fileName, content) => {
|
||||
originalWriteFile.call(host, fileName, content);
|
||||
const path = host.toFullPath(fileName);
|
||||
host.writtenFiles.set(path, true);
|
||||
};
|
||||
return host;
|
||||
return TestFSWithWatch.changeToHostTrackingWrittenFiles(
|
||||
createWatchedSystem(fileOrFolderList, params)
|
||||
);
|
||||
}
|
||||
|
||||
export function createSolutionBuilder(system: WatchedSystem, rootNames: readonly string[], defaultOptions?: BuildOptions) {
|
||||
@@ -710,8 +704,8 @@ let x: string = 10;`);
|
||||
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));
|
||||
const expectedProjectFiles = () => [libFile, ...tests, ...logic.slice(1), ...core.slice(1, core.length - 1)].map(f => f.path);
|
||||
const expectedProgramFiles = () => [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, logicIndexDts];
|
||||
|
||||
function createSolutionAndWatchMode() {
|
||||
@@ -723,12 +717,19 @@ let x: string = 10;`);
|
||||
}
|
||||
|
||||
function verifyWatches(host: TsBuildWatchSystem, withTsserver?: boolean) {
|
||||
verifyWatchesOfProject(host, withTsserver ? expectedWatchedFiles().filter(f => f !== tests[1].path.toLowerCase()) : expectedWatchedFiles(), expectedWatchedDirectoriesRecursive);
|
||||
verifyWatchesOfProject(
|
||||
host,
|
||||
withTsserver ?
|
||||
[...core.slice(0, core.length - 1), ...logic, tests[0], libFile].map(f => f.path.toLowerCase()) :
|
||||
[core[0], logic[0], ...tests, libFile].map(f => f.path).concat([coreIndexDts, coreAnotherModuleDts, logicIndexDts].map(f => f.toLowerCase())),
|
||||
expectedWatchedDirectoriesRecursive
|
||||
);
|
||||
}
|
||||
|
||||
function verifyScenario(
|
||||
edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder<EmitAndSemanticDiagnosticsBuilderProgram>) => void,
|
||||
expectedFilesAfterEdit: () => readonly string[]
|
||||
expectedProgramFilesAfterEdit: () => readonly string[],
|
||||
expectedProjectFilesAfterEdit: () => readonly string[]
|
||||
) {
|
||||
it("with tsc-watch", () => {
|
||||
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
|
||||
@@ -737,7 +738,7 @@ let x: string = 10;`);
|
||||
|
||||
host.checkTimeoutQueueLengthAndRun(1);
|
||||
checkOutputErrorsIncremental(host, emptyArray);
|
||||
checkProgramActualFiles(watch(), expectedFilesAfterEdit());
|
||||
checkProgramActualFiles(watch(), expectedProgramFilesAfterEdit());
|
||||
|
||||
});
|
||||
|
||||
@@ -747,7 +748,7 @@ let x: string = 10;`);
|
||||
edit(host, solutionBuilder);
|
||||
|
||||
host.checkTimeoutQueueLengthAndRun(2);
|
||||
checkProjectActualFiles(service, tests[0].path, [tests[0].path, ...expectedFilesAfterEdit()]);
|
||||
checkProjectActualFiles(service, tests[0].path, expectedProjectFilesAfterEdit());
|
||||
});
|
||||
}
|
||||
|
||||
@@ -777,7 +778,7 @@ function foo() {
|
||||
|
||||
// not ideal, but currently because of d.ts but no new file is written
|
||||
// There will be timeout queued even though file contents are same
|
||||
}, expectedProgramFiles);
|
||||
}, expectedProgramFiles, expectedProjectFiles);
|
||||
});
|
||||
|
||||
describe("non local edit in ts file, rebuilds in watch compilation", () => {
|
||||
@@ -787,7 +788,7 @@ export function gfoo() {
|
||||
}`);
|
||||
solutionBuilder.invalidateProject(logic[0].path.toLowerCase() as ResolvedConfigFilePath);
|
||||
solutionBuilder.buildNextInvalidatedProject();
|
||||
}, expectedProgramFiles);
|
||||
}, expectedProgramFiles, expectedProjectFiles);
|
||||
});
|
||||
|
||||
describe("change in project reference config file builds correctly", () => {
|
||||
@@ -798,7 +799,7 @@ export function gfoo() {
|
||||
}));
|
||||
solutionBuilder.invalidateProject(logic[0].path.toLowerCase() as ResolvedConfigFilePath, ConfigFileProgramReloadLevel.Full);
|
||||
solutionBuilder.buildNextInvalidatedProject();
|
||||
}, () => [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")]);
|
||||
}, () => [tests[1].path, libFile.path, coreIndexDts, coreAnotherModuleDts, projectFilePath(SubProject.logic, "decls/index.d.ts")], expectedProjectFiles);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -888,7 +889,9 @@ export function gfoo() {
|
||||
const aDts = dtsFile(multiFolder ? "a/index" : "a"), bDts = dtsFile(multiFolder ? "b/index" : "b");
|
||||
const expectedFiles = [jsFile(multiFolder ? "a/index" : "a"), aDts, jsFile(multiFolder ? "b/index" : "b"), bDts, jsFile(multiFolder ? "c/index" : "c")];
|
||||
const expectedProgramFiles = [cTs.path, libFile.path, aDts, refs.path, bDts];
|
||||
const expectedProjectFiles = [cTs.path, libFile.path, aTs.path, refs.path, bTs.path];
|
||||
const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase());
|
||||
const expectedProjectWatchedFiles = expectedProjectFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase());
|
||||
const expectedWatchedDirectories = multiFolder ? [
|
||||
getProjectPath(project).toLowerCase() // watches for directories created for resolution of b
|
||||
] : emptyArray;
|
||||
@@ -926,22 +929,29 @@ export function gfoo() {
|
||||
}
|
||||
|
||||
function verifyProject(host: TsBuildWatchSystem, service: projectSystem.TestProjectService, orphanInfos?: readonly string[]) {
|
||||
verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos);
|
||||
verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos });
|
||||
}
|
||||
|
||||
function verifyServerState(
|
||||
host: TsBuildWatchSystem,
|
||||
service: projectSystem.TestProjectService,
|
||||
expectedProgramFiles: readonly string[],
|
||||
expectedWatchedFiles: readonly string[],
|
||||
expectedWatchedDirectoriesRecursive: readonly string[],
|
||||
orphanInfos?: readonly string[]) {
|
||||
checkProjectActualFiles(service, cTsconfig.path, expectedProgramFiles.concat(cTsconfig.path));
|
||||
const watchedFiles = expectedWatchedFiles.filter(f => f !== cTs.path.toLowerCase());
|
||||
if (orphanInfos) {
|
||||
interface VerifyServerState {
|
||||
host: TsBuildWatchSystem;
|
||||
service: projectSystem.TestProjectService;
|
||||
expectedProjectFiles: readonly string[];
|
||||
expectedProjectWatchedFiles: readonly string[];
|
||||
expectedWatchedDirectoriesRecursive: readonly string[];
|
||||
orphanInfos?: readonly string[];
|
||||
}
|
||||
function verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos }: VerifyServerState) {
|
||||
checkProjectActualFiles(service, cTsconfig.path, expectedProjectFiles.concat(cTsconfig.path));
|
||||
const watchedFiles = expectedProjectWatchedFiles.filter(f => f !== cTs.path.toLowerCase());
|
||||
const actualOrphan = arrayFrom(mapDefinedIterator(
|
||||
service.filenameToScriptInfo.values(),
|
||||
v => v.containingProjects.length === 0 ? v.fileName : undefined
|
||||
));
|
||||
assert.equal(actualOrphan.length, orphanInfos ? orphanInfos.length : 0, `Orphans found: ${JSON.stringify(actualOrphan, /*replacer*/ undefined, " ")}`);
|
||||
if (orphanInfos && orphanInfos.length) {
|
||||
for (const orphan of orphanInfos) {
|
||||
const info = service.getScriptInfoForPath(orphan as Path);
|
||||
assert.isDefined(info);
|
||||
assert.isDefined(info, `${orphan} expected to be present. Actual: ${JSON.stringify(actualOrphan, /*replacer*/ undefined, " ")}`);
|
||||
assert.equal(info!.containingProjects.length, 0);
|
||||
watchedFiles.push(orphan);
|
||||
}
|
||||
@@ -949,16 +959,20 @@ export function gfoo() {
|
||||
verifyWatchesOfProject(host, watchedFiles, expectedWatchedDirectoriesRecursive, expectedWatchedDirectories);
|
||||
}
|
||||
|
||||
function verifyScenario(
|
||||
edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder<EmitAndSemanticDiagnosticsBuilderProgram>) => void,
|
||||
expectedEditErrors: readonly string[],
|
||||
expectedProgramFiles: readonly string[],
|
||||
expectedWatchedFiles: readonly string[],
|
||||
expectedWatchedDirectoriesRecursive: readonly string[],
|
||||
dependencies: readonly [string, readonly string[]][],
|
||||
revert?: (host: TsBuildWatchSystem) => void,
|
||||
orphanInfosAfterEdit?: readonly string[],
|
||||
orphanInfosAfterRevert?: readonly string[]) {
|
||||
interface VerifyScenario {
|
||||
edit: (host: TsBuildWatchSystem, solutionBuilder: SolutionBuilder<EmitAndSemanticDiagnosticsBuilderProgram>) => void;
|
||||
expectedEditErrors: readonly string[];
|
||||
expectedProgramFiles: readonly string[];
|
||||
expectedProjectFiles: readonly string[];
|
||||
expectedWatchedFiles: readonly string[];
|
||||
expectedProjectWatchedFiles: readonly string[];
|
||||
expectedWatchedDirectoriesRecursive: readonly string[];
|
||||
dependencies: readonly [string, readonly string[]][];
|
||||
revert?: (host: TsBuildWatchSystem) => void;
|
||||
orphanInfosAfterEdit?: readonly string[];
|
||||
orphanInfosAfterRevert?: readonly string[];
|
||||
}
|
||||
function verifyScenario({ edit, expectedEditErrors, expectedProgramFiles, expectedProjectFiles, expectedWatchedFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, dependencies, revert, orphanInfosAfterEdit, orphanInfosAfterRevert }: VerifyScenario) {
|
||||
it("with tsc-watch", () => {
|
||||
const { host, solutionBuilder, watch } = createSolutionAndWatchMode();
|
||||
|
||||
@@ -985,7 +999,7 @@ export function gfoo() {
|
||||
edit(host, solutionBuilder);
|
||||
|
||||
host.checkTimeoutQueueLengthAndRun(2);
|
||||
verifyServerState(host, service, expectedProgramFiles, expectedWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfosAfterEdit);
|
||||
verifyServerState({ host, service, expectedProjectFiles, expectedProjectWatchedFiles, expectedWatchedDirectoriesRecursive, orphanInfos: orphanInfosAfterEdit });
|
||||
|
||||
if (revert) {
|
||||
revert(host);
|
||||
@@ -1010,20 +1024,21 @@ export function gfoo() {
|
||||
});
|
||||
|
||||
describe("non local edit updates the program and watch correctly", () => {
|
||||
verifyScenario(
|
||||
(host, solutionBuilder) => {
|
||||
verifyScenario({
|
||||
edit: (host, solutionBuilder) => {
|
||||
// edit
|
||||
host.writeFile(bTs.path, `${bTs.content}
|
||||
export function gfoo() {
|
||||
}`);
|
||||
solutionBuilder.invalidateProject(bTsconfig.path.toLowerCase() as ResolvedConfigFilePath);
|
||||
host.writeFile(bTs.path, `${bTs.content}\nexport function gfoo() {\n}`);
|
||||
solutionBuilder.invalidateProject((bTsconfig.path.toLowerCase() as ResolvedConfigFilePath));
|
||||
solutionBuilder.buildNextInvalidatedProject();
|
||||
},
|
||||
emptyArray,
|
||||
expectedEditErrors: emptyArray,
|
||||
expectedProgramFiles,
|
||||
expectedProjectFiles,
|
||||
expectedWatchedFiles,
|
||||
expectedProjectWatchedFiles,
|
||||
expectedWatchedDirectoriesRecursive,
|
||||
defaultDependencies);
|
||||
dependencies: defaultDependencies
|
||||
});
|
||||
});
|
||||
|
||||
describe("edit on config file", () => {
|
||||
@@ -1032,30 +1047,32 @@ export function gfoo() {
|
||||
path: getFilePathInProject(project, "nrefs/a.d.ts"),
|
||||
content: refs.content
|
||||
};
|
||||
verifyScenario(
|
||||
host => {
|
||||
verifyScenario({
|
||||
edit: host => {
|
||||
const cTsConfigJson = JSON.parse(cTsconfig.content);
|
||||
host.ensureFileOrFolder(nrefs);
|
||||
cTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
|
||||
host.writeFile(cTsconfig.path, JSON.stringify(cTsConfigJson));
|
||||
},
|
||||
emptyArray,
|
||||
expectedProgramFiles.map(nrefReplacer),
|
||||
expectedWatchedFiles.map(nrefReplacer),
|
||||
expectedWatchedDirectoriesRecursive.map(nrefReplacer),
|
||||
[
|
||||
expectedEditErrors: emptyArray,
|
||||
expectedProgramFiles: expectedProgramFiles.map(nrefReplacer),
|
||||
expectedProjectFiles: expectedProjectFiles.map(nrefReplacer),
|
||||
expectedWatchedFiles: expectedWatchedFiles.map(nrefReplacer),
|
||||
expectedProjectWatchedFiles: expectedProjectWatchedFiles.map(nrefReplacer),
|
||||
expectedWatchedDirectoriesRecursive: expectedWatchedDirectoriesRecursive.map(nrefReplacer),
|
||||
dependencies: [
|
||||
[aDts, [aDts]],
|
||||
[bDts, [bDts, aDts]],
|
||||
[nrefs.path, [nrefs.path]],
|
||||
[cTs.path, [cTs.path, nrefs.path, bDts]]
|
||||
],
|
||||
// revert the update
|
||||
host => host.writeFile(cTsconfig.path, cTsconfig.content),
|
||||
revert: host => host.writeFile(cTsconfig.path, cTsconfig.content),
|
||||
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[refs.path.toLowerCase()],
|
||||
orphanInfosAfterEdit: [refs.path.toLowerCase()],
|
||||
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[nrefs.path.toLowerCase()]
|
||||
);
|
||||
orphanInfosAfterRevert: [nrefs.path.toLowerCase()]
|
||||
});
|
||||
});
|
||||
|
||||
describe("edit in referenced config file", () => {
|
||||
@@ -1064,82 +1081,84 @@ export function gfoo() {
|
||||
content: "export declare class A {}"
|
||||
};
|
||||
const expectedProgramFiles = [cTs.path, bDts, nrefs.path, refs.path, libFile.path];
|
||||
const expectedProjectFiles = [cTs.path, bTs.path, nrefs.path, refs.path, libFile.path];
|
||||
const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario
|
||||
verifyScenario(
|
||||
host => {
|
||||
verifyScenario({
|
||||
edit: host => {
|
||||
const bTsConfigJson = JSON.parse(bTsconfig.content);
|
||||
host.ensureFileOrFolder(nrefs);
|
||||
bTsConfigJson.compilerOptions.paths = { "@ref/*": nrefsPath };
|
||||
host.writeFile(bTsconfig.path, JSON.stringify(bTsConfigJson));
|
||||
},
|
||||
emptyArray,
|
||||
expectedEditErrors: emptyArray,
|
||||
expectedProgramFiles,
|
||||
expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()),
|
||||
(multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()),
|
||||
[
|
||||
expectedProjectFiles,
|
||||
expectedWatchedFiles: expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()),
|
||||
expectedProjectWatchedFiles: expectedProjectFiles.concat(cTsconfig.path, bTsconfig.path, aTsconfig.path).map(s => s.toLowerCase()),
|
||||
expectedWatchedDirectoriesRecursive: (multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive).concat(getFilePathInProject(project, "nrefs").toLowerCase()),
|
||||
dependencies: [
|
||||
[nrefs.path, [nrefs.path]],
|
||||
[bDts, [bDts, nrefs.path]],
|
||||
[refs.path, [refs.path]],
|
||||
[cTs.path, [cTs.path, refs.path, bDts]],
|
||||
],
|
||||
// revert the update
|
||||
host => host.writeFile(bTsconfig.path, bTsconfig.content),
|
||||
revert: host => host.writeFile(bTsconfig.path, bTsconfig.content),
|
||||
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[aDts.toLowerCase()],
|
||||
orphanInfosAfterEdit: [aTs.path.toLowerCase()],
|
||||
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[nrefs.path.toLowerCase()]
|
||||
);
|
||||
orphanInfosAfterRevert: [nrefs.path.toLowerCase()]
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleting referenced config file", () => {
|
||||
const expectedProgramFiles = [cTs.path, bTs.path, refs.path, libFile.path];
|
||||
const expectedWatchedFiles = expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase());
|
||||
const [, ...expectedWatchedDirectoriesRecursiveWithoutA] = expectedWatchedDirectoriesRecursive; // Not looking in a folder for resolution in multi folder scenario
|
||||
// Resolutions should change now
|
||||
// Should map to b.ts instead with options from our own config
|
||||
verifyScenario(
|
||||
host => host.deleteFile(bTsconfig.path),
|
||||
[
|
||||
verifyScenario({
|
||||
edit: host => host.deleteFile(bTsconfig.path),
|
||||
expectedEditErrors: [
|
||||
`${multiFolder ? "c/tsconfig.json" : "tsconfig.c.json"}(9,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "b" : "tsconfig.b.json"}' not found.\n`
|
||||
],
|
||||
expectedProgramFiles,
|
||||
expectedProgramFiles.concat(cTsconfig.path, bTsconfig.path).map(s => s.toLowerCase()),
|
||||
multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive,
|
||||
[
|
||||
expectedProjectFiles: expectedProgramFiles,
|
||||
expectedWatchedFiles,
|
||||
expectedProjectWatchedFiles: expectedWatchedFiles,
|
||||
expectedWatchedDirectoriesRecursive: multiFolder ? expectedWatchedDirectoriesRecursiveWithoutA : expectedWatchedDirectoriesRecursive,
|
||||
dependencies: [
|
||||
[bTs.path, [bTs.path, refs.path]],
|
||||
[refs.path, [refs.path]],
|
||||
[cTs.path, [cTs.path, refs.path, bTs.path]],
|
||||
],
|
||||
// revert the update
|
||||
host => host.writeFile(bTsconfig.path, bTsconfig.content),
|
||||
revert: host => host.writeFile(bTsconfig.path, bTsconfig.content),
|
||||
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[bDts.toLowerCase(), aDts.toLowerCase(), aTsconfig.path.toLowerCase()],
|
||||
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[bTs.path.toLowerCase()]
|
||||
);
|
||||
orphanInfosAfterEdit: [aTs.path.toLowerCase(), aTsconfig.path.toLowerCase()],
|
||||
});
|
||||
});
|
||||
|
||||
describe("deleting transitively referenced config file", () => {
|
||||
verifyScenario(
|
||||
host => host.deleteFile(aTsconfig.path),
|
||||
[
|
||||
verifyScenario({
|
||||
edit: host => host.deleteFile(aTsconfig.path),
|
||||
expectedEditErrors: [
|
||||
`${multiFolder ? "b/tsconfig.json" : "tsconfig.b.json"}(10,21): error TS6053: File '/user/username/projects/transitiveReferences/${multiFolder ? "a" : "tsconfig.a.json"}' not found.\n`
|
||||
],
|
||||
expectedProgramFiles.map(s => s.replace(aDts, aTs.path)),
|
||||
expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())),
|
||||
expectedProgramFiles: expectedProgramFiles.map(s => s.replace(aDts, aTs.path)),
|
||||
expectedProjectFiles,
|
||||
expectedWatchedFiles: expectedWatchedFiles.map(s => s.replace(aDts.toLowerCase(), aTs.path.toLocaleLowerCase())),
|
||||
expectedProjectWatchedFiles,
|
||||
expectedWatchedDirectoriesRecursive,
|
||||
[
|
||||
dependencies: [
|
||||
[aTs.path, [aTs.path]],
|
||||
[bDts, [bDts, aTs.path]],
|
||||
[refs.path, [refs.path]],
|
||||
[cTs.path, [cTs.path, refs.path, bDts]],
|
||||
],
|
||||
// revert the update
|
||||
host => host.writeFile(aTsconfig.path, aTsconfig.content),
|
||||
// AfterEdit:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[aDts.toLowerCase()],
|
||||
// AfterRevert:: Extra watched files on server since the script infos arent deleted till next file open
|
||||
[aTs.path.toLowerCase()]
|
||||
);
|
||||
revert: host => host.writeFile(aTsconfig.path, aTsconfig.content),
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ namespace ts {
|
||||
}
|
||||
}
|
||||
|
||||
function createReportErrorSummary(options: CompilerOptions): ReportEmitErrorSummary | undefined {
|
||||
function createReportErrorSummary(sys: TscCompileSystem, options: CompilerOptions): ReportEmitErrorSummary | undefined {
|
||||
return options.pretty ?
|
||||
errorCount => sys.write(getErrorSummaryText(errorCount, sys.newLine)) :
|
||||
undefined;
|
||||
@@ -93,7 +93,7 @@ namespace ts {
|
||||
program,
|
||||
reportDiagnostic,
|
||||
s => sys.write(s + sys.newLine),
|
||||
createReportErrorSummary(options)
|
||||
createReportErrorSummary(sys, options)
|
||||
);
|
||||
baselineBuildInfo([config], sys.vfs, sys.writtenFiles);
|
||||
return sys.exit(exitStatus);
|
||||
@@ -109,7 +109,7 @@ namespace ts {
|
||||
configFileParsingDiagnostics: getConfigFileParsingDiagnostics(config),
|
||||
projectReferences,
|
||||
reportDiagnostic,
|
||||
reportErrorSummary: createReportErrorSummary(options),
|
||||
reportErrorSummary: createReportErrorSummary(sys, options),
|
||||
});
|
||||
baselineBuildInfo([config], sys.vfs, sys.writtenFiles);
|
||||
return sys.exit(exitCode);
|
||||
@@ -131,7 +131,7 @@ namespace ts {
|
||||
/*createProgram*/ undefined,
|
||||
reportDiagnostic,
|
||||
createBuilderStatusReporter(sys, buildOptions.pretty),
|
||||
createReportErrorSummary(buildOptions)
|
||||
createReportErrorSummary(sys, buildOptions)
|
||||
);
|
||||
fakes.patchSolutionBuilderHost(buildHost, sys);
|
||||
const builder = createSolutionBuilder(buildHost, projects, buildOptions);
|
||||
|
||||
@@ -179,7 +179,7 @@ namespace ts.projectSystem {
|
||||
}
|
||||
|
||||
function verifyUserTsConfigProject(session: TestSession) {
|
||||
checkProjectActualFiles(session.getProjectService().configuredProjects.get(userTsconfig.path)!, [userTs.path, aDts.path, userTsconfig.path]);
|
||||
checkProjectActualFiles(session.getProjectService().configuredProjects.get(userTsconfig.path)!, [userTs.path, aTs.path, userTsconfig.path]);
|
||||
}
|
||||
|
||||
it("goToDefinition", () => {
|
||||
@@ -450,6 +450,13 @@ namespace ts.projectSystem {
|
||||
name: "function f(): void",
|
||||
},
|
||||
references: [
|
||||
makeReferenceEntry({
|
||||
file: aTs,
|
||||
text: "f",
|
||||
options: { index: 1 },
|
||||
contextText: "function f() {}",
|
||||
isDefinition: true
|
||||
}),
|
||||
{
|
||||
fileName: bTs.path,
|
||||
isDefinition: false,
|
||||
@@ -457,13 +464,6 @@ namespace ts.projectSystem {
|
||||
isWriteAccess: false,
|
||||
textSpan: { start: 0, length: 1 },
|
||||
},
|
||||
makeReferenceEntry({
|
||||
file: aTs,
|
||||
text: "f",
|
||||
options: { index: 1 },
|
||||
contextText: "function f() {}",
|
||||
isDefinition: true
|
||||
})
|
||||
],
|
||||
}
|
||||
]);
|
||||
|
||||
@@ -73,44 +73,64 @@ namespace ts.projectSystem {
|
||||
verifyEvent(project, `Change in config file detected`);
|
||||
});
|
||||
|
||||
it("when opening original location project", () => {
|
||||
const aDTs: File = {
|
||||
path: `${projectRoot}/a/a.d.ts`,
|
||||
content: `export declare class A {
|
||||
describe("when opening original location project", () => {
|
||||
it("with project references", () => {
|
||||
verify();
|
||||
});
|
||||
|
||||
it("when disableSourceOfProjectReferenceRedirect is true", () => {
|
||||
verify(/*disableSourceOfProjectReferenceRedirect*/ true);
|
||||
});
|
||||
|
||||
function verify(disableSourceOfProjectReferenceRedirect?: true) {
|
||||
const aDTs: File = {
|
||||
path: `${projectRoot}/a/a.d.ts`,
|
||||
content: `export declare class A {
|
||||
}
|
||||
//# sourceMappingURL=a.d.ts.map
|
||||
`
|
||||
};
|
||||
const aDTsMap: File = {
|
||||
path: `${projectRoot}/a/a.d.ts.map`,
|
||||
content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}`
|
||||
};
|
||||
const bTs: File = {
|
||||
path: bTsPath,
|
||||
content: `import {A} from "../a/a"; new A();`
|
||||
};
|
||||
const configB: File = {
|
||||
path: configBPath,
|
||||
content: JSON.stringify({
|
||||
references: [{ path: "../a" }]
|
||||
})
|
||||
};
|
||||
};
|
||||
const aDTsMap: File = {
|
||||
path: `${projectRoot}/a/a.d.ts.map`,
|
||||
content: `{"version":3,"file":"a.d.ts","sourceRoot":"","sources":["./a.ts"],"names":[],"mappings":"AAAA,qBAAa,CAAC;CAAI"}`
|
||||
};
|
||||
const bTs: File = {
|
||||
path: bTsPath,
|
||||
content: `import {A} from "../a/a"; new A();`
|
||||
};
|
||||
const configB: File = {
|
||||
path: configBPath,
|
||||
content: JSON.stringify({
|
||||
...(disableSourceOfProjectReferenceRedirect && {
|
||||
compilerOptions: {
|
||||
disableSourceOfProjectReferenceRedirect
|
||||
}
|
||||
}),
|
||||
references: [{ path: "../a" }]
|
||||
})
|
||||
};
|
||||
|
||||
const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionToVerifyEvent(files.concat(aDTs, aDTsMap, bTs, configB));
|
||||
verifyEventWithOpenTs(bTs, configB.path, 1);
|
||||
const { service, session, verifyEventWithOpenTs, verifyEvent } = createSessionToVerifyEvent(files.concat(aDTs, aDTsMap, bTs, configB));
|
||||
verifyEventWithOpenTs(bTs, configB.path, 1);
|
||||
|
||||
session.executeCommandSeq<protocol.ReferencesRequest>({
|
||||
command: protocol.CommandTypes.References,
|
||||
arguments: {
|
||||
file: bTs.path,
|
||||
...protocolLocationFromSubstring(bTs.content, "A()")
|
||||
}
|
||||
});
|
||||
session.executeCommandSeq<protocol.ReferencesRequest>({
|
||||
command: protocol.CommandTypes.References,
|
||||
arguments: {
|
||||
file: bTs.path,
|
||||
...protocolLocationFromSubstring(bTs.content, "A()")
|
||||
}
|
||||
});
|
||||
|
||||
checkNumberOfProjects(service, { configuredProjects: 2 });
|
||||
const project = service.configuredProjects.get(configA.path)!;
|
||||
assert.isDefined(project);
|
||||
verifyEvent(project, `Creating project for original file: ${aTs.path} for location: ${aDTs.path}`);
|
||||
checkNumberOfProjects(service, { configuredProjects: 2 });
|
||||
const project = service.configuredProjects.get(configA.path)!;
|
||||
assert.isDefined(project);
|
||||
verifyEvent(
|
||||
project,
|
||||
disableSourceOfProjectReferenceRedirect ?
|
||||
`Creating project for original file: ${aTs.path} for location: ${aDTs.path}` :
|
||||
`Creating project for original file: ${aTs.path}`
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
describe("with external projects and config files ", () => {
|
||||
|
||||
@@ -491,8 +491,8 @@ namespace ts.projectSystem {
|
||||
checkArray("Open files", arrayFrom(projectService.openFiles.keys(), path => projectService.getScriptInfoForPath(path as Path)!.fileName), expectedFiles.map(file => file.path));
|
||||
}
|
||||
|
||||
export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: readonly string[]) {
|
||||
checkArray("ScriptInfos files", arrayFrom(projectService.filenameToScriptInfo.values(), info => info.fileName), expectedFiles);
|
||||
export function checkScriptInfos(projectService: server.ProjectService, expectedFiles: readonly string[], additionInfo?: string) {
|
||||
checkArray(`ScriptInfos files: ${additionInfo || ""}`, arrayFrom(projectService.filenameToScriptInfo.values(), info => info.fileName), expectedFiles);
|
||||
}
|
||||
|
||||
export function protocolLocationFromSubstring(str: string, substring: string): protocol.Location {
|
||||
@@ -501,7 +501,7 @@ namespace ts.projectSystem {
|
||||
return protocolToLocation(str)(start);
|
||||
}
|
||||
|
||||
function protocolToLocation(text: string): (pos: number) => protocol.Location {
|
||||
export function protocolToLocation(text: string): (pos: number) => protocol.Location {
|
||||
const lineStarts = computeLineStarts(text);
|
||||
return pos => {
|
||||
const x = computeLineAndCharacterOfPosition(lineStarts, pos);
|
||||
|
||||
@@ -0,0 +1,410 @@
|
||||
namespace ts.projectSystem {
|
||||
describe("unittests:: tsserver:: with project references and compile on save", () => {
|
||||
const projectLocation = "/user/username/projects/myproject";
|
||||
const dependecyLocation = `${projectLocation}/dependency`;
|
||||
const usageLocation = `${projectLocation}/usage`;
|
||||
const dependencyTs: File = {
|
||||
path: `${dependecyLocation}/fns.ts`,
|
||||
content: `export function fn1() { }
|
||||
export function fn2() { }
|
||||
`
|
||||
};
|
||||
const dependencyConfig: File = {
|
||||
path: `${dependecyLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({
|
||||
compilerOptions: { composite: true, declarationDir: "../decls" },
|
||||
compileOnSave: true
|
||||
})
|
||||
};
|
||||
const usageTs: File = {
|
||||
path: `${usageLocation}/usage.ts`,
|
||||
content: `import {
|
||||
fn1,
|
||||
fn2,
|
||||
} from '../decls/fns'
|
||||
fn1();
|
||||
fn2();
|
||||
`
|
||||
};
|
||||
const usageConfig: File = {
|
||||
path: `${usageLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({
|
||||
compileOnSave: true,
|
||||
references: [{ path: "../dependency" }]
|
||||
})
|
||||
};
|
||||
|
||||
interface VerifySingleScenarioWorker extends VerifySingleScenario {
|
||||
withProject: boolean;
|
||||
}
|
||||
function verifySingleScenarioWorker({
|
||||
withProject, scenario, openFiles, requestArgs, change, expectedResult
|
||||
}: VerifySingleScenarioWorker) {
|
||||
it(scenario, () => {
|
||||
const host = TestFSWithWatch.changeToHostTrackingWrittenFiles(
|
||||
createServerHost([dependencyTs, dependencyConfig, usageTs, usageConfig, libFile])
|
||||
);
|
||||
const session = createSession(host);
|
||||
openFilesForSession(openFiles(), session);
|
||||
const reqArgs = requestArgs();
|
||||
const {
|
||||
expectedAffected,
|
||||
expectedEmit: { expectedEmitSuccess, expectedFiles },
|
||||
expectedEmitOutput
|
||||
} = expectedResult(withProject);
|
||||
|
||||
if (change) {
|
||||
session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({
|
||||
command: protocol.CommandTypes.CompileOnSaveAffectedFileList,
|
||||
arguments: { file: dependencyTs.path }
|
||||
});
|
||||
const { file, insertString } = change();
|
||||
if (session.getProjectService().openFiles.has(file.path)) {
|
||||
const toLocation = protocolToLocation(file.content);
|
||||
const location = toLocation(file.content.length);
|
||||
session.executeCommandSeq<protocol.ChangeRequest>({
|
||||
command: protocol.CommandTypes.Change,
|
||||
arguments: {
|
||||
file: file.path,
|
||||
...location,
|
||||
endLine: location.line,
|
||||
endOffset: location.offset,
|
||||
insertString
|
||||
}
|
||||
});
|
||||
}
|
||||
else {
|
||||
host.writeFile(file.path, `${file.content}${insertString}`);
|
||||
}
|
||||
host.writtenFiles.clear();
|
||||
}
|
||||
|
||||
const args = withProject ? reqArgs : { file: reqArgs.file };
|
||||
// Verify CompileOnSaveAffectedFileList
|
||||
const actualAffectedFiles = session.executeCommandSeq<protocol.CompileOnSaveAffectedFileListRequest>({
|
||||
command: protocol.CommandTypes.CompileOnSaveAffectedFileList,
|
||||
arguments: args
|
||||
}).response as protocol.CompileOnSaveAffectedFileListSingleProject[];
|
||||
assert.deepEqual(actualAffectedFiles, expectedAffected, "Affected files");
|
||||
|
||||
// Verify CompileOnSaveEmit
|
||||
const actualEmit = session.executeCommandSeq<protocol.CompileOnSaveEmitFileRequest>({
|
||||
command: protocol.CommandTypes.CompileOnSaveEmitFile,
|
||||
arguments: args
|
||||
}).response;
|
||||
assert.deepEqual(actualEmit, expectedEmitSuccess, "Emit files");
|
||||
assert.equal(host.writtenFiles.size, expectedFiles.length);
|
||||
for (const file of expectedFiles) {
|
||||
assert.equal(host.readFile(file.path), file.content, `Expected to write ${file.path}`);
|
||||
assert.isTrue(host.writtenFiles.has(file.path), `${file.path} is newly written`);
|
||||
}
|
||||
|
||||
// Verify EmitOutput
|
||||
const { exportedModulesFromDeclarationEmit: _1, ...actualEmitOutput } = session.executeCommandSeq<protocol.EmitOutputRequest>({
|
||||
command: protocol.CommandTypes.EmitOutput,
|
||||
arguments: args
|
||||
}).response as EmitOutput;
|
||||
assert.deepEqual(actualEmitOutput, expectedEmitOutput, "Emit output");
|
||||
});
|
||||
}
|
||||
|
||||
interface VerifySingleScenario {
|
||||
scenario: string;
|
||||
openFiles: () => readonly File[];
|
||||
requestArgs: () => protocol.FileRequestArgs;
|
||||
skipWithoutProject?: boolean;
|
||||
change?: () => SingleScenarioChange;
|
||||
expectedResult: GetSingleScenarioResult;
|
||||
}
|
||||
function verifySingleScenario(scenario: VerifySingleScenario) {
|
||||
if (!scenario.skipWithoutProject) {
|
||||
describe("without specifying project file", () => {
|
||||
verifySingleScenarioWorker({
|
||||
withProject: false,
|
||||
...scenario
|
||||
});
|
||||
});
|
||||
}
|
||||
describe("with specifying project file", () => {
|
||||
verifySingleScenarioWorker({
|
||||
withProject: true,
|
||||
...scenario
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface SingleScenarioExpectedEmit {
|
||||
expectedEmitSuccess: boolean;
|
||||
expectedFiles: readonly File[];
|
||||
}
|
||||
interface SingleScenarioResult {
|
||||
expectedAffected: protocol.CompileOnSaveAffectedFileListSingleProject[];
|
||||
expectedEmit: SingleScenarioExpectedEmit;
|
||||
expectedEmitOutput: EmitOutput;
|
||||
}
|
||||
type GetSingleScenarioResult = (withProject: boolean) => SingleScenarioResult;
|
||||
interface SingleScenarioChange {
|
||||
file: File;
|
||||
insertString: string;
|
||||
}
|
||||
interface ScenarioDetails {
|
||||
scenarioName: string;
|
||||
requestArgs: () => protocol.FileRequestArgs;
|
||||
skipWithoutProject?: boolean;
|
||||
initial: GetSingleScenarioResult;
|
||||
localChangeToDependency: GetSingleScenarioResult;
|
||||
localChangeToUsage: GetSingleScenarioResult;
|
||||
changeToDependency: GetSingleScenarioResult;
|
||||
changeToUsage: GetSingleScenarioResult;
|
||||
}
|
||||
interface VerifyScenario {
|
||||
openFiles: () => readonly File[];
|
||||
scenarios: readonly ScenarioDetails[];
|
||||
}
|
||||
|
||||
const localChange = "function fn3() { }";
|
||||
const change = `export ${localChange}`;
|
||||
const changeJs = `function fn3() { }
|
||||
exports.fn3 = fn3;`;
|
||||
const changeDts = "export declare function fn3(): void;";
|
||||
function verifyScenario({ openFiles, scenarios }: VerifyScenario) {
|
||||
for (const {
|
||||
scenarioName, requestArgs, skipWithoutProject, initial,
|
||||
localChangeToDependency, localChangeToUsage,
|
||||
changeToDependency, changeToUsage
|
||||
} of scenarios) {
|
||||
describe(scenarioName, () => {
|
||||
verifySingleScenario({
|
||||
scenario: "with initial file open",
|
||||
openFiles,
|
||||
requestArgs,
|
||||
skipWithoutProject,
|
||||
expectedResult: initial
|
||||
});
|
||||
|
||||
verifySingleScenario({
|
||||
scenario: "with local change to dependency",
|
||||
openFiles,
|
||||
requestArgs,
|
||||
skipWithoutProject,
|
||||
change: () => ({ file: dependencyTs, insertString: localChange }),
|
||||
expectedResult: localChangeToDependency
|
||||
});
|
||||
|
||||
verifySingleScenario({
|
||||
scenario: "with local change to usage",
|
||||
openFiles,
|
||||
requestArgs,
|
||||
skipWithoutProject,
|
||||
change: () => ({ file: usageTs, insertString: localChange }),
|
||||
expectedResult: localChangeToUsage
|
||||
});
|
||||
|
||||
verifySingleScenario({
|
||||
scenario: "with change to dependency",
|
||||
openFiles,
|
||||
requestArgs,
|
||||
skipWithoutProject,
|
||||
change: () => ({ file: dependencyTs, insertString: change }),
|
||||
expectedResult: changeToDependency
|
||||
});
|
||||
|
||||
verifySingleScenario({
|
||||
scenario: "with change to usage",
|
||||
openFiles,
|
||||
requestArgs,
|
||||
skipWithoutProject,
|
||||
change: () => ({ file: usageTs, insertString: change }),
|
||||
expectedResult: changeToUsage
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function expectedAffectedFiles(config: File, fileNames: File[]): protocol.CompileOnSaveAffectedFileListSingleProject {
|
||||
return {
|
||||
projectFileName: config.path,
|
||||
fileNames: fileNames.map(f => f.path),
|
||||
projectUsesOutFile: false
|
||||
};
|
||||
}
|
||||
|
||||
function expectedUsageEmit(appendJsText?: string): SingleScenarioExpectedEmit {
|
||||
const appendJs = appendJsText ? `${appendJsText}
|
||||
` : "";
|
||||
return {
|
||||
expectedEmitSuccess: true,
|
||||
expectedFiles: [{
|
||||
path: `${usageLocation}/usage.js`,
|
||||
content: `"use strict";
|
||||
exports.__esModule = true;
|
||||
var fns_1 = require("../decls/fns");
|
||||
fns_1.fn1();
|
||||
fns_1.fn2();
|
||||
${appendJs}`
|
||||
}]
|
||||
};
|
||||
}
|
||||
|
||||
function expectedEmitOutput({ expectedFiles }: SingleScenarioExpectedEmit): EmitOutput {
|
||||
return {
|
||||
outputFiles: expectedFiles.map(({ path, content }) => ({
|
||||
name: path,
|
||||
text: content,
|
||||
writeByteOrderMark: false
|
||||
})),
|
||||
emitSkipped: false
|
||||
};
|
||||
}
|
||||
|
||||
function expectedUsageEmitOutput(appendJsText?: string): EmitOutput {
|
||||
return expectedEmitOutput(expectedUsageEmit(appendJsText));
|
||||
}
|
||||
|
||||
function noEmit(): SingleScenarioExpectedEmit {
|
||||
return {
|
||||
expectedEmitSuccess: false,
|
||||
expectedFiles: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
function noEmitOutput(): EmitOutput {
|
||||
return {
|
||||
emitSkipped: true,
|
||||
outputFiles: []
|
||||
};
|
||||
}
|
||||
|
||||
function expectedDependencyEmit(appendJsText?: string, appendDtsText?: string): SingleScenarioExpectedEmit {
|
||||
const appendJs = appendJsText ? `${appendJsText}
|
||||
` : "";
|
||||
const appendDts = appendDtsText ? `${appendDtsText}
|
||||
` : "";
|
||||
return {
|
||||
expectedEmitSuccess: true,
|
||||
expectedFiles: [
|
||||
{
|
||||
path: `${dependecyLocation}/fns.js`,
|
||||
content: `"use strict";
|
||||
exports.__esModule = true;
|
||||
function fn1() { }
|
||||
exports.fn1 = fn1;
|
||||
function fn2() { }
|
||||
exports.fn2 = fn2;
|
||||
${appendJs}`
|
||||
},
|
||||
{
|
||||
path: `${projectLocation}/decls/fns.d.ts`,
|
||||
content: `export declare function fn1(): void;
|
||||
export declare function fn2(): void;
|
||||
${appendDts}`
|
||||
}
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
function expectedDependencyEmitOutput(appendJsText?: string, appendDtsText?: string): EmitOutput {
|
||||
return expectedEmitOutput(expectedDependencyEmit(appendJsText, appendDtsText));
|
||||
}
|
||||
|
||||
function scenarioDetailsOfUsage(isDependencyOpen?: boolean): ScenarioDetails[] {
|
||||
return [
|
||||
{
|
||||
scenarioName: "Of usageTs",
|
||||
requestArgs: () => ({ file: usageTs.path, projectFileName: usageConfig.path }),
|
||||
initial: () => initialUsageTs(),
|
||||
// no change to usage so same as initial only usage file
|
||||
localChangeToDependency: () => initialUsageTs(),
|
||||
localChangeToUsage: () => initialUsageTs(localChange),
|
||||
changeToDependency: () => initialUsageTs(),
|
||||
changeToUsage: () => initialUsageTs(changeJs)
|
||||
},
|
||||
{
|
||||
scenarioName: "Of dependencyTs in usage project",
|
||||
requestArgs: () => ({ file: dependencyTs.path, projectFileName: usageConfig.path }),
|
||||
skipWithoutProject: !!isDependencyOpen,
|
||||
initial: () => initialDependencyTs(),
|
||||
localChangeToDependency: () => initialDependencyTs(/*noUsageFiles*/ true),
|
||||
localChangeToUsage: () => initialDependencyTs(/*noUsageFiles*/ true),
|
||||
changeToDependency: () => initialDependencyTs(),
|
||||
changeToUsage: () => initialDependencyTs(/*noUsageFiles*/ true)
|
||||
}
|
||||
];
|
||||
|
||||
function initialUsageTs(jsText?: string) {
|
||||
return {
|
||||
expectedAffected: [
|
||||
expectedAffectedFiles(usageConfig, [usageTs])
|
||||
],
|
||||
expectedEmit: expectedUsageEmit(jsText),
|
||||
expectedEmitOutput: expectedUsageEmitOutput(jsText)
|
||||
};
|
||||
}
|
||||
|
||||
function initialDependencyTs(noUsageFiles?: true) {
|
||||
return {
|
||||
expectedAffected: [
|
||||
expectedAffectedFiles(usageConfig, noUsageFiles ? [] : [usageTs])
|
||||
],
|
||||
expectedEmit: noEmit(),
|
||||
expectedEmitOutput: noEmitOutput()
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
function scenarioDetailsOfDependencyWhenOpen(): ScenarioDetails {
|
||||
return {
|
||||
scenarioName: "Of dependencyTs",
|
||||
requestArgs: () => ({ file: dependencyTs.path, projectFileName: dependencyConfig.path }),
|
||||
initial,
|
||||
localChangeToDependency: withProject => ({
|
||||
expectedAffected: withProject ?
|
||||
[
|
||||
expectedAffectedFiles(dependencyConfig, [dependencyTs])
|
||||
] :
|
||||
[
|
||||
expectedAffectedFiles(usageConfig, []),
|
||||
expectedAffectedFiles(dependencyConfig, [dependencyTs])
|
||||
],
|
||||
expectedEmit: expectedDependencyEmit(localChange),
|
||||
expectedEmitOutput: expectedDependencyEmitOutput(localChange)
|
||||
}),
|
||||
localChangeToUsage: withProject => initial(withProject, /*noUsageFiles*/ true),
|
||||
changeToDependency: withProject => initial(withProject, /*noUsageFiles*/ undefined, changeJs, changeDts),
|
||||
changeToUsage: withProject => initial(withProject, /*noUsageFiles*/ true)
|
||||
};
|
||||
|
||||
function initial(withProject: boolean, noUsageFiles?: true, appendJs?: string, appendDts?: string): SingleScenarioResult {
|
||||
return {
|
||||
expectedAffected: withProject ?
|
||||
[
|
||||
expectedAffectedFiles(dependencyConfig, [dependencyTs])
|
||||
] :
|
||||
[
|
||||
expectedAffectedFiles(usageConfig, noUsageFiles ? [] : [usageTs]),
|
||||
expectedAffectedFiles(dependencyConfig, [dependencyTs])
|
||||
],
|
||||
expectedEmit: expectedDependencyEmit(appendJs, appendDts),
|
||||
expectedEmitOutput: expectedDependencyEmitOutput(appendJs, appendDts)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
describe("when dependency project is not open", () => {
|
||||
verifyScenario({
|
||||
openFiles: () => [usageTs],
|
||||
scenarios: scenarioDetailsOfUsage()
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the depedency file is open", () => {
|
||||
verifyScenario({
|
||||
openFiles: () => [usageTs, dependencyTs],
|
||||
scenarios: [
|
||||
...scenarioDetailsOfUsage(/*isDependencyOpen*/ true),
|
||||
scenarioDetailsOfDependencyWhenOpen(),
|
||||
]
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
namespace ts.projectSystem {
|
||||
describe("unittests:: tsserver:: with project references and error reporting", () => {
|
||||
const projectLocation = "/user/username/projects/myproject";
|
||||
const dependecyLocation = `${projectLocation}/dependency`;
|
||||
const usageLocation = `${projectLocation}/usage`;
|
||||
|
||||
interface CheckErrorsInFile {
|
||||
session: TestSession;
|
||||
host: TestServerHost;
|
||||
expected: GetErrDiagnostics;
|
||||
expectedSequenceId?: number;
|
||||
}
|
||||
function checkErrorsInFile({ session, host, expected: { file, syntax, semantic, suggestion }, expectedSequenceId }: CheckErrorsInFile) {
|
||||
host.checkTimeoutQueueLengthAndRun(1);
|
||||
checkErrorMessage(session, "syntaxDiag", { file: file.path, diagnostics: syntax });
|
||||
session.clearMessages();
|
||||
|
||||
host.runQueuedImmediateCallbacks(1);
|
||||
checkErrorMessage(session, "semanticDiag", { file: file.path, diagnostics: semantic });
|
||||
session.clearMessages();
|
||||
|
||||
host.runQueuedImmediateCallbacks(1);
|
||||
checkErrorMessage(session, "suggestionDiag", { file: file.path, diagnostics: suggestion });
|
||||
if (expectedSequenceId !== undefined) {
|
||||
checkCompleteEvent(session, 2, expectedSequenceId);
|
||||
}
|
||||
session.clearMessages();
|
||||
}
|
||||
|
||||
interface CheckAllErrors {
|
||||
session: TestSession;
|
||||
host: TestServerHost;
|
||||
expected: readonly GetErrDiagnostics[];
|
||||
expectedSequenceId: number;
|
||||
}
|
||||
function checkAllErrors({ session, host, expected, expectedSequenceId }: CheckAllErrors) {
|
||||
for (let i = 0; i < expected.length; i++) {
|
||||
checkErrorsInFile({
|
||||
session,
|
||||
host,
|
||||
expected: expected[i],
|
||||
expectedSequenceId: i === expected.length - 1 ? expectedSequenceId : undefined
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
function verifyErrorsUsingGeterr({ allFiles, openFiles, expectedGetErr }: VerifyScenario) {
|
||||
it("verifies the errors in open file", () => {
|
||||
const host = createServerHost([...allFiles(), libFile]);
|
||||
const session = createSession(host, { canUseEvents: true, });
|
||||
openFilesForSession(openFiles(), session);
|
||||
|
||||
session.clearMessages();
|
||||
const expectedSequenceId = session.getNextSeq();
|
||||
const expected = expectedGetErr();
|
||||
session.executeCommandSeq<protocol.GeterrRequest>({
|
||||
command: protocol.CommandTypes.Geterr,
|
||||
arguments: {
|
||||
delay: 0,
|
||||
files: expected.map(f => f.file.path)
|
||||
}
|
||||
});
|
||||
|
||||
checkAllErrors({ session, host, expected, expectedSequenceId });
|
||||
});
|
||||
}
|
||||
|
||||
function verifyErrorsUsingGeterrForProject({ allFiles, openFiles, expectedGetErrForProject }: VerifyScenario) {
|
||||
it("verifies the errors in projects", () => {
|
||||
const host = createServerHost([...allFiles(), libFile]);
|
||||
const session = createSession(host, { canUseEvents: true, });
|
||||
openFilesForSession(openFiles(), session);
|
||||
|
||||
session.clearMessages();
|
||||
for (const expected of expectedGetErrForProject()) {
|
||||
const expectedSequenceId = session.getNextSeq();
|
||||
session.executeCommandSeq<protocol.GeterrForProjectRequest>({
|
||||
command: protocol.CommandTypes.GeterrForProject,
|
||||
arguments: {
|
||||
delay: 0,
|
||||
file: expected.project
|
||||
}
|
||||
});
|
||||
|
||||
checkAllErrors({ session, host, expected: expected.errors, expectedSequenceId });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function verifyErrorsUsingSyncMethods({ allFiles, openFiles, expectedSyncDiagnostics }: VerifyScenario) {
|
||||
it("verifies the errors using sync commands", () => {
|
||||
const host = createServerHost([...allFiles(), libFile]);
|
||||
const session = createSession(host);
|
||||
openFilesForSession(openFiles(), session);
|
||||
for (const { file, project, syntax, semantic, suggestion } of expectedSyncDiagnostics()) {
|
||||
const actualSyntax = session.executeCommandSeq<protocol.SyntacticDiagnosticsSyncRequest>({
|
||||
command: protocol.CommandTypes.SyntacticDiagnosticsSync,
|
||||
arguments: {
|
||||
file: file.path,
|
||||
projectFileName: project
|
||||
}
|
||||
}).response as protocol.Diagnostic[];
|
||||
assert.deepEqual(actualSyntax, syntax, `Syntax diagnostics for file: ${file.path}, project: ${project}`);
|
||||
const actualSemantic = session.executeCommandSeq<protocol.SemanticDiagnosticsSyncRequest>({
|
||||
command: protocol.CommandTypes.SemanticDiagnosticsSync,
|
||||
arguments: {
|
||||
file: file.path,
|
||||
projectFileName: project
|
||||
}
|
||||
}).response as protocol.Diagnostic[];
|
||||
assert.deepEqual(actualSemantic, semantic, `Semantic diagnostics for file: ${file.path}, project: ${project}`);
|
||||
const actualSuggestion = session.executeCommandSeq<protocol.SuggestionDiagnosticsSyncRequest>({
|
||||
command: protocol.CommandTypes.SuggestionDiagnosticsSync,
|
||||
arguments: {
|
||||
file: file.path,
|
||||
projectFileName: project
|
||||
}
|
||||
}).response as protocol.Diagnostic[];
|
||||
assert.deepEqual(actualSuggestion, suggestion, `Suggestion diagnostics for file: ${file.path}, project: ${project}`);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function verifyConfigFileErrors({ allFiles, openFiles, expectedConfigFileDiagEvents }: VerifyScenario) {
|
||||
it("verify config file errors", () => {
|
||||
const host = createServerHost([...allFiles(), libFile]);
|
||||
const { session, events } = createSessionWithEventTracking<server.ConfigFileDiagEvent>(host, server.ConfigFileDiagEvent);
|
||||
|
||||
for (const file of openFiles()) {
|
||||
session.executeCommandSeq<protocol.OpenRequest>({
|
||||
command: protocol.CommandTypes.Open,
|
||||
arguments: { file: file.path }
|
||||
});
|
||||
}
|
||||
|
||||
assert.deepEqual(events, expectedConfigFileDiagEvents().map(data => ({
|
||||
eventName: server.ConfigFileDiagEvent,
|
||||
data
|
||||
})));
|
||||
});
|
||||
}
|
||||
|
||||
interface GetErrDiagnostics {
|
||||
file: File;
|
||||
syntax: protocol.Diagnostic[];
|
||||
semantic: protocol.Diagnostic[];
|
||||
suggestion: protocol.Diagnostic[];
|
||||
}
|
||||
interface GetErrForProjectDiagnostics {
|
||||
project: string;
|
||||
errors: readonly GetErrDiagnostics[];
|
||||
}
|
||||
interface SyncDiagnostics extends GetErrDiagnostics {
|
||||
project?: string;
|
||||
}
|
||||
interface VerifyScenario {
|
||||
allFiles: () => readonly File[];
|
||||
openFiles: () => readonly File[];
|
||||
expectedGetErr: () => readonly GetErrDiagnostics[];
|
||||
expectedGetErrForProject: () => readonly GetErrForProjectDiagnostics[];
|
||||
expectedSyncDiagnostics: () => readonly SyncDiagnostics[];
|
||||
expectedConfigFileDiagEvents: () => readonly server.ConfigFileDiagEvent["data"][];
|
||||
}
|
||||
function verifyScenario(scenario: VerifyScenario) {
|
||||
verifyErrorsUsingGeterr(scenario);
|
||||
verifyErrorsUsingGeterrForProject(scenario);
|
||||
verifyErrorsUsingSyncMethods(scenario);
|
||||
verifyConfigFileErrors(scenario);
|
||||
}
|
||||
|
||||
function emptyDiagnostics(file: File): GetErrDiagnostics {
|
||||
return {
|
||||
file,
|
||||
syntax: emptyArray,
|
||||
semantic: emptyArray,
|
||||
suggestion: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
function syncDiagnostics(diagnostics: GetErrDiagnostics, project: string): SyncDiagnostics {
|
||||
return { project, ...diagnostics };
|
||||
}
|
||||
|
||||
interface VerifyUsageAndDependency {
|
||||
allFiles: readonly [File, File, File, File]; // dependencyTs, dependencyConfig, usageTs, usageConfig
|
||||
usageDiagnostics(): GetErrDiagnostics;
|
||||
dependencyDiagnostics(): GetErrDiagnostics;
|
||||
|
||||
}
|
||||
function verifyUsageAndDependency({ allFiles, usageDiagnostics, dependencyDiagnostics }: VerifyUsageAndDependency) {
|
||||
const [dependencyTs, dependencyConfig, usageTs, usageConfig] = allFiles;
|
||||
function usageProjectDiagnostics(): GetErrForProjectDiagnostics {
|
||||
return {
|
||||
project: usageTs.path,
|
||||
errors: [
|
||||
usageDiagnostics(),
|
||||
emptyDiagnostics(dependencyTs)
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
function dependencyProjectDiagnostics(): GetErrForProjectDiagnostics {
|
||||
return {
|
||||
project: dependencyTs.path,
|
||||
errors: [
|
||||
dependencyDiagnostics()
|
||||
]
|
||||
};
|
||||
}
|
||||
|
||||
function usageConfigDiag(): server.ConfigFileDiagEvent["data"] {
|
||||
return {
|
||||
triggerFile: usageTs.path,
|
||||
configFileName: usageConfig.path,
|
||||
diagnostics: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
function dependencyConfigDiag(): server.ConfigFileDiagEvent["data"] {
|
||||
return {
|
||||
triggerFile: dependencyTs.path,
|
||||
configFileName: dependencyConfig.path,
|
||||
diagnostics: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
describe("when dependency project is not open", () => {
|
||||
verifyScenario({
|
||||
allFiles: () => allFiles,
|
||||
openFiles: () => [usageTs],
|
||||
expectedGetErr: () => [
|
||||
usageDiagnostics()
|
||||
],
|
||||
expectedGetErrForProject: () => [
|
||||
usageProjectDiagnostics(),
|
||||
{
|
||||
project: dependencyTs.path,
|
||||
errors: [
|
||||
emptyDiagnostics(dependencyTs),
|
||||
usageDiagnostics()
|
||||
]
|
||||
}
|
||||
],
|
||||
expectedSyncDiagnostics: () => [
|
||||
// Without project
|
||||
usageDiagnostics(),
|
||||
emptyDiagnostics(dependencyTs),
|
||||
// With project
|
||||
syncDiagnostics(usageDiagnostics(), usageConfig.path),
|
||||
syncDiagnostics(emptyDiagnostics(dependencyTs), usageConfig.path),
|
||||
],
|
||||
expectedConfigFileDiagEvents: () => [
|
||||
usageConfigDiag()
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe("when the depedency file is open", () => {
|
||||
verifyScenario({
|
||||
allFiles: () => allFiles,
|
||||
openFiles: () => [usageTs, dependencyTs],
|
||||
expectedGetErr: () => [
|
||||
usageDiagnostics(),
|
||||
dependencyDiagnostics(),
|
||||
],
|
||||
expectedGetErrForProject: () => [
|
||||
usageProjectDiagnostics(),
|
||||
dependencyProjectDiagnostics()
|
||||
],
|
||||
expectedSyncDiagnostics: () => [
|
||||
// Without project
|
||||
usageDiagnostics(),
|
||||
dependencyDiagnostics(),
|
||||
// With project
|
||||
syncDiagnostics(usageDiagnostics(), usageConfig.path),
|
||||
syncDiagnostics(emptyDiagnostics(dependencyTs), usageConfig.path),
|
||||
syncDiagnostics(dependencyDiagnostics(), dependencyConfig.path),
|
||||
],
|
||||
expectedConfigFileDiagEvents: () => [
|
||||
usageConfigDiag(),
|
||||
dependencyConfigDiag()
|
||||
],
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe("with module scenario", () => {
|
||||
const dependencyTs: File = {
|
||||
path: `${dependecyLocation}/fns.ts`,
|
||||
content: `export function fn1() { }
|
||||
export function fn2() { }
|
||||
// Introduce error for fnErr import in main
|
||||
// export function fnErr() { }
|
||||
// Error in dependency ts file
|
||||
export let x: string = 10;`
|
||||
};
|
||||
const dependencyConfig: File = {
|
||||
path: `${dependecyLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({ compilerOptions: { composite: true, declarationDir: "../decls" } })
|
||||
};
|
||||
const usageTs: File = {
|
||||
path: `${usageLocation}/usage.ts`,
|
||||
content: `import {
|
||||
fn1,
|
||||
fn2,
|
||||
fnErr
|
||||
} from '../decls/fns'
|
||||
fn1();
|
||||
fn2();
|
||||
fnErr();
|
||||
`
|
||||
};
|
||||
const usageConfig: File = {
|
||||
path: `${usageLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({
|
||||
compilerOptions: { composite: true },
|
||||
references: [{ path: "../dependency" }]
|
||||
})
|
||||
};
|
||||
function usageDiagnostics(): GetErrDiagnostics {
|
||||
return {
|
||||
file: usageTs,
|
||||
syntax: emptyArray,
|
||||
semantic: [
|
||||
createDiagnostic(
|
||||
{ line: 4, offset: 5 },
|
||||
{ line: 4, offset: 10 },
|
||||
Diagnostics.Module_0_has_no_exported_member_1,
|
||||
[`"../dependency/fns"`, "fnErr"],
|
||||
"error",
|
||||
)
|
||||
],
|
||||
suggestion: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
function dependencyDiagnostics(): GetErrDiagnostics {
|
||||
return {
|
||||
file: dependencyTs,
|
||||
syntax: emptyArray,
|
||||
semantic: [
|
||||
createDiagnostic(
|
||||
{ line: 6, offset: 12 },
|
||||
{ line: 6, offset: 13 },
|
||||
Diagnostics.Type_0_is_not_assignable_to_type_1,
|
||||
["10", "string"],
|
||||
"error",
|
||||
)
|
||||
],
|
||||
suggestion: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
verifyUsageAndDependency({
|
||||
allFiles: [dependencyTs, dependencyConfig, usageTs, usageConfig],
|
||||
usageDiagnostics,
|
||||
dependencyDiagnostics
|
||||
});
|
||||
});
|
||||
|
||||
describe("with non module --out", () => {
|
||||
const dependencyTs: File = {
|
||||
path: `${dependecyLocation}/fns.ts`,
|
||||
content: `function fn1() { }
|
||||
function fn2() { }
|
||||
// Introduce error for fnErr import in main
|
||||
// function fnErr() { }
|
||||
// Error in dependency ts file
|
||||
let x: string = 10;`
|
||||
};
|
||||
const dependencyConfig: File = {
|
||||
path: `${dependecyLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({ compilerOptions: { composite: true, outFile: "../dependency.js" } })
|
||||
};
|
||||
const usageTs: File = {
|
||||
path: `${usageLocation}/usage.ts`,
|
||||
content: `fn1();
|
||||
fn2();
|
||||
fnErr();
|
||||
`
|
||||
};
|
||||
const usageConfig: File = {
|
||||
path: `${usageLocation}/tsconfig.json`,
|
||||
content: JSON.stringify({
|
||||
compilerOptions: { composite: true, outFile: "../usage.js" },
|
||||
references: [{ path: "../dependency" }]
|
||||
})
|
||||
};
|
||||
function usageDiagnostics(): GetErrDiagnostics {
|
||||
return {
|
||||
file: usageTs,
|
||||
syntax: emptyArray,
|
||||
semantic: [
|
||||
createDiagnostic(
|
||||
{ line: 3, offset: 1 },
|
||||
{ line: 3, offset: 6 },
|
||||
Diagnostics.Cannot_find_name_0,
|
||||
["fnErr"],
|
||||
"error",
|
||||
)
|
||||
],
|
||||
suggestion: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
function dependencyDiagnostics(): GetErrDiagnostics {
|
||||
return {
|
||||
file: dependencyTs,
|
||||
syntax: emptyArray,
|
||||
semantic: [
|
||||
createDiagnostic(
|
||||
{ line: 6, offset: 5 },
|
||||
{ line: 6, offset: 6 },
|
||||
Diagnostics.Type_0_is_not_assignable_to_type_1,
|
||||
["10", "string"],
|
||||
"error",
|
||||
)
|
||||
],
|
||||
suggestion: emptyArray
|
||||
};
|
||||
}
|
||||
|
||||
verifyUsageAndDependency({
|
||||
allFiles: [dependencyTs, dependencyConfig, usageTs, usageConfig],
|
||||
usageDiagnostics,
|
||||
dependencyDiagnostics
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
Reference in new issue
Block a user