Fixed bug in the type evaluation of expressions with + or - operators and integer literal operands. These expressions should evaluate to a literal type, not an int.

This commit is contained in:
Eric Traut 2020-08-19 22:17:51 -07:00
parent b8fc77b296
commit 6944f70f9f
2 changed files with 22 additions and 0 deletions

View File

@ -6561,6 +6561,25 @@ export function createTypeEvaluator(importLookup: ImportLookup, printTypeFlags:
}
}
// Handle the special case where the unary operator is + or -, the operand
// is a literal int, and the resulting type is an int. In these cases, we'll
// want to interpret the resulting type as a literal.
if (node.operator === OperatorType.Add || node.operator === OperatorType.Subtract) {
if (
isObject(type) &&
ClassType.isBuiltIn(type.classType, 'int') &&
isObject(exprType) &&
ClassType.isBuiltIn(exprType.classType, 'int') &&
typeof exprType.classType.literalValue === 'number'
) {
const value =
node.operator === OperatorType.Add
? exprType.classType.literalValue
: -exprType.classType.literalValue;
type = ObjectType.create(ClassType.cloneWithLiteral(type.classType, value));
}
}
return { type, node };
}

View File

@ -39,3 +39,6 @@ invalidType = 3 # type: Literal[3.4]
# This should generate an error because 2
# is not a valid literal value.
mismatch = 2 # type: Literal[3, 4, '5']
a: Literal[3] = -(-(+++3))
b: Literal[-2] = +-+2