// Copyright 2014 The Bazel Authors. 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.devtools.build.buildjar;

import com.google.devtools.build.buildjar.javac.BlazeJavacResult;
import com.google.devtools.build.buildjar.javac.FormattedDiagnostic;
import com.google.devtools.build.buildjar.javac.JavacRunner;
import java.io.IOException;
import java.util.regex.Pattern;

/**
 * A variant of SimpleJavaLibraryBuilder that attempts to reduce the compile-time classpath right
 * before invoking the compiler, based on extra information from provided .jdeps files. This mode is
 * enabled via the --reduce_classpath flag, only when Blaze runs with --experimental_java_classpath.
 *
 * <p>A fall-back mechanism detects whether javac fails because the classpath is incorrectly
 * discarding required entries, and re-attempts to compile with the full classpath.
 */
public class ReducedClasspathJavaLibraryBuilder extends SimpleJavaLibraryBuilder {

  /**
   * Attempts to minimize the compile-time classpath before invoking javac, falling back to a
   * regular compile.
   *
   * @param build A JavaLibraryBuildRequest request object describing what to compile
   * @throws IOException clean-up up the output directory fails
   */
  @Override
  BlazeJavacResult compileSources(JavaLibraryBuildRequest build, JavacRunner javacRunner)
      throws IOException {
    // Minimize classpath, but only if we're actually compiling some sources (some invocations of
    // JavaBuilder are only building resource jars).
    String compressedClasspath = build.getClassPath();
    if (!build.getSourceFiles().isEmpty()) {
      compressedClasspath =
          build.getDependencyModule().computeStrictClasspath(build.getClassPath());
    }
    if (compressedClasspath.isEmpty()) {
      // If the empty classpath is specified and javac is invoked programatically,
      // javac falls back to using the host classpath. We don't want JavaBuilder
      // to leak onto the compilation classpath, so we add the (hopefully empty)
      // class output directory to prevent that from happening.
      compressedClasspath = build.getClassDir();
    }

    // Compile!
    BlazeJavacResult result =
        javacRunner.invokeJavac(build.toBlazeJavacArguments(compressedClasspath));

    // If javac errored out because of missing entries on the classpath, give it another try.
    // TODO(bazel-team): check performance impact of additional retries.
    if (shouldFallBack(result)) {
      // TODO(cushon): warn for transitive classpath fallback

      // Reset output directories
      prepareSourceCompilation(build);

      // Fall back to the regular compile, but add extra checks to catch transitive uses
      result = javacRunner.invokeJavac(build.toBlazeJavacArguments(build.getClassPath()));
    }
    return result;
  }

  private static boolean shouldFallBack(BlazeJavacResult result) {
    if (result.javacResult().isOK()) {
      return false;
    }
    for (FormattedDiagnostic diagnostic : result.diagnostics()) {
      if (hasRecognizedError(diagnostic.getFormatted())) {
        return true;
      }
    }
    if (result.output().contains("com.sun.tools.javac.code.Symbol$CompletionFailure")) {
      return true;
    }
    return false;
  }

  private static final Pattern MISSING_PACKAGE =
      Pattern.compile("error: package ([\\p{javaJavaIdentifierPart}\\.]+) does not exist");

  private static boolean hasRecognizedError(String output) {
    // TODO(cushon): usage diagnostic codes instead
    return output.contains("error: cannot access")
        || output.contains("error: cannot find symbol")
        || MISSING_PACKAGE.matcher(output).find()
        // TODO(cushon): -Xdoclint:reference is probably a bad idea
        || output.contains("error: reference not found");
  }
}

@@ -881,40 +881,8 @@
 ion;
-%0Aimport java.util.regex.Pattern;
 %0A%0A/*
@@ -3524,185 +3524,222 @@
     
-if (hasRecognizedError(diagnostic.getFormatted())) %7B%0A        return true;%0A      %7D
+System.err.println(diagnostic.getCode());%0A      String code = diagnostic.getCode();%0A      if (code.contains(%22doesnt.exist%22)
 %0A    
-%7D%0A
     
-if (result.output().contains(%22com.sun.tools.javac.code.Symbol$CompletionFailure
+  %7C%7C code.contains(%22cant.resolve%22)%0A          %7C%7C code.contains(%22cant.access
 %22)) %7B%0A
+  
     
@@ -3761,356 +3761,275 @@
     
+  
 %7D%0A    
-return false;%0A  %7D%0A%0A  private static final Pattern MISSING_PACKAGE =%0A      Pattern.compile(%22error: package (%5B%5C%5Cp%7BjavaJavaIdentifierPart%7D%5C%5C.%5D+) does not exist%22);%0A%0A  private static boolean hasRecognizedError(String output) %7B%0A    // TODO(cushon): usage diagnostic codes instead%0A    return output.contains(%22error: cannot access%22)%0A        %7C%7C 
+  // handle -Xdoclint:reference errors, which don't have a diagnostic code%0A      // TODO(cushon): this is locale-dependent%0A      if (diagnostic.getFormatted().contains(%22error: reference not found%22)) %7B%0A        return true;%0A      %7D%0A    %7D%0A    if (result.
 output
+()
 .con
@@ -4039,210 +4039,104 @@
 ns(%22
-error: cannot find symbol%22)%0A        %7C%7C MISSING_PACKAGE.matcher(output).find()%0A        // TODO(cushon): -Xdoclint:reference is probably a bad idea
+com.sun.tools.javac.code.Symbol$CompletionFailure%22)) %7B%0A      return true;
 %0A    
+%7D%0A
     
-%7C%7C output.contains(%22error: reference not found%22)
+return false
 ;%0A  

Make reduced classpath fallback locale-independent