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

Infer string literals at comparison locations #6196

Closed
wants to merge 31 commits into from
Closed
Show file tree
Hide file tree
Changes from 8 commits
Commits
Show all changes
31 commits
Select commit Hold shift + click to select a range
0d2fb26
Added tests.
DanielRosenwasser Dec 21, 2015
639d9bf
Accepted baselines.
DanielRosenwasser Dec 22, 2015
13ec5d7
Infer string literal types at comparison locations.
DanielRosenwasser Dec 22, 2015
e109b17
Accepted baselines.
DanielRosenwasser Dec 22, 2015
de9789a
Removed ad-hoc string-like checking for type assertions, switch/cases…
DanielRosenwasser Dec 22, 2015
d0a8573
Accepted baselines.
DanielRosenwasser Dec 22, 2015
e452955
Amended tests.
DanielRosenwasser Dec 22, 2015
ced65ac
Accepted baselines.
DanielRosenwasser Dec 22, 2015
881b52d
Separated logic out to 'shouldAcquireLiteralType'.
DanielRosenwasser Dec 22, 2015
8365410
Amended comment.
DanielRosenwasser Dec 22, 2015
58580ed
Rewrote loop, amended comment.
DanielRosenwasser Dec 22, 2015
069ff33
Add conditional expressions, be more conservative in checks for '||'.
DanielRosenwasser Dec 23, 2015
2874156
Added more to test.
DanielRosenwasser Dec 23, 2015
e2ddb29
Accepted baselines.
DanielRosenwasser Dec 23, 2015
f7e9135
Merge branch 'master' into literalTypeLocations
DanielRosenwasser Jan 5, 2016
e6bd7ad
Added test.
DanielRosenwasser Jan 5, 2016
16fe01b
Accepted baselines.
DanielRosenwasser Jan 5, 2016
bc34ebb
Added RHS operands of '&&' and ',' as match locations.
DanielRosenwasser Jan 5, 2016
4eced90
Accepted baselines.
DanielRosenwasser Jan 5, 2016
01cc2f1
Added tests for type assertions in match locations.
DanielRosenwasser Jan 8, 2016
259a3cf
Accepted baselines.
DanielRosenwasser Jan 8, 2016
cc2ab55
Factored out operand detection logic and made it recursive.
DanielRosenwasser Jan 8, 2016
5b9e5d1
Included type assertions in operand detection logic.
DanielRosenwasser Jan 8, 2016
fdd7fde
Accepted baselines.
DanielRosenwasser Jan 8, 2016
09d1762
Fix lint issues.
DanielRosenwasser Jan 8, 2016
dec70f1
Added scenario to tests.
DanielRosenwasser Jan 8, 2016
1dd43fa
Accepted baselines.
DanielRosenwasser Jan 8, 2016
ab25584
Merge branch 'master' into literalTypeLocations
DanielRosenwasser Jan 8, 2016
9673152
Merge branch 'master' into literalTypeLocations
DanielRosenwasser Apr 5, 2016
6b8bac3
Accepted other baselines.
DanielRosenwasser Apr 5, 2016
740792c
Merge branch 'master' into literalTypeLocations
DanielRosenwasser Jun 10, 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
77 changes: 45 additions & 32 deletions src/compiler/checker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7334,24 +7334,37 @@ namespace ts {
return undefined;
}

function getContextualTypeForBinaryOperand(node: Expression): Type {
function getContextualTypeForBinaryOperand(node: Expression, literalNode: StringLiteral): Type {
const binaryExpression = <BinaryExpression>node.parent;
const operator = binaryExpression.operatorToken.kind;
if (operator >= SyntaxKind.FirstAssignment && operator <= SyntaxKind.LastAssignment) {

if (SyntaxKind.FirstAssignment <= operator && operator <= SyntaxKind.LastAssignment) {
Copy link
Member

Choose a reason for hiding this comment

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

Purely stylistic, but everywhere else in the compiler we always put the constant on the right hand side (as the code was originally written). I'd prefer to keep things consistent.

// In an assignment expression, the right operand is contextually typed by the type of the left operand.
if (node === binaryExpression.right) {
return checkExpression(binaryExpression.left);
}
return undefined;
Copy link
Contributor

Choose a reason for hiding this comment

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

Probably don't need this

}
else if (operator === SyntaxKind.BarBarToken) {
// When an || expression has a contextual type, the operands are contextually typed by that type. When an ||
// expression has no contextual type, the right operand is contextually typed by the type of the left operand.
let type = getContextualType(binaryExpression);
if (!type && node === binaryExpression.right) {
type = checkExpression(binaryExpression.left);
}
return type;

switch (operator) {
case SyntaxKind.BarBarToken:
// When an || expression has a contextual type, the operands are contextually typed by that type. When an ||
// expression has no contextual type, the right operand is contextually typed by the type of the left operand.
let type = getContextualTypeWorker(binaryExpression, literalNode);
if (!type && node === binaryExpression.right) {
type = checkExpression(binaryExpression.left);
}
return type;
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
case SyntaxKind.EqualsEqualsToken:
case SyntaxKind.ExclamationEqualsToken:
if (literalNode) {
return getStringLiteralTypeForText(literalNode.text);
}
break;
}

return undefined;
}

Expand Down Expand Up @@ -7459,9 +7472,9 @@ namespace ts {
}

// In a contextually typed conditional expression, the true/false expressions are contextually typed by the same type.
function getContextualTypeForConditionalOperand(node: Expression): Type {
function getContextualTypeForConditionalOperand(node: Expression, literalNode: StringLiteral): Type {
const conditional = <ConditionalExpression>node.parent;
return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualType(conditional) : undefined;
return node === conditional.whenTrue || node === conditional.whenFalse ? getContextualTypeWorker(conditional, literalNode) : undefined;
}

function getContextualTypeForJsxExpression(expr: JsxExpression | JsxSpreadAttribute): Type {
Expand Down Expand Up @@ -7509,6 +7522,14 @@ namespace ts {
* @returns the contextual type of an expression.
*/
function getContextualType(node: Expression): Type {
return getContextualTypeWorker(node, /*literalNode*/ undefined);
}

function getLiteralContextualType(literalNode: StringLiteral) {
return getContextualTypeWorker(literalNode, literalNode);
}

function getContextualTypeWorker(node: Expression, literalNode: StringLiteral): Type {
Copy link
Contributor

Choose a reason for hiding this comment

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

I would just make a separate function that has separate rules for the contextual string literal types. Right now, it is just being packed along in the calls to getContextualTypeWorker, but whenever it's needed, it results in a completely different code path. To me that's a sign that it really has nothing to do with contextual types.

In other words, I think it's more straightforward to implement it as its own walk up the AST.

Copy link
Member Author

Choose a reason for hiding this comment

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

I was thinking about it on the bus and I agree.

if (isInsideWithStatementBody(node)) {
// We cannot answer semantic questions within a with block, do not proceed any further
return undefined;
Expand Down Expand Up @@ -7536,21 +7557,27 @@ namespace ts {
case SyntaxKind.AsExpression:
return getTypeFromTypeNode((<AssertionExpression>parent).type);
case SyntaxKind.BinaryExpression:
return getContextualTypeForBinaryOperand(node);
return getContextualTypeForBinaryOperand(node, literalNode);
case SyntaxKind.PropertyAssignment:
return getContextualTypeForObjectLiteralElement(<ObjectLiteralElement>parent);
case SyntaxKind.ArrayLiteralExpression:
return getContextualTypeForElementExpression(node);
case SyntaxKind.ConditionalExpression:
return getContextualTypeForConditionalOperand(node);
return getContextualTypeForConditionalOperand(node, literalNode);
case SyntaxKind.TemplateSpan:
Debug.assert(parent.parent.kind === SyntaxKind.TemplateExpression);
return getContextualTypeForSubstitutionExpression(<TemplateExpression>parent.parent, node);
case SyntaxKind.ParenthesizedExpression:
return getContextualType(<ParenthesizedExpression>parent);
return getContextualTypeWorker(<ParenthesizedExpression>parent, literalNode);
case SyntaxKind.JsxExpression:
case SyntaxKind.JsxSpreadAttribute:
return getContextualTypeForJsxExpression(<JsxExpression>parent);
case SyntaxKind.SwitchStatement:
case SyntaxKind.CaseClause:
if (literalNode) {
return getStringLiteralTypeForText(literalNode.text);
}
break;
}
return undefined;
}
Expand Down Expand Up @@ -9869,11 +9896,7 @@ namespace ts {
if (produceDiagnostics && targetType !== unknownType) {
const widenedType = getWidenedType(exprType);

// Permit 'number[] | "foo"' to be asserted to 'string'.
const bothAreStringLike =
someConstituentTypeHasKind(targetType, TypeFlags.StringLike) &&
someConstituentTypeHasKind(widenedType, TypeFlags.StringLike);
if (!bothAreStringLike && !(isTypeAssignableTo(targetType, widenedType))) {
if (!isTypeAssignableTo(targetType, widenedType)) {
checkTypeAssignableTo(exprType, targetType, node, Diagnostics.Neither_type_0_nor_type_1_is_assignable_to_the_other);
}
}
Expand Down Expand Up @@ -10723,10 +10746,6 @@ namespace ts {
case SyntaxKind.ExclamationEqualsToken:
case SyntaxKind.EqualsEqualsEqualsToken:
case SyntaxKind.ExclamationEqualsEqualsToken:
// Permit 'number[] | "foo"' to be asserted to 'string'.
if (someConstituentTypeHasKind(leftType, TypeFlags.StringLike) && someConstituentTypeHasKind(rightType, TypeFlags.StringLike)) {
return booleanType;
}
if (!isTypeAssignableTo(leftType, rightType) && !isTypeAssignableTo(rightType, leftType)) {
reportOperatorError();
}
Expand Down Expand Up @@ -10866,7 +10885,7 @@ namespace ts {
}

function checkStringLiteralExpression(node: StringLiteral): Type {
const contextualType = getContextualType(node);
const contextualType = getLiteralContextualType(node);
Copy link
Contributor

Choose a reason for hiding this comment

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

Does this even need to be a type? I mean, do you actually use the type for anything, or just check if it exists? I feel like a boolean is more appropriate.

Copy link
Member Author

Choose a reason for hiding this comment

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

That actually might be a better way to go about it.

if (contextualType && contextualTypeIsStringLiteralType(contextualType)) {
return getStringLiteralTypeForText(node.text);
}
Expand Down Expand Up @@ -13249,7 +13268,6 @@ namespace ts {
let hasDuplicateDefaultClause = false;

const expressionType = checkExpression(node.expression);
const expressionTypeIsStringLike = someConstituentTypeHasKind(expressionType, TypeFlags.StringLike);
forEach(node.caseBlock.clauses, clause => {
// Grammar check for duplicate default clauses, skip if we already report duplicate default clause
if (clause.kind === SyntaxKind.DefaultClause && !hasDuplicateDefaultClause) {
Expand All @@ -13271,12 +13289,7 @@ namespace ts {
// In a 'switch' statement, each 'case' expression must be of a type that is assignable to or from the type of the 'switch' expression.
const caseType = checkExpression(caseClause.expression);

const expressionTypeIsAssignableToCaseType =
// Permit 'number[] | "foo"' to be asserted to 'string'.
(expressionTypeIsStringLike && someConstituentTypeHasKind(caseType, TypeFlags.StringLike)) ||
isTypeAssignableTo(expressionType, caseType);

if (!expressionTypeIsAssignableToCaseType) {
if (!isTypeAssignableTo(expressionType, caseType)) {
// 'expressionType is not assignable to caseType', try the reversed check and report errors if it fails
checkTypeAssignableTo(caseType, expressionType, caseClause.expression, /*headMessage*/ undefined);
}
Expand Down
8 changes: 4 additions & 4 deletions tests/baselines/reference/TypeGuardWithEnumUnion.types
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ function f1(x: Color | string) {
>typeof x === "number" : boolean
>typeof x : string
>x : Color | string
>"number" : string
>"number" : "number"

var y = x;
>y : Color
Expand Down Expand Up @@ -43,7 +43,7 @@ function f2(x: Color | string | string[]) {
>typeof x === "object" : boolean
>typeof x : string
>x : Color | string | string[]
>"object" : string
>"object" : "object"

var y = x;
>y : string[]
Expand All @@ -56,7 +56,7 @@ function f2(x: Color | string | string[]) {
>typeof x === "number" : boolean
>typeof x : string
>x : Color | string | string[]
>"number" : string
>"number" : "number"

var z = x;
>z : Color
Expand All @@ -78,7 +78,7 @@ function f2(x: Color | string | string[]) {
>typeof x === "string" : boolean
>typeof x : string
>x : Color | string | string[]
>"string" : string
>"string" : "string"

var a = x;
>a : string
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/anonymousClassExpression1.types
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@ function f() {
>typeof class {} === "function" : boolean
>typeof class {} : string
>class {} : typeof (Anonymous class)
>"function" : string
>"function" : "function"
}
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ class A {
>v : string

case "test": use(this);
>"test" : string
>"test" : "test"
>use(this) : void
>use : (a: any) => void
>this : this
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ if (typeof x !== "string") {
>typeof x !== "string" : boolean
>typeof x : string
>x : string | StringTreeCollection
>"string" : string
>"string" : "string"

x[0] = "";
>x[0] = "" : string
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ typeof "123" == "string" ? exprBoolean1 : exprBoolean2;
>typeof "123" == "string" : boolean
>typeof "123" : string
>"123" : string
>"string" : string
>"string" : "string"
>exprBoolean1 : boolean
>exprBoolean2 : boolean

Expand Down Expand Up @@ -264,7 +264,7 @@ var resultIsBoolean3 = typeof "123" == "string" ? exprBoolean1 : exprBoolean2;
>typeof "123" == "string" : boolean
>typeof "123" : string
>"123" : string
>"string" : string
>"string" : "string"
>exprBoolean1 : boolean
>exprBoolean2 : boolean

Expand Down Expand Up @@ -301,7 +301,7 @@ var resultIsStringOrBoolean4 = typeof "123" === "string" ? exprString1 : exprBoo
>typeof "123" === "string" : boolean
>typeof "123" : string
>"123" : string
>"string" : string
>"string" : "string"
>exprString1 : string
>exprBoolean1 : boolean

Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ function foo(a: string): string | number {
if (a === "hello") {
>a === "hello" : boolean
>a : string
>"hello" : string
>"hello" : "hello"

return a.length;
>a.length : number
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ class Wat {
>() => test == 'abc' : () => boolean
>test == 'abc' : boolean
>test : string
>'abc' : string
>'abc' : "abc"

static whatever() {
>whatever : () => void
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/es3defaultAliasIsQuoted.types
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,5 @@ assert(Foo.CONSTANT === "Foo");
>Foo.CONSTANT : string
>Foo : typeof Foo
>CONSTANT : string
>"Foo" : string
>"Foo" : "Foo"

Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ if (typeof x !== "string") {
>typeof x !== "string" : boolean
>typeof x : string
>x : string | StringTreeArray
>"string" : string
>"string" : "string"

x.push("");
>x.push("") : number
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,5 +52,5 @@ thing.doSomething((x, y) => x.name === "bob"); // should not error
>x.name : string
>x : { name: string; id: number; }
>name : string
>"bob" : string
>"bob" : "bob"

Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ module Bugs {
>args[index] : any
>args : any[]
>index : any
>'undefined' : string
>'undefined' : "undefined"

? args[index]
>args[index] : any
Expand Down
2 changes: 1 addition & 1 deletion tests/baselines/reference/overloadReturnTypes.types
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ function attr(nameOrMap: any, value?: string): any {
>typeof nameOrMap === "object" : boolean
>typeof nameOrMap : string
>nameOrMap : any
>"object" : string
>"object" : "object"

// handle map case
return new Accessor;
Expand Down
4 changes: 2 additions & 2 deletions tests/baselines/reference/stringLiteralCheckedInIf01.types
Original file line number Diff line number Diff line change
Expand Up @@ -16,15 +16,15 @@ function f(foo: T) {
if (foo === "a") {
>foo === "a" : boolean
>foo : ("a" | "b")[] | "a" | "b"
>"a" : string
>"a" : "a"

return foo;
>foo : ("a" | "b")[] | "a" | "b"
}
else if (foo === "b") {
>foo === "b" : boolean
>foo : ("a" | "b")[] | "a" | "b"
>"b" : string
>"b" : "b"

return foo;
>foo : ("a" | "b")[] | "a" | "b"
Expand Down
4 changes: 2 additions & 2 deletions tests/baselines/reference/stringLiteralCheckedInIf02.types
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,10 @@ function isS(t: T): t is S {
>t === "a" || t === "b" : boolean
>t === "a" : boolean
>t : ("a" | "b")[] | "a" | "b"
>"a" : string
>"a" : "a"
>t === "b" : boolean
>t : ("a" | "b")[] | "a" | "b"
>"b" : string
>"b" : "b"
}

function f(foo: T) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,10 @@ switch (foo) {
>foo : ("a" | "b")[] | "a" | "b"

case "a":
>"a" : string
>"a" : "a"

case "b":
>"b" : string
>"b" : "b"

break;
default:
Expand Down
Loading