|
| 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.Map; |
| 23 | +import java.util.Optional; |
| 24 | +import java.util.Set; |
| 25 | +import java.util.function.Predicate; |
| 26 | +import javax.annotation.Nullable; |
| 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.symbols.FunctionSymbol; |
| 31 | +import org.sonar.plugins.python.api.symbols.Symbol; |
| 32 | +import org.sonar.plugins.python.api.symbols.Symbol.Kind; |
| 33 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 34 | +import org.sonar.plugins.python.api.tree.Expression; |
| 35 | +import org.sonar.plugins.python.api.tree.Name; |
| 36 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 37 | +import org.sonar.plugins.python.api.tree.Tree; |
| 38 | +import org.sonar.python.cfg.fixpoint.ReachingDefinitionsAnalysis; |
| 39 | +import org.sonar.python.semantic.ClassSymbolImpl; |
| 40 | +import org.sonar.python.semantic.SymbolUtils; |
| 41 | +import org.sonar.python.tree.TreeUtils; |
| 42 | + |
| 43 | +@Rule(key = "S6709") |
| 44 | +public class RandomSeedCheck extends PythonSubscriptionCheck { |
| 45 | + |
| 46 | + private static final String NUMPY_SEED_ARG_NAME = "seed"; |
| 47 | + |
| 48 | + private static final Map<String, String> SEED_METHODS_TO_CHECK = Map.of( |
| 49 | + "numpy.seed", NUMPY_SEED_ARG_NAME, |
| 50 | + "numpy.random.seed", NUMPY_SEED_ARG_NAME, |
| 51 | + "numpy.random.default_rng", NUMPY_SEED_ARG_NAME, |
| 52 | + "numpy.random.SeedSequence", "entropy", |
| 53 | + "numpy.random.PCG64", NUMPY_SEED_ARG_NAME, |
| 54 | + "numpy.random.PCG64DXSM", NUMPY_SEED_ARG_NAME, |
| 55 | + "numpy.random.MT19937", NUMPY_SEED_ARG_NAME, |
| 56 | + "numpy.random.SFC64", NUMPY_SEED_ARG_NAME, |
| 57 | + "numpy.random.Philox", NUMPY_SEED_ARG_NAME); |
| 58 | + |
| 59 | + private static final String SKLEARN_FQN = "sklearn"; |
| 60 | + private static final String SKLEARN_ARG_NAME = "random_state"; |
| 61 | + |
| 62 | + private static final String MESSAGE = "Provide a seed for this random generator."; |
| 63 | + private static final String SKLEARN_MESSAGE = "Provide a seed for the random_state parameter."; |
| 64 | + |
| 65 | + private ReachingDefinitionsAnalysis reachingDefinitionsAnalysis; |
| 66 | + |
| 67 | + @Override |
| 68 | + public void initialize(Context context) { |
| 69 | + context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, |
| 70 | + ctx -> this.reachingDefinitionsAnalysis = new ReachingDefinitionsAnalysis(ctx.pythonFile())); |
| 71 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, this::checkEmptySeedCall); |
| 72 | + } |
| 73 | + |
| 74 | + private void checkEmptySeedCall(SubscriptionContext ctx) { |
| 75 | + CallExpression call = (CallExpression) ctx.syntaxNode(); |
| 76 | + |
| 77 | + Optional<Symbol> maybeCalleeSymbol = Optional.ofNullable(call.calleeSymbol()); |
| 78 | + |
| 79 | + maybeCalleeSymbol |
| 80 | + .map(Symbol::fullyQualifiedName) |
| 81 | + .map(SEED_METHODS_TO_CHECK::get) |
| 82 | + .filter(argName -> isArgumentAbsentOrNone(TreeUtils.nthArgumentOrKeyword(0, argName, call.arguments()))) |
| 83 | + .map(arg -> MESSAGE) |
| 84 | + .or(() -> maybeCalleeSymbol |
| 85 | + .filter(symbol -> symbol.fullyQualifiedName() != null && symbol.fullyQualifiedName().startsWith(SKLEARN_FQN)) |
| 86 | + .filter(RandomSeedCheck::hasRandomStateParameter) |
| 87 | + .filter(symbol -> isArgumentAbsentOrNone(TreeUtils.argumentByKeyword(SKLEARN_ARG_NAME, call.arguments()))) |
| 88 | + .map(symbol -> SKLEARN_MESSAGE)) |
| 89 | + .ifPresent(message -> ctx.addIssue(call.callee(), message)); |
| 90 | + } |
| 91 | + |
| 92 | + private static boolean hasRandomStateParameter(Symbol calleeSymbol) { |
| 93 | + return isClassInstantiationWithRandomStateParameter(calleeSymbol) |
| 94 | + .or(() -> isFunctionWithRandomStateParameter(calleeSymbol)) |
| 95 | + .orElse(false); |
| 96 | + } |
| 97 | + |
| 98 | + private static Optional<Boolean> isClassInstantiationWithRandomStateParameter(Symbol calleeSymbol) { |
| 99 | + return Optional.of(calleeSymbol) |
| 100 | + .filter(s -> s.is(Kind.CLASS)) |
| 101 | + .map(ClassSymbolImpl.class::cast) |
| 102 | + .map(classSymbol -> classSymbol.declaredMembers() |
| 103 | + .stream() |
| 104 | + .filter(member -> "__init__".equals(member.name())) |
| 105 | + .toList()) |
| 106 | + .filter(members -> members.size() == 1) |
| 107 | + .map(members -> members.get(0)) |
| 108 | + .map(RandomSeedCheck::hasRandomStateParameter); |
| 109 | + } |
| 110 | + |
| 111 | + private static Optional<Boolean> isFunctionWithRandomStateParameter(Symbol calleeSymbol) { |
| 112 | + return Optional.of(calleeSymbol) |
| 113 | + .filter(s1 -> s1.is(Kind.FUNCTION)) |
| 114 | + .map(SymbolUtils::getFunctionSymbols) |
| 115 | + .filter(symbols -> symbols.size() == 1) |
| 116 | + .map(symbols -> symbols.get(0)) |
| 117 | + .map(symbol -> symbol.parameters() |
| 118 | + .stream() |
| 119 | + .map(FunctionSymbol.Parameter::name) |
| 120 | + .anyMatch(SKLEARN_ARG_NAME::equals)); |
| 121 | + } |
| 122 | + |
| 123 | + private boolean isArgumentAbsentOrNone(@Nullable RegularArgument arg) { |
| 124 | + return arg == null || arg.expression().is(Tree.Kind.NONE) || isAssignedNone(arg.expression()); |
| 125 | + } |
| 126 | + |
| 127 | + private boolean isAssignedNone(Expression exp) { |
| 128 | + return Optional.of(exp) |
| 129 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(Name.class)) |
| 130 | + .map(reachingDefinitionsAnalysis::valuesAtLocation) |
| 131 | + .filter(Predicate.not(Set::isEmpty)) |
| 132 | + .filter(values -> values.stream().allMatch(value -> value.is(Tree.Kind.NONE))).isPresent(); |
| 133 | + } |
| 134 | +} |
0 commit comments