|
| 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 | +package org.sonar.python.checks; |
| 18 | + |
| 19 | +import java.util.List; |
| 20 | +import java.util.Map; |
| 21 | +import java.util.Optional; |
| 22 | +import javax.annotation.Nullable; |
| 23 | +import org.sonar.check.Rule; |
| 24 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 25 | +import org.sonar.plugins.python.api.tree.Argument; |
| 26 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 27 | +import org.sonar.plugins.python.api.tree.ComprehensionClause; |
| 28 | +import org.sonar.plugins.python.api.tree.ComprehensionExpression; |
| 29 | +import org.sonar.plugins.python.api.tree.Expression; |
| 30 | +import org.sonar.plugins.python.api.tree.Name; |
| 31 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 32 | +import org.sonar.plugins.python.api.tree.Tree; |
| 33 | +import org.sonar.plugins.python.api.tree.Tuple; |
| 34 | +import org.sonar.plugins.python.api.types.v2.PythonType; |
| 35 | +import org.sonar.plugins.python.api.types.v2.TriBool; |
| 36 | +import org.sonar.python.semantic.v2.SymbolV2; |
| 37 | +import org.sonar.python.types.v2.TypeCheckBuilder; |
| 38 | +import org.sonar.python.types.v2.TypeCheckMap; |
| 39 | + |
| 40 | +@Rule(key = "S7494") |
| 41 | +public class RewriteCollectionConstructorAsComprehensionCheck extends PythonSubscriptionCheck { |
| 42 | + |
| 43 | + private static final Map<String, String> COLLECTION_MESSAGES = Map.of( |
| 44 | + "list", "Replace list constructor call with a list comprehension.", |
| 45 | + "set", "Replace set constructor call with a set comprehension.", |
| 46 | + "dict", "Replace dict constructor call with a dictionary comprehension." |
| 47 | + ); |
| 48 | + |
| 49 | + private TypeCheckMap<String> collectionTypeCheckerMap = null; |
| 50 | + private TypeCheckBuilder dictTypeChecker = null; |
| 51 | + |
| 52 | + @Override |
| 53 | + public void initialize(Context context) { |
| 54 | + collectionTypeCheckerMap = new TypeCheckMap<>(); |
| 55 | + context.registerSyntaxNodeConsumer(Tree.Kind.FILE_INPUT, ctx -> { |
| 56 | + for (var collectionEntry : COLLECTION_MESSAGES.entrySet()) { |
| 57 | + TypeCheckBuilder typeChecker = ctx.typeChecker().typeCheckBuilder().isTypeWithFqn(collectionEntry.getKey()); |
| 58 | + collectionTypeCheckerMap.put(typeChecker, collectionEntry.getValue()); |
| 59 | + |
| 60 | + if ("dict".equals(collectionEntry.getKey())) { |
| 61 | + dictTypeChecker = typeChecker; |
| 62 | + } |
| 63 | + } |
| 64 | + }); |
| 65 | + |
| 66 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, ctx -> { |
| 67 | + CallExpression callExpression = (CallExpression) ctx.syntaxNode(); |
| 68 | + List<Argument> arguments = callExpression.arguments(); |
| 69 | + |
| 70 | + String message = getMessageForConstructor(callExpression).orElse(null); |
| 71 | + if (message == null) { |
| 72 | + return; |
| 73 | + } |
| 74 | + |
| 75 | + ComprehensionExpression generator = getSingleGeneratorArg(arguments).orElse(null); |
| 76 | + if (generator == null) { |
| 77 | + return; |
| 78 | + } |
| 79 | + |
| 80 | + if (isGeneratorTransformingData(generator, callExpression.callee().typeV2())) { |
| 81 | + ctx.addIssue(callExpression.callee(), message); |
| 82 | + } |
| 83 | + }); |
| 84 | + } |
| 85 | + |
| 86 | + private Optional<String> getMessageForConstructor(CallExpression callExpression) { |
| 87 | + return collectionTypeCheckerMap.getOptionalForType(callExpression.callee().typeV2()); |
| 88 | + } |
| 89 | + |
| 90 | + private static Optional<ComprehensionExpression> getSingleGeneratorArg(List<Argument> arguments) { |
| 91 | + if (arguments.size() != 1) { |
| 92 | + return Optional.empty(); |
| 93 | + } |
| 94 | + |
| 95 | + if (!(arguments.get(0) instanceof RegularArgument regularArg)) { |
| 96 | + return Optional.empty(); |
| 97 | + } |
| 98 | + |
| 99 | + Expression argument = regularArg.expression(); |
| 100 | + if (!argument.is(Tree.Kind.GENERATOR_EXPR)) { |
| 101 | + return Optional.empty(); |
| 102 | + } |
| 103 | + |
| 104 | + return Optional.of((ComprehensionExpression) argument); |
| 105 | + } |
| 106 | + |
| 107 | + private boolean isGeneratorTransformingData(ComprehensionExpression generator, PythonType methodType) { |
| 108 | + if (hasMultipleNestedClauses(generator.comprehensionFor())) { |
| 109 | + return true; |
| 110 | + } |
| 111 | + if (dictTypeChecker.check(methodType) == TriBool.TRUE) { |
| 112 | + return isDictTransformingData(generator); |
| 113 | + } else { |
| 114 | + return isListOrSetComprehensionTransformingData(generator); |
| 115 | + } |
| 116 | + } |
| 117 | + |
| 118 | + private static boolean hasMultipleNestedClauses(ComprehensionClause clause) { |
| 119 | + return clause.nestedClause() != null; |
| 120 | + } |
| 121 | + |
| 122 | + private static boolean isDictTransformingData(ComprehensionExpression generator) { |
| 123 | + Expression resultExpr = generator.resultExpression(); |
| 124 | + Expression loopVarExpr = generator.comprehensionFor().loopExpression(); |
| 125 | + |
| 126 | + var resultTuple = getTwoNamedTuple(resultExpr); |
| 127 | + var varTuple = getTwoNamedTuple(loopVarExpr); |
| 128 | + |
| 129 | + if (resultTuple != null && varTuple != null) { |
| 130 | + return !resultTuple.equals(varTuple); |
| 131 | + } |
| 132 | + |
| 133 | + return true; |
| 134 | + } |
| 135 | + |
| 136 | + private static TwoNamedTuple getTwoNamedTuple(Expression expr) { |
| 137 | + if (expr instanceof Tuple tuple && tuple.elements().size() == 2) { |
| 138 | + var elements = tuple.elements(); |
| 139 | + if (elements.get(0) instanceof Name name1 && elements.get(1) instanceof Name name2) { |
| 140 | + return new TwoNamedTuple(name1.symbolV2(), name2.symbolV2()); |
| 141 | + } |
| 142 | + } |
| 143 | + return null; |
| 144 | + } |
| 145 | + |
| 146 | + private record TwoNamedTuple(@Nullable SymbolV2 symbol1, @Nullable SymbolV2 symbol2) { |
| 147 | + } |
| 148 | + |
| 149 | + private static boolean isListOrSetComprehensionTransformingData(ComprehensionExpression generator) { |
| 150 | + Expression elementExpr = generator.resultExpression(); |
| 151 | + Expression loopVarExpr = generator.comprehensionFor().loopExpression(); |
| 152 | + |
| 153 | + if (elementExpr instanceof Name elementName && loopVarExpr instanceof Name loopVarName) { |
| 154 | + return elementName.symbolV2() != loopVarName.symbolV2(); |
| 155 | + } |
| 156 | + |
| 157 | + return true; |
| 158 | + } |
| 159 | +} |
0 commit comments