diff --git a/packages/pyright-internal/src/analyzer/binder.ts b/packages/pyright-internal/src/analyzer/binder.ts index c281bb775b..1c764f35ba 100644 --- a/packages/pyright-internal/src/analyzer/binder.ts +++ b/packages/pyright-internal/src/analyzer/binder.ts @@ -784,7 +784,7 @@ export class Binder extends ParseTreeWalker { AnalyzerNodeInfo.setTypeParameterSymbol(name, symbol); if (this._activeTypeParams.has(name.value)) { - this._addError( + this._addSyntaxError( Localizer.Diagnostic.typeParameterExistingTypeParameter().format({ name: name.value }), name ); @@ -1017,7 +1017,7 @@ export class Binder extends ParseTreeWalker { const evaluationNode = ParseTreeUtils.getEvaluationNodeForAssignmentExpression(node); if (!evaluationNode) { - this._addError(Localizer.Diagnostic.assignmentExprContext(), node); + this._addSyntaxError(Localizer.Diagnostic.assignmentExprContext(), node); this.walk(node.name); } else { // Bind the name to the containing scope. This special logic is required @@ -1033,7 +1033,7 @@ export class Binder extends ParseTreeWalker { while (curScope && curScope !== containerScope) { const localSymbol = curScope.lookUpSymbol(node.name.value); if (localSymbol) { - this._addError( + this._addSyntaxError( Localizer.Diagnostic.assignmentExprComprehension().format({ name: node.name.value }), node.name ); @@ -1204,7 +1204,7 @@ export class Binder extends ParseTreeWalker { if (node.asyncToken && !this._fileInfo.ipythonMode) { const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node); if (!enclosingFunction || !enclosingFunction.isAsync) { - this._addError(Localizer.Diagnostic.asyncNotInAsyncFunction(), node.asyncToken); + this._addSyntaxError(Localizer.Diagnostic.asyncNotInAsyncFunction(), node.asyncToken); } } @@ -1256,7 +1256,7 @@ export class Binder extends ParseTreeWalker { override visitYield(node: YieldNode): boolean { if (this._isInListComprehension(node, /* ignoreOutermostIterable */ true)) { - this._addError(Localizer.Diagnostic.yieldWithinListCompr(), node); + this._addSyntaxError(Localizer.Diagnostic.yieldWithinListCompr(), node); } this._bindYield(node); @@ -1265,7 +1265,7 @@ export class Binder extends ParseTreeWalker { override visitYieldFrom(node: YieldFromNode): boolean { if (this._isInListComprehension(node, /* ignoreOutermostIterable */ true)) { - this._addError(Localizer.Diagnostic.yieldWithinListCompr(), node); + this._addSyntaxError(Localizer.Diagnostic.yieldWithinListCompr(), node); } this._bindYield(node); @@ -1629,7 +1629,7 @@ export class Binder extends ParseTreeWalker { // generator expressions is deferred and therefore can be // run within the context of an async function later. if (node.parent?.nodeType !== ParseNodeType.ListComprehension) { - this._addError(Localizer.Diagnostic.awaitNotInAsync(), node); + this._addSyntaxError(Localizer.Diagnostic.awaitNotInAsync(), node); } } @@ -1644,14 +1644,14 @@ export class Binder extends ParseTreeWalker { // Is the binding inconsistent? if (this._currentScope.getBindingType(nameValue) === NameBindingType.Nonlocal) { - this._addError(Localizer.Diagnostic.nonLocalRedefinition().format({ name: nameValue }), name); + this._addSyntaxError(Localizer.Diagnostic.nonLocalRedefinition().format({ name: nameValue }), name); } const valueWithScope = this._currentScope.lookUpSymbolRecursive(nameValue); // Was the name already assigned within this scope before it was declared global? if (valueWithScope && valueWithScope.scope === this._currentScope) { - this._addError(Localizer.Diagnostic.globalReassignment().format({ name: nameValue }), name); + this._addSyntaxError(Localizer.Diagnostic.globalReassignment().format({ name: nameValue }), name); } // Add it to the global scope if it's not already added. @@ -1669,23 +1669,23 @@ export class Binder extends ParseTreeWalker { const globalScope = this._currentScope.getGlobalScope().scope; if (this._currentScope === globalScope) { - this._addError(Localizer.Diagnostic.nonLocalInModule(), node); + this._addSyntaxError(Localizer.Diagnostic.nonLocalInModule(), node); } else { node.nameList.forEach((name) => { const nameValue = name.value; // Is the binding inconsistent? if (this._currentScope.getBindingType(nameValue) === NameBindingType.Global) { - this._addError(Localizer.Diagnostic.globalRedefinition().format({ name: nameValue }), name); + this._addSyntaxError(Localizer.Diagnostic.globalRedefinition().format({ name: nameValue }), name); } const valueWithScope = this._currentScope.lookUpSymbolRecursive(nameValue); // Was the name already assigned within this scope before it was declared nonlocal? if (valueWithScope && valueWithScope.scope === this._currentScope) { - this._addError(Localizer.Diagnostic.nonLocalReassignment().format({ name: nameValue }), name); + this._addSyntaxError(Localizer.Diagnostic.nonLocalReassignment().format({ name: nameValue }), name); } else if (!valueWithScope || valueWithScope.scope === globalScope) { - this._addError(Localizer.Diagnostic.nonLocalNoBinding().format({ name: nameValue }), name); + this._addSyntaxError(Localizer.Diagnostic.nonLocalNoBinding().format({ name: nameValue }), name); } if (valueWithScope) { @@ -1792,7 +1792,7 @@ export class Binder extends ParseTreeWalker { if (node.isWildcardImport) { if (ParseTreeUtils.getEnclosingClass(node) || ParseTreeUtils.getEnclosingFunction(node)) { - this._addError(Localizer.Diagnostic.wildcardInFunction(), node); + this._addSyntaxError(Localizer.Diagnostic.wildcardInFunction(), node); } if (importInfo) { @@ -2071,7 +2071,7 @@ export class Binder extends ParseTreeWalker { // Top level async with is allowed in ipython mode. const enclosingFunction = ParseTreeUtils.getEnclosingFunction(node); if (!enclosingFunction || !enclosingFunction.isAsync) { - this._addError(Localizer.Diagnostic.asyncNotInAsyncFunction(), node.asyncToken); + this._addSyntaxError(Localizer.Diagnostic.asyncNotInAsyncFunction(), node.asyncToken); } } }); @@ -2188,7 +2188,7 @@ export class Binder extends ParseTreeWalker { // generator expressions is deferred and therefore can be // run within the context of an async function later. if (node.parent?.nodeType === ParseNodeType.List) { - this._addError(Localizer.Diagnostic.asyncNotInAsyncFunction(), compr.asyncToken); + this._addSyntaxError(Localizer.Diagnostic.asyncNotInAsyncFunction(), compr.asyncToken); } } } @@ -4158,12 +4158,12 @@ export class Binder extends ParseTreeWalker { if (!functionNode) { if (!ParseTreeUtils.getEnclosingLambda(node)) { - this._addError(Localizer.Diagnostic.yieldOutsideFunction(), node); + this._addSyntaxError(Localizer.Diagnostic.yieldOutsideFunction(), node); } } else if (functionNode.isAsync && node.nodeType === ParseNodeType.YieldFrom) { // PEP 525 indicates that 'yield from' is not allowed in an // async function. - this._addError(Localizer.Diagnostic.yieldFromOutsideAsync(), node); + this._addSyntaxError(Localizer.Diagnostic.yieldFromOutsideAsync(), node); } if (this._targetFunctionDeclaration) { @@ -4190,15 +4190,9 @@ export class Binder extends ParseTreeWalker { let diagnostic: Diagnostic | undefined; switch (diagLevel) { case 'error': - diagnostic = this._addError(message, textRange); - break; - case 'warning': - diagnostic = this._addWarning(message, textRange); - break; - case 'information': - diagnostic = this._addInformation(message, textRange); + diagnostic = this._fileInfo.diagnosticSink.addDiagnosticWithTextRange(diagLevel, message, textRange); break; case 'none': @@ -4215,17 +4209,9 @@ export class Binder extends ParseTreeWalker { return diagnostic; } - private _addError(message: string, textRange: TextRange) { + private _addSyntaxError(message: string, textRange: TextRange) { return this._fileInfo.diagnosticSink.addDiagnosticWithTextRange('error', message, textRange); } - - private _addWarning(message: string, textRange: TextRange) { - return this._fileInfo.diagnosticSink.addDiagnosticWithTextRange('warning', message, textRange); - } - - private _addInformation(message: string, textRange: TextRange) { - return this._fileInfo.diagnosticSink.addDiagnosticWithTextRange('information', message, textRange); - } } export class YieldFinder extends ParseTreeWalker { diff --git a/packages/pyright-internal/src/analyzer/checker.ts b/packages/pyright-internal/src/analyzer/checker.ts index 18dfb2ea71..8fba300a9c 100644 --- a/packages/pyright-internal/src/analyzer/checker.ts +++ b/packages/pyright-internal/src/analyzer/checker.ts @@ -321,7 +321,9 @@ export class Checker extends ParseTreeWalker { !ClassType.isBuiltIn(baseClassType, 'Generic') ) { if (!ClassType.isProtocolClass(baseClassType)) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.protocolBaseClass().format({ classType: classTypeResult.classType.details.name, baseType: baseClassType.details.name, @@ -540,7 +542,9 @@ export class Checker extends ParseTreeWalker { }); if (paramSpecParams.length === 1 && paramSpecParams[0].typeAnnotation) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.paramSpecArgsKwargsUsage(), paramSpecParams[0].typeAnnotation ); @@ -937,7 +941,12 @@ export class Checker extends ParseTreeWalker { if (enclosingFunctionNode?.isAsync && node.returnExpression) { const functionDecl = AnalyzerNodeInfo.getDeclaration(enclosingFunctionNode); if (functionDecl?.type === DeclarationType.Function && functionDecl.isGenerator) { - this._evaluator.addError(Localizer.Diagnostic.returnInAsyncGenerator(), node.returnExpression); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.returnInAsyncGenerator(), + node.returnExpression + ); } } @@ -1126,7 +1135,9 @@ export class Checker extends ParseTreeWalker { }); if (!diagAddendum.isEmpty()) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.expectedExceptionObj() + diagAddendum.getString(), node.valueExpression ); @@ -1211,7 +1222,9 @@ export class Checker extends ParseTreeWalker { scope.type !== ScopeType.Module && scope.type !== ScopeType.Builtin ) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.typeAliasNotInModuleOrClass(), node.leftExpression.typeAnnotation ); @@ -1408,7 +1421,12 @@ export class Checker extends ParseTreeWalker { (fStringContainer.token.flags & quoteTypeMask) === (stringNode.token.flags & quoteTypeMask) ) ) { - this._evaluator.addError(Localizer.Diagnostic.formatStringNestedQuote(), stringNode); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.formatStringNestedQuote(), + stringNode + ); } } } @@ -1529,7 +1547,12 @@ export class Checker extends ParseTreeWalker { node.module.nameParts[0].value === '__future__' ) { if (!ParseTreeUtils.isValidLocationForFutureImport(node)) { - this._evaluator.addError(Localizer.Diagnostic.futureImportLocationNotAllowed(), node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.futureImportLocationNotAllowed(), + node + ); } } @@ -1633,7 +1656,12 @@ export class Checker extends ParseTreeWalker { const scope = getScopeForNode(node); if (scope) { if (scope.type !== ScopeType.Class && scope.type !== ScopeType.Module && scope.type !== ScopeType.Builtin) { - this._evaluator.addError(Localizer.Diagnostic.typeAliasStatementBadScope(), node.name); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typeAliasStatementBadScope(), + node.name + ); } } @@ -2947,7 +2975,9 @@ export class Checker extends ParseTreeWalker { } if (!diagAddendum.isEmpty()) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.exceptionTypeNotClass().format({ type: this._evaluator.printType(exceptionType), }), @@ -3133,7 +3163,12 @@ export class Checker extends ParseTreeWalker { decls.forEach((decl) => { if (this._evaluator.isFinalVariableDeclaration(decl)) { if (sawFinal) { - this._evaluator.addError(Localizer.Diagnostic.finalRedeclaration().format({ name }), decl.node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.finalRedeclaration().format({ name }), + decl.node + ); } sawFinal = true; } @@ -3145,7 +3180,12 @@ export class Checker extends ParseTreeWalker { // the assignment is within an `__init__` method, so ignore class // scopes here. if (scopeType !== ScopeType.Class) { - this._evaluator.addError(Localizer.Diagnostic.finalReassigned().format({ name }), decl.node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.finalReassigned().format({ name }), + decl.node + ); } } sawAssignment = true; @@ -3183,7 +3223,12 @@ export class Checker extends ParseTreeWalker { } if (!isImplicitlyAssigned && !isProtocolClass) { - this._evaluator.addError(Localizer.Diagnostic.finalUnassigned().format({ name }), firstDecl.node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.finalUnassigned().format({ name }), + firstDecl.node + ); } } } @@ -3197,7 +3242,12 @@ export class Checker extends ParseTreeWalker { if (typeAliasDecl && decls.length > 1) { decls.forEach((decl) => { if (decl !== typeAliasDecl) { - this._evaluator.addError(Localizer.Diagnostic.typeAliasRedeclared().format({ name }), decl.node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typeAliasRedeclared().format({ name }), + decl.node + ); } }); } @@ -4565,7 +4615,12 @@ export class Checker extends ParseTreeWalker { // strings, and "pass" statements or ellipses. private _validateTypedDictClassSuite(suiteNode: SuiteNode) { const emitBadStatementError = (node: ParseNode) => { - this._evaluator.addError(Localizer.Diagnostic.typedDictBadVar(), node); + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictBadVar(), + node + ); }; suiteNode.statements.forEach((statement) => { @@ -4788,7 +4843,9 @@ export class Checker extends ParseTreeWalker { !SymbolNameUtils.isPrivateName(name) ) { const decl = localSymbol.getDeclarations()[0]; - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.finalRedeclarationBySubclass().format({ name, className: parentSymbol.classType.details.name, @@ -4820,7 +4877,9 @@ export class Checker extends ParseTreeWalker { ClassType.isSameGenericClass(symbolType, classType) && symbolType.literalValue !== undefined ) { - this._evaluator.addError( + this._evaluator.addDiagnostic( + this._fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.duplicateEnumMember().format({ name }), decls[1].node ); diff --git a/packages/pyright-internal/src/analyzer/dataClasses.ts b/packages/pyright-internal/src/analyzer/dataClasses.ts index d500682787..2e9f12c374 100644 --- a/packages/pyright-internal/src/analyzer/dataClasses.ts +++ b/packages/pyright-internal/src/analyzer/dataClasses.ts @@ -504,7 +504,12 @@ export function synthesizeDataClassMethods( const effectiveName = entry.alias || entry.name; if (!entry.alias && entry.nameNode && isPrivateName(entry.nameNode.value)) { - evaluator.addError(Localizer.Diagnostic.dataClassFieldWithPrivateName(), entry.nameNode); + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.dataClassFieldWithPrivateName(), + entry.nameNode + ); } const functionParam: FunctionParameter = { @@ -1019,7 +1024,12 @@ export function validateDataClassTransformDecorator( // Parse the arguments to the call. node.arguments.forEach((arg) => { if (!arg.name || arg.argumentCategory !== ArgumentCategory.Simple) { - evaluator.addError(Localizer.Diagnostic.dataClassTransformPositionalParam(), arg); + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.dataClassTransformPositionalParam(), + arg + ); return; } @@ -1031,7 +1041,9 @@ export function validateDataClassTransformDecorator( fileInfo.definedConstants ); if (value === undefined) { - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformExpectedBoolLiteral(), arg.valueExpression ); @@ -1049,7 +1061,9 @@ export function validateDataClassTransformDecorator( fileInfo.definedConstants ); if (value === undefined) { - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformExpectedBoolLiteral(), arg.valueExpression ); @@ -1067,7 +1081,9 @@ export function validateDataClassTransformDecorator( fileInfo.definedConstants ); if (value === undefined) { - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformExpectedBoolLiteral(), arg.valueExpression ); @@ -1085,7 +1101,9 @@ export function validateDataClassTransformDecorator( fileInfo.definedConstants ); if (value === undefined) { - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformExpectedBoolLiteral(), arg.valueExpression ); @@ -1114,7 +1132,9 @@ export function validateDataClassTransformDecorator( !isOverloadedFunction(entry.type) ) ) { - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformFieldSpecifier().format({ type: evaluator.printType(valueType), }), @@ -1137,7 +1157,9 @@ export function validateDataClassTransformDecorator( } default: - evaluator.addError( + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.dataClassTransformUnknownArgument().format({ name: arg.name.value }), arg.valueExpression ); diff --git a/packages/pyright-internal/src/analyzer/namedTuples.ts b/packages/pyright-internal/src/analyzer/namedTuples.ts index 3adb19d812..c1c2df5b15 100644 --- a/packages/pyright-internal/src/analyzer/namedTuples.ts +++ b/packages/pyright-internal/src/analyzer/namedTuples.ts @@ -8,6 +8,7 @@ * classes with defined entry names and types. */ +import { DiagnosticRule } from '../common/diagnosticRules'; import { convertOffsetsToRange } from '../common/positionUtils'; import { TextRange } from '../common/textRange'; import { Localizer } from '../localization/localize'; @@ -81,11 +82,21 @@ export function createNamedTupleType( } if (argList.length === 0) { - evaluator.addError(Localizer.Diagnostic.namedTupleFirstArg(), errorNode); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleFirstArg(), + errorNode + ); } else { const nameArg = argList[0]; if (nameArg.argumentCategory !== ArgumentCategory.Simple) { - evaluator.addError(Localizer.Diagnostic.namedTupleFirstArg(), argList[0].valueExpression || errorNode); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleFirstArg(), + argList[0].valueExpression || errorNode + ); } else if (nameArg.valueExpression && nameArg.valueExpression.nodeType === ParseNodeType.StringList) { className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } @@ -157,7 +168,12 @@ export function createNamedTupleType( const entryTypes: Type[] = []; if (argList.length < 2) { - evaluator.addError(Localizer.Diagnostic.namedTupleSecondArg(), errorNode); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleSecondArg(), + errorNode + ); addGenericGetAttribute = true; } else { const entriesArg = argList[1]; @@ -251,7 +267,12 @@ export function createNamedTupleType( evaluator.getTypeOfExpressionExpectingType(entryTypeNode).type ); } else { - evaluator.addError(Localizer.Diagnostic.namedTupleNameType(), entry); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleNameType(), + entry + ); } } else { entryNameNode = entry; @@ -268,7 +289,12 @@ export function createNamedTupleType( entryName = nameTypeResult.type.literalValue as string; if (!entryName) { - evaluator.addError(Localizer.Diagnostic.namedTupleEmptyName(), entryNameNode); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleEmptyName(), + entryNameNode + ); } else { entryName = renameKeyword(evaluator, entryName, allowRename, entryNameNode, index); } @@ -284,7 +310,12 @@ export function createNamedTupleType( } if (entryMap.has(entryName)) { - evaluator.addError(Localizer.Diagnostic.namedTupleNameUnique(), entryNameNode || entry); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleNameUnique(), + entryNameNode || entry + ); } // Record names in a map to detect duplicates. @@ -486,6 +517,11 @@ function renameKeyword( return `_${index}`; } - evaluator.addError(Localizer.Diagnostic.namedTupleNameKeyword(), errorNode); + evaluator.addDiagnostic( + getFileInfo(errorNode).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.namedTupleNameKeyword(), + errorNode + ); return name; } diff --git a/packages/pyright-internal/src/analyzer/operations.ts b/packages/pyright-internal/src/analyzer/operations.ts index a6d09baf47..1ac998dcad 100644 --- a/packages/pyright-internal/src/analyzer/operations.ts +++ b/packages/pyright-internal/src/analyzer/operations.ts @@ -612,7 +612,13 @@ export function getTypeOfBinaryOperation( // If the left type is Any, we can't say for sure whether this // is an illegal syntax or a valid application of the "|" operator. if (!isAnyOrUnknown(adjustedLeftType)) { - evaluator.addError(Localizer.Diagnostic.unionSyntaxIllegal(), node, node.operatorToken); + evaluator.addDiagnostic( + getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.unionSyntaxIllegal(), + node, + node.operatorToken + ); } } @@ -691,7 +697,12 @@ export function getTypeOfBinaryOperation( if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { // Exempt "|" because it might be a union operation involving unknowns. if (node.operator !== OperatorType.BitwiseOr) { - evaluator.addError(Localizer.Diagnostic.binaryOperationNotAllowed(), node); + evaluator.addDiagnostic( + getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.binaryOperationNotAllowed(), + node + ); return { type: UnknownType.create() }; } } @@ -950,7 +961,12 @@ export function getTypeOfUnaryOperation( inferenceContext: InferenceContext | undefined ): TypeResult { if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { - evaluator.addError(Localizer.Diagnostic.unaryOperationNotAllowed(), node); + evaluator.addDiagnostic( + getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.unaryOperationNotAllowed(), + node + ); return { type: UnknownType.create() }; } @@ -1069,8 +1085,15 @@ export function getTypeOfTernaryOperation( flags: EvaluatorFlags, inferenceContext: InferenceContext | undefined ): TypeResult { + const fileInfo = getFileInfo(node); + if ((flags & EvaluatorFlags.ExpectingTypeAnnotation) !== 0) { - evaluator.addError(Localizer.Diagnostic.ternaryNotAllowed(), node); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.ternaryNotAllowed(), + node + ); return { type: UnknownType.create() }; } @@ -1080,7 +1103,6 @@ export function getTypeOfTernaryOperation( let isIncomplete = false; let typeErrors = false; - const fileInfo = getFileInfo(node); const constExprValue = evaluateStaticBoolExpression( node.testExpression, fileInfo.executionEnvironment, diff --git a/packages/pyright-internal/src/analyzer/typeEvaluator.ts b/packages/pyright-internal/src/analyzer/typeEvaluator.ts index 41fca15d6e..328ca5047b 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluator.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluator.ts @@ -3102,10 +3102,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions return addDiagnosticWithSuppressionCheck('information', message, node, range); } - function addWarning(message: string, node: ParseNode, range?: TextRange) { - return addDiagnosticWithSuppressionCheck('warning', message, node, range); - } - function addError(message: string, node: ParseNode, range?: TextRange) { return addDiagnosticWithSuppressionCheck('error', message, node, range); } @@ -26761,8 +26757,6 @@ export function createTypeEvaluator(importLookup: ImportLookup, evaluatorOptions isFinalVariable, isFinalVariableDeclaration, isExplicitTypeAliasDeclaration, - addError, - addWarning, addInformation, addUnusedCode, addUnreachableCode, diff --git a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts index 57a8103839..55ea3f3c6f 100644 --- a/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts +++ b/packages/pyright-internal/src/analyzer/typeEvaluatorTypes.ts @@ -632,8 +632,6 @@ export interface TypeEvaluator { isFinalVariableDeclaration: (decl: Declaration) => boolean; isExplicitTypeAliasDeclaration: (decl: Declaration) => boolean; - addError: (message: string, node: ParseNode, range?: TextRange) => Diagnostic | undefined; - addWarning: (message: string, node: ParseNode, range?: TextRange) => Diagnostic | undefined; addInformation: (message: string, node: ParseNode, range?: TextRange) => Diagnostic | undefined; addUnusedCode: (node: ParseNode, textRange: TextRange) => void; addUnreachableCode: (node: ParseNode, textRange: TextRange) => void; diff --git a/packages/pyright-internal/src/analyzer/typedDicts.ts b/packages/pyright-internal/src/analyzer/typedDicts.ts index 6cd3874ee3..771c4c254c 100644 --- a/packages/pyright-internal/src/analyzer/typedDicts.ts +++ b/packages/pyright-internal/src/analyzer/typedDicts.ts @@ -79,7 +79,12 @@ export function createTypedDictType( // Point2D = TypedDict('Point2D', x=int, y=int, label=str) let className: string | undefined; if (argList.length === 0) { - evaluator.addError(Localizer.Diagnostic.typedDictFirstArg(), errorNode); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictFirstArg(), + errorNode + ); } else { const nameArg = argList[0]; if ( @@ -87,7 +92,12 @@ export function createTypedDictType( !nameArg.valueExpression || nameArg.valueExpression.nodeType !== ParseNodeType.StringList ) { - evaluator.addError(Localizer.Diagnostic.typedDictFirstArg(), argList[0].valueExpression || errorNode); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictFirstArg(), + argList[0].valueExpression || errorNode + ); } else { className = nameArg.valueExpression.strings.map((s) => s.value).join(''); } @@ -115,7 +125,12 @@ export function createTypedDictType( let usingDictSyntax = false; if (argList.length < 2) { - evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDict(), errorNode); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictSecondArgDict(), + errorNode + ); } else { const entriesArg = argList[1]; @@ -136,7 +151,12 @@ export function createTypedDictType( } if (entrySet.has(entry.name.value)) { - evaluator.addError(Localizer.Diagnostic.typedDictEntryUnique(), entry.valueExpression); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictEntryUnique(), + entry.valueExpression + ); continue; } @@ -144,7 +164,6 @@ export function createTypedDictType( entrySet.add(entry.name.value); const newSymbol = new Symbol(SymbolFlags.InstanceMember); - const fileInfo = AnalyzerNodeInfo.getFileInfo(errorNode); const declaration: VariableDeclaration = { type: DeclarationType.Variable, node: entry.name, @@ -164,7 +183,12 @@ export function createTypedDictType( classFields.set(entry.name.value, newSymbol); } } else { - evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDict(), errorNode); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictSecondArgDict(), + errorNode + ); } } @@ -179,7 +203,9 @@ export function createTypedDictType( arg.valueExpression.constType === KeywordType.True ) ) { - evaluator.addError( + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.typedDictBoolParam().format({ name: arg.name.value }), arg.valueExpression || errorNode ); @@ -187,7 +213,12 @@ export function createTypedDictType( classType.details.flags |= ClassTypeFlags.CanOmitDictValues; } } else { - evaluator.addError(Localizer.Diagnostic.typedDictExtraArgs(), arg.valueExpression || errorNode); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictExtraArgs(), + arg.valueExpression || errorNode + ); } } } @@ -201,7 +232,9 @@ export function createTypedDictType( if (typedDictTarget.nodeType === ParseNodeType.Name) { if (typedDictTarget.value !== className) { - evaluator.addError( + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, Localizer.Diagnostic.typedDictAssignedName().format({ name: className, }), @@ -737,23 +770,43 @@ function getTypedDictFieldsFromDictSyntax( entryDict.entries.forEach((entry) => { if (entry.nodeType !== ParseNodeType.DictionaryKeyEntry) { - evaluator.addError(Localizer.Diagnostic.typedDictSecondArgDictEntry(), entry); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictSecondArgDictEntry(), + entry + ); return; } if (entry.keyExpression.nodeType !== ParseNodeType.StringList) { - evaluator.addError(Localizer.Diagnostic.typedDictEntryName(), entry.keyExpression); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictEntryName(), + entry.keyExpression + ); return; } const entryName = entry.keyExpression.strings.map((s) => s.value).join(''); if (!entryName) { - evaluator.addError(Localizer.Diagnostic.typedDictEmptyName(), entry.keyExpression); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictEmptyName(), + entry.keyExpression + ); return; } if (entrySet.has(entryName)) { - evaluator.addError(Localizer.Diagnostic.typedDictEntryUnique(), entry.keyExpression); + evaluator.addDiagnostic( + fileInfo.diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typedDictEntryUnique(), + entry.keyExpression + ); return; } @@ -1081,7 +1134,12 @@ export function getTypeOfIndexedTypedDict( usage: EvaluatorUsage ): TypeResult | undefined { if (node.items.length !== 1) { - evaluator.addError(Localizer.Diagnostic.typeArgsMismatchOne().format({ received: node.items.length }), node); + evaluator.addDiagnostic( + AnalyzerNodeInfo.getFileInfo(node).diagnosticRuleSet.reportGeneralTypeIssues, + DiagnosticRule.reportGeneralTypeIssues, + Localizer.Diagnostic.typeArgsMismatchOne().format({ received: node.items.length }), + node + ); return { type: UnknownType.create() }; } diff --git a/packages/pyright-internal/src/parser/parser.ts b/packages/pyright-internal/src/parser/parser.ts index 0bf7f0d327..6970d4d184 100644 --- a/packages/pyright-internal/src/parser/parser.ts +++ b/packages/pyright-internal/src/parser/parser.ts @@ -242,9 +242,9 @@ export class Parser { this._getNextToken(); const indentToken = nextToken as IndentToken; if (indentToken.isIndentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), indentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), indentToken); } else { - this._addError(Localizer.Diagnostic.unexpectedIndent(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.unexpectedIndent(), nextToken); } } @@ -304,7 +304,7 @@ export class Parser { parseTree = exprListResult.parseError; } else { if (exprListResult.list.length === 0) { - this._addError(Localizer.Diagnostic.expectedExpr(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedExpr(), this._peekToken()); } parseTree = this._makeExpressionOrTuple(exprListResult, /* enclosedInParens */ false); } @@ -315,7 +315,7 @@ export class Parser { } if (!this._atEof()) { - this._addError(Localizer.Diagnostic.unexpectedExprToken(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.unexpectedExprToken(), this._peekToken()); } return { @@ -356,7 +356,7 @@ export class Parser { // Handle the errant condition of a dedent token here to provide // better recovery. if (this._consumeTokenIfType(TokenType.Dedent)) { - this._addError(Localizer.Diagnostic.unexpectedUnindent(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.unexpectedUnindent(), this._peekToken()); } switch (this._peekKeywordType()) { @@ -446,7 +446,7 @@ export class Parser { return this._parseForStatement(asyncToken); } - this._addError(Localizer.Diagnostic.unexpectedAsyncToken(), asyncToken); + this._addSyntaxError(Localizer.Diagnostic.unexpectedAsyncToken(), asyncToken); return undefined; } @@ -456,7 +456,7 @@ export class Parser { const typeToken = this._getKeywordToken(KeywordType.Type); if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_12) { - this._addError(Localizer.Diagnostic.typeAliasStatementIllegal(), typeToken); + this._addSyntaxError(Localizer.Diagnostic.typeAliasStatementIllegal(), typeToken); } const nameToken = this._getTokenIfIdentifier(); @@ -473,7 +473,7 @@ export class Parser { assignToken.type !== TokenType.Operator || (assignToken as OperatorToken).operatorType !== OperatorType.Assign ) { - this._addError(Localizer.Diagnostic.expectedEquals(), assignToken); + this._addSyntaxError(Localizer.Diagnostic.expectedEquals(), assignToken); } else { this._getNextToken(); } @@ -495,7 +495,7 @@ export class Parser { if (firstToken.type === TokenType.CloseBracket) { if (typeVariableNodes.length === 0) { - this._addError(Localizer.Diagnostic.typeParametersMissing(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.typeParametersMissing(), this._peekToken()); } break; } @@ -514,7 +514,7 @@ export class Parser { const closingToken = this._peekToken(); if (closingToken.type !== TokenType.CloseBracket) { - this._addError(Localizer.Diagnostic.expectedCloseBracket(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseBracket(), this._peekToken()); this._consumeTokensUntilType([TokenType.NewLine, TokenType.CloseBracket, TokenType.Colon]); } else { this._getNextToken(); @@ -534,7 +534,7 @@ export class Parser { const nameToken = this._getTokenIfIdentifier(); if (!nameToken) { - this._addError(Localizer.Diagnostic.expectedTypeParameterName(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedTypeParameterName(), this._peekToken()); return undefined; } @@ -545,7 +545,7 @@ export class Parser { boundExpression = this._parseExpression(/* allowUnpack */ false); if (typeParamCategory !== TypeParameterCategory.TypeVar) { - this._addError(Localizer.Diagnostic.typeParameterBoundNotAllowed(), boundExpression); + this._addSyntaxError(Localizer.Diagnostic.typeParameterBoundNotAllowed(), boundExpression); } } @@ -556,7 +556,7 @@ export class Parser { ); if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_13) { - this._addError(Localizer.Diagnostic.typeVarDefaultIllegal(), defaultExpression); + this._addSyntaxError(Localizer.Diagnostic.typeVarDefaultIllegal(), defaultExpression); } } @@ -608,7 +608,7 @@ export class Parser { const nextToken = this._peekToken(); if (!this._consumeTokenIfType(TokenType.Colon)) { - this._addError(Localizer.Diagnostic.expectedColon(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.expectedColon(), nextToken); // Try to perform parse recovery by consuming tokens until // we find the end of the line. @@ -619,15 +619,15 @@ export class Parser { extendRange(matchNode, nextToken); if (!this._consumeTokenIfType(TokenType.NewLine)) { - this._addError(Localizer.Diagnostic.expectedNewline(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.expectedNewline(), nextToken); } else { const possibleIndent = this._peekToken(); if (!this._consumeTokenIfType(TokenType.Indent)) { - this._addError(Localizer.Diagnostic.expectedIndentedBlock(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIndentedBlock(), this._peekToken()); } else { const indentToken = possibleIndent as IndentToken; if (indentToken.isIndentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), indentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), indentToken); } } @@ -638,9 +638,9 @@ export class Parser { this._getNextToken(); const indentToken = possibleUnexpectedIndent as IndentToken; if (indentToken.isIndentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), indentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), indentToken); } else { - this._addError(Localizer.Diagnostic.unexpectedIndent(), possibleUnexpectedIndent); + this._addSyntaxError(Localizer.Diagnostic.unexpectedIndent(), possibleUnexpectedIndent); } } @@ -658,10 +658,10 @@ export class Parser { const dedentToken = this._peekToken() as DedentToken; if (this._consumeTokenIfType(TokenType.Dedent)) { if (!dedentToken.matchesIndent) { - this._addError(Localizer.Diagnostic.inconsistentIndent(), dedentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentIndent(), dedentToken); } if (dedentToken.isDedentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), dedentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), dedentToken); } break; } @@ -675,20 +675,20 @@ export class Parser { if (matchNode.cases.length > 0) { extendRange(matchNode, matchNode.cases[matchNode.cases.length - 1]); } else { - this._addError(Localizer.Diagnostic.zeroCaseStatementsFound(), matchToken); + this._addSyntaxError(Localizer.Diagnostic.zeroCaseStatementsFound(), matchToken); } } // This feature requires Python 3.10. if (this._getLanguageVersion() < PythonVersion.V3_10) { - this._addError(Localizer.Diagnostic.matchIncompatible(), matchToken); + this._addSyntaxError(Localizer.Diagnostic.matchIncompatible(), matchToken); } // Validate that only the last entry uses an irrefutable pattern. for (let i = 0; i < matchNode.cases.length - 1; i++) { const caseNode = matchNode.cases[i]; if (!caseNode.guardExpression && caseNode.isIrrefutable) { - this._addError(Localizer.Diagnostic.casePatternIsIrrefutable(), caseNode.pattern); + this._addSyntaxError(Localizer.Diagnostic.casePatternIsIrrefutable(), caseNode.pattern); } } @@ -702,7 +702,7 @@ export class Parser { const caseToken = this._peekToken(); if (!this._consumeTokenIfKeyword(KeywordType.Case)) { - this._addError(Localizer.Diagnostic.expectedCase(), caseToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCase(), caseToken); return undefined; } @@ -712,7 +712,7 @@ export class Parser { if (patternList.parseError) { casePattern = patternList.parseError; } else if (patternList.list.length === 0) { - this._addError(Localizer.Diagnostic.expectedPatternExpr(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedPatternExpr(), this._peekToken()); casePattern = ErrorNode.create(caseToken, ErrorExpressionCategory.MissingPattern); } else if (patternList.list.length === 1 && !patternList.trailingComma) { const pattern = patternList.list[0].orPatterns[0]; @@ -766,7 +766,7 @@ export class Parser { ) { const reportTargetIfDuplicate = (nameNode: NameNode) => { if (globalNameMap.has(nameNode.value) || localNameMap.has(nameNode.value)) { - this._addError( + this._addSyntaxError( Localizer.Diagnostic.duplicateCapturePatternTarget().format({ name: nameNode.value, }), @@ -907,7 +907,7 @@ export class Parser { ); if (starEntries.length > 1) { - this._addError(Localizer.Diagnostic.duplicateStarPattern(), starEntries[1].orPatterns[0]); + this._addSyntaxError(Localizer.Diagnostic.duplicateStarPattern(), starEntries[1].orPatterns[0]); } return patternList; @@ -931,7 +931,7 @@ export class Parser { // Star patterns cannot be ORed with other patterns. orPatterns.forEach((patternAtom) => { if (patternAtom.nodeType === ParseNodeType.PatternCapture && patternAtom.isStar) { - this._addError(Localizer.Diagnostic.starPatternInOrPattern(), patternAtom); + this._addSyntaxError(Localizer.Diagnostic.starPatternInOrPattern(), patternAtom); } }); } @@ -942,7 +942,7 @@ export class Parser { if (nameToken) { target = NameNode.create(nameToken); } else { - this._addError(Localizer.Diagnostic.expectedNameAfterAs(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedNameAfterAs(), this._peekToken()); } } @@ -953,13 +953,13 @@ export class Parser { orPatterns[0].nodeType === ParseNodeType.PatternCapture && orPatterns[0].isStar ) { - this._addError(Localizer.Diagnostic.starPatternInAsPattern(), orPatterns[0]); + this._addSyntaxError(Localizer.Diagnostic.starPatternInAsPattern(), orPatterns[0]); } // Validate that irrefutable patterns are not in any entries other than the last. orPatterns.forEach((orPattern, index) => { if (index < orPatterns.length - 1 && this._isPatternIrrefutable(orPattern)) { - this._addError(Localizer.Diagnostic.orPatternIrrefutable(), orPattern); + this._addSyntaxError(Localizer.Diagnostic.orPatternIrrefutable(), orPattern); } }); @@ -981,7 +981,7 @@ export class Parser { name: missingNames.map((name) => `"${name}"`).join(', '), }) ); - this._addError(Localizer.Diagnostic.orPatternMissingName() + diag.getString(), orPattern); + this._addSyntaxError(Localizer.Diagnostic.orPatternMissingName() + diag.getString(), orPattern); } }); @@ -1026,7 +1026,7 @@ export class Parser { const classPattern = PatternClassNode.create(classNameExpr, args); if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); // Consume the remainder of tokens on the line for error // recovery. @@ -1047,7 +1047,7 @@ export class Parser { const starToken = this._getNextToken(); const identifierToken = this._getTokenIfIdentifier(); if (!identifierToken) { - this._addError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); return ErrorNode.create(starToken, ErrorExpressionCategory.MissingExpression); } else { return PatternCaptureNode.create(NameNode.create(identifierToken), starToken); @@ -1087,7 +1087,7 @@ export class Parser { ) { extendRange(casePattern, endToken); } else { - this._addError( + this._addSyntaxError( nextToken.type === TokenType.OpenParenthesis ? Localizer.Diagnostic.expectedCloseParen() : Localizer.Diagnostic.expectedCloseBracket(), @@ -1108,7 +1108,7 @@ export class Parser { if (this._consumeTokenIfType(TokenType.CloseCurlyBrace)) { extendRange(mappingPattern, lastToken); } else { - this._addError(Localizer.Diagnostic.expectedCloseBrace(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseBrace(), nextToken); this._consumeTokensUntilType([TokenType.Colon, TokenType.CloseCurlyBrace]); } @@ -1144,7 +1144,7 @@ export class Parser { if (arg.name) { sawKeywordArg = true; } else if (sawKeywordArg && !arg.name) { - this._addError(Localizer.Diagnostic.positionArgAfterNamedArg(), arg); + this._addSyntaxError(Localizer.Diagnostic.positionArgAfterNamedArg(), arg); } argList.push(arg); @@ -1203,7 +1203,7 @@ export class Parser { // Check for f-strings, which are not allowed. stringList.strings.forEach((stringAtom) => { if (stringAtom.nodeType === ParseNodeType.FormatString) { - this._addError(Localizer.Diagnostic.formatStringInPattern(), stringAtom); + this._addSyntaxError(Localizer.Diagnostic.formatStringInPattern(), stringAtom); } }); @@ -1245,7 +1245,7 @@ export class Parser { } if (realValue.nodeType !== ParseNodeType.Number || (imagValue !== undefined && realValue.isImaginary)) { - this._addError(Localizer.Diagnostic.expectedComplexNumberLiteral(), expression); + this._addSyntaxError(Localizer.Diagnostic.expectedComplexNumberLiteral(), expression); imagValue = undefined; } } @@ -1256,7 +1256,7 @@ export class Parser { } if (imagValue.nodeType !== ParseNodeType.Number || !imagValue.isImaginary) { - this._addError(Localizer.Diagnostic.expectedComplexNumberLiteral(), expression); + this._addSyntaxError(Localizer.Diagnostic.expectedComplexNumberLiteral(), expression); } } @@ -1272,7 +1272,7 @@ export class Parser { (entry) => entry.nodeType === ParseNodeType.PatternMappingExpandEntry ); if (starStarEntries.length > 1) { - this._addError(Localizer.Diagnostic.duplicateStarStarPattern(), starStarEntries[1]); + this._addSyntaxError(Localizer.Diagnostic.duplicateStarStarPattern(), starStarEntries[1]); } return PatternMappingNode.create(firstToken, itemList.list); @@ -1291,13 +1291,13 @@ export class Parser { if (this._consumeTokenIfOperator(OperatorType.Power)) { const identifierToken = this._getTokenIfIdentifier(); if (!identifierToken) { - this._addError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); return ErrorNode.create(this._peekToken(), ErrorExpressionCategory.MissingPattern); } const nameNode = NameNode.create(identifierToken); if (identifierToken.value === '_') { - this._addError(Localizer.Diagnostic.starStarWildcardNotAllowed(), nameNode); + this._addSyntaxError(Localizer.Diagnostic.starStarWildcardNotAllowed(), nameNode); } return PatternMappingExpandEntryNode.create(doubleStar, nameNode); @@ -1312,20 +1312,20 @@ export class Parser { if (patternCaptureOrValue.nodeType === ParseNodeType.PatternValue) { keyExpression = patternCaptureOrValue; } else { - this._addError(Localizer.Diagnostic.expectedPatternValue(), patternCaptureOrValue); + this._addSyntaxError(Localizer.Diagnostic.expectedPatternValue(), patternCaptureOrValue); keyExpression = ErrorNode.create(this._peekToken(), ErrorExpressionCategory.MissingPattern); } } } if (!keyExpression) { - this._addError(Localizer.Diagnostic.expectedPatternExpr(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedPatternExpr(), this._peekToken()); keyExpression = ErrorNode.create(this._peekToken(), ErrorExpressionCategory.MissingPattern); } let valuePattern: PatternAtomNode | undefined; if (!this._consumeTokenIfType(TokenType.Colon)) { - this._addError(Localizer.Diagnostic.expectedColon(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedColon(), this._peekToken()); valuePattern = ErrorNode.create(this._peekToken(), ErrorExpressionCategory.MissingPattern); } else { valuePattern = this._parsePatternAs(); @@ -1346,7 +1346,7 @@ export class Parser { const nameNode = NameNode.create(identifierToken); nameOrMember = nameOrMember ? MemberAccessNode.create(nameOrMember, nameNode) : nameNode; } else { - this._addError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); break; } @@ -1356,7 +1356,7 @@ export class Parser { } if (!nameOrMember) { - this._addError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); return ErrorNode.create(this._peekToken(), ErrorExpressionCategory.MissingPattern); } @@ -1424,7 +1424,7 @@ export class Parser { const suite = SuiteNode.create(nextToken); if (!this._consumeTokenIfType(TokenType.Colon)) { - this._addError(Localizer.Diagnostic.expectedColon(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.expectedColon(), nextToken); // Try to perform parse recovery by consuming tokens. if (this._consumeTokensUntilType([TokenType.NewLine, TokenType.Colon])) { @@ -1450,7 +1450,7 @@ export class Parser { if (nextToken.type === TokenType.Dedent) { if ((nextToken as DedentToken).isDedentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), nextToken); } indent--; @@ -1490,13 +1490,13 @@ export class Parser { const possibleIndent = this._peekToken(); if (!this._consumeTokenIfType(TokenType.Indent)) { - this._addError(Localizer.Diagnostic.expectedIndentedBlock(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIndentedBlock(), this._peekToken()); return suite; } const bodyIndentToken = possibleIndent as IndentToken; if (bodyIndentToken.isIndentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), bodyIndentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), bodyIndentToken); } while (true) { @@ -1506,18 +1506,18 @@ export class Parser { this._getNextToken(); const indentToken = nextToken as IndentToken; if (indentToken.isIndentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), indentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), indentToken); } else { - this._addError(Localizer.Diagnostic.unexpectedIndent(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.unexpectedIndent(), nextToken); } } else if (nextToken.type === TokenType.Dedent) { // When we see a dedent, stop before parsing the dedented statement. const dedentToken = nextToken as DedentToken; if (!dedentToken.matchesIndent) { - this._addError(Localizer.Diagnostic.inconsistentIndent(), dedentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentIndent(), dedentToken); } if (dedentToken.isDedentAmbiguous) { - this._addError(Localizer.Diagnostic.inconsistentTabs(), dedentToken); + this._addSyntaxError(Localizer.Diagnostic.inconsistentTabs(), dedentToken); } // When the suite is incomplete (no statements), leave the dedent token for @@ -1611,7 +1611,7 @@ export class Parser { let sawStar = false; seqExpr.expressions.forEach((expr) => { if (expr.nodeType === ParseNodeType.Unpack && !sawStar) { - this._addError(Localizer.Diagnostic.unpackOperatorNotAllowed(), expr); + this._addSyntaxError(Localizer.Diagnostic.unpackOperatorNotAllowed(), expr); sawStar = true; } }); @@ -1652,9 +1652,9 @@ export class Parser { } if (target.nodeType === ParseNodeType.Unpack) { - this._addError(Localizer.Diagnostic.unpackIllegalInComprehension(), target); + this._addSyntaxError(Localizer.Diagnostic.unpackIllegalInComprehension(), target); } else if (target.nodeType === ParseNodeType.DictionaryExpandEntry) { - this._addError(Localizer.Diagnostic.dictExpandIllegalInComprehension(), target); + this._addSyntaxError(Localizer.Diagnostic.dictExpandIllegalInComprehension(), target); } const listCompNode = ListComprehensionNode.create(target, isGenerator); @@ -1786,7 +1786,7 @@ export class Parser { let isExceptGroup = false; if (this._consumeTokenIfOperator(OperatorType.Multiply)) { if (this._getLanguageVersion() < PythonVersion.V3_11 && !this._parseOptions.isStubFile) { - this._addError(Localizer.Diagnostic.exceptionGroupIncompatible(), possibleStarToken); + this._addSyntaxError(Localizer.Diagnostic.exceptionGroupIncompatible(), possibleStarToken); } isExceptGroup = true; } @@ -1799,13 +1799,13 @@ export class Parser { if (this._consumeTokenIfKeyword(KeywordType.As)) { symbolName = this._getTokenIfIdentifier(); if (!symbolName) { - this._addError(Localizer.Diagnostic.expectedNameAfterAs(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedNameAfterAs(), this._peekToken()); } } else { // Handle the python 2.x syntax in a graceful manner. const peekToken = this._peekToken(); if (this._consumeTokenIfType(TokenType.Comma)) { - this._addError(Localizer.Diagnostic.expectedAsAfterException(), peekToken); + this._addSyntaxError(Localizer.Diagnostic.expectedAsAfterException(), peekToken); // Parse the expression expected in python 2.x, but discard it. this._parseTestExpression(/* allowAssignmentExpression */ false); @@ -1815,12 +1815,12 @@ export class Parser { if (!typeExpr) { if (sawCatchAllExcept) { - this._addError(Localizer.Diagnostic.duplicateCatchAll(), exceptToken); + this._addSyntaxError(Localizer.Diagnostic.duplicateCatchAll(), exceptToken); } sawCatchAllExcept = true; } else { if (sawCatchAllExcept) { - this._addError(Localizer.Diagnostic.namedExceptAfterCatchAll(), typeExpr); + this._addSyntaxError(Localizer.Diagnostic.namedExceptAfterCatchAll(), typeExpr); } } @@ -1857,7 +1857,7 @@ export class Parser { } if (!tryNode.finallySuite && tryNode.exceptClauses.length === 0) { - this._addError(Localizer.Diagnostic.tryWithoutExcept(), tryToken); + this._addSyntaxError(Localizer.Diagnostic.tryWithoutExcept(), tryToken); } return tryNode; @@ -1870,7 +1870,7 @@ export class Parser { const nameToken = this._getTokenIfIdentifier(); if (!nameToken) { - this._addError(Localizer.Diagnostic.expectedFunctionName(), defToken); + this._addSyntaxError(Localizer.Diagnostic.expectedFunctionName(), defToken); return ErrorNode.create( defToken, ErrorExpressionCategory.MissingFunctionParameterList, @@ -1885,12 +1885,12 @@ export class Parser { typeParameters = this._parseTypeParameterList(); if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_12) { - this._addError(Localizer.Diagnostic.functionTypeParametersIllegal(), typeParameters); + this._addSyntaxError(Localizer.Diagnostic.functionTypeParametersIllegal(), typeParameters); } } const openParenToken = this._peekToken(); if (!this._consumeTokenIfType(TokenType.OpenParenthesis)) { - this._addError(Localizer.Diagnostic.expectedOpenParen(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedOpenParen(), this._peekToken()); return ErrorNode.create( nameToken, ErrorExpressionCategory.MissingFunctionParameterList, @@ -1902,7 +1902,7 @@ export class Parser { const paramList = this._parseVarArgsList(TokenType.CloseParenthesis, /* allowAnnotations */ true); if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); this._consumeTokensUntilType([TokenType.Colon]); } @@ -1992,24 +1992,24 @@ export class Parser { if (param.name) { const name = param.name.value; if (paramMap.has(name)) { - this._addError(Localizer.Diagnostic.duplicateParam().format({ name }), param.name); + this._addSyntaxError(Localizer.Diagnostic.duplicateParam().format({ name }), param.name); } else { paramMap.set(name, name); } } else if (param.category === ParameterCategory.Simple) { if (paramList.length === 0) { - this._addError(Localizer.Diagnostic.positionOnlyFirstParam(), param); + this._addSyntaxError(Localizer.Diagnostic.positionOnlyFirstParam(), param); } } if (param.category === ParameterCategory.Simple) { if (!param.name) { if (sawPositionOnlySeparator) { - this._addError(Localizer.Diagnostic.duplicatePositionOnly(), param); + this._addSyntaxError(Localizer.Diagnostic.duplicatePositionOnly(), param); } else if (sawKeywordOnlySeparator) { - this._addError(Localizer.Diagnostic.positionOnlyAfterKeywordOnly(), param); + this._addSyntaxError(Localizer.Diagnostic.positionOnlyAfterKeywordOnly(), param); } else if (sawArgs) { - this._addError(Localizer.Diagnostic.positionOnlyAfterArgs(), param); + this._addSyntaxError(Localizer.Diagnostic.positionOnlyAfterArgs(), param); } sawPositionOnlySeparator = true; } else { @@ -2022,7 +2022,7 @@ export class Parser { } else if (sawDefaultParam && !sawKeywordOnlySeparator && !sawArgs) { // Report this error only once. if (!reportedNonDefaultParamErr) { - this._addError(Localizer.Diagnostic.nonDefaultAfterDefault(), param); + this._addSyntaxError(Localizer.Diagnostic.nonDefaultAfterDefault(), param); reportedNonDefaultParamErr = true; } } @@ -2034,14 +2034,14 @@ export class Parser { if (param.category === ParameterCategory.ArgsList) { if (!param.name) { if (sawKeywordOnlySeparator) { - this._addError(Localizer.Diagnostic.duplicateKeywordOnly(), param); + this._addSyntaxError(Localizer.Diagnostic.duplicateKeywordOnly(), param); } else if (sawArgs) { - this._addError(Localizer.Diagnostic.keywordOnlyAfterArgs(), param); + this._addSyntaxError(Localizer.Diagnostic.keywordOnlyAfterArgs(), param); } sawKeywordOnlySeparator = true; } else { if (sawKeywordOnlySeparator || sawArgs) { - this._addError(Localizer.Diagnostic.duplicateArgsParam(), param); + this._addSyntaxError(Localizer.Diagnostic.duplicateArgsParam(), param); } sawArgs = true; } @@ -2049,16 +2049,16 @@ export class Parser { if (param.category === ParameterCategory.KwargsDict) { if (sawKwArgs) { - this._addError(Localizer.Diagnostic.duplicateKwargsParam(), param); + this._addSyntaxError(Localizer.Diagnostic.duplicateKwargsParam(), param); } sawKwArgs = true; // A **kwargs cannot immediately follow a keyword-only separator ("*"). if (sawKeywordOnlySeparator && !sawKeywordOnlyParamAfterSeparator) { - this._addError(Localizer.Diagnostic.keywordParameterMissing(), param); + this._addSyntaxError(Localizer.Diagnostic.keywordParameterMissing(), param); } } else if (sawKwArgs) { - this._addError(Localizer.Diagnostic.paramAfterKwargsParam(), param); + this._addSyntaxError(Localizer.Diagnostic.paramAfterKwargsParam(), param); } const foundComma = this._consumeTokenIfType(TokenType.Comma); @@ -2081,7 +2081,7 @@ export class Parser { if (paramList.length > 0) { const lastParam = paramList[paramList.length - 1]; if (lastParam.category === ParameterCategory.ArgsList && !lastParam.name) { - this._addError(Localizer.Diagnostic.expectedNamedParameter(), lastParam); + this._addSyntaxError(Localizer.Diagnostic.expectedNamedParameter(), lastParam); } } @@ -2099,7 +2099,7 @@ export class Parser { starCount = 2; } else if (this._consumeTokenIfOperator(OperatorType.Divide)) { if (this._getLanguageVersion() < PythonVersion.V3_8 && !this._parseOptions.isStubFile) { - this._addError(Localizer.Diagnostic.positionOnlyIncompatible(), firstToken); + this._addSyntaxError(Localizer.Diagnostic.positionOnlyIncompatible(), firstToken); } slashCount = 1; } @@ -2120,9 +2120,9 @@ export class Parser { if (this._consumeTokensUntilType([TokenType.CloseParenthesis])) { this._getNextToken(); } - this._addError(Localizer.Diagnostic.sublistParamsIncompatible(), sublistStart); + this._addSyntaxError(Localizer.Diagnostic.sublistParamsIncompatible(), sublistStart); } else { - this._addError(Localizer.Diagnostic.expectedParamName(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedParamName(), this._peekToken()); } } @@ -2151,7 +2151,7 @@ export class Parser { extendRange(paramNode, paramNode.defaultValue); if (starCount > 0) { - this._addError(Localizer.Diagnostic.defaultValueNotAllowed(), paramNode.defaultValue); + this._addSyntaxError(Localizer.Diagnostic.defaultValueNotAllowed(), paramNode.defaultValue); } } @@ -2203,7 +2203,7 @@ export class Parser { if (isParenthesizedWithItemList) { this._consumeTokenIfType(TokenType.OpenParenthesis); if (this._getLanguageVersion() < PythonVersion.V3_9) { - this._addError(Localizer.Diagnostic.parenthesizedContextManagerIllegal(), possibleParen); + this._addSyntaxError(Localizer.Diagnostic.parenthesizedContextManagerIllegal(), possibleParen); } } @@ -2221,7 +2221,7 @@ export class Parser { if (isParenthesizedWithItemList) { if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), possibleParen); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), possibleParen); } } @@ -2284,7 +2284,7 @@ export class Parser { this._getNextToken(); if (this._peekKeywordType() !== KeywordType.Def) { - this._addError(Localizer.Diagnostic.expectedFunctionAfterAsync(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedFunctionAfterAsync(), this._peekToken()); } else { return this._parseFunctionDef(nextToken, decoratorList); } @@ -2295,7 +2295,7 @@ export class Parser { } } - this._addError(Localizer.Diagnostic.expectedAfterDecorator(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedAfterDecorator(), this._peekToken()); // Return a dummy class declaration so the completion provider has // some parse nodes to work with. @@ -2323,14 +2323,14 @@ export class Parser { } if (!isSupportedExpressionForm) { - this._addError(Localizer.Diagnostic.expectedDecoratorExpr(), expression); + this._addSyntaxError(Localizer.Diagnostic.expectedDecoratorExpr(), expression); } } const decoratorNode = DecoratorNode.create(atOperator, expression); if (!this._consumeTokenIfType(TokenType.NewLine)) { - this._addError(Localizer.Diagnostic.expectedDecoratorNewline(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedDecoratorNewline(), this._peekToken()); this._consumeTokensUntilType([TokenType.NewLine]); } @@ -2353,7 +2353,7 @@ export class Parser { let nameToken = this._getTokenIfIdentifier(); if (!nameToken) { - this._addError(Localizer.Diagnostic.expectedClassName(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedClassName(), this._peekToken()); nameToken = IdentifierToken.create(0, 0, '', /* comments */ undefined); } @@ -2363,7 +2363,7 @@ export class Parser { typeParameters = this._parseTypeParameterList(); if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_12) { - this._addError(Localizer.Diagnostic.classTypeParametersIllegal(), typeParameters); + this._addSyntaxError(Localizer.Diagnostic.classTypeParametersIllegal(), typeParameters); } } @@ -2373,7 +2373,7 @@ export class Parser { argList = this._parseArgList().args; if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); } } @@ -2406,7 +2406,7 @@ export class Parser { const breakToken = this._getKeywordToken(KeywordType.Break); if (!this._isInLoop) { - this._addError(Localizer.Diagnostic.breakOutsideLoop(), breakToken); + this._addSyntaxError(Localizer.Diagnostic.breakOutsideLoop(), breakToken); } return BreakNode.create(breakToken); @@ -2416,9 +2416,9 @@ export class Parser { const continueToken = this._getKeywordToken(KeywordType.Continue); if (!this._isInLoop) { - this._addError(Localizer.Diagnostic.continueOutsideLoop(), continueToken); + this._addSyntaxError(Localizer.Diagnostic.continueOutsideLoop(), continueToken); } else if (this._isInFinally) { - this._addError(Localizer.Diagnostic.continueInFinally(), continueToken); + this._addSyntaxError(Localizer.Diagnostic.continueInFinally(), continueToken); } return ContinueNode.create(continueToken); @@ -2431,7 +2431,7 @@ export class Parser { const returnNode = ReturnNode.create(returnToken); if (!this._isInFunction) { - this._addError(Localizer.Diagnostic.returnOutsideFunction(), returnToken); + this._addSyntaxError(Localizer.Diagnostic.returnOutsideFunction(), returnToken); } if (!this._isNextTokenNeverExpression()) { @@ -2467,7 +2467,7 @@ export class Parser { const possibleInputToken = this._peekToken(); if (!this._consumeTokenIfKeyword(KeywordType.Import)) { - this._addError(Localizer.Diagnostic.expectedImport(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedImport(), this._peekToken()); if (!modName.hasTrailingDot) { importFromNode.missingImportKeyword = true; } @@ -2499,7 +2499,7 @@ export class Parser { if (this._consumeTokenIfKeyword(KeywordType.As)) { const aliasName = this._getTokenIfIdentifier(); if (!aliasName) { - this._addError(Localizer.Diagnostic.expectedImportAlias(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedImportAlias(), this._peekToken()); } else { importFromAsNode.alias = NameNode.create(aliasName); importFromAsNode.alias.parent = importFromAsNode; @@ -2524,7 +2524,7 @@ export class Parser { } if (importFromNode.imports.length === 0) { - this._addError(Localizer.Diagnostic.expectedImportSymbols(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedImportSymbols(), this._peekToken()); } if (inParen) { @@ -2532,12 +2532,12 @@ export class Parser { const nextToken = this._peekToken(); if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); } else { extendRange(importFromNode, nextToken); } } else if (trailingCommaToken) { - this._addError(Localizer.Diagnostic.trailingCommaInFromImport(), trailingCommaToken); + this._addSyntaxError(Localizer.Diagnostic.trailingCommaInFromImport(), trailingCommaToken); } } } @@ -2596,12 +2596,12 @@ export class Parser { importAsNode.alias.parent = importAsNode; extendRange(importAsNode, importAsNode.alias); } else { - this._addError(Localizer.Diagnostic.expectedImportAlias(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedImportAlias(), this._peekToken()); } } if (importAsNode.module.leadingDots > 0) { - this._addError(Localizer.Diagnostic.relativeImportNotAllowed(), importAsNode.module); + this._addSyntaxError(Localizer.Diagnostic.relativeImportNotAllowed(), importAsNode.module); } importNode.list.push(importAsNode); @@ -2676,7 +2676,7 @@ export class Parser { const identifier = this._getTokenIfIdentifier(); if (!identifier) { if (!allowJustDots || moduleNameNode.leadingDots === 0 || moduleNameNode.nameParts.length > 0) { - this._addError(Localizer.Diagnostic.expectedModuleName(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedModuleName(), this._peekToken()); moduleNameNode.hasTrailingDot = true; } break; @@ -2733,7 +2733,7 @@ export class Parser { while (true) { const name = this._getTokenIfIdentifier(); if (!name) { - this._addError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedIdentifier(), this._peekToken()); break; } @@ -2804,7 +2804,7 @@ export class Parser { const exprListResult = this._parseExpressionList(/* allowStar */ true); if (!exprListResult.parseError && exprListResult.list.length === 0) { - this._addError(Localizer.Diagnostic.expectedDelExpr(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedDelExpr(), this._peekToken()); } const delNode = DelNode.create(delToken); delNode.expressions = exprListResult.list; @@ -2825,7 +2825,7 @@ export class Parser { const nextToken = this._peekToken(); if (this._consumeTokenIfKeyword(KeywordType.From)) { if (this._getLanguageVersion() < PythonVersion.V3_3) { - this._addError(Localizer.Diagnostic.yieldFromIllegal(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.yieldFromIllegal(), nextToken); } return YieldFromNode.create(yieldToken, this._parseTestExpression(/* allowAssignmentExpression */ false)); } @@ -2865,7 +2865,7 @@ export class Parser { const firstCharCode = text.charCodeAt(0); // Remove any non-printable characters. - this._addError( + this._addSyntaxError( Localizer.Diagnostic.invalidTokenChars().format({ text: `\\u${firstCharCode.toString(16)}` }), invalidToken ); @@ -2896,7 +2896,7 @@ export class Parser { } if (!this._consumeTokenIfType(TokenType.NewLine)) { - this._addError(Localizer.Diagnostic.expectedNewlineOrSemicolon(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedNewlineOrSemicolon(), this._peekToken()); } return statement; @@ -2981,7 +2981,7 @@ export class Parser { // that's surrounded by parens. if (exprListResult.list.length === 1 && !exprListResult.trailingComma) { if (exprListResult.list[0].nodeType === ParseNodeType.Unpack) { - this._addError(Localizer.Diagnostic.unpackOperatorNotAllowed(), exprListResult.list[0]); + this._addSyntaxError(Localizer.Diagnostic.unpackOperatorNotAllowed(), exprListResult.list[0]); } return exprListResult.list[0]; } @@ -3010,7 +3010,7 @@ export class Parser { errorToken: Token ): ExpressionNode { if (this._isNextTokenNeverExpression()) { - this._addError(getErrorString(), errorToken); + this._addSyntaxError(getErrorString(), errorToken); return ErrorNode.create(errorToken, errorCategory); } @@ -3075,7 +3075,7 @@ export class Parser { for (const expr of exprListResult.list) { if (expr.nodeType === ParseNodeType.Unpack) { if (sawStar) { - this._addError(Localizer.Diagnostic.duplicateUnpack(), expr); + this._addSyntaxError(Localizer.Diagnostic.duplicateUnpack(), expr); break; } sawStar = true; @@ -3161,11 +3161,11 @@ export class Parser { } if (!this._assignmentExpressionsAllowed || disallowAssignmentExpression) { - this._addError(Localizer.Diagnostic.walrusNotAllowed(), walrusToken); + this._addSyntaxError(Localizer.Diagnostic.walrusNotAllowed(), walrusToken); } if (this._getLanguageVersion() < PythonVersion.V3_8) { - this._addError(Localizer.Diagnostic.walrusIllegal(), walrusToken); + this._addSyntaxError(Localizer.Diagnostic.walrusIllegal(), walrusToken); } const rightExpr = this._parseTestExpression(/* allowAssignmentExpression */ false); @@ -3237,7 +3237,7 @@ export class Parser { if (Tokenizer.isOperatorComparison(this._peekOperatorType())) { comparisonOperator = this._peekOperatorType(); if (comparisonOperator === OperatorType.LessOrGreaterThan) { - this._addError(Localizer.Diagnostic.operatorLessOrGreaterDeprecated(), peekToken); + this._addSyntaxError(Localizer.Diagnostic.operatorLessOrGreaterDeprecated(), peekToken); comparisonOperator = OperatorType.NotEquals; } this._getNextToken(); @@ -3458,7 +3458,7 @@ export class Parser { if (this._peekKeywordType() === KeywordType.Await) { awaitToken = this._getKeywordToken(KeywordType.Await); if (this._getLanguageVersion() < PythonVersion.V3_5) { - this._addError(Localizer.Diagnostic.awaitIllegal(), awaitToken); + this._addSyntaxError(Localizer.Diagnostic.awaitIllegal(), awaitToken); } } @@ -3484,7 +3484,10 @@ export class Parser { argListResult.args.forEach((arg) => { if (arg.valueExpression.nodeType === ParseNodeType.ListComprehension) { if (!arg.valueExpression.isParenthesized) { - this._addError(Localizer.Diagnostic.generatorNotParenthesized(), arg.valueExpression); + this._addSyntaxError( + Localizer.Diagnostic.generatorNotParenthesized(), + arg.valueExpression + ); } } }); @@ -3493,7 +3496,7 @@ export class Parser { const nextToken = this._peekToken(); let isArgListTerminated = false; if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), startOfTrailerToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), startOfTrailerToken); // Consume the remainder of tokens on the line for error // recovery. @@ -3513,7 +3516,7 @@ export class Parser { if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) { atomExpression = ErrorNode.create(atomExpression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); } // If the argument list wasn't terminated, break out of the loop @@ -3566,7 +3569,7 @@ export class Parser { if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) { atomExpression = ErrorNode.create(atomExpression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); } } else if (this._consumeTokenIfType(TokenType.Dot)) { // Is it a member access? @@ -3584,7 +3587,7 @@ export class Parser { if (atomExpression.maxChildDepth !== undefined && atomExpression.maxChildDepth >= maxChildNodeDepth) { atomExpression = ErrorNode.create(atomExpression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), atomExpression); } } else { break; @@ -3631,7 +3634,7 @@ export class Parser { if (nameExpr.nodeType === ParseNodeType.Name) { nameIdentifier = nameExpr.token; } else { - this._addError(Localizer.Diagnostic.expectedParamName(), nameExpr); + this._addSyntaxError(Localizer.Diagnostic.expectedParamName(), nameExpr); } } else if ( valueExpr.nodeType === ParseNodeType.Name && @@ -3642,7 +3645,7 @@ export class Parser { // Python 3.10 and newer allow assignment expressions to be used inside of a subscript. if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_10) { - this._addError(Localizer.Diagnostic.assignmentExprInSubscript(), valueExpr); + this._addSyntaxError(Localizer.Diagnostic.assignmentExprInSubscript(), valueExpr); } } } @@ -3656,12 +3659,12 @@ export class Parser { if (argNode.name) { sawKeywordArg = true; } else if (sawKeywordArg && argNode.argumentCategory === ArgumentCategory.Simple) { - this._addError(Localizer.Diagnostic.positionArgAfterNamedArg(), argNode); + this._addSyntaxError(Localizer.Diagnostic.positionArgAfterNamedArg(), argNode); } argList.push(argNode); if (argNode.name) { - this._addError(Localizer.Diagnostic.keywordSubscriptIllegal(), argNode.name); + this._addSyntaxError(Localizer.Diagnostic.keywordSubscriptIllegal(), argNode.name); } if (argType !== ArgumentCategory.Simple) { @@ -3671,11 +3674,11 @@ export class Parser { this._getLanguageVersion() >= PythonVersion.V3_11; if (argType === ArgumentCategory.UnpackedList && !unpackListAllowed) { - this._addError(Localizer.Diagnostic.unpackedSubscriptIllegal(), argNode); + this._addSyntaxError(Localizer.Diagnostic.unpackedSubscriptIllegal(), argNode); } if (argType === ArgumentCategory.UnpackedDictionary) { - this._addError(Localizer.Diagnostic.unpackedDictSubscriptIllegal(), argNode); + this._addSyntaxError(Localizer.Diagnostic.unpackedDictSubscriptIllegal(), argNode); } } @@ -3784,7 +3787,7 @@ export class Parser { if (arg.name) { sawKeywordArg = true; } else if (sawKeywordArg && arg.argumentCategory === ArgumentCategory.Simple) { - this._addError(Localizer.Diagnostic.positionArgAfterNamedArg(), arg); + this._addSyntaxError(Localizer.Diagnostic.positionArgAfterNamedArg(), arg); } argList.push(arg); @@ -3823,7 +3826,7 @@ export class Parser { if (nameExpr.nodeType === ParseNodeType.Name) { nameIdentifier = nameExpr.token; } else { - this._addError(Localizer.Diagnostic.expectedParamName(), nameExpr); + this._addSyntaxError(Localizer.Diagnostic.expectedParamName(), nameExpr); } } else { const listComp = this._tryParseListComprehension(valueExpr, /* isGenerator */ true); @@ -3871,7 +3874,7 @@ export class Parser { // Atoms with backticks are no longer allowed in Python 3.x, but they // were a thing in Python 2.x. We'll parse them to improve parse recovery // and emit an error. - this._addError(Localizer.Diagnostic.backticksIllegal(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.backticksIllegal(), nextToken); const expressionNode = this._parseTestListAsExpression(ErrorExpressionCategory.MissingExpression, () => Localizer.Diagnostic.expectedExpr() @@ -3946,7 +3949,7 @@ export class Parser { childNode?: ExpressionNode, additionalStopTokens?: TokenType[] ): ErrorNode { - this._addError(errorMsg, targetToken ?? this._peekToken()); + this._addSyntaxError(errorMsg, targetToken ?? this._peekToken()); const stopTokens = [TokenType.NewLine]; if (additionalStopTokens) { @@ -3972,7 +3975,7 @@ export class Parser { const argList = this._parseVarArgsList(TokenType.Colon, /* allowAnnotations */ false); if (!this._consumeTokenIfType(TokenType.Colon)) { - this._addError(Localizer.Diagnostic.expectedColon(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedColon(), this._peekToken()); } let testExpr: ExpressionNode; @@ -4138,11 +4141,11 @@ export class Parser { if (keyExpression && valueExpression) { if (keyExpression.nodeType === ParseNodeType.Unpack) { - this._addError(Localizer.Diagnostic.unpackInDict(), keyExpression); + this._addSyntaxError(Localizer.Diagnostic.unpackInDict(), keyExpression); } if (isSet) { - this._addError(Localizer.Diagnostic.keyValueInSet(), valueExpression); + this._addSyntaxError(Localizer.Diagnostic.keyValueInSet(), valueExpression); } else { const keyEntryNode = DictionaryKeyEntryNode.create(keyExpression, valueExpression); let dictEntry: DictionaryEntryNode = keyEntryNode; @@ -4152,7 +4155,7 @@ export class Parser { sawListComprehension = true; if (!isFirstEntry) { - this._addError(Localizer.Diagnostic.comprehensionInDict(), dictEntry); + this._addSyntaxError(Localizer.Diagnostic.comprehensionInDict(), dictEntry); } } dictionaryEntries.push(dictEntry); @@ -4160,7 +4163,7 @@ export class Parser { } } else if (doubleStarExpression) { if (isSet) { - this._addError(Localizer.Diagnostic.unpackInSet(), doubleStarExpression); + this._addSyntaxError(Localizer.Diagnostic.unpackInSet(), doubleStarExpression); } else { const listEntryNode = DictionaryExpandEntryNode.create(doubleStarExpression); extendRange(listEntryNode, doubleStar); @@ -4171,7 +4174,7 @@ export class Parser { sawListComprehension = true; if (!isFirstEntry) { - this._addError(Localizer.Diagnostic.comprehensionInDict(), doubleStarExpression); + this._addSyntaxError(Localizer.Diagnostic.comprehensionInDict(), doubleStarExpression); } } dictionaryEntries.push(expandEntryNode); @@ -4187,7 +4190,7 @@ export class Parser { ); const keyEntryNode = DictionaryKeyEntryNode.create(keyExpression, missingValueErrorNode); dictionaryEntries.push(keyEntryNode); - this._addError(Localizer.Diagnostic.dictKeyValuePairs(), keyExpression); + this._addSyntaxError(Localizer.Diagnostic.dictKeyValuePairs(), keyExpression); } else { const listComp = this._tryParseListComprehension(keyExpression, /* isGenerator */ false); if (listComp) { @@ -4195,7 +4198,7 @@ export class Parser { sawListComprehension = true; if (!isFirstEntry) { - this._addError(Localizer.Diagnostic.comprehensionInSet(), keyExpression); + this._addSyntaxError(Localizer.Diagnostic.comprehensionInSet(), keyExpression); } } setEntries.push(keyExpression); @@ -4220,7 +4223,7 @@ export class Parser { let closeCurlyBrace: Token | undefined = this._peekToken(); if (!this._consumeTokenIfType(TokenType.CloseCurlyBrace)) { - this._addError(Localizer.Diagnostic.expectedCloseBrace(), startBrace); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseBrace(), startBrace); closeCurlyBrace = undefined; } @@ -4325,7 +4328,7 @@ export class Parser { leftExpr = TypeAnnotationNode.create(leftExpr, annotationExpr); if (!this._parseOptions.isStubFile && this._getLanguageVersion() < PythonVersion.V3_6) { - this._addError(Localizer.Diagnostic.varAnnotationIllegal(), annotationExpr); + this._addSyntaxError(Localizer.Diagnostic.varAnnotationIllegal(), annotationExpr); } if (!this._consumeTokenIfOperator(OperatorType.Assign)) { @@ -4440,7 +4443,7 @@ export class Parser { private _parseFunctionTypeAnnotation(): FunctionAnnotationNode | undefined { const openParenToken = this._peekToken(); if (!this._consumeTokenIfType(TokenType.OpenParenthesis)) { - this._addError(Localizer.Diagnostic.expectedOpenParen(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedOpenParen(), this._peekToken()); return undefined; } @@ -4470,12 +4473,12 @@ export class Parser { } if (!this._consumeTokenIfType(TokenType.CloseParenthesis)) { - this._addError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); + this._addSyntaxError(Localizer.Diagnostic.expectedCloseParen(), openParenToken); this._consumeTokensUntilType([TokenType.Colon]); } if (!this._consumeTokenIfType(TokenType.Arrow)) { - this._addError(Localizer.Diagnostic.expectedArrow(), this._peekToken()); + this._addSyntaxError(Localizer.Diagnostic.expectedArrow(), this._peekToken()); return undefined; } @@ -4506,7 +4509,7 @@ export class Parser { !this._isParsingQuotedText && this._getLanguageVersion() < PythonVersion.V3_11 ) { - this._addError(Localizer.Diagnostic.unpackedSubscriptIllegal(), startToken); + this._addSyntaxError(Localizer.Diagnostic.unpackedSubscriptIllegal(), startToken); } let result = this._parseTestExpression(/* allowAssignmentExpression */ false); @@ -4524,24 +4527,24 @@ export class Parser { unescapedResult?: StringTokenUtils.UnescapedString ) { if (stringToken.flags & StringTokenFlags.Unterminated) { - this._addError(Localizer.Diagnostic.stringUnterminated(), stringToken); + this._addSyntaxError(Localizer.Diagnostic.stringUnterminated(), stringToken); } if (unescapedResult?.nonAsciiInBytes) { - this._addError(Localizer.Diagnostic.stringNonAsciiBytes(), stringToken); + this._addSyntaxError(Localizer.Diagnostic.stringNonAsciiBytes(), stringToken); } if (stringToken.flags & StringTokenFlags.Format) { if (this._getLanguageVersion() < PythonVersion.V3_6) { - this._addError(Localizer.Diagnostic.formatStringIllegal(), stringToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringIllegal(), stringToken); } if (stringToken.flags & StringTokenFlags.Bytes) { - this._addError(Localizer.Diagnostic.formatStringBytes(), stringToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringBytes(), stringToken); } if (stringToken.flags & StringTokenFlags.Unicode) { - this._addError(Localizer.Diagnostic.formatStringUnicode(), stringToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringUnicode(), stringToken); } } } @@ -4613,7 +4616,7 @@ export class Parser { ); parseResults.diagnostics.forEach((diag) => { - this._addError(diag.message, stringListNode); + this._addSyntaxError(diag.message, stringListNode); }); if (!parseResults.parseTree) { @@ -4639,7 +4642,7 @@ export class Parser { ); parseResults.diagnostics.forEach((diag) => { - this._addError(diag.message, stringListNode); + this._addSyntaxError(diag.message, stringListNode); }); if (!parseResults.parseTree || parseResults.parseTree.nodeType !== ParseNodeType.FunctionAnnotation) { @@ -4688,7 +4691,7 @@ export class Parser { ) { // This feature requires Python 3.8 or newer. if (this._parseOptions.pythonVersion < PythonVersion.V3_8) { - this._addError(Localizer.Diagnostic.formatStringDebuggingIllegal(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringDebuggingIllegal(), nextToken); } this._getNextToken(); @@ -4701,7 +4704,7 @@ export class Parser { nextToken = this._peekToken(); if (nextToken.type !== TokenType.Identifier) { - this._addError(Localizer.Diagnostic.formatStringExpectedConversion(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringExpectedConversion(), nextToken); } else { this._getNextToken(); nextToken = this._peekToken(); @@ -4715,7 +4718,7 @@ export class Parser { } if (nextToken.type !== TokenType.CloseCurlyBrace) { - this._addError(Localizer.Diagnostic.formatStringUnterminated(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringUnterminated(), nextToken); return false; } else { this._getNextToken(); @@ -4747,7 +4750,7 @@ export class Parser { // The Python interpreter reports an error at the point where the // nesting level exceeds 1. Don't report the error again for deeper nestings. if (nestingDepth === 2) { - this._addError(Localizer.Diagnostic.formatStringNestedFormatSpecifier(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.formatStringNestedFormatSpecifier(), nextToken); } this._parseFStringReplacementField(fieldExpressions, middleTokens, formatExpressions, nestingDepth + 1); @@ -4772,7 +4775,7 @@ export class Parser { endToken = nextToken as FStringEndToken; if ((endToken.flags & StringTokenFlags.Unterminated) !== 0) { - this._addError(Localizer.Diagnostic.stringUnterminated(), startToken); + this._addSyntaxError(Localizer.Diagnostic.stringUnterminated(), startToken); } this._getNextToken(); break; @@ -4802,7 +4805,7 @@ export class Parser { this._getNextToken(); } - this._addError( + this._addSyntaxError( nextToken.type === TokenType.CloseCurlyBrace ? Localizer.Diagnostic.formatStringBrace() : Localizer.Diagnostic.stringUnterminated(), @@ -4827,12 +4830,12 @@ export class Parser { // or type evaluator. if (leftExpression.maxChildDepth !== undefined && leftExpression.maxChildDepth >= maxChildNodeDepth) { leftExpression = ErrorNode.create(leftExpression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), leftExpression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), leftExpression); } if (rightExpression.maxChildDepth !== undefined && rightExpression.maxChildDepth >= maxChildNodeDepth) { rightExpression = ErrorNode.create(rightExpression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), rightExpression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), rightExpression); } return BinaryOperationNode.create(leftExpression, rightExpression, operatorToken, operator); @@ -4844,7 +4847,7 @@ export class Parser { // or type evaluator. if (expression.maxChildDepth !== undefined && expression.maxChildDepth >= maxChildNodeDepth) { expression = ErrorNode.create(expression, ErrorExpressionCategory.MaxDepthExceeded); - this._addError(Localizer.Diagnostic.maxParseDepthExceeded(), expression); + this._addSyntaxError(Localizer.Diagnostic.maxParseDepthExceeded(), expression); } return UnaryOperationNode.create(operatorToken, expression, operator); @@ -4872,11 +4875,11 @@ export class Parser { // parse errors that span strings. if (stringNode.strings.length > 1) { if (this._isParsingQuotedText) { - this._addError(Localizer.Diagnostic.annotationSpansStrings(), stringNode); + this._addSyntaxError(Localizer.Diagnostic.annotationSpansStrings(), stringNode); } } else if (stringNode.strings[0].nodeType === ParseNodeType.FormatString) { if (this._isParsingQuotedText) { - this._addError(Localizer.Diagnostic.annotationFormatString(), stringNode); + this._addSyntaxError(Localizer.Diagnostic.annotationFormatString(), stringNode); } } else { const stringToken = stringNode.strings[0].token; @@ -4889,7 +4892,7 @@ export class Parser { // error ranges back to the escaped text. if (unescapedString.length !== stringToken.length - prefixLength - stringToken.quoteMarkLength) { if (this._isParsingQuotedText) { - this._addError(Localizer.Diagnostic.annotationStringEscape(), stringNode); + this._addSyntaxError(Localizer.Diagnostic.annotationStringEscape(), stringNode); } } else { const parser = new Parser(); @@ -4908,7 +4911,7 @@ export class Parser { this._parseOptions.reportErrorsForParsedStringContents ) { parseResults.diagnostics.forEach((diag) => { - this._addError(diag.message, stringNode); + this._addSyntaxError(diag.message, stringNode); }); if (parseResults.parseTree) { @@ -4942,7 +4945,7 @@ export class Parser { for (const expr of possibleTupleExpr.expressions) { if (expr.nodeType === ParseNodeType.Unpack) { - this._addError(Localizer.Diagnostic.unpackTuplesIllegal(), expr); + this._addSyntaxError(Localizer.Diagnostic.unpackTuplesIllegal(), expr); return; } } @@ -5069,7 +5072,7 @@ export class Parser { // If the next token is invalid, treat it as an identifier. if (nextToken.type === TokenType.Invalid) { this._getNextToken(); - this._addError(Localizer.Diagnostic.invalidIdentifierChar(), nextToken); + this._addSyntaxError(Localizer.Diagnostic.invalidIdentifierChar(), nextToken); return IdentifierToken.create(nextToken.start, nextToken.length, '', nextToken.comments); } @@ -5155,7 +5158,7 @@ export class Parser { } } - private _addError(message: string, range: TextRange) { + private _addSyntaxError(message: string, range: TextRange) { assert(range !== undefined); if (!this._areErrorsSuppressed) {