From 2c92ecb6ab28e25a8b89a541a05cd2e7ca4868db Mon Sep 17 00:00:00 2001 From: crypt0lith <118923461+crypt0lith@users.noreply.github.com> Date: Sun, 25 Oct 2026 03:13:29 -0500 Subject: [PATCH 1/5] Evaluate static conditions with the literal operand on the left Static condition evaluation recognizes sys.version_info, sys.version_info[0], sys.platform, os.name and defined constants only as the left operand of a comparison, so '(3, 14) <= sys.version_info' is analyzed as a runtime check. Swap the operands and mirror the operator when only the left operand is a literal. Fixes microsoft#11927 --- .../src/analyzer/staticExpressions.ts | 92 ++++++++++++------- .../src/tests/samples/staticExpression1.py | 25 +++++ .../src/tests/typeEvaluator8.test.ts | 4 +- 3 files changed, 87 insertions(+), 34 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/staticExpressions.ts b/packages/pyright-internal/src/analyzer/staticExpressions.ts index 7db9ce250557..73066544cb56 100644 --- a/packages/pyright-internal/src/analyzer/staticExpressions.ts +++ b/packages/pyright-internal/src/analyzer/staticExpressions.ts @@ -22,6 +22,15 @@ import { } from '../parser/parseNodes'; import { KeywordType, OperatorType } from '../parser/tokenizerTypes'; +const _mirroredComparisonOperators: Map = new Map([ + [OperatorType.GreaterThan, OperatorType.LessThan], + [OperatorType.LessThan, OperatorType.GreaterThan], + [OperatorType.GreaterThanOrEqual, OperatorType.LessThanOrEqual], + [OperatorType.LessThanOrEqual, OperatorType.GreaterThanOrEqual], + [OperatorType.Equals, OperatorType.Equals], + [OperatorType.NotEquals, OperatorType.NotEquals], +]); + // Returns undefined if the expression cannot be evaluated // statically as a bool value or true/false if it can. export function evaluateStaticBoolExpression( @@ -129,68 +138,79 @@ function _evaluateStaticBoolOrBoolLikeExpression( } } + let leftExpr = node.d.leftExpr; + let rightExpr = node.d.rightExpr; + let operator: OperatorType = node.d.operator; + + const mirroredOperator = _mirroredComparisonOperators.get(operator); if ( - _isSysVersionInfoExpression(node.d.leftExpr, sysImportAliases) && - node.d.rightExpr.nodeType === ParseNodeType.Tuple + mirroredOperator !== undefined && + _isStaticComparisonLiteral(leftExpr) && + !_isStaticComparisonLiteral(rightExpr) ) { + [leftExpr, rightExpr] = [rightExpr, leftExpr]; + operator = mirroredOperator; + } + + if (_isSysVersionInfoExpression(leftExpr, sysImportAliases) && rightExpr.nodeType === ParseNodeType.Tuple) { // Handle the special case of "sys.version_info >= (3, x)" - const comparisonVersion = _convertTupleToVersion(node.d.rightExpr); - return _evaluateVersionBinaryOperation(node.d.operator, execEnv.pythonVersion, comparisonVersion); + const comparisonVersion = _convertTupleToVersion(rightExpr); + return _evaluateVersionBinaryOperation(operator, execEnv.pythonVersion, comparisonVersion); } if ( - node.d.leftExpr.nodeType === ParseNodeType.Index && - _isSysVersionInfoExpression(node.d.leftExpr.d.leftExpr, sysImportAliases) && - node.d.leftExpr.d.items.length === 1 && - !node.d.leftExpr.d.trailingComma && - !node.d.leftExpr.d.items[0].d.name && - node.d.leftExpr.d.items[0].d.argCategory === ArgCategory.Simple && - node.d.leftExpr.d.items[0].d.valueExpr.nodeType === ParseNodeType.Number && - !node.d.leftExpr.d.items[0].d.valueExpr.d.isImaginary && - node.d.leftExpr.d.items[0].d.valueExpr.d.value === 0 && - node.d.rightExpr.nodeType === ParseNodeType.Number && - node.d.rightExpr.d.isInteger && - typeof node.d.rightExpr.d.value === 'number' + leftExpr.nodeType === ParseNodeType.Index && + _isSysVersionInfoExpression(leftExpr.d.leftExpr, sysImportAliases) && + leftExpr.d.items.length === 1 && + !leftExpr.d.trailingComma && + !leftExpr.d.items[0].d.name && + leftExpr.d.items[0].d.argCategory === ArgCategory.Simple && + leftExpr.d.items[0].d.valueExpr.nodeType === ParseNodeType.Number && + !leftExpr.d.items[0].d.valueExpr.d.isImaginary && + leftExpr.d.items[0].d.valueExpr.d.value === 0 && + rightExpr.nodeType === ParseNodeType.Number && + rightExpr.d.isInteger && + typeof rightExpr.d.value === 'number' ) { // Handle the special case of "sys.version_info[0] >= X" return _evaluateVersionBinaryOperation( - node.d.operator, + operator, PythonVersion.create(execEnv.pythonVersion.major, 0), - PythonVersion.create(node.d.rightExpr.d.value, 0) + PythonVersion.create(rightExpr.d.value, 0) ); } if ( - _isSysPlatformInfoExpression(node.d.leftExpr, sysImportAliases) && - node.d.rightExpr.nodeType === ParseNodeType.StringList + _isSysPlatformInfoExpression(leftExpr, sysImportAliases) && + rightExpr.nodeType === ParseNodeType.StringList ) { // Handle the special case of "sys.platform != 'X'" - const comparisonPlatform = node.d.rightExpr.d.strings.map((s) => s.d.value).join(''); + const comparisonPlatform = rightExpr.d.strings.map((s) => s.d.value).join(''); const expectedPlatformName = _getExpectedPlatformNameFromPlatform(execEnv); - return _evaluateStringBinaryOperation(node.d.operator, expectedPlatformName, comparisonPlatform); + return _evaluateStringBinaryOperation(operator, expectedPlatformName, comparisonPlatform); } - if (_isOsNameInfoExpression(node.d.leftExpr) && node.d.rightExpr.nodeType === ParseNodeType.StringList) { + if (_isOsNameInfoExpression(leftExpr) && rightExpr.nodeType === ParseNodeType.StringList) { // Handle the special case of "os.name == 'X'" - const comparisonOsName = node.d.rightExpr.d.strings.map((s) => s.d.value).join(''); + const comparisonOsName = rightExpr.d.strings.map((s) => s.d.value).join(''); const expectedOsName = _getExpectedOsNameFromPlatform(execEnv); if (expectedOsName !== undefined) { - return _evaluateStringBinaryOperation(node.d.operator, expectedOsName, comparisonOsName); + return _evaluateStringBinaryOperation(operator, expectedOsName, comparisonOsName); } } else { // Handle the special case of == 'X' or != 'X'. - if (node.d.rightExpr.nodeType === ParseNodeType.StringList) { + if (rightExpr.nodeType === ParseNodeType.StringList) { let constantValue: string | number | boolean | undefined; - if (node.d.leftExpr.nodeType === ParseNodeType.Name) { - constantValue = definedConstants.get(node.d.leftExpr.d.value); - } else if (node.d.leftExpr.nodeType === ParseNodeType.MemberAccess) { - constantValue = definedConstants.get(node.d.leftExpr.d.member.d.value); + if (leftExpr.nodeType === ParseNodeType.Name) { + constantValue = definedConstants.get(leftExpr.d.value); + } else if (leftExpr.nodeType === ParseNodeType.MemberAccess) { + constantValue = definedConstants.get(leftExpr.d.member.d.value); } if (constantValue !== undefined && typeof constantValue === 'string') { - const comparisonStringName = node.d.rightExpr.d.strings.map((s) => s.d.value).join(''); - return _evaluateStringBinaryOperation(node.d.operator, constantValue, comparisonStringName); + const comparisonStringName = rightExpr.d.strings.map((s) => s.d.value).join(''); + return _evaluateStringBinaryOperation(operator, constantValue, comparisonStringName); } } } @@ -425,6 +445,14 @@ function _evaluateStringBinaryOperation( return undefined; } +function _isStaticComparisonLiteral(node: ExpressionNode): boolean { + return ( + node.nodeType === ParseNodeType.Tuple || + node.nodeType === ParseNodeType.Number || + node.nodeType === ParseNodeType.StringList + ); +} + function _isSysVersionInfoExpression(node: ExpressionNode, sysImportAliases: string[] = ['sys']): boolean { if (node.nodeType === ParseNodeType.MemberAccess) { if (node.d.leftExpr.nodeType === ParseNodeType.Name && node.d.member.d.value === 'version_info') { diff --git a/packages/pyright-internal/src/tests/samples/staticExpression1.py b/packages/pyright-internal/src/tests/samples/staticExpression1.py index 400bb1546058..82a4d469aff9 100644 --- a/packages/pyright-internal/src/tests/samples/staticExpression1.py +++ b/packages/pyright-internal/src/tests/samples/staticExpression1.py @@ -11,16 +11,31 @@ else: x = "error!" +if "linux" == sys.platform: + x = 1 +else: + x = "error!" + if sys.version_info >= (3, 9): x = 1 else: x = "error!" +if (3, 9) <= sys.version_info: + x = 1 +else: + x = "error!" + if os.name == "posix": x = 1 else: x = "error!" +if "posix" == os.name: + x = 1 +else: + x = "error!" + if True: x = 1 else: @@ -51,6 +66,11 @@ else: x = "error!" +if "hi!" == DEFINED_STR: + x = 1 +else: + x = "error!" + class Dummy: DEFINED_FALSE: bool @@ -74,3 +94,8 @@ class Dummy: x = 1 else: x = "error!" + +if "hi!" == dummy.DEFINED_STR: + x = 1 +else: + x = "error!" diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index f38c313460e2..5af3b305e5c1 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -1150,13 +1150,13 @@ test('StaticExpression1', () => { configOptions.defaultPythonPlatform = 'windows'; const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults1, 9); + TestUtils.validateResults(analysisResults1, 14); configOptions.defaultPythonVersion = pythonVersion3_11; configOptions.defaultPythonPlatform = 'Linux'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults2, 6); + TestUtils.validateResults(analysisResults2, 8); configOptions.defineConstant.set('DEFINED_TRUE', true); configOptions.defineConstant.set('DEFINED_FALSE', false); From a5f89873634034c5ab4ef05c98cc0d95add12b29 Mon Sep 17 00:00:00 2001 From: crypt0lith <118923461+crypt0lith@users.noreply.github.com> Date: Fri, 30 Oct 2026 13:00:57 -0500 Subject: [PATCH 2/5] Fix bytes and f-strings compared as str with sys.platform and os.name --- .../src/analyzer/staticExpressions.ts | 36 ++++++++++++++----- .../src/tests/samples/staticExpression1.py | 18 ++++++++++ .../src/tests/typeEvaluator8.test.ts | 6 ++-- 3 files changed, 48 insertions(+), 12 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/staticExpressions.ts b/packages/pyright-internal/src/analyzer/staticExpressions.ts index 73066544cb56..5e515e1c47fe 100644 --- a/packages/pyright-internal/src/analyzer/staticExpressions.ts +++ b/packages/pyright-internal/src/analyzer/staticExpressions.ts @@ -20,7 +20,7 @@ import { StringListNode, TupleNode, } from '../parser/parseNodes'; -import { KeywordType, OperatorType } from '../parser/tokenizerTypes'; +import { KeywordType, OperatorType, StringTokenFlags } from '../parser/tokenizerTypes'; const _mirroredComparisonOperators: Map = new Map([ [OperatorType.GreaterThan, OperatorType.LessThan], @@ -185,18 +185,16 @@ function _evaluateStaticBoolOrBoolLikeExpression( rightExpr.nodeType === ParseNodeType.StringList ) { // Handle the special case of "sys.platform != 'X'" - const comparisonPlatform = rightExpr.d.strings.map((s) => s.d.value).join(''); - const expectedPlatformName = _getExpectedPlatformNameFromPlatform(execEnv); - return _evaluateStringBinaryOperation(operator, expectedPlatformName, comparisonPlatform); + return _evaluateStrComparisonToStringList( + operator, + rightExpr, + _getExpectedPlatformNameFromPlatform(execEnv) + ); } if (_isOsNameInfoExpression(leftExpr) && rightExpr.nodeType === ParseNodeType.StringList) { // Handle the special case of "os.name == 'X'" - const comparisonOsName = rightExpr.d.strings.map((s) => s.d.value).join(''); - const expectedOsName = _getExpectedOsNameFromPlatform(execEnv); - if (expectedOsName !== undefined) { - return _evaluateStringBinaryOperation(operator, expectedOsName, comparisonOsName); - } + return _evaluateStrComparisonToStringList(operator, rightExpr, _getExpectedOsNameFromPlatform(execEnv)); } else { // Handle the special case of == 'X' or != 'X'. if (rightExpr.nodeType === ParseNodeType.StringList) { @@ -445,6 +443,26 @@ function _evaluateStringBinaryOperation( return undefined; } +function _evaluateStrComparisonToStringList( + operator: OperatorType, + node: StringListNode, + expectedValue: string | undefined +): boolean | undefined { + if (node.d.strings.some((s) => s.nodeType === ParseNodeType.FormatString)) { + return undefined; + } + if (node.d.strings.some((s) => s.d.token.flags & StringTokenFlags.Bytes)) { + if (operator === OperatorType.Equals) { + return false; + } else if (operator === OperatorType.NotEquals) { + return true; + } else { + return undefined; + } + } + return _evaluateStringBinaryOperation(operator, expectedValue, node.d.strings.map((s) => s.d.value).join('')); +} + function _isStaticComparisonLiteral(node: ExpressionNode): boolean { return ( node.nodeType === ParseNodeType.Tuple || diff --git a/packages/pyright-internal/src/tests/samples/staticExpression1.py b/packages/pyright-internal/src/tests/samples/staticExpression1.py index 82a4d469aff9..e3da6fc47e6a 100644 --- a/packages/pyright-internal/src/tests/samples/staticExpression1.py +++ b/packages/pyright-internal/src/tests/samples/staticExpression1.py @@ -36,6 +36,24 @@ else: x = "error!" +if sys.platform != b"linux": + x = 1 +else: + x = "error!" + +if os.name != b"posix": + x = 1 +else: + x = "error!" + +if sys.platform == f"linux": + # This should generate an error. + x = "error!" + +if os.name == f"posix": + # This should generate an error. + x = "error!" + if True: x = 1 else: diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index 5af3b305e5c1..b8d43fca1355 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -1150,19 +1150,19 @@ test('StaticExpression1', () => { configOptions.defaultPythonPlatform = 'windows'; const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults1, 14); + TestUtils.validateResults(analysisResults1, 16); configOptions.defaultPythonVersion = pythonVersion3_11; configOptions.defaultPythonPlatform = 'Linux'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults2, 8); + TestUtils.validateResults(analysisResults2, 10); configOptions.defineConstant.set('DEFINED_TRUE', true); configOptions.defineConstant.set('DEFINED_FALSE', false); configOptions.defineConstant.set('DEFINED_STR', 'hi!'); const analysisResults3 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults3, 0); + TestUtils.validateResults(analysisResults3, 2); }); test('StaticExpression2', () => { From d200ac9a0aca43260dbc9cfa86e139e2b3900cab Mon Sep 17 00:00:00 2001 From: crypt0lith <118923461+crypt0lith@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:30:21 -0600 Subject: [PATCH 3/5] Require imported module for sys, os and typing static conditions Static condition evaluation recognizes sys.version_info, sys.platform, os.name and typing.TYPE_CHECKING from the spelling of the name before the dot, so a parameter that shadows the module is evaluated as the module, and os.name is evaluated without an import of os. Evaluate them only when every declaration of that name in scope is an import of the module. Fixes microsoft#12033 --- .../pyright-internal/src/analyzer/binder.ts | 14 +-- .../pyright-internal/src/analyzer/checker.ts | 3 +- .../src/analyzer/dataClasses.ts | 26 ++++-- .../src/analyzer/namedTuples.ts | 4 +- .../src/analyzer/operations.ts | 3 +- .../src/analyzer/staticExpressions.ts | 89 ++++++++----------- .../src/analyzer/typeEvaluator.ts | 6 +- .../src/tests/samples/staticExpression1.py | 49 ++++++++++ .../src/tests/typeEvaluator8.test.ts | 6 +- 9 files changed, 120 insertions(+), 80 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/binder.ts b/packages/pyright-internal/src/analyzer/binder.ts index 0e16dbd3d6b4..dc193ef2fa79 100644 --- a/packages/pyright-internal/src/analyzer/binder.ts +++ b/packages/pyright-internal/src/analyzer/binder.ts @@ -299,9 +299,6 @@ export class Binder extends ParseTreeWalker { // Aliases of "typing" and "typing_extensions". private _typingImportAliases: string[] = []; - // Aliases of "sys". - private _sysImportAliases: string[] = []; - // Aliases of "dataclasses". private _dataclassesImportAliases: string[] = []; @@ -1583,8 +1580,7 @@ export class Binder extends ParseTreeWalker { node.d.testExpr, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, - this._typingImportAliases, - this._sysImportAliases + this._currentScope ); this._nodeInfo.setStaticConditionValue(node, constExprValue); @@ -1626,8 +1622,7 @@ export class Binder extends ParseTreeWalker { node.d.testExpr, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, - this._typingImportAliases, - this._sysImportAliases + this._currentScope ); const preLoopLabel = this._createLoopLabel(); @@ -2003,8 +1998,6 @@ export class Binder extends ParseTreeWalker { if (node.d.module.d.nameParts.length === 1) { if (firstNamePartValue === 'typing' || firstNamePartValue === 'typing_extensions') { this._typingImportAliases.push(node.d.alias?.d.value ?? firstNamePartValue); - } else if (firstNamePartValue === 'sys') { - this._sysImportAliases.push(node.d.alias?.d.value ?? firstNamePartValue); } else if (firstNamePartValue === 'dataclasses') { this._dataclassesImportAliases.push(node.d.alias?.d.value ?? firstNamePartValue); } @@ -3301,8 +3294,7 @@ export class Binder extends ParseTreeWalker { expression, this._fileInfo.executionEnvironment, this._fileInfo.definedConstants, - this._typingImportAliases, - this._sysImportAliases + this._currentScope ); if ( (staticValue === true && flags & FlowFlags.FalseCondition) || diff --git a/packages/pyright-internal/src/analyzer/checker.ts b/packages/pyright-internal/src/analyzer/checker.ts index 67e61b6ab949..ee4c26cd0fd3 100644 --- a/packages/pyright-internal/src/analyzer/checker.ts +++ b/packages/pyright-internal/src/analyzer/checker.ts @@ -2250,7 +2250,8 @@ export class Checker extends ParseTreeWalker { evaluateStaticBoolExpression( node, this._fileInfo.executionEnvironment, - this._fileInfo.definedConstants + this._fileInfo.definedConstants, + getScopeForNode(node, this._nodeInfo) ) === undefined ) { let isPossiblyTrue = false; diff --git a/packages/pyright-internal/src/analyzer/dataClasses.ts b/packages/pyright-internal/src/analyzer/dataClasses.ts index a361d53669d7..465454e8e09f 100644 --- a/packages/pyright-internal/src/analyzer/dataClasses.ts +++ b/packages/pyright-internal/src/analyzer/dataClasses.ts @@ -38,6 +38,7 @@ import { getTypeSourceId, getTypeVarScopesForNode, } from './parseTreeUtils'; +import { getScopeForNode } from './scopeUtils'; import { evaluateStaticBoolExpression } from './staticExpressions'; import { Symbol, SymbolFlags } from './symbol'; import { isPrivateName } from './symbolNameUtils'; @@ -388,7 +389,8 @@ export function synthesizeDataClassMethods( evaluateStaticBoolExpression( initArg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(initArg.d.valueExpr, nodeInfo) ) ?? includeInInit; } else { includeInInit = @@ -407,7 +409,8 @@ export function synthesizeDataClassMethods( evaluateStaticBoolExpression( kwOnlyArg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(kwOnlyArg.d.valueExpr, nodeInfo) ) ?? isKeywordOnly; } else { isKeywordOnly = @@ -1391,7 +1394,8 @@ export function validateDataClassTransformDecorator( const value = evaluateStaticBoolExpression( arg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(arg.d.valueExpr, nodeInfo) ); if (value === undefined) { evaluator.addDiagnostic( @@ -1410,7 +1414,8 @@ export function validateDataClassTransformDecorator( const value = evaluateStaticBoolExpression( arg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(arg.d.valueExpr, nodeInfo) ); if (value === undefined) { evaluator.addDiagnostic( @@ -1429,7 +1434,8 @@ export function validateDataClassTransformDecorator( const value = evaluateStaticBoolExpression( arg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(arg.d.valueExpr, nodeInfo) ); if (value === undefined) { evaluator.addDiagnostic( @@ -1448,7 +1454,8 @@ export function validateDataClassTransformDecorator( const value = evaluateStaticBoolExpression( arg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(arg.d.valueExpr, nodeInfo) ); if (value === undefined) { evaluator.addDiagnostic( @@ -1569,7 +1576,12 @@ function applyDataClassBehaviorOverride( nodeInfo: AnalyzerNodeInfoAccessor ) { const fileInfo = nodeInfo.getFileInfo(errorNode); - const value = evaluateStaticBoolExpression(argValueExpr, fileInfo.executionEnvironment, fileInfo.definedConstants); + const value = evaluateStaticBoolExpression( + argValueExpr, + fileInfo.executionEnvironment, + fileInfo.definedConstants, + getScopeForNode(argValueExpr, nodeInfo) + ); applyDataClassBehaviorOverrideValue(evaluator, errorNode, classType, argName, value, behaviors); } diff --git a/packages/pyright-internal/src/analyzer/namedTuples.ts b/packages/pyright-internal/src/analyzer/namedTuples.ts index ecc6caf953a2..c96e3de0b911 100644 --- a/packages/pyright-internal/src/analyzer/namedTuples.ts +++ b/packages/pyright-internal/src/analyzer/namedTuples.ts @@ -18,6 +18,7 @@ import { Tokenizer } from '../parser/tokenizer'; import { AnalyzerNodeInfoAccessor } from './analyzerNodeInfo'; import { DeclarationType, VariableDeclaration } from './declaration'; import * as ParseTreeUtils from './parseTreeUtils'; +import { getScopeForNode } from './scopeUtils'; import { evaluateStaticBoolExpression } from './staticExpressions'; import { Symbol, SymbolFlags } from './symbol'; import { Arg, TypeEvaluator } from './typeEvaluatorTypes'; @@ -74,7 +75,8 @@ export function createNamedTupleType( const renameValue = evaluateStaticBoolExpression( renameArg.valueExpression, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(renameArg.valueExpression, nodeInfo) ); if (renameValue === true) { allowRename = true; diff --git a/packages/pyright-internal/src/analyzer/operations.ts b/packages/pyright-internal/src/analyzer/operations.ts index 1e07860faabb..d3d0b2b72d37 100644 --- a/packages/pyright-internal/src/analyzer/operations.ts +++ b/packages/pyright-internal/src/analyzer/operations.ts @@ -851,7 +851,8 @@ export function getTypeOfTernaryOperation( const constExprValue = evaluateStaticBoolExpression( node.d.testExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(node.d.testExpr, getInfoReader(evaluator)) ); if (constExprValue !== false && evaluator.isNodeReachable(node.d.ifExpr)) { diff --git a/packages/pyright-internal/src/analyzer/staticExpressions.ts b/packages/pyright-internal/src/analyzer/staticExpressions.ts index 5e515e1c47fe..12f5bcde7ecf 100644 --- a/packages/pyright-internal/src/analyzer/staticExpressions.ts +++ b/packages/pyright-internal/src/analyzer/staticExpressions.ts @@ -21,6 +21,8 @@ import { TupleNode, } from '../parser/parseNodes'; import { KeywordType, OperatorType, StringTokenFlags } from '../parser/tokenizerTypes'; +import { DeclarationType } from './declaration'; +import { Scope } from './scope'; const _mirroredComparisonOperators: Map = new Map([ [OperatorType.GreaterThan, OperatorType.LessThan], @@ -37,17 +39,9 @@ export function evaluateStaticBoolExpression( node: ExpressionNode, execEnv: ExecutionEnvironment, definedConstants: Map, - typingImportAliases?: string[], - sysImportAliases?: string[] + scope: Scope | undefined ): boolean | undefined { - return _evaluateStaticBoolOrBoolLikeExpression( - node, - execEnv, - definedConstants, - typingImportAliases, - sysImportAliases, - _evaluateBoolConstant - ); + return _evaluateStaticBoolOrBoolLikeExpression(node, execEnv, definedConstants, scope, _evaluateBoolConstant); } // Similar to evaluateStaticBoolExpression except that it handles other non-bool @@ -57,17 +51,9 @@ export function evaluateStaticBoolLikeExpression( node: ExpressionNode, execEnv: ExecutionEnvironment, definedConstants: Map, - typingImportAliases?: string[], - sysImportAliases?: string[] + scope: Scope | undefined ): boolean | undefined { - return _evaluateStaticBoolOrBoolLikeExpression( - node, - execEnv, - definedConstants, - typingImportAliases, - sysImportAliases, - _evaluateBoolLikeLiteral - ); + return _evaluateStaticBoolOrBoolLikeExpression(node, execEnv, definedConstants, scope, _evaluateBoolLikeLiteral); } // Shared implementation of the two functions above. @@ -76,8 +62,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( node: ExpressionNode, execEnv: ExecutionEnvironment, definedConstants: Map, - typingImportAliases: string[] | undefined, - sysImportAliases: string[] | undefined, + scope: Scope | undefined, evaluateLeafAsBool: (node: ExpressionNode) => boolean | undefined ): boolean | undefined { if (node.nodeType === ParseNodeType.AssignmentExpression) { @@ -85,8 +70,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( node.d.rightExpr, execEnv, definedConstants, - typingImportAliases, - sysImportAliases, + scope, evaluateLeafAsBool ); } @@ -97,8 +81,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( node.d.expr, execEnv, definedConstants, - typingImportAliases, - sysImportAliases, + scope, // `not x` always forces a truthiness context on its operand and yields real `bool`. // So the operand is folded with the bool-like leaf even for strict callers. _evaluateBoolLikeLiteral @@ -114,16 +97,14 @@ function _evaluateStaticBoolOrBoolLikeExpression( node.d.leftExpr, execEnv, definedConstants, - typingImportAliases, - sysImportAliases, + scope, evaluateLeafAsBool ); const rightValue = _evaluateStaticBoolOrBoolLikeExpression( node.d.rightExpr, execEnv, definedConstants, - typingImportAliases, - sysImportAliases, + scope, evaluateLeafAsBool ); @@ -152,7 +133,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( operator = mirroredOperator; } - if (_isSysVersionInfoExpression(leftExpr, sysImportAliases) && rightExpr.nodeType === ParseNodeType.Tuple) { + if (_isSysVersionInfoExpression(leftExpr, scope) && rightExpr.nodeType === ParseNodeType.Tuple) { // Handle the special case of "sys.version_info >= (3, x)" const comparisonVersion = _convertTupleToVersion(rightExpr); return _evaluateVersionBinaryOperation(operator, execEnv.pythonVersion, comparisonVersion); @@ -160,7 +141,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( if ( leftExpr.nodeType === ParseNodeType.Index && - _isSysVersionInfoExpression(leftExpr.d.leftExpr, sysImportAliases) && + _isSysVersionInfoExpression(leftExpr.d.leftExpr, scope) && leftExpr.d.items.length === 1 && !leftExpr.d.trailingComma && !leftExpr.d.items[0].d.name && @@ -180,10 +161,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( ); } - if ( - _isSysPlatformInfoExpression(leftExpr, sysImportAliases) && - rightExpr.nodeType === ParseNodeType.StringList - ) { + if (_isSysPlatformInfoExpression(leftExpr, scope) && rightExpr.nodeType === ParseNodeType.StringList) { // Handle the special case of "sys.platform != 'X'" return _evaluateStrComparisonToStringList( operator, @@ -192,7 +170,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( ); } - if (_isOsNameInfoExpression(leftExpr) && rightExpr.nodeType === ParseNodeType.StringList) { + if (_isOsNameInfoExpression(leftExpr, scope) && rightExpr.nodeType === ParseNodeType.StringList) { // Handle the special case of "os.name == 'X'" return _evaluateStrComparisonToStringList(operator, rightExpr, _getExpectedOsNameFromPlatform(execEnv)); } else { @@ -223,10 +201,10 @@ function _evaluateStaticBoolOrBoolLikeExpression( } } else if (node.nodeType === ParseNodeType.MemberAccess) { if ( - typingImportAliases && node.d.member.d.value === 'TYPE_CHECKING' && node.d.leftExpr.nodeType === ParseNodeType.Name && - typingImportAliases.some((alias) => alias === (node.d.leftExpr as NameNode).d.value) + (_isImportedModuleName(node.d.leftExpr, 'typing', scope) || + _isImportedModuleName(node.d.leftExpr, 'typing_extensions', scope)) ) { return true; } @@ -471,44 +449,47 @@ function _isStaticComparisonLiteral(node: ExpressionNode): boolean { ); } -function _isSysVersionInfoExpression(node: ExpressionNode, sysImportAliases: string[] = ['sys']): boolean { +function _isSysVersionInfoExpression(node: ExpressionNode, scope: Scope | undefined): boolean { if (node.nodeType === ParseNodeType.MemberAccess) { if (node.d.leftExpr.nodeType === ParseNodeType.Name && node.d.member.d.value === 'version_info') { - if (sysImportAliases.some((alias) => alias === (node.d.leftExpr as NameNode).d.value)) { - return true; - } + return _isImportedModuleName(node.d.leftExpr, 'sys', scope); } } return false; } -function _isSysPlatformInfoExpression(node: ExpressionNode, sysImportAliases: string[] = ['sys']): boolean { +function _isSysPlatformInfoExpression(node: ExpressionNode, scope: Scope | undefined): boolean { if (node.nodeType === ParseNodeType.MemberAccess) { if (node.d.leftExpr.nodeType === ParseNodeType.Name && node.d.member.d.value === 'platform') { - if (sysImportAliases.some((alias) => alias === (node.d.leftExpr as NameNode).d.value)) { - return true; - } + return _isImportedModuleName(node.d.leftExpr, 'sys', scope); } } return false; } -function _isOsNameInfoExpression(node: ExpressionNode): boolean { +function _isOsNameInfoExpression(node: ExpressionNode, scope: Scope | undefined): boolean { if (node.nodeType === ParseNodeType.MemberAccess) { - if ( - node.d.leftExpr.nodeType === ParseNodeType.Name && - node.d.leftExpr.d.value === 'os' && - node.d.member.d.value === 'name' - ) { - return true; + if (node.d.leftExpr.nodeType === ParseNodeType.Name && node.d.member.d.value === 'name') { + return _isImportedModuleName(node.d.leftExpr, 'os', scope); } } return false; } +function _isImportedModuleName(node: NameNode, moduleName: string, scope: Scope | undefined): boolean { + const declarations = scope?.lookUpSymbolRecursive(node.d.value)?.symbol.getDeclarations() ?? []; + + return ( + declarations.length > 0 && + declarations.every( + (decl) => decl.type === DeclarationType.Alias && decl.moduleName === moduleName && !decl.symbolName + ) + ); +} + function _getExpectedPlatformNameFromPlatform(execEnv: ExecutionEnvironment): string | undefined { if (execEnv.pythonPlatform === PythonPlatform.Darwin) { return 'darwin'; diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 0b56dfe057aa..26d061bb1da9 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -12003,7 +12003,8 @@ export function createTypeEvaluator( const constExprValue = evaluateStaticBoolExpression( node.d.rightExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(node.d.rightExpr) ); if (constExprValue !== undefined) { @@ -12527,7 +12528,8 @@ export function createTypeEvaluator( const constArgValue = evaluateStaticBoolExpression( arg.d.valueExpr, fileInfo.executionEnvironment, - fileInfo.definedConstants + fileInfo.definedConstants, + getScopeForNode(arg.d.valueExpr) ); if (constArgValue === undefined) { diff --git a/packages/pyright-internal/src/tests/samples/staticExpression1.py b/packages/pyright-internal/src/tests/samples/staticExpression1.py index e3da6fc47e6a..9fe0e83cb46c 100644 --- a/packages/pyright-internal/src/tests/samples/staticExpression1.py +++ b/packages/pyright-internal/src/tests/samples/staticExpression1.py @@ -3,6 +3,7 @@ import sys import os +import typing x: int @@ -117,3 +118,51 @@ class Dummy: x = 1 else: x = "error!" + + +class FakeSys: + version_info = (2, 7) + platform = "darwin" + + +class FakeOs: + name = "java" + + +class FakeTyping: + TYPE_CHECKING = False + + +def func1(sys: FakeSys) -> None: + if sys.version_info < (3, 0): + # This should generate an error. + y: int = "error!" + + +def func2(sys: FakeSys) -> None: + if sys.version_info[0] < 3: + # This should generate an error. + y: int = "error!" + + +def func3(sys: FakeSys) -> None: + if sys.platform == "darwin": + # This should generate an error. + y: int = "error!" + + +def func4(os: FakeOs) -> None: + if os.name == "java": + # This should generate an error. + y: int = "error!" + + +def func5(sys: FakeSys) -> None: + y = sys.platform == "darwin" + reveal_type(y, expected_text="bool") + + +def func6(typing: FakeTyping) -> None: + if not typing.TYPE_CHECKING: + # This should generate an error. + y: int = "error!" diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index f76a1ee51775..a8c87185eeda 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -1347,19 +1347,19 @@ test('StaticExpression1', () => { configOptions.defaultPythonPlatform = 'windows'; const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults1, 16); + TestUtils.validateResults(analysisResults1, 21); configOptions.defaultPythonVersion = pythonVersion3_11; configOptions.defaultPythonPlatform = 'Linux'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults2, 10); + TestUtils.validateResults(analysisResults2, 15); configOptions.defineConstant.set('DEFINED_TRUE', true); configOptions.defineConstant.set('DEFINED_FALSE', false); configOptions.defineConstant.set('DEFINED_STR', 'hi!'); const analysisResults3 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults3, 2); + TestUtils.validateResults(analysisResults3, 7); }); test('StaticExpression2', () => { From 520aad6cffe935619744b1ded5ea2d5bc6024d38 Mon Sep 17 00:00:00 2001 From: crypt0lith <118923461+crypt0lith@users.noreply.github.com> Date: Tue, 17 Nov 2026 19:45:42 -0600 Subject: [PATCH 4/5] Compare sys.version_info with tuples elementwise Static condition evaluation compares sys.version_info with a tuple through PythonVersion, which treats the two as equal when either lacks a micro version, so sys.version_info compares equal to a tuple of the configured major and minor version. Compare them elementwise as tuples, and don't evaluate a comparison that depends on a part of the version that isn't configured. Fixes microsoft#12034 --- .../src/analyzer/staticExpressions.ts | 99 ++++++++++--------- .../src/tests/samples/staticExpression1.py | 24 +++++ .../src/tests/typeEvaluator8.test.ts | 6 +- 3 files changed, 80 insertions(+), 49 deletions(-) diff --git a/packages/pyright-internal/src/analyzer/staticExpressions.ts b/packages/pyright-internal/src/analyzer/staticExpressions.ts index 12f5bcde7ecf..7465d62edf61 100644 --- a/packages/pyright-internal/src/analyzer/staticExpressions.ts +++ b/packages/pyright-internal/src/analyzer/staticExpressions.ts @@ -9,7 +9,7 @@ */ import { ExecutionEnvironment, PythonPlatform } from '../common/configOptions'; -import { PythonReleaseLevel, PythonVersion } from '../common/pythonVersion'; +import { PythonVersion } from '../common/pythonVersion'; import { ArgCategory, DictionaryEntryNode, @@ -135,8 +135,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( if (_isSysVersionInfoExpression(leftExpr, scope) && rightExpr.nodeType === ParseNodeType.Tuple) { // Handle the special case of "sys.version_info >= (3, x)" - const comparisonVersion = _convertTupleToVersion(rightExpr); - return _evaluateVersionBinaryOperation(operator, execEnv.pythonVersion, comparisonVersion); + return _evaluateComparisonResult(operator, _compareVersionInfoToTuple(execEnv.pythonVersion, rightExpr)); } if ( @@ -313,61 +312,69 @@ function _evaluateDictTruthiness(items: DictionaryEntryNode[]): boolean | undefi return undefined; } -function _convertTupleToVersion(node: TupleNode): PythonVersion | undefined { - if (node.d.items.length >= 2) { - if ( - node.d.items[0].nodeType === ParseNodeType.Number && - !node.d.items[0].d.isImaginary && - node.d.items[1].nodeType === ParseNodeType.Number && - !node.d.items[1].d.isImaginary - ) { - const majorNode = node.d.items[0]; - const minorNode = node.d.items[1]; - if (typeof majorNode.d.value !== 'number' || typeof minorNode.d.value !== 'number') { +// Compares sys.version_info with the tuple as Python compares tuples. Returns undefined +// if the result depends on a part of the version that isn't configured. +function _compareVersionInfoToTuple(version: PythonVersion, node: TupleNode): number | undefined { + const versionInfo = [version.major, version.minor, version.micro, version.releaseLevel, version.serial]; + + for (let i = 0; i < node.d.items.length; i++) { + if (i >= versionInfo.length) { + return -1; + } + + const value = versionInfo[i]; + const item = node.d.items[i]; + + if (typeof value === 'number') { + if (item.nodeType !== ParseNodeType.Number || item.d.isImaginary || typeof item.d.value !== 'number') { return undefined; } - const major = majorNode.d.value; - const minor = minorNode.d.value; - let micro: number | undefined; - if ( - node.d.items.length >= 3 && - node.d.items[2].nodeType === ParseNodeType.Number && - !node.d.items[2].d.isImaginary && - typeof node.d.items[2].d.value === 'number' - ) { - micro = node.d.items[2].d.value; + if (value !== item.d.value) { + return value < item.d.value ? -1 : 1; } - - let releaseLevel: PythonReleaseLevel | undefined; + } else if (typeof value === 'string') { if ( - node.d.items.length >= 4 && - node.d.items[3].nodeType === ParseNodeType.StringList && - node.d.items[3].d.strings.length === 1 && - node.d.items[3].d.strings[0].nodeType === ParseNodeType.String + item.nodeType !== ParseNodeType.StringList || + item.d.strings.length !== 1 || + item.d.strings[0].nodeType !== ParseNodeType.String || + item.d.strings[0].d.token.flags & StringTokenFlags.Bytes ) { - releaseLevel = node.d.items[3].d.strings[0].d.value as PythonReleaseLevel; + return undefined; } - let serial: number | undefined; - if ( - node.d.items.length >= 5 && - node.d.items[4].nodeType === ParseNodeType.Number && - !node.d.items[4].d.isImaginary && - typeof node.d.items[4].d.value === 'number' - ) { - serial = node.d.items[4].d.value; + const itemValue = item.d.strings[0].d.value; + if (value !== itemValue) { + return value < itemValue ? -1 : 1; } - - return PythonVersion.create(major, minor, micro, releaseLevel, serial); - } - } else if (node.d.items.length === 1) { - const major = node.d.items[0] as NumberNode; - if (typeof major.d.value === 'number') { - return PythonVersion.create(major.d.value, 0); + } else { + return undefined; } } + return node.d.items.length < versionInfo.length ? 1 : 0; +} + +function _evaluateComparisonResult(operatorType: OperatorType, comparison: number | undefined): boolean | undefined { + if (comparison === undefined) { + return undefined; + } + + switch (operatorType) { + case OperatorType.LessThan: + return comparison < 0; + case OperatorType.LessThanOrEqual: + return comparison <= 0; + case OperatorType.GreaterThan: + return comparison > 0; + case OperatorType.GreaterThanOrEqual: + return comparison >= 0; + case OperatorType.Equals: + return comparison === 0; + case OperatorType.NotEquals: + return comparison !== 0; + } + return undefined; } diff --git a/packages/pyright-internal/src/tests/samples/staticExpression1.py b/packages/pyright-internal/src/tests/samples/staticExpression1.py index 9fe0e83cb46c..82417e87b221 100644 --- a/packages/pyright-internal/src/tests/samples/staticExpression1.py +++ b/packages/pyright-internal/src/tests/samples/staticExpression1.py @@ -27,6 +27,30 @@ else: x = "error!" +if sys.version_info > (3, 8): + x = 1 +else: + x = "error!" + +if sys.version_info <= (3, 8): + x = "error!" +else: + x = 1 + +if sys.version_info != (3, 8): + x = 1 +else: + x = "error!" + +if sys.version_info == (3, 8): + x = "error!" +else: + x = 1 + +if sys.version_info > (3, 8, 1): + # This should generate an error. + x = "error!" + if os.name == "posix": x = 1 else: diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index a8c87185eeda..b1bceafe16d4 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -1347,19 +1347,19 @@ test('StaticExpression1', () => { configOptions.defaultPythonPlatform = 'windows'; const analysisResults1 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults1, 21); + TestUtils.validateResults(analysisResults1, 22); configOptions.defaultPythonVersion = pythonVersion3_11; configOptions.defaultPythonPlatform = 'Linux'; const analysisResults2 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults2, 15); + TestUtils.validateResults(analysisResults2, 16); configOptions.defineConstant.set('DEFINED_TRUE', true); configOptions.defineConstant.set('DEFINED_FALSE', false); configOptions.defineConstant.set('DEFINED_STR', 'hi!'); const analysisResults3 = TestUtils.typeAnalyzeSampleFiles(['staticExpression1.py'], configOptions); - TestUtils.validateResults(analysisResults3, 7); + TestUtils.validateResults(analysisResults3, 8); }); test('StaticExpression2', () => { From a2ea6f94494d8b839856870d919d2067b56e541c Mon Sep 17 00:00:00 2001 From: Bill Schnurr Date: Fri, 20 Nov 2026 14:47:17 -0700 Subject: [PATCH 5/5] Fix configured constant string comparisons Handle byte literals and formatted strings consistently when evaluating reachability, preserving reachable diagnostics and inferred alternatives. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- .../src/analyzer/staticExpressions.ts | 3 +- .../staticExpressionDefinedConstants1.py | 114 ++++++++++++++++++ .../src/tests/typeEvaluator8.test.ts | 19 +++ 3 files changed, 134 insertions(+), 2 deletions(-) create mode 100644 packages/pyright-internal/src/tests/samples/staticExpressionDefinedConstants1.py diff --git a/packages/pyright-internal/src/analyzer/staticExpressions.ts b/packages/pyright-internal/src/analyzer/staticExpressions.ts index 7465d62edf61..1b69e93920db 100644 --- a/packages/pyright-internal/src/analyzer/staticExpressions.ts +++ b/packages/pyright-internal/src/analyzer/staticExpressions.ts @@ -184,8 +184,7 @@ function _evaluateStaticBoolOrBoolLikeExpression( } if (constantValue !== undefined && typeof constantValue === 'string') { - const comparisonStringName = rightExpr.d.strings.map((s) => s.d.value).join(''); - return _evaluateStringBinaryOperation(operator, constantValue, comparisonStringName); + return _evaluateStrComparisonToStringList(operator, rightExpr, constantValue); } } } diff --git a/packages/pyright-internal/src/tests/samples/staticExpressionDefinedConstants1.py b/packages/pyright-internal/src/tests/samples/staticExpressionDefinedConstants1.py new file mode 100644 index 000000000000..eec753e40aa8 --- /dev/null +++ b/packages/pyright-internal/src/tests/samples/staticExpressionDefinedConstants1.py @@ -0,0 +1,114 @@ +MODE: str = "hi!" + + +class Config: + MODE: str = "hi!" + + +config = Config() + + +def bytes_equal_left() -> int: + if b"hi!" == MODE: + return "unreachable" + return "reachable" + + +def bytes_equal_right() -> int: + if MODE == b"hi!": + return "unreachable" + return "reachable" + + +def bytes_not_equal_left() -> int: + if b"hi!" != MODE: + return "reachable" + return "unreachable" + + +def bytes_not_equal_right() -> int: + if MODE != b"hi!": + return "reachable" + return "unreachable" + + +def bytes_member() -> int: + if b"hi!" != config.MODE: + return "reachable" + return "unreachable" + + +def formatted_equal_left(value: str) -> int: + if f"{value}" == MODE: + return "reachable" + return "also reachable" + + +def formatted_equal_right(value: str) -> int: + if MODE == f"{value}": + return "reachable" + return "also reachable" + + +def formatted_not_equal_left(value: str) -> int: + if f"{value}" != MODE: + return "reachable" + return "also reachable" + + +def formatted_not_equal_right(value: str) -> int: + if MODE != f"{value}": + return "reachable" + return "also reachable" + + +def formatted_constant() -> int: + if f"{'hi!'}" == MODE: + return "reachable" + return 0 + + +def formatted_concatenated(value: str) -> int: + if "hi" f"{value}" == MODE: + return "reachable" + return "also reachable" + + +def formatted_member(value: str) -> int: + if config.MODE == f"{value}": + return "reachable" + return "also reachable" + + +def ordinary_equal() -> int: + if MODE == "hi!": + return 0 + return "unreachable" + + +def ordinary_concatenated() -> int: + if "hi" "!" == MODE: + return 0 + return "unreachable" + + +def ordinary_unequal() -> int: + if "other" == config.MODE: + return "unreachable" + return 0 + + +def takes_int(value: int) -> None: + pass + + +def expression_types(value: str) -> None: + formatted_eq = 1 if f"{value}" == MODE else "fallback" + reveal_type(formatted_eq, expected_text="Literal[1, 'fallback']") + formatted_ne = 1 if MODE != f"{value}" else "fallback" + reveal_type(formatted_ne, expected_text="Literal[1, 'fallback']") + takes_int(formatted_ne) + bytes_ne = 1 if b"hi!" != MODE else "fallback" + reveal_type(bytes_ne, expected_text="Literal[1]") + ordinary = 1 if "hi" "!" == MODE else "fallback" + reveal_type(ordinary, expected_text="Literal[1]") diff --git a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts index b1bceafe16d4..da8bdb23ff00 100644 --- a/packages/pyright-internal/src/tests/typeEvaluator8.test.ts +++ b/packages/pyright-internal/src/tests/typeEvaluator8.test.ts @@ -1362,6 +1362,25 @@ test('StaticExpression1', () => { TestUtils.validateResults(analysisResults3, 8); }); +test('StaticExpressionDefinedConstants1', () => { + const configOptions = new ConfigOptions(Uri.empty()); + configOptions.defaultPythonVersion = pythonVersion3_13; + configOptions.defaultPythonPlatform = 'Linux'; + configOptions.defineConstant.set('MODE', 'hi!'); + + const analysisResults = TestUtils.typeAnalyzeSampleFiles(['staticExpressionDefinedConstants1.py'], configOptions); + const expectedLines = [14, 20, 25, 31, 37, 43, 44, 49, 50, 55, 56, 61, 62, 67, 73, 74, 79, 80]; + const expectedDiagnostics = expectedLines.map((line) => [line, DiagnosticRule.reportReturnType]); + expectedDiagnostics.push([110, DiagnosticRule.reportArgumentType]); + TestUtils.validateResults(analysisResults, expectedDiagnostics.length); + assert.deepStrictEqual( + [...analysisResults[0].errors] + .sort((a, b) => a.range.start.line - b.range.start.line) + .map((diagnostic) => [diagnostic.range.start.line + 1, diagnostic.getRule()]), + expectedDiagnostics + ); +}); + test('StaticExpression2', () => { const analysisResults = TestUtils.typeAnalyzeSampleFiles(['staticExpression2.py']);