Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Type inference in conditional types #21496

Merged
merged 66 commits into from
Feb 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
66 commits
Select commit Hold shift + click to select a range
57ca768
Initial implementation of conditional type operator
ahejlsberg Dec 5, 2017
063eed1
Add type relationships and distribute over union types
ahejlsberg Dec 8, 2017
ec2bdfd
Add 'T extends U' type operator
ahejlsberg Dec 12, 2017
43e195d
Clean up isGenericXXXType functions
ahejlsberg Dec 12, 2017
61225cc
Introduce TypeFlags.Instatiable
ahejlsberg Dec 13, 2017
9f74a7a
Rename TypeVariable to InstantiableType
ahejlsberg Dec 13, 2017
20434fa
Inference for conditional and extends type operators
ahejlsberg Dec 13, 2017
ddc631c
Fix typo
ahejlsberg Dec 13, 2017
000f121
Improve conditional type constraint checking
ahejlsberg Dec 13, 2017
27b945b
Handle constraints for distributive conditional types
ahejlsberg Dec 16, 2017
f59e2e6
Accept new baselines
ahejlsberg Dec 17, 2017
14590f1
Move JsxAttributes and MarkerType from TypeFlags to ObjectFlags
ahejlsberg Dec 18, 2017
100e4f6
Accept new baselines
ahejlsberg Dec 18, 2017
c5fd2f1
Parse xxx? as JSDoc type when not followed by token that starts type
ahejlsberg Dec 19, 2017
341c397
Accept new baselines
ahejlsberg Dec 19, 2017
3f4911f
Fix linting error
ahejlsberg Dec 20, 2017
abc8110
Merge branch 'master' into conditionalTypes
ahejlsberg Jan 3, 2018
bb23bb2
Propagate both TypeFlags and ObjectFlags in getSpreadType
ahejlsberg Jan 3, 2018
c10a552
Eagerly evaluate S extends T when S is definitely or definitely not a…
ahejlsberg Jan 14, 2018
53b1572
Revert to extends check being part of conditional type
ahejlsberg Jan 15, 2018
5094f76
Remove 'T extends U' type constructor
ahejlsberg Jan 15, 2018
925da86
Accept new baselines
ahejlsberg Jan 15, 2018
e8d1740
Introduce substitution types to use for constrained type parameters
ahejlsberg Jan 15, 2018
15baf0e
Accept new baselines
ahejlsberg Jan 15, 2018
9598acd
Properly handle 'any' and 'never' as conditional check type
ahejlsberg Jan 15, 2018
e96ec8c
Erase substitution types in type references and type alias instantiat…
ahejlsberg Jan 16, 2018
d52fa71
Optimize the sameMap function
ahejlsberg Jan 16, 2018
4ec6fdd
Merge branch 'master' into conditionalTypes
ahejlsberg Jan 17, 2018
fd0dd6e
Separate code path for conditional type instantiation
ahejlsberg Jan 18, 2018
c360c24
Fix parsing
ahejlsberg Jan 19, 2018
0e73240
Disallow conditional type following 'extends'
ahejlsberg Jan 19, 2018
5204fd5
Add T is related to { [P in xxx]: T[P] } type relationship
ahejlsberg Jan 20, 2018
eb314d0
Add tests
ahejlsberg Jan 20, 2018
cdd50d4
Accept new baselines
ahejlsberg Jan 20, 2018
fc7d1c3
Revise comments
ahejlsberg Jan 20, 2018
f19959a
Cache substitution types and remove erasure that was too eager
ahejlsberg Jan 20, 2018
b869290
Remove unnecessary caching of substitution types
ahejlsberg Jan 21, 2018
4c7ec3c
Shared code path for getConditionalType and instantiateConditionalType
ahejlsberg Jan 21, 2018
b42c6b1
Only conditional types that check naked type parameter distribute ove…
ahejlsberg Jan 24, 2018
8e337b5
Fix bug in resolveMappedTypeMembers
ahejlsberg Jan 24, 2018
d608941
Implement type inference in conditional types
ahejlsberg Jan 25, 2018
490d656
Remove pointless fourslash tests
ahejlsberg Jan 25, 2018
4d62df4
Accept new baselines
ahejlsberg Jan 25, 2018
ef0c3b7
Change precedence of 'infer T' to match 'keyof T'
ahejlsberg Jan 25, 2018
f59f3a2
Check 'infer' declarations are in extends clause of conditional type
ahejlsberg Jan 25, 2018
60c9249
Properly handle inferred type parameters in declaration emitter
ahejlsberg Jan 26, 2018
e450212
Infer intersection types for multiple contravariant candidates
ahejlsberg Jan 26, 2018
fa6c4b7
Check for definitely false condition first
ahejlsberg Jan 26, 2018
edffb12
Cache 'any' instantiations for faster conditional type resolution
ahejlsberg Jan 27, 2018
c6f0dfb
Add definitelyAssignableRelation
ahejlsberg Jan 30, 2018
4f2b5f3
Merge branch 'master' into conditionalTypes
ahejlsberg Jan 30, 2018
f990e4e
Merge branch 'master' into conditionalTypes
ahejlsberg Jan 30, 2018
01516c8
Update to use TypeFlags.Instantiable in instantiateSymbol
ahejlsberg Jan 30, 2018
34505c1
Add tests
ahejlsberg Jan 30, 2018
03a3847
Accept new baselines
ahejlsberg Jan 30, 2018
7c241ba
Merge branch 'conditionalTypes' into inferTypes
ahejlsberg Jan 30, 2018
5702f61
Always use strict rules for contravariant inferences
ahejlsberg Jan 31, 2018
1275a20
Accept new baselines
ahejlsberg Jan 31, 2018
afec056
Add more error case checks
ahejlsberg Jan 31, 2018
36a49ad
Accept new baselines
ahejlsberg Jan 31, 2018
d4dc67a
Merge branch 'master' into conditionalTypes
ahejlsberg Feb 3, 2018
7034d67
Merge branch 'conditionalTypes' into inferTypes
ahejlsberg Feb 3, 2018
7bb8cfe
Resolve to type in true branch for 'never extends never'
ahejlsberg Feb 3, 2018
a712344
Add tests
ahejlsberg Feb 3, 2018
04260d6
Accept new baselines
ahejlsberg Feb 3, 2018
4ae8445
Properly classify output text in emitter
ahejlsberg Feb 3, 2018
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
34 changes: 33 additions & 1 deletion src/compiler/binder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ namespace ts {
HasLocals = 1 << 5,
IsInterface = 1 << 6,
IsObjectLiteralOrClassExpressionMethod = 1 << 7,
IsInferenceContainer = 1 << 8,
}

const binder = createBinder();
Expand All @@ -119,6 +120,7 @@ namespace ts {
let parent: Node;
let container: Node;
let blockScopeContainer: Node;
let inferenceContainer: Node;
let lastContainer: Node;
let seenThisKeyword: boolean;

Expand Down Expand Up @@ -186,6 +188,7 @@ namespace ts {
parent = undefined;
container = undefined;
blockScopeContainer = undefined;
inferenceContainer = undefined;
lastContainer = undefined;
seenThisKeyword = false;
currentFlow = undefined;
Expand Down Expand Up @@ -561,6 +564,13 @@ namespace ts {
bindChildren(node);
node.flags = seenThisKeyword ? node.flags | NodeFlags.ContainsThis : node.flags & ~NodeFlags.ContainsThis;
}
else if (containerFlags & ContainerFlags.IsInferenceContainer) {
const saveInferenceContainer = inferenceContainer;
inferenceContainer = node;
node.locals = undefined;
bindChildren(node);
inferenceContainer = saveInferenceContainer;
}
else {
bindChildren(node);
}
Expand Down Expand Up @@ -1417,6 +1427,9 @@ namespace ts {
case SyntaxKind.MappedType:
return ContainerFlags.IsContainer | ContainerFlags.HasLocals;

case SyntaxKind.ConditionalType:
return ContainerFlags.IsInferenceContainer;

case SyntaxKind.SourceFile:
return ContainerFlags.IsContainer | ContainerFlags.IsControlFlowContainer | ContainerFlags.HasLocals;

Expand Down Expand Up @@ -2059,7 +2072,7 @@ namespace ts {
case SyntaxKind.TypePredicate:
return checkTypePredicate(node as TypePredicateNode);
case SyntaxKind.TypeParameter:
return declareSymbolAndAddToSymbolTable(<Declaration>node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
return bindTypeParameter(node as TypeParameterDeclaration);
case SyntaxKind.Parameter:
return bindParameter(<ParameterDeclaration>node);
case SyntaxKind.VariableDeclaration:
Expand Down Expand Up @@ -2576,6 +2589,23 @@ namespace ts {
: declareSymbolAndAddToSymbolTable(node, symbolFlags, symbolExcludes);
}

function bindTypeParameter(node: TypeParameterDeclaration) {
if (node.parent.kind === SyntaxKind.InferType) {
if (inferenceContainer) {
if (!inferenceContainer.locals) {
inferenceContainer.locals = createSymbolTable();
}
declareSymbol(inferenceContainer.locals, /*parent*/ undefined, node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
}
else {
bindAnonymousDeclaration(node, SymbolFlags.TypeParameter, getDeclarationName(node));
}
}
else {
declareSymbolAndAddToSymbolTable(node, SymbolFlags.TypeParameter, SymbolFlags.TypeParameterExcludes);
}
}

// reachability checks

function shouldReportErrorOnModuleDeclaration(node: ModuleDeclaration): boolean {
Expand Down Expand Up @@ -3440,6 +3470,8 @@ namespace ts {
case SyntaxKind.TupleType:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.ConditionalType:
case SyntaxKind.InferType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.InterfaceDeclaration:
case SyntaxKind.TypeAliasDeclaration:
Expand Down
422 changes: 347 additions & 75 deletions src/compiler/checker.ts

Large diffs are not rendered by default.

20 changes: 9 additions & 11 deletions src/compiler/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -439,23 +439,21 @@ namespace ts {
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[];
export function sameMap<T>(array: ReadonlyArray<T>, f: (x: T, i: number) => T): ReadonlyArray<T>;
export function sameMap<T>(array: T[], f: (x: T, i: number) => T): T[] {
let result: T[];
if (array) {
for (let i = 0; i < array.length; i++) {
if (result) {
result.push(f(array[i], i));
}
else {
const item = array[i];
const mapped = f(item, i);
if (item !== mapped) {
result = array.slice(0, i);
result.push(mapped);
const item = array[i];
const mapped = f(item, i);
if (item !== mapped) {
const result = array.slice(0, i);
result.push(mapped);
for (i++; i < array.length; i++) {
result.push(f(array[i], i));
}
return result;
}
}
}
return result || array;
return array;
}

/**
Expand Down
22 changes: 22 additions & 0 deletions src/compiler/declarationEmitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -450,6 +450,10 @@ namespace ts {
return emitUnionType(<UnionTypeNode>type);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>type);
case SyntaxKind.ConditionalType:
return emitConditionalType(<ConditionalTypeNode>type);
case SyntaxKind.InferType:
return emitInferType(<InferTypeNode>type);
case SyntaxKind.ParenthesizedType:
return emitParenType(<ParenthesizedTypeNode>type);
case SyntaxKind.TypeOperator:
Expand Down Expand Up @@ -545,6 +549,24 @@ namespace ts {
emitSeparatedList(type.types, " & ", emitType);
}

function emitConditionalType(node: ConditionalTypeNode) {
emitType(node.checkType);
write(" extends ");
emitType(node.extendsType);
write(" ? ");
const prevEnclosingDeclaration = enclosingDeclaration;
enclosingDeclaration = node.trueType;
emitType(node.trueType);
enclosingDeclaration = prevEnclosingDeclaration;
write(" : ");
emitType(node.falseType);
}

function emitInferType(node: InferTypeNode) {
write("infer ");
writeTextOfNode(currentText, node.typeParameter.name);
}

function emitParenType(type: ParenthesizedTypeNode) {
write("(");
emitType(type.type);
Expand Down
4 changes: 4 additions & 0 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -947,6 +947,10 @@
"category": "Error",
"code": 1337
},
"'infer' declarations are only permitted in the 'extends' clause of a conditional type.": {
"category": "Error",
"code": 1338
},

"Duplicate identifier '{0}'.": {
"category": "Error",
Expand Down
26 changes: 26 additions & 0 deletions src/compiler/emitter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -600,6 +600,10 @@ namespace ts {
return emitUnionType(<UnionTypeNode>node);
case SyntaxKind.IntersectionType:
return emitIntersectionType(<IntersectionTypeNode>node);
case SyntaxKind.ConditionalType:
return emitConditionalType(<ConditionalTypeNode>node);
case SyntaxKind.InferType:
return emitInferType(<InferTypeNode>node);
case SyntaxKind.ParenthesizedType:
return emitParenthesizedType(<ParenthesizedTypeNode>node);
case SyntaxKind.ExpressionWithTypeArguments:
Expand Down Expand Up @@ -1190,6 +1194,28 @@ namespace ts {
emitList(node, node.types, ListFormat.IntersectionTypeConstituents);
}

function emitConditionalType(node: ConditionalTypeNode) {
emit(node.checkType);
writeSpace();
writeKeyword("extends");
writeSpace();
emit(node.extendsType);
writeSpace();
writePunctuation("?");
writeSpace();
emit(node.trueType);
writeSpace();
writePunctuation(":");
writeSpace();
emit(node.falseType);
}

function emitInferType(node: InferTypeNode) {
writeKeyword("infer");
writeSpace();
emit(node.typeParameter);
}

function emitParenthesizedType(node: ParenthesizedTypeNode) {
writePunctuation("(");
emit(node.type);
Expand Down
36 changes: 35 additions & 1 deletion src/compiler/factory.ts
Original file line number Diff line number Diff line change
Expand Up @@ -731,6 +731,36 @@ namespace ts {
: node;
}

export function createConditionalTypeNode(checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode) {
const node = createSynthesizedNode(SyntaxKind.ConditionalType) as ConditionalTypeNode;
node.checkType = parenthesizeConditionalTypeMember(checkType);
node.extendsType = parenthesizeConditionalTypeMember(extendsType);
node.trueType = trueType;
node.falseType = falseType;
return node;
}

export function updateConditionalTypeNode(node: ConditionalTypeNode, checkType: TypeNode, extendsType: TypeNode, trueType: TypeNode, falseType: TypeNode) {
return node.checkType !== checkType
|| node.extendsType !== extendsType
|| node.trueType !== trueType
|| node.falseType !== falseType
? updateNode(createConditionalTypeNode(checkType, extendsType, trueType, falseType), node)
: node;
}

export function createInferTypeNode(typeParameter: TypeParameterDeclaration) {
const node = <InferTypeNode>createSynthesizedNode(SyntaxKind.InferType);
node.typeParameter = typeParameter;
return node;
}

export function updateInferTypeNode(node: InferTypeNode, typeParameter: TypeParameterDeclaration) {
return node.typeParameter !== typeParameter
? updateNode(createInferTypeNode(typeParameter), node)
: node;
}

export function createParenthesizedType(type: TypeNode) {
const node = <ParenthesizedTypeNode>createSynthesizedNode(SyntaxKind.ParenthesizedType);
node.type = type;
Expand Down Expand Up @@ -4094,6 +4124,10 @@ namespace ts {
return expression;
}

export function parenthesizeConditionalTypeMember(member: TypeNode) {
return member.kind === SyntaxKind.ConditionalType ? createParenthesizedType(member) : member;
}

export function parenthesizeElementTypeMember(member: TypeNode) {
switch (member.kind) {
case SyntaxKind.UnionType:
Expand All @@ -4102,7 +4136,7 @@ namespace ts {
case SyntaxKind.ConstructorType:
return createParenthesizedType(member);
}
return member;
return parenthesizeConditionalTypeMember(member);
}

export function parenthesizeArrayTypeMember(member: TypeNode) {
Expand Down
44 changes: 42 additions & 2 deletions src/compiler/parser.ts
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,13 @@ namespace ts {
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
return visitNodes(cbNode, cbNodes, (<UnionOrIntersectionTypeNode>node).types);
case SyntaxKind.ConditionalType:
return visitNode(cbNode, (<ConditionalTypeNode>node).checkType) ||
visitNode(cbNode, (<ConditionalTypeNode>node).extendsType) ||
visitNode(cbNode, (<ConditionalTypeNode>node).trueType) ||
visitNode(cbNode, (<ConditionalTypeNode>node).falseType);
case SyntaxKind.InferType:
return visitNode(cbNode, (<InferTypeNode>node).typeParameter);
case SyntaxKind.ParenthesizedType:
case SyntaxKind.TypeOperator:
return visitNode(cbNode, (<ParenthesizedTypeNode | TypeOperatorNode>node).type);
Expand Down Expand Up @@ -1494,6 +1501,11 @@ namespace ts {
return isStartOfExpression();
}

function nextTokenIsStartOfType() {
nextToken();
return isStartOfType();
}

// True if positioned at a list terminator
function isListTerminator(kind: ParsingContext): boolean {
if (token() === SyntaxKind.EndOfFileToken) {
Expand Down Expand Up @@ -2757,6 +2769,7 @@ namespace ts {
case SyntaxKind.QuestionToken:
case SyntaxKind.ExclamationToken:
case SyntaxKind.DotDotDotToken:
case SyntaxKind.InferKeyword:
return true;
case SyntaxKind.MinusToken:
return !inStartOfParameter && lookAhead(nextTokenIsNumericLiteral);
Expand Down Expand Up @@ -2789,6 +2802,10 @@ namespace ts {
type = createJSDocPostfixType(SyntaxKind.JSDocNonNullableType, type);
break;
case SyntaxKind.QuestionToken:
// If not in JSDoc and next token is start of a type we have a conditional type
if (!(contextFlags & NodeFlags.JSDoc) && lookAhead(nextTokenIsStartOfType)) {
return type;
}
type = createJSDocPostfixType(SyntaxKind.JSDocNullableType, type);
break;
case SyntaxKind.OpenBracketToken:
Expand Down Expand Up @@ -2829,12 +2846,23 @@ namespace ts {
return finishNode(node);
}

function parseInferType(): InferTypeNode {
const node = <InferTypeNode>createNode(SyntaxKind.InferType);
parseExpected(SyntaxKind.InferKeyword);
const typeParameter = <TypeParameterDeclaration>createNode(SyntaxKind.TypeParameter);
typeParameter.name = parseIdentifier();
node.typeParameter = finishNode(typeParameter);
return finishNode(node);
}

function parseTypeOperatorOrHigher(): TypeNode {
const operator = token();
switch (operator) {
case SyntaxKind.KeyOfKeyword:
case SyntaxKind.UniqueKeyword:
return parseTypeOperator(operator);
case SyntaxKind.InferKeyword:
return parseInferType();
case SyntaxKind.DotDotDotToken: {
const result = createNode(SyntaxKind.JSDocVariadicType) as JSDocVariadicType;
nextToken();
Expand Down Expand Up @@ -2950,14 +2978,26 @@ namespace ts {
return doOutsideOfContext(NodeFlags.TypeExcludesFlags, parseTypeWorker);
}

function parseTypeWorker(): TypeNode {
function parseTypeWorker(noConditionalTypes?: boolean): TypeNode {
if (isStartOfFunctionType()) {
return parseFunctionOrConstructorType(SyntaxKind.FunctionType);
}
if (token() === SyntaxKind.NewKeyword) {
return parseFunctionOrConstructorType(SyntaxKind.ConstructorType);
}
return parseUnionTypeOrHigher();
const type = parseUnionTypeOrHigher();
if (!noConditionalTypes && parseOptional(SyntaxKind.ExtendsKeyword)) {
const node = <ConditionalTypeNode>createNode(SyntaxKind.ConditionalType, type.pos);
node.checkType = type;
// The type following 'extends' is not permitted to be another conditional type
node.extendsType = parseTypeWorker(/*noConditionalTypes*/ true);
parseExpected(SyntaxKind.QuestionToken);
node.trueType = parseTypeWorker();
parseExpected(SyntaxKind.ColonToken);
node.falseType = parseTypeWorker();
return finishNode(node);
}
return type;
}

function parseTypeAnnotation(): TypeNode {
Expand Down
1 change: 1 addition & 0 deletions src/compiler/scanner.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,6 +92,7 @@ namespace ts {
"implements": SyntaxKind.ImplementsKeyword,
"import": SyntaxKind.ImportKeyword,
"in": SyntaxKind.InKeyword,
"infer": SyntaxKind.InferKeyword,
"instanceof": SyntaxKind.InstanceOfKeyword,
"interface": SyntaxKind.InterfaceKeyword,
"is": SyntaxKind.IsKeyword,
Expand Down
1 change: 1 addition & 0 deletions src/compiler/transformers/ts.ts
Original file line number Diff line number Diff line change
Expand Up @@ -385,6 +385,7 @@ namespace ts {
case SyntaxKind.TypeReference:
case SyntaxKind.UnionType:
case SyntaxKind.IntersectionType:
case SyntaxKind.ConditionalType:
case SyntaxKind.ParenthesizedType:
case SyntaxKind.ThisType:
case SyntaxKind.TypeOperator:
Expand Down