/*
 * Copyright 2012 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.errorprone.bugpatterns;

import static com.google.errorprone.BugPattern.Category.GUAVA;
import static com.google.errorprone.BugPattern.MaturityLevel.EXPERIMENTAL;
import static com.google.errorprone.BugPattern.SeverityLevel.ERROR;
import static com.google.errorprone.bugpatterns.BugChecker.MethodInvocationTreeMatcher;

import com.google.errorprone.BugPattern;
import com.google.errorprone.VisitorState;
import com.google.errorprone.fixes.SuggestedFix;
import com.google.errorprone.matchers.Description;
import com.google.errorprone.matchers.Matcher;
import com.google.errorprone.matchers.Matchers;
import com.sun.source.tree.ExpressionTree;
import com.sun.source.tree.LiteralTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.tools.javac.tree.JCTree.JCExpression;
import com.sun.tools.javac.util.List;

/**
 * @author Louis Wasserman
 */
@BugPattern(name = "PreconditionsTooManyArgs",
    summary = "Precondition check format string expects fewer arguments",
    explanation = "The Guava Preconditions checks expect error messages to use %s as a "
        + "placeholder, and to take the corresponding number of arguments.  This bug can indicate "
        + "an improper format string, or simply forgetting to add all the arguments.",
    category = GUAVA, maturity = EXPERIMENTAL, severity = ERROR)
public class PreconditionsTooManyArgs extends BugChecker implements MethodInvocationTreeMatcher {

  @SuppressWarnings("unchecked")
  private static final
      Matcher<MethodInvocationTree> PRECONDITIONS_CHECK = Matchers.methodSelect(
          Matchers.<ExpressionTree>anyOf(
            Matchers.staticMethod("com.google.common.base.Preconditions", "checkArgument"),
            Matchers.staticMethod("com.google.common.base.Preconditions", "checkNotNull"),
            Matchers.staticMethod("com.google.common.base.Preconditions", "checkState")));

  private static int expectedArguments(String formatString) {
    int count = 0;
    for (int i = formatString.indexOf("%s"); i != -1; i = formatString.indexOf("%s", i + 1)) {
      count++;
    }
    return count;
  }

  @Override
  public Description matchMethodInvocation(MethodInvocationTree t, VisitorState state) {
    if (PRECONDITIONS_CHECK.matches(t, state) && t.getArguments().size() >= 2
        && t.getArguments().get(1) instanceof LiteralTree) {
      LiteralTree formatStringTree = (LiteralTree) t.getArguments().get(1);
      if (formatStringTree.getValue() instanceof String) {
        String formatString = (String) formatStringTree.getValue();
        int expectedArgs = expectedArguments(formatString);
        if (expectedArgs < t.getArguments().size() - 2) {
          return describe(t, state);
        }
      }
    }
    return Description.NO_MATCH;
  }

  /**
   * Matches most {@code java.util.Formatter} and {@code java.text.MessageFormat}
   * format placeholders, other than %s itself.
   *
   * This does not need to be completely exhaustive, since it is only used to suggest fixes.
   */
  private static final String BAD_PLACEHOLDER_REGEX = "%(?:\\d+\\$)??[dbBhHScCdoxXeEfgGaAtTn]|" +
      "\\{\\d+\\}";

  public Description describe(MethodInvocationTree t, VisitorState state) {
    LiteralTree formatTree = (LiteralTree) t.getArguments().get(1);
    String formatString = (String) formatTree.getValue();

    String fixedFormatString = formatString.replaceAll(BAD_PLACEHOLDER_REGEX, "%s");
    SuggestedFix fix = new SuggestedFix();
    if (expectedArguments(fixedFormatString) == t.getArguments().size() - 2) {
      fix.replace(formatTree, "\"" + fixedFormatString + "\"");
      return describeMatch(formatTree, fix);
    } else {
      fix.replace(t, state.getTreeMaker()
          .App((JCExpression) t.getMethodSelect(), List.of((JCExpression) t.getArguments().get(0)))
          .toString());
      return describeMatch(t, fix);
    }
  }
}

@@ -1228,16 +1228,17 @@
 tchers;%0A
+%0A
 import c
@@ -1403,59 +1403,8 @@
 Tree
-.JCExpression;%0Aimport com.sun.tools.javac.util.List
 ;%0A%0A/
@@ -3625,18 +3625,29 @@
 _REGEX =
- %22
+%0A      %22%5C%5C$s%7C
 %25(?:%5C%5Cd+
@@ -3681,19 +3681,8 @@
 Tn%5D%7C
-%22 +%0A      %22
 %5C%5C%7B%5C
@@ -3831,24 +3831,25 @@
 s().get(1);%0A
+%0A
     String f
@@ -3840,32 +3840,37 @@
 );%0A%0A    String f
+ixedF
 ormatString = (S
@@ -3871,84 +3871,71 @@
 g = 
-(String) formatTree.getValue();%0A%0A    String fixedFormatString = formatString
+state.getSourceForNode((JCTree) formatTree).toString()%0A        
 .rep
@@ -4127,15 +4127,8 @@
 ree,
- %22%5C%22%22 +
  fix
@@ -4145,15 +4145,8 @@
 ring
- + %22%5C%22%22
 );%0A 
@@ -4212,154 +4212,386 @@
     
-fix.replace(t, state.getTreeMaker()%0A          .App((JCExpression) t.getMethodSelect(), List.of((JCExpression) t.getArguments().get(0)))%0A          
+int missing = t.getArguments().size() - 2 - expectedArguments(fixedFormatString);%0A      StringBuilder builder = new StringBuilder(fixedFormatString);%0A      builder.deleteCharAt(builder.length() - 1);%0A      builder.append(%22 %5B%25s%22);%0A      for (int i = 1; i %3C missing; i++) %7B%0A        builder.append(%22, %25s%22);%0A      %7D%0A      builder.append(%22%5D%5C%22%22);%0A      fix.replace(formatTree, builder
 .toS
@@ -4648,8 +4648,9 @@
 %7D%0A  %7D%0A%7D%0A
+%0A

Improve the suggested fix of PreconditionsTooManyArgs to be more behavior-preserving in the case that there aren't obvious placeholders in the format string.