|
| 1 | +/* |
| 2 | + * SonarQube Python Plugin |
| 3 | + * Copyright (C) 2011-2025 SonarSource SA |
| 4 | + * mailto:info AT sonarsource DOT com |
| 5 | + * |
| 6 | + * This program is free software; you can redistribute it and/or |
| 7 | + * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA. |
| 8 | + * |
| 9 | + * This program is distributed in the hope that it will be useful, |
| 10 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 11 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. |
| 12 | + * See the Sonar Source-Available License for more details. |
| 13 | + * |
| 14 | + * You should have received a copy of the Sonar Source-Available License |
| 15 | + * along with this program; if not, see https://sonarsource.com/license/ssal/ |
| 16 | + */ |
| 17 | + |
| 18 | +package org.sonar.python.checks; |
| 19 | + |
| 20 | +import javax.annotation.Nullable; |
| 21 | + |
| 22 | +import org.sonar.check.Rule; |
| 23 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 24 | +import org.sonar.plugins.python.api.SubscriptionContext; |
| 25 | +import org.sonar.plugins.python.api.tree.BaseTreeVisitor; |
| 26 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 27 | +import org.sonar.plugins.python.api.tree.ExceptClause; |
| 28 | +import org.sonar.plugins.python.api.tree.Expression; |
| 29 | +import org.sonar.plugins.python.api.tree.Name; |
| 30 | +import org.sonar.plugins.python.api.tree.RaiseStatement; |
| 31 | +import org.sonar.plugins.python.api.tree.ReturnStatement; |
| 32 | +import org.sonar.plugins.python.api.tree.Token; |
| 33 | +import org.sonar.plugins.python.api.tree.Tree; |
| 34 | +import org.sonar.plugins.python.api.tree.Tree.Kind; |
| 35 | +import org.sonar.plugins.python.api.tree.TryStatement; |
| 36 | +import org.sonar.python.tree.TreeUtils; |
| 37 | +import org.sonar.python.types.v2.TypeCheckMap; |
| 38 | + |
| 39 | +@Rule(key = "S7497") |
| 40 | +public class CancellationReraisedInAsyncCheck extends PythonSubscriptionCheck { |
| 41 | + |
| 42 | + private static final String MESSAGE = "Ensure that the %s exception is re-raised after your cleanup code."; |
| 43 | + |
| 44 | + private static final String ASYNCIO_CANCELLED_ERROR = "asyncio.CancelledError"; |
| 45 | + private static final String TRIO_CANCELLED = "trio.Cancelled"; |
| 46 | + private static final String ANYIO_CANCELLED = "anyio.get_cancelled_exc_class"; |
| 47 | + private static final String MESSAGE_SECONDARY = "This function is async."; |
| 48 | + |
| 49 | + private TypeCheckMap<String> cancelledExceptionTypeCheckMap; |
| 50 | + |
| 51 | + @Override |
| 52 | + public void initialize(Context context) { |
| 53 | + context.registerSyntaxNodeConsumer(Kind.FILE_INPUT, this::initializeChecksForFile); |
| 54 | + context.registerSyntaxNodeConsumer(Kind.TRY_STMT, this::checkTryStatement); |
| 55 | + } |
| 56 | + |
| 57 | + private void initializeChecksForFile(SubscriptionContext ctx) { |
| 58 | + cancelledExceptionTypeCheckMap = new TypeCheckMap<>(); |
| 59 | + cancelledExceptionTypeCheckMap.put(ctx.typeChecker().typeCheckBuilder().isTypeOrInstanceWithName(ASYNCIO_CANCELLED_ERROR), ASYNCIO_CANCELLED_ERROR); |
| 60 | + cancelledExceptionTypeCheckMap.put(ctx.typeChecker().typeCheckBuilder().isTypeWithFqn(TRIO_CANCELLED), TRIO_CANCELLED); |
| 61 | + cancelledExceptionTypeCheckMap.put(ctx.typeChecker().typeCheckBuilder().isTypeOrInstanceWithName(ANYIO_CANCELLED), "cancellation"); |
| 62 | + |
| 63 | + } |
| 64 | + |
| 65 | + private void checkTryStatement(SubscriptionContext context) { |
| 66 | + var tryStatement = (TryStatement) context.syntaxNode(); |
| 67 | + var enclosingAsyncToken = TreeUtils.asyncTokenOfEnclosingFunction(tryStatement).orElse(null); |
| 68 | + |
| 69 | + if (enclosingAsyncToken == null) { |
| 70 | + return; |
| 71 | + } |
| 72 | + |
| 73 | + tryStatement.exceptClauses().forEach(exceptClause -> checkExceptClause(context, exceptClause, enclosingAsyncToken)); |
| 74 | + } |
| 75 | + |
| 76 | + private void checkExceptClause(SubscriptionContext subscriptionContext, ExceptClause exceptClause, Token enclosingAsyncToken) { |
| 77 | + var exception = exceptClause.exception(); |
| 78 | + if (exception == null) { |
| 79 | + return; |
| 80 | + } |
| 81 | + String isOffendingException = isOffendingException(exception); |
| 82 | + if (isOffendingException.isEmpty()) { |
| 83 | + return; |
| 84 | + } |
| 85 | + |
| 86 | + var isCompliant = true; |
| 87 | + var hasTopLevelPass = exceptClause.body().statements().stream().anyMatch(s -> s.is(Kind.PASS_STMT)); |
| 88 | + if (hasTopLevelPass) { |
| 89 | + isCompliant = false; |
| 90 | + } else { |
| 91 | + var complianceChecker = new ComplianceChecker(exceptClause); |
| 92 | + exceptClause.accept(complianceChecker); |
| 93 | + isCompliant = complianceChecker.isCompliant(); |
| 94 | + } |
| 95 | + |
| 96 | + if (!isCompliant) { |
| 97 | + subscriptionContext.addIssue( |
| 98 | + exception, |
| 99 | + String.format(MESSAGE, isOffendingException)) |
| 100 | + .secondary(enclosingAsyncToken, MESSAGE_SECONDARY); |
| 101 | + } |
| 102 | + } |
| 103 | + |
| 104 | + private String isOffendingException(Expression exception) { |
| 105 | + var isOffendingTypeOpt = cancelledExceptionTypeCheckMap.getOptionalForType(exception.typeV2()); |
| 106 | + if (isOffendingTypeOpt.isPresent()) { |
| 107 | + return isOffendingTypeOpt.get(); |
| 108 | + } |
| 109 | + if (exception instanceof CallExpression callExpression) { |
| 110 | + var result = cancelledExceptionTypeCheckMap.getOptionalForType(callExpression.callee().typeV2()); |
| 111 | + if (result.isPresent()) { |
| 112 | + return result.get(); |
| 113 | + } |
| 114 | + } |
| 115 | + return ""; |
| 116 | + |
| 117 | + } |
| 118 | + |
| 119 | + private static boolean isReRaise(RaiseStatement raiseStatement, ExceptClause exceptClause) { |
| 120 | + var isBareRaise = raiseStatement.expressions().isEmpty(); |
| 121 | + var exceptionInstanceName = TreeUtils.toOptionalInstanceOf(Name.class, exceptClause.exceptionInstance()); |
| 122 | + |
| 123 | + var isReRaise = raiseStatement.expressions().size() == 1 && exceptionInstanceName.isPresent() |
| 124 | + && raiseStatement.expressions().get(0).is(Kind.NAME) |
| 125 | + && ((Name) raiseStatement.expressions().get(0)).name().equals(exceptionInstanceName.get().name()); |
| 126 | + |
| 127 | + return isBareRaise || isReRaise; |
| 128 | + } |
| 129 | + |
| 130 | + static class ComplianceChecker extends BaseTreeVisitor { |
| 131 | + private final ExceptClause exceptClause; |
| 132 | + private boolean hasRaiseStatement = false; |
| 133 | + private boolean isCompliant = true; |
| 134 | + |
| 135 | + ComplianceChecker(ExceptClause exceptClause) { |
| 136 | + this.exceptClause = exceptClause; |
| 137 | + } |
| 138 | + |
| 139 | + boolean isCompliant() { |
| 140 | + // If we never found a raise statement, it's not compliant |
| 141 | + return isCompliant && hasRaiseStatement; |
| 142 | + } |
| 143 | + |
| 144 | + @Override |
| 145 | + public void visitRaiseStatement(RaiseStatement raiseStatement) { |
| 146 | + hasRaiseStatement = true; |
| 147 | + |
| 148 | + // Check if this is a proper re-raise |
| 149 | + if (!isReRaise(raiseStatement, exceptClause)) { |
| 150 | + isCompliant = false; |
| 151 | + return; |
| 152 | + } |
| 153 | + |
| 154 | + super.visitRaiseStatement(raiseStatement); |
| 155 | + } |
| 156 | + |
| 157 | + @Override |
| 158 | + public void visitReturnStatement(ReturnStatement returnStatement) { |
| 159 | + isCompliant = false; |
| 160 | + } |
| 161 | + |
| 162 | + @Override |
| 163 | + protected void scan(@Nullable Tree tree) { |
| 164 | + if (!isCompliant) { |
| 165 | + return; |
| 166 | + } |
| 167 | + super.scan(tree); |
| 168 | + } |
| 169 | + } |
| 170 | +} |
0 commit comments