All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.sonar.java.checks.ArrayDesignatorOnVariableCheck Maven / Gradle / Ivy

The newest version!
/*
 * SonarQube Java
 * Copyright (C) 2012-2025 SonarSource SA
 * mailto:info AT sonarsource DOT com
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the Sonar Source-Available License Version 1, as published by SonarSource SA.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the Sonar Source-Available License for more details.
 *
 * You should have received a copy of the Sonar Source-Available License
 * along with this program; if not, see https://sonarsource.com/license/ssal/
 */
package org.sonar.java.checks;

import java.util.Collections;
import java.util.List;
import java.util.Optional;
import javax.annotation.Nullable;
import org.sonar.check.Rule;
import org.sonar.java.checks.helpers.QuickFixHelper;
import org.sonar.java.reporting.JavaQuickFix;
import org.sonar.java.reporting.JavaTextEdit;
import org.sonar.plugins.java.api.IssuableSubscriptionVisitor;
import org.sonar.plugins.java.api.location.Position;
import org.sonar.plugins.java.api.tree.ArrayTypeTree;
import org.sonar.plugins.java.api.tree.IdentifierTree;
import org.sonar.plugins.java.api.tree.SyntaxToken;
import org.sonar.plugins.java.api.tree.Tree;
import org.sonar.plugins.java.api.tree.TypeTree;
import org.sonar.plugins.java.api.tree.VariableTree;

@Rule(key = "S1197")
public class ArrayDesignatorOnVariableCheck extends IssuableSubscriptionVisitor {

  @Override
  public List nodesToVisit() {
    return Collections.singletonList(Tree.Kind.VARIABLE);
  }

  @Override
  public void visitNode(Tree tree) {
    VariableTree variableTree = (VariableTree) tree;
    IdentifierTree identifierTree = variableTree.simpleName();
    MisplacedArray.find(variableTree.type(), identifierTree.identifierToken())
      .ifPresent(misplaced -> QuickFixHelper.newIssue(context)
        .forRule(this)
        .onRange(identifierTree, misplaced.lastArray.closeBracketToken())
        .withMessage("Move the array designators " + misplaced.replacement + " to the type.")
        .withQuickFixes(() -> isDeclarationTypeUsedBySeveralVariable(variableTree)
          ? Collections.emptyList()
          : Collections.singletonList(createQuickFix(misplaced, "variable type")))
        .report());
  }

  static JavaQuickFix createQuickFix(MisplacedArray misplaced, String type) {
    return JavaQuickFix.newQuickFix("Move " + misplaced.replacement + " to the " + type)
      .addTextEdit(JavaTextEdit.removeBetweenTree(
        misplaced.firstArray.openBracketToken(),
        misplaced.lastArray.closeBracketToken()))
      .addTextEdit(JavaTextEdit.insertAfterTree(
        misplaced.firstArray.type(),
        misplaced.replacement))
      .build();
  }

  private static boolean isDeclarationTypeUsedBySeveralVariable(VariableTree current) {
    return QuickFixHelper.previousVariable(current).isPresent() || QuickFixHelper.nextVariable(current).isPresent();
  }

  static class MisplacedArray {
    ArrayTypeTree firstArray;
    ArrayTypeTree lastArray;
    String replacement;

    private MisplacedArray(ArrayTypeTree lastArrayType, SyntaxToken identifierToken) {
      firstArray = lastArrayType;
      lastArray = lastArrayType;
      StringBuilder replacementBuilder = new StringBuilder("[]");
      while (firstArray.type().is(Tree.Kind.ARRAY_TYPE)) {
        ArrayTypeTree previous = (ArrayTypeTree) firstArray.type();
        if (!isInvalidPosition(previous, identifierToken)) {
          break;
        }
        replacementBuilder.append("[]");
        firstArray = previous;
      }
      replacement = replacementBuilder.toString();
    }

    static Optional find(@Nullable TypeTree type, SyntaxToken identifierToken) {
      return Optional.ofNullable(type)
        .filter(t -> t.is(Tree.Kind.ARRAY_TYPE))
        .map(ArrayTypeTree.class::cast)
        .filter(arrayType -> isInvalidPosition(arrayType, identifierToken))
        .map(arrayType -> new MisplacedArray(arrayType, identifierToken));
    }

    private static boolean isInvalidPosition(ArrayTypeTree arrayTypeTree, SyntaxToken identifierToken) {
      SyntaxToken openBracketToken = arrayTypeTree.openBracketToken();
      return openBracketToken != null && Position.startOf(identifierToken).isBefore(Position.startOf(openBracketToken));
    }

  }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy