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

Introduce the "comparable" relation #5517

Merged
merged 24 commits into from
Mar 30, 2016
Merged
Show file tree
Hide file tree
Changes from 19 commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
002bb6f
Added tests.
DanielRosenwasser Oct 27, 2015
7426aca
Accepted baselines.
DanielRosenwasser Oct 27, 2015
43f158d
Added "comparability" relation. It's currently equivalent to assignab…
DanielRosenwasser Oct 27, 2015
1edb007
Check for partial satisfiability when using the comparable relationship.
DanielRosenwasser Oct 28, 2015
9a5e3e3
Avoid a redundant stricter check when using the new relation.
DanielRosenwasser Oct 28, 2015
42b3ce4
Rename the relationship to "matchable by".
DanielRosenwasser Oct 28, 2015
929808e
Accepted baselines.
DanielRosenwasser Oct 29, 2015
262352e
Added tests on intersection types.
DanielRosenwasser Oct 28, 2015
bdb1db5
Matchable should have no effect on intersections.
DanielRosenwasser Oct 28, 2015
441dd78
Accepted baselines.
DanielRosenwasser Oct 29, 2015
841789d
Renamed the relationship back to "comparable".
DanielRosenwasser Oct 29, 2015
5cb95d4
Renamed test directory.
DanielRosenwasser Oct 29, 2015
ab7c4e5
Accepted baselines.
DanielRosenwasser Oct 29, 2015
e224083
Updated error message.
DanielRosenwasser Nov 4, 2015
fa6e181
Accepted baselines.
DanielRosenwasser Nov 4, 2015
80a50aa
Appease the almighty linter.
DanielRosenwasser Nov 4, 2015
42c49ce
Style.
DanielRosenwasser Nov 4, 2015
6c8c122
'with' to 'to'
DanielRosenwasser Nov 4, 2015
f6eacb9
Accepted baselines.
DanielRosenwasser Nov 4, 2015
a37b731
Changed type assertion error message.
DanielRosenwasser Nov 5, 2015
e0385a4
Accepted baselines.
DanielRosenwasser Nov 5, 2015
0a706c4
Merge branch 'master' into comparableRelation
DanielRosenwasser Nov 5, 2015
a3faca5
Merge branch 'master' into comparableRelation
DanielRosenwasser Mar 30, 2016
3cc64cb
Undo comment override from merge.
DanielRosenwasser Mar 30, 2016
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 59 additions & 22 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,7 @@ namespace ts {

let subtypeRelation: Map<RelationComparisonResult> = {};
let assignableRelation: Map<RelationComparisonResult> = {};
let comparableRelation: Map<RelationComparisonResult> = {};
let identityRelation: Map<RelationComparisonResult> = {};

// This is for caching the result of getSymbolDisplayBuilder. Do not access directly.
Expand Down Expand Up @@ -4738,6 +4739,14 @@ namespace ts {
return checkTypeAssignableTo(source, target, /*errorNode*/ undefined);
}

/**
* This is *not* a bi-directional relationship.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this true of isTypeAssignableTo too? Its former usage in this diff indicates 'yes'.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It is true of isTypeAssignableTo but isTypeAssignableTo has a clear direction; on the other hand, isTypeComparableTo is vague enough that it warrants a comment. One would think that A being comparable to B implies that B is comarable to A, but that's not quite the case.

I could have made isTypeComparableTo a bidirectional relation, but I decided not to based on the way in which we use the relation in type assertions. Specifically, with type assertions, we check whether the expression type is comparable to the asserted type and that the asserted type is comparable to the widened type of the expression.

Actually, I'm not sure if there is any reason we don't check against the widened type for both. I'll experiment with it.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

As discussed offline, I think that's a bug. I will change that in a later PR

* If one needs to check both directions for comparability, use a second call to this function or 'checkTypeComparableTo'.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All uses do need to check both directions, so probably you should have a version that does that. You might not even need the uni-directional ones except for consistency with the other relations.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

*/
function isTypeComparableTo(source: Type, target: Type): boolean {
return checkTypeComparableTo(source, target, /*errorNode*/ undefined);
}

function checkTypeSubtypeOf(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean {
return checkTypeRelatedTo(source, target, subtypeRelation, errorNode, headMessage, containingMessageChain);
}
Expand All @@ -4746,6 +4755,14 @@ namespace ts {
return checkTypeRelatedTo(source, target, assignableRelation, errorNode, headMessage, containingMessageChain);
}

/**
* This is *not* a bi-directional relationship.
* If one needs to check both directions for comparability, use a second call to this function or 'isTypeComparableTo'.
*/
function checkTypeComparableTo(source: Type, target: Type, errorNode: Node, headMessage?: DiagnosticMessage, containingMessageChain?: DiagnosticMessageChain): boolean {
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: This function is hard to read on a portrait (1200 px) monitor with github's generous margins cutting it down to about 700 px. Might not be worth fixing.

return checkTypeRelatedTo(source, target, comparableRelation, errorNode, headMessage, containingMessageChain);
}

function isSignatureAssignableTo(source: Signature, target: Signature): boolean {
let sourceType = getOrCreateTypeFromSignature(source);
let targetType = getOrCreateTypeFromSignature(target);
Expand All @@ -4756,7 +4773,7 @@ namespace ts {
* Checks if 'source' is related to 'target' (e.g.: is a assignable to).
* @param source The left-hand-side of the relation.
* @param target The right-hand-side of the relation.
* @param relation The relation considered. One of 'identityRelation', 'assignableRelation', or 'subTypeRelation'.
* @param relation The relation considered. One of 'identityRelation', 'assignableRelation', 'subTypeRelation', or 'comparableRelation'.
* Used as both to determine which checks are performed and as a cache of previously computed results.
* @param errorNode The suggested node upon which all errors will be reported, if defined. This may or may not be the actual node used.
* @param headMessage If the error chain should be prepended by a head message, then headMessage will be used.
Expand All @@ -4781,6 +4798,7 @@ namespace ts {

Debug.assert(relation !== identityRelation || !errorNode, "no error reporting in identity checking");

const isAssignableOrComparableRelation = relation === assignableRelation || relation === comparableRelation;
let result = isRelatedTo(source, target, errorNode !== undefined, headMessage);
if (overflow) {
error(errorNode, Diagnostics.Excessive_stack_depth_comparing_types_0_and_1, typeToString(source), typeToString(target));
Expand Down Expand Up @@ -4814,7 +4832,14 @@ namespace ts {
sourceType = typeToString(source, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType);
targetType = typeToString(target, /*enclosingDeclaration*/ undefined, TypeFormatFlags.UseFullyQualifiedType);
}
reportError(message || Diagnostics.Type_0_is_not_assignable_to_type_1, sourceType, targetType);

if (!message) {
message = relation === comparableRelation ?
Diagnostics.Type_0_is_not_comparable_to_type_1 :
Diagnostics.Type_0_is_not_assignable_to_type_1;
}

reportError(message, sourceType, targetType);
}

// Compare two types and return
Expand All @@ -4834,7 +4859,7 @@ namespace ts {
if (source === nullType && target !== undefinedType) return Ternary.True;
if (source.flags & TypeFlags.Enum && target === numberType) return Ternary.True;
if (source.flags & TypeFlags.StringLiteral && target === stringType) return Ternary.True;
if (relation === assignableRelation) {
if (isAssignableOrComparableRelation) {
if (isTypeAny(source)) return Ternary.True;
if (source === numberType && target.flags & TypeFlags.Enum) return Ternary.True;
}
Expand All @@ -4857,29 +4882,39 @@ namespace ts {

let saveErrorInfo = errorInfo;

// Note that the "each" checks must precede the "some" checks to produce the correct results
// Note that these checks are specifically ordered to produce correct results.
if (source.flags & TypeFlags.Union) {
if (result = eachTypeRelatedToType(<UnionType>source, target, reportErrors)) {
if (relation === comparableRelation) {
result = someTypeRelatedToType(source as UnionType, target, reportErrors);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please choose one cast syntax and make at least the changed lines use it, preferably something like all the casts in the function.

}
else {
result = eachTypeRelatedToType(source as UnionType, target, reportErrors);
}

if (result) {
return result;
}
}
else if (target.flags & TypeFlags.Intersection) {
if (result = typeRelatedToEachType(source, <IntersectionType>target, reportErrors)) {
result = typeRelatedToEachType(source, target as IntersectionType, reportErrors);

if (result) {
return result;
}
}
else {
// It is necessary to try "some" checks on both sides because there may be nested "each" checks
// It is necessary to try these "some" checks on both sides because there may be nested "each" checks
// on either side that need to be prioritized. For example, A | B = (A | B) & (C | D) or
// A & B = (A & B) | (C & D).
if (source.flags & TypeFlags.Intersection) {
// If target is a union type the following check will report errors so we suppress them here
if (result = someTypeRelatedToType(<IntersectionType>source, target, reportErrors && !(target.flags & TypeFlags.Union))) {
// If target is a union type then the check following this one will report errors,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this improves on the old wording.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It does if you have more context. "The following check" implies "the one directly below"

// so we'll suppress any errors we could run into here.
if (result = someTypeRelatedToType(source as IntersectionType, target, reportErrors && !(target.flags & TypeFlags.Union))) {
return result;
}
}
if (target.flags & TypeFlags.Union) {
if (result = typeRelatedToSomeType(source, <UnionType>target, reportErrors)) {
if (result = typeRelatedToSomeType(source, target as UnionType, reportErrors)) {
return result;
}
}
Expand Down Expand Up @@ -4942,8 +4977,8 @@ namespace ts {
}
if (source.flags & TypeFlags.Union && target.flags & TypeFlags.Union ||
source.flags & TypeFlags.Intersection && target.flags & TypeFlags.Intersection) {
if (result = eachTypeRelatedToSomeType(<UnionOrIntersectionType>source, <UnionOrIntersectionType>target)) {
if (result &= eachTypeRelatedToSomeType(<UnionOrIntersectionType>target, <UnionOrIntersectionType>source)) {
if (result = eachTypeRelatedToSomeType(<UnionOrIntersectionType>source, <UnionOrIntersectionType>target, /*reportErrors*/ false)) {
if (result &= eachTypeRelatedToSomeType(<UnionOrIntersectionType>target, <UnionOrIntersectionType>source, /*reportErrors*/ false)) {
return result;
}
}
Expand All @@ -4958,7 +4993,7 @@ namespace ts {
function isKnownProperty(type: Type, name: string): boolean {
if (type.flags & TypeFlags.ObjectType) {
const resolved = resolveStructuredTypeMembers(type);
if (relation === assignableRelation && (type === globalObjectType || resolved.properties.length === 0) ||
if (isAssignableOrComparableRelation && (type === globalObjectType || resolved.properties.length === 0) ||
resolved.stringIndexType || resolved.numberIndexType || getPropertyOfType(type, name)) {
return true;
}
Expand Down Expand Up @@ -4992,11 +5027,11 @@ namespace ts {
return false;
}

function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType): Ternary {
function eachTypeRelatedToSomeType(source: UnionOrIntersectionType, target: UnionOrIntersectionType, reportErrors: boolean): Ternary {
let result = Ternary.True;
let sourceTypes = source.types;
for (let sourceType of sourceTypes) {
let related = typeRelatedToSomeType(sourceType, target, false);
let related = typeRelatedToSomeType(sourceType, target, reportErrors);
if (!related) {
return Ternary.False;
}
Expand Down Expand Up @@ -9381,8 +9416,9 @@ namespace ts {
let targetType = getTypeFromTypeNode(node.type);
if (produceDiagnostics && targetType !== unknownType) {
let widenedType = getWidenedType(exprType);
if (!(isTypeAssignableTo(targetType, widenedType))) {
checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);

if (!isTypeComparableTo(targetType, widenedType)) {
checkTypeComparableTo(exprType, targetType, node);
}
}
return targetType;
Expand Down Expand Up @@ -10225,7 +10261,7 @@ namespace ts {
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
if (!isTypeComparableTo(leftType, rightType) && !isTypeComparableTo(rightType, leftType)) {
reportOperatorError();
}
return booleanType;
Expand Down Expand Up @@ -12689,12 +12725,13 @@ namespace ts {

if (produceDiagnostics && clause.kind === SyntaxKind.CaseClause) {
let caseClause = <CaseClause>clause;
// TypeScript 1.0 spec (April 2014):5.9
// TypeScript 1.0 spec (April 2014): 5.9
// In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression.
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

update 'assignable' to 'comparable'

// TODO (drosen): this needs to be amended to reflect the "comparable" relationship.
let caseType = checkExpression(caseClause.expression);
if (!isTypeAssignableTo(expressionType, caseType)) {
// check 'expressionType isAssignableTo caseType' failed, try the reversed check and report errors if it fails
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);

if (!isTypeComparableTo(expressionType, caseType)) {
checkTypeComparableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);
}
}
forEach(clause.statements, checkSourceElement);
Expand Down
8 changes: 4 additions & 4 deletions src/compiler/diagnosticMessages.json
Original file line number Diff line number Diff line change
Expand Up @@ -888,6 +888,10 @@
"category": "Error",
"code": 2322
},
"Type '{0}' is not comparable to type '{1}'.": {
"category": "Error",
"code": 2323
},
"Property '{0}' is missing in type '{1}'.": {
"category": "Error",
"code": 2324
Expand Down Expand Up @@ -996,10 +1000,6 @@
"category": "Error",
"code": 2351
},
"Neither type '{0}' nor type '{1}' is assignable to the other.": {
"category": "Error",
"code": 2352
},
"Object literal may only specify known properties, and '{0}' does not exist in type '{1}'.": {
"category": "Error",
"code": 2353
Expand Down
10 changes: 5 additions & 5 deletions tests/baselines/reference/arrayCast.errors.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
tests/cases/compiler/arrayCast.ts(3,23): error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
tests/cases/compiler/arrayCast.ts(3,23): error TS2323: Type '{ foo: string; }[]' is not comparable to type '{ id: number; }[]'.
Type '{ foo: string; }' is not comparable to type '{ id: number; }'.
Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.


Expand All @@ -8,9 +8,9 @@ tests/cases/compiler/arrayCast.ts(3,23): error TS2352: Neither type '{ foo: stri
// has type { foo: string }[], which is not assignable to { id: number }[].
<{ id: number; }[]>[{ foo: "s" }];
~~~~~~~~
!!! error TS2352: Neither type '{ foo: string; }[]' nor type '{ id: number; }[]' is assignable to the other.
!!! error TS2352: Type '{ foo: string; }' is not assignable to type '{ id: number; }'.
!!! error TS2352: Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.
!!! error TS2323: Type '{ foo: string; }[]' is not comparable to type '{ id: number; }[]'.
!!! error TS2323: Type '{ foo: string; }' is not comparable to type '{ id: number; }'.
!!! error TS2323: Object literal may only specify known properties, and 'foo' does not exist in type '{ id: number; }'.

// Should succeed, as the {} element causes the type of the array to be {}[]
<{ id: number; }[]>[{ foo: "s" }, {}];
4 changes: 2 additions & 2 deletions tests/baselines/reference/asOperator2.errors.txt
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
tests/cases/conformance/expressions/asOperator/asOperator2.ts(1,9): error TS2323: Type 'number' is not comparable to type 'string'.


==== tests/cases/conformance/expressions/asOperator/asOperator2.ts (1 errors) ====
var x = 23 as string;
~~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
!!! error TS2323: Type 'number' is not comparable to type 'string'.

8 changes: 4 additions & 4 deletions tests/baselines/reference/asOperatorContextualType.errors.txt
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts(2,9): error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
Type 'number' is not assignable to type 'string'.
tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts(2,9): error TS2323: Type '(v: number) => number' is not comparable to type '(x: number) => string'.
Type 'number' is not comparable to type 'string'.


==== tests/cases/conformance/expressions/asOperator/asOperatorContextualType.ts (1 errors) ====
// should error
var x = (v => v) as (x: number) => string;
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
!!! error TS2352: Neither type '(v: number) => number' nor type '(x: number) => string' is assignable to the other.
!!! error TS2352: Type 'number' is not assignable to type 'string'.
!!! error TS2323: Type '(v: number) => number' is not comparable to type '(x: number) => string'.
!!! error TS2323: Type 'number' is not comparable to type 'string'.
4 changes: 2 additions & 2 deletions tests/baselines/reference/asOperatorNames.errors.txt
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
tests/cases/conformance/expressions/asOperator/asOperatorNames.ts(2,9): error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
tests/cases/conformance/expressions/asOperator/asOperatorNames.ts(2,9): error TS2323: Type 'number' is not comparable to type 'string'.


==== tests/cases/conformance/expressions/asOperator/asOperatorNames.ts (1 errors) ====
var a = 20;
var b = a as string;
~~~~~~~~~~~
!!! error TS2352: Neither type 'number' nor type 'string' is assignable to the other.
!!! error TS2323: Type 'number' is not comparable to type 'string'.
var as = "hello";
var as1 = as as string;

Loading