|
| 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.LinkedHashSet; |
| 23 | +import java.util.List; |
| 24 | +import java.util.Objects; |
| 25 | +import java.util.Optional; |
| 26 | +import java.util.Set; |
| 27 | +import java.util.regex.Matcher; |
| 28 | +import java.util.regex.Pattern; |
| 29 | +import java.util.stream.Collectors; |
| 30 | +import org.sonar.check.Rule; |
| 31 | +import org.sonar.plugins.python.api.PythonSubscriptionCheck; |
| 32 | +import org.sonar.plugins.python.api.SubscriptionContext; |
| 33 | +import org.sonar.plugins.python.api.symbols.Symbol; |
| 34 | +import org.sonar.plugins.python.api.tree.Argument; |
| 35 | +import org.sonar.plugins.python.api.tree.CallExpression; |
| 36 | +import org.sonar.plugins.python.api.tree.RegularArgument; |
| 37 | +import org.sonar.plugins.python.api.tree.StringLiteral; |
| 38 | +import org.sonar.plugins.python.api.tree.Tree; |
| 39 | +import org.sonar.python.tree.TreeUtils; |
| 40 | + |
| 41 | +@Rule(key = "S6984") |
| 42 | +public class EinopsSyntaxCheck extends PythonSubscriptionCheck { |
| 43 | + |
| 44 | + private static final String MESSAGE_TEMPLATE = "Fix the syntax of this einops operation: %s."; |
| 45 | + private static final String NESTED_PARENTHESIS_MESSAGE = "nested parenthesis are not allowed"; |
| 46 | + private static final String LHS_ELLIPSIS_MESSAGE = "Ellipsis inside parenthesis on the left side is not allowed"; |
| 47 | + private static final String UNBALANCED_PARENTHESIS_MESSAGE = "parenthesis are unbalanced"; |
| 48 | + private static final Set<String> FQN_TO_CHECK = Set.of("einops.repeat", "einops.reduce", "einops.rearrange"); |
| 49 | + private static final Pattern ellipsisPattern = Pattern.compile("\\((.*)\\)"); |
| 50 | + |
| 51 | + @Override |
| 52 | + public void initialize(Context context) { |
| 53 | + context.registerSyntaxNodeConsumer(Tree.Kind.CALL_EXPR, EinopsSyntaxCheck::checkEinopsSyntax); |
| 54 | + } |
| 55 | + |
| 56 | + private static void checkEinopsSyntax(SubscriptionContext ctx) { |
| 57 | + CallExpression callExpression = (CallExpression) ctx.syntaxNode(); |
| 58 | + Symbol calleeSymbol = callExpression.calleeSymbol(); |
| 59 | + if (calleeSymbol != null && calleeSymbol.fullyQualifiedName() != null && FQN_TO_CHECK.contains(calleeSymbol.fullyQualifiedName())) { |
| 60 | + extractPatternFromCallExpr(callExpression).ifPresent(stringLiteral -> { |
| 61 | + var maybePattern = toEinopsPattern(stringLiteral); |
| 62 | + if (maybePattern.isPresent()) { |
| 63 | + var pattern = maybePattern.get(); |
| 64 | + checkForEllipsisInParenthesis(ctx, pattern); |
| 65 | + checkForUnbalancedParenthesis(ctx, pattern); |
| 66 | + checkForUnusedParameter(ctx, callExpression.arguments(), pattern); |
| 67 | + } else { |
| 68 | + ctx.addIssue(callExpression.callee(), "Provide a valid einops pattern."); |
| 69 | + } |
| 70 | + }); |
| 71 | + } |
| 72 | + } |
| 73 | + |
| 74 | + private static void checkForUnusedParameter(SubscriptionContext ctx, List<Argument> arguments, EinopsPattern pattern) { |
| 75 | + List<String> argsToCheck = arguments.stream() |
| 76 | + .map(TreeUtils.toInstanceOfMapper(RegularArgument.class)) |
| 77 | + .filter(Objects::nonNull) |
| 78 | + .filter(arg -> arg.expression().is(Tree.Kind.NUMERIC_LITERAL)) |
| 79 | + .filter(arg -> arg.keywordArgument() != null) |
| 80 | + .map(arg -> arg.keywordArgument().name()) |
| 81 | + .filter(argName -> !pattern.lhs.identifiers.contains(argName)) |
| 82 | + .filter(argName -> !pattern.rhs.identifiers.contains(argName)) |
| 83 | + .toList(); |
| 84 | + |
| 85 | + if (!argsToCheck.isEmpty()) { |
| 86 | + var isPlural = argsToCheck.size() > 1; |
| 87 | + var missingParameters = argsToCheck.stream().collect(Collectors.joining(", ")); |
| 88 | + var missingParametersMessage = String.format("the parameter%s %s do%s not appear in the pattern", isPlural ? "s" : "", missingParameters, isPlural ? "" : "es"); |
| 89 | + ctx.addIssue(pattern.originalPattern(), String.format(MESSAGE_TEMPLATE, missingParametersMessage)); |
| 90 | + } |
| 91 | + } |
| 92 | + |
| 93 | + private static void checkForUnbalancedParenthesis(SubscriptionContext ctx, EinopsPattern pattern) { |
| 94 | + pattern.lhs.state.errorMessage.or(() -> pattern.rhs.state.errorMessage) |
| 95 | + .ifPresent(message -> ctx.addIssue(pattern.originalPattern(), String.format(MESSAGE_TEMPLATE, message))); |
| 96 | + } |
| 97 | + |
| 98 | + private static void checkForEllipsisInParenthesis(SubscriptionContext ctx, EinopsPattern pattern) { |
| 99 | + Matcher m = ellipsisPattern.matcher(pattern.lhs.originalPattern); |
| 100 | + if (m.find() && (m.group().contains("...") || m.group().contains("…"))) { |
| 101 | + ctx.addIssue(pattern.originalPattern(), String.format(MESSAGE_TEMPLATE, LHS_ELLIPSIS_MESSAGE)); |
| 102 | + } |
| 103 | + } |
| 104 | + |
| 105 | + private record EinopsPattern(StringLiteral originalPattern, EinopsSide lhs, EinopsSide rhs) { |
| 106 | + } |
| 107 | + |
| 108 | + private record EinopsSide(String originalPattern, Set<String> identifiers, ParenthesisState state) { |
| 109 | + } |
| 110 | + |
| 111 | + private record ParenthesisState(boolean hasOpenParenthesis, Optional<String> errorMessage) { |
| 112 | + } |
| 113 | + |
| 114 | + private static Optional<StringLiteral> extractPatternFromCallExpr(CallExpression callExpression) { |
| 115 | + return Optional.ofNullable(TreeUtils.nthArgumentOrKeyword(1, "pattern", callExpression.arguments())) |
| 116 | + .map(RegularArgument::expression) |
| 117 | + .flatMap(TreeUtils.toOptionalInstanceOfMapper(StringLiteral.class)); |
| 118 | + } |
| 119 | + |
| 120 | + private static Optional<EinopsPattern> toEinopsPattern(StringLiteral pattern) { |
| 121 | + String[] split = pattern.trimmedQuotesValue().split("->"); |
| 122 | + if (split.length == 2) { |
| 123 | + var lhsStr = split[0].trim(); |
| 124 | + var rhsStr = split[1].trim(); |
| 125 | + if (!lhsStr.isEmpty() && !rhsStr.isEmpty()) { |
| 126 | + var lhs = parseEinopsPattern(lhsStr); |
| 127 | + var rhs = parseEinopsPattern(rhsStr); |
| 128 | + return Optional.of(new EinopsPattern(pattern, lhs, rhs)); |
| 129 | + } |
| 130 | + } |
| 131 | + return Optional.empty(); |
| 132 | + } |
| 133 | + |
| 134 | + private static EinopsSide parseEinopsPattern(String pattern) { |
| 135 | + Set<String> identifiers = new LinkedHashSet<>(); |
| 136 | + var currentIdentifier = new StringBuilder(); |
| 137 | + ParenthesisState state = new ParenthesisState(false, Optional.empty()); |
| 138 | + for (int i = 0; i < pattern.length(); i++) { |
| 139 | + char c = pattern.charAt(i); |
| 140 | + if (c == ' ' || c == '(' || c == ')') { |
| 141 | + if (!currentIdentifier.isEmpty()) { |
| 142 | + identifiers.add(currentIdentifier.toString()); |
| 143 | + currentIdentifier.setLength(0); |
| 144 | + } |
| 145 | + state = checkParenthesisBalance(c, state); |
| 146 | + } else if (Character.isLetterOrDigit(c) || c == '_' || c == '…') { |
| 147 | + currentIdentifier.append(c); |
| 148 | + } |
| 149 | + } |
| 150 | + if (!currentIdentifier.isEmpty()) { |
| 151 | + identifiers.add(currentIdentifier.toString()); |
| 152 | + } |
| 153 | + if (state.hasOpenParenthesis && state.errorMessage.isEmpty()) { |
| 154 | + state = new ParenthesisState(true, Optional.of(UNBALANCED_PARENTHESIS_MESSAGE)); |
| 155 | + } |
| 156 | + return new EinopsSide(pattern, identifiers, state); |
| 157 | + } |
| 158 | + |
| 159 | + private static ParenthesisState checkParenthesisBalance(char c, ParenthesisState state) { |
| 160 | + Optional<String> errorMessage = state.errorMessage; |
| 161 | + if (' ' == c) { |
| 162 | + return state; |
| 163 | + } |
| 164 | + if ('(' == c && state.hasOpenParenthesis) { |
| 165 | + errorMessage = Optional.of(NESTED_PARENTHESIS_MESSAGE); |
| 166 | + } |
| 167 | + if (')' == c && !state.hasOpenParenthesis && errorMessage.isEmpty()) { |
| 168 | + errorMessage = Optional.of(UNBALANCED_PARENTHESIS_MESSAGE); |
| 169 | + } |
| 170 | + return new ParenthesisState('(' == c, errorMessage); |
| 171 | + } |
| 172 | +} |
0 commit comments