|
| 1 | +/* |
| 2 | + * SonarQube Python Plugin |
| 3 | + * Copyright (C) 2011-2024 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 GNU Lesser General Public |
| 8 | + * License as published by the Free Software Foundation; either |
| 9 | + * version 3 of the License, or (at your option) any later version. |
| 10 | + * |
| 11 | + * This program is distributed in the hope that it will be useful, |
| 12 | + * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 13 | + * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU |
| 14 | + * Lesser General Public License for more details. |
| 15 | + * |
| 16 | + * You should have received a copy of the GNU Lesser General Public License |
| 17 | + * along with this program; if not, write to the Free Software Foundation, |
| 18 | + * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 19 | + */ |
| 20 | +package org.sonar.python.checks; |
| 21 | + |
| 22 | +import java.util.HashMap; |
| 23 | +import java.util.Map; |
| 24 | +import java.util.Optional; |
| 25 | +import java.util.Set; |
| 26 | +import java.util.stream.Stream; |
| 27 | +import org.sonar.check.Rule; |
| 28 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 29 | +import org.sonar.plugins.python.api.SubscriptionContext; |
| 30 | +import org.sonar.plugins.python.api.quickfix.PythonQuickFix; |
| 31 | +import org.sonar.plugins.python.api.symbols.ClassSymbol; |
| 32 | +import org.sonar.plugins.python.api.tree.AssignmentStatement; |
| 33 | +import org.sonar.plugins.python.api.tree.BaseTreeVisitor; |
| 34 | +import org.sonar.plugins.python.api.tree.ClassDef; |
| 35 | +import org.sonar.plugins.python.api.tree.QualifiedExpression; |
| 36 | +import org.sonar.plugins.python.api.tree.Tree; |
| 37 | +import org.sonar.plugins.python.api.tree.Tuple; |
| 38 | +import org.sonar.python.quickfix.TextEditUtils; |
| 39 | +import org.sonar.python.tree.FunctionDefImpl; |
| 40 | +import org.sonar.python.tree.TreeUtils; |
| 41 | + |
| 42 | +@Rule(key = "S6974") |
| 43 | +public class SkLearnEstimatorDontInitializeEstimatedValuesCheck extends PythonSubscriptionCheck { |
| 44 | + |
| 45 | + private static final String BASE_ESTIMATOR_FULLY_QUALIFIED_NAME = "sklearn.base.BaseEstimator"; |
| 46 | + private static final Set<String> MIXINS_FULLY_QUALIFIED_NAME = Set.of( |
| 47 | + "sklearn.base.BiclusterMixin", |
| 48 | + "sklearn.base.ClassifierMixin", |
| 49 | + "sklearn.base.ClusterMixin", |
| 50 | + "sklearn.base.DensityMixin", |
| 51 | + "sklearn.base.MetaEstimatorMixin", |
| 52 | + "sklearn.base.OneToOneFeatureMixin", |
| 53 | + "sklearn.base.OutlierMixin", |
| 54 | + "sklearn.base.RegressorMixin", |
| 55 | + "sklearn.base.TransformerMixin"); |
| 56 | + |
| 57 | + private static final String MESSAGE = "Move this estimated attribute in the `fit` method."; |
| 58 | + private static final String MESSAGE_SECONDARY = "The attribute is used in this estimator"; |
| 59 | + public static final String QUICK_FIX_MESSAGE = "Remove the statement"; |
| 60 | + public static final String QUICK_FIX_RENAME_MESSAGE = "Remove all trailing underscores from the variable name"; |
| 61 | + |
| 62 | + @Override |
| 63 | + public void initialize(Context context) { |
| 64 | + context.registerSyntaxNodeConsumer(Tree.Kind.FUNCDEF, SkLearnEstimatorDontInitializeEstimatedValuesCheck::checkFunction); |
| 65 | + } |
| 66 | + |
| 67 | + private static boolean inheritsMixin(ClassSymbol classSymbol) { |
| 68 | + return MIXINS_FULLY_QUALIFIED_NAME.stream().anyMatch(classSymbol::isOrExtends); |
| 69 | + } |
| 70 | + |
| 71 | + private static void checkFunction(SubscriptionContext subscriptionContext) { |
| 72 | + FunctionDefImpl functionDef = (FunctionDefImpl) subscriptionContext.syntaxNode(); |
| 73 | + if (!"__init__".equals(functionDef.name().name())) { |
| 74 | + return; |
| 75 | + } |
| 76 | + |
| 77 | + var classDef = (ClassDef) TreeUtils.firstAncestorOfKind(functionDef, Tree.Kind.CLASSDEF); |
| 78 | + if (classDef == null) { |
| 79 | + return; |
| 80 | + } |
| 81 | + var classSymbol = TreeUtils.getClassSymbolFromDef(classDef); |
| 82 | + if (classSymbol == null) { |
| 83 | + return; |
| 84 | + } |
| 85 | + boolean inheritsBaseEstimator = Optional.of(classSymbol) |
| 86 | + .map(classSymbol1 -> classSymbol1.isOrExtends(BASE_ESTIMATOR_FULLY_QUALIFIED_NAME)) |
| 87 | + .orElse(false); |
| 88 | + |
| 89 | + if (!inheritsBaseEstimator && !inheritsMixin(classSymbol)) { |
| 90 | + return; |
| 91 | + } |
| 92 | + |
| 93 | + var visitor = new VariableDeclarationEndingWithUnderscoreVisitor(); |
| 94 | + functionDef.body().accept(visitor); |
| 95 | + var offendingVariables = visitor.qualifiedExpressions; |
| 96 | + var secondaryLocation = classDef.name(); |
| 97 | + offendingVariables |
| 98 | + .forEach((qualifiedExpression, assignmentStatement) -> { |
| 99 | + var issue = subscriptionContext.addIssue(qualifiedExpression.name(), MESSAGE).secondary(secondaryLocation, MESSAGE_SECONDARY); |
| 100 | + |
| 101 | + createQuickFix(assignmentStatement).ifPresent(issue::addQuickFix); |
| 102 | + issue.addQuickFix(createQuickFixRename(qualifiedExpression)); |
| 103 | + }); |
| 104 | + } |
| 105 | + |
| 106 | + private static PythonQuickFix createQuickFixRename(QualifiedExpression qualifiedExpression) { |
| 107 | + var quickFix = PythonQuickFix.newQuickFix(QUICK_FIX_RENAME_MESSAGE); |
| 108 | + var newName = qualifiedExpression.name().name().replaceAll("_+$", ""); |
| 109 | + return quickFix.addTextEdit(TextEditUtils.renameAllUsages(qualifiedExpression.name(), newName)).build(); |
| 110 | + } |
| 111 | + |
| 112 | + private static Optional<PythonQuickFix> createQuickFix(AssignmentStatement assignmentStatement) { |
| 113 | + |
| 114 | + var builder = PythonQuickFix.newQuickFix(QUICK_FIX_MESSAGE); |
| 115 | + |
| 116 | + if (assignmentStatement.lhsExpressions().size() != 1 || assignmentStatement.lhsExpressions().stream().anyMatch(expressions -> expressions.expressions().size() != 1)) { |
| 117 | + return Optional.empty(); |
| 118 | + } |
| 119 | + builder.addTextEdit(TextEditUtils.removeStatement(assignmentStatement)); |
| 120 | + if (assignmentStatement.assignedValue().is(Tree.Kind.NONE)) { |
| 121 | + return Optional.of(builder.build()); |
| 122 | + } |
| 123 | + return Optional.empty(); |
| 124 | + } |
| 125 | + |
| 126 | + private static class VariableDeclarationEndingWithUnderscoreVisitor extends BaseTreeVisitor { |
| 127 | + |
| 128 | + private final Map<QualifiedExpression, AssignmentStatement> qualifiedExpressions = new HashMap<>(); |
| 129 | + |
| 130 | + private static boolean isOffendingQualifiedExpression(QualifiedExpression qualifiedExpression) { |
| 131 | + return !qualifiedExpression.name().name().startsWith("__") && qualifiedExpression.name().name().endsWith("_") && qualifiedExpression.qualifier().is(Tree.Kind.NAME) |
| 132 | + && "self".equals(((org.sonar.plugins.python.api.tree.Name) qualifiedExpression.qualifier()).name()); |
| 133 | + } |
| 134 | + |
| 135 | + @Override |
| 136 | + public void visitAssignmentStatement(AssignmentStatement pyAssignmentStatementTree) { |
| 137 | + var offendingQualifiedExpressions = pyAssignmentStatementTree.lhsExpressions() |
| 138 | + .stream() |
| 139 | + .flatMap(expressionList -> expressionList.expressions().stream()) |
| 140 | + .filter(expression -> expression.is(Tree.Kind.QUALIFIED_EXPR)) |
| 141 | + .map(QualifiedExpression.class::cast); |
| 142 | + |
| 143 | + var offendingTuples = pyAssignmentStatementTree.lhsExpressions() |
| 144 | + .stream() |
| 145 | + .flatMap(expressionList -> expressionList.expressions().stream()) |
| 146 | + .filter(expression -> expression.is(Tree.Kind.TUPLE)) |
| 147 | + .map(Tuple.class::cast) |
| 148 | + .flatMap(tuple -> tuple.elements().stream()) |
| 149 | + .filter(expression -> expression.is(Tree.Kind.QUALIFIED_EXPR)) |
| 150 | + .map(QualifiedExpression.class::cast); |
| 151 | + |
| 152 | + Stream.concat( |
| 153 | + offendingQualifiedExpressions, offendingTuples) |
| 154 | + .filter(VariableDeclarationEndingWithUnderscoreVisitor::isOffendingQualifiedExpression) |
| 155 | + .forEach(qualifiedExpression -> qualifiedExpressions.put(qualifiedExpression, pyAssignmentStatementTree)); |
| 156 | + super.visitAssignmentStatement(pyAssignmentStatementTree); |
| 157 | + } |
| 158 | + } |
| 159 | +} |
0 commit comments