enum ConflictCategory {
  CLASS_NOT_FOUND,
  METHOD_SIGNATURE_NOT_FOUND,
  FIELD_NOT_FOUND
} @AutoMatter
public interface AccessedField {

  ClassTypeDescriptor owner();

  TypeDescriptor descriptor();

  String name();

  int lineNumber();

  /** List of exception classes that protect this method call * */
  List<ClassTypeDescriptor> caughtExceptions();

  default String pretty() {
    return descriptor().toString() + " " + owner().toString() + "." + name();
  }
} @AutoMatter
public interface Artifact {

  /** "Name" of artifact, for example a directory path or jar file or something else symbolic. */
  ArtifactName name();

  /** Map of classname to class object. Names are com/foo/bar/Baz. Returned map is immutable. */
  Map<ClassTypeDescriptor, DeclaredClass> classes();
} public class ArtifactName {
  private final String name;

  public ArtifactName(String name) {
    this.name = name;
  }

  public String name() {
    return name;
  }

  @Override
  public String toString() {
    return "ArtifactName:" + name;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ArtifactName that = (ArtifactName) o;

    return name.equals(that.name);
  }

  @Override
  public int hashCode() {
    return name.hashCode();
  }
} @AutoMatter
public interface CalledMethod {

  /** Owning class of method being called */
  ClassTypeDescriptor owner();

  MethodDescriptor descriptor();

  boolean isStatic();

  int lineNumber();

  /** List of exception classes that protect this method call * */
  List<ClassTypeDescriptor> caughtExceptions();

  default String pretty() {
    return owner().toString() + "." + descriptor().prettyWithoutReturnType();
  }
} public class ClassTypeDescriptor implements TypeDescriptor {

  private final String className;

  ClassTypeDescriptor(String className) {
    this.className = Objects.requireNonNull(className).replace('/', '.');
    if (className.endsWith(";")) {
      throw new InputMismatchException(
          "Got a signature where a class name was expected: " + className);
    }
  }

  public String getClassName() {
    return className;
  }

  @Override
  public String toString() {
    return className;
  }

  @Override
  public boolean equals(Object o) {
    if (this == o) {
      return true;
    }
    if (o == null || getClass() != o.getClass()) {
      return false;
    }

    ClassTypeDescriptor that = (ClassTypeDescriptor) o;

    if (!className.equals(that.className)) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode() {
    return className.hashCode();
  }
} @AutoMatter
public interface DeclaredClass {

  // names are com/foo/bar/Baz
  ClassTypeDescriptor className();

  // parent are class names: com/foo/bar/Baz
  Set<ClassTypeDescriptor> parents();
  // also includes other classes that are loaded by this class, even though
  // no methods on those classes are explicitly called
  Set<ClassTypeDescriptor> loadedClasses();

  Map<MethodDescriptor, DeclaredMethod> methods();

  Set<DeclaredField> fields();
} @AutoMatter
/** Represents field in a class */
public interface DeclaredField {
  String name();

  TypeDescriptor descriptor();
} @AutoMatter
// TODO: rename to something better - ImplementedMethod ? DefinedMethod ?
/** Represents methods in a class */
public interface DeclaredMethod {
  MethodDescriptor descriptor();

  boolean isStatic();

  int lineNumber();

  /** Calls that this method makes to other methods */
  Set<CalledMethod> methodCalls();

  Set<AccessedField> fieldAccesses();
} public interface Dependency {

  ClassTypeDescriptor fromClass();

  MethodDescriptor fromMethod();

  int fromLineNumber();

  ClassTypeDescriptor targetClass();

  String describe();
} @AutoMatter
public interface MethodDescriptor {

  TypeDescriptor returnType();

  String name();

  List<TypeDescriptor> parameterTypes();

  // TODO: add modifiers

  default String pretty() {
    return returnType().toString() + " " + name() + prettyParameters();
  }

  default String prettyWithoutReturnType() {
    return name() + prettyParameters();
  }

  default String prettyParameters() {
    StringJoiner joiner = new StringJoiner(", ", "(", ")");

    parameterTypes().stream().map(TypeDescriptor::toString).forEach(joiner::add);

    return joiner.toString();
  }
} public interface TypeDescriptor {}
import static java.util.stream.Collectors.toList;
import com.spotify.missinglink.Conflict.ConflictCategory;
import com.spotify.missinglink.datamodel.AccessedField;
import com.spotify.missinglink.datamodel.Artifact;
import com.spotify.missinglink.datamodel.ArtifactName;
import com.spotify.missinglink.datamodel.CalledMethod;
import com.spotify.missinglink.datamodel.ClassTypeDescriptor;
import com.spotify.missinglink.datamodel.DeclaredClass;
import com.spotify.missinglink.datamodel.DeclaredField;
import com.spotify.missinglink.datamodel.DeclaredFieldBuilder;
import com.spotify.missinglink.datamodel.DeclaredMethod;
import com.spotify.missinglink.datamodel.Dependency;
import com.spotify.missinglink.datamodel.FieldDependencyBuilder;
import com.spotify.missinglink.datamodel.MethodDependencyBuilder;
import com.spotify.missinglink.datamodel.MethodDescriptor;
import com.spotify.missinglink.datamodel.TypeDescriptor;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Set;
/*-
 * -\-\-
 * missinglink-core
 * --
 * Copyright (C) 2016 - 2021 Spotify AB
 * --
 * 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.
 * -/-/-
 */

/*
 * Copyright (c) 2015 Spotify AB
 *
 * 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.spotify.missinglink;



/**
 * Inputs:
 *
 * <p>1) The full set of artifact dependencies (D). This can be extracted from the dependency graph.
 * The exact structure of the graph is not interesting, only knowing which dependencies are a part
 * of it. Note that this means that the same library can appear multiple times (with different
 * versions) 2) The classpath of artifacts that is actually used (C). Ordering is important here. If
 * a class appears more than once, the first occurrence will be used.
 *
 * <p>Assumptions:
 *
 * <p>1) Each artifact could be compiled successfully using their own dependencies. 2) Each artifact
 * was compiled against the same JDK, or at the very least only using parts of the JDK that didn't
 * change compatibility. This is not a fully safe assumption, but to catch the kind of problems that
 * could occur due to this would need a more broad analysis.
 *
 * <p>Strategy: 1) Identify which classes are a part of D but does not exist in C. This is the
 * missing set (M) 2) Identify which classes are a part of D but are replaced in D (or is not the
 * first occurrence) This is the suspicious set (S) 3) Walk through the class hierarchy graph. If
 * something depends on something in M, also add that class to M. If something depends on something
 * in S, also add that class to S 4) Walk through the method call graph, starting from the main
 * entry point (the primary artifact) Whenever a method call is reached, check if the class and
 * method exists. If it doesn't exist, also look in parent classes (implementations could exist both
 * in superclasses and interfaces).
 *
 * <p>Note that we only need to try to verify the method if it's made to a class that is in M or S.
 * If it is in M: fail. If it is in S: check it.
 *
 * <p>If we don't have access to one of the parents, we could simply assume that the call is safe
 * This would however lead to all methods being marked as safe, since everything ultimately inherits
 * from Object (or some other jdk class).
 *
 * <p>The alternative is to mark such calls as failures, which may lead to false positives. This
 * might be ok for the MVP.
 *
 * <p>So we need to have the JDK classes (or some other provided dependencies) as input in order to
 * lookup inheritance.
 *
 * <p>
 *
 * <p>
 *
 * <p>For now, this is not really in place - we simply just look at all the things in the classpath
 */
public class ConflictChecker {

  public static final ArtifactName UNKNOWN_ARTIFACT_NAME = new ArtifactName("<unknown>");

  /**
   * @param projectArtifact the main artifact of the project we're verifying (this is considered the
   *     entry point for reachability)
   * @param artifactsToCheck all artifacts that are on the runtime classpath
   * @param allArtifacts all artifacts, including implicit artifacts (runtime provided artifacts)
   * @return a list of conflicts
   */
  public List<Conflict> check(
      Artifact projectArtifact, List<Artifact> artifactsToCheck, List<Artifact> allArtifacts) {

    final CheckerStateBuilder stateBuilder = new CheckerStateBuilder();

    createCanonicalClassMapping(stateBuilder, allArtifacts);
    CheckerState state = stateBuilder.build();

    // brute-force reachability analysis
    Set<TypeDescriptor> reachableClasses =
        reachableFrom(projectArtifact.classes().values(), state.knownClasses());

    final List<Conflict> conflicts = new ArrayList<>();

    // Then go through everything in the classpath to make sure all the method calls / field
    // references
    // are satisfied.
    for (Artifact artifact : artifactsToCheck) {
      for (DeclaredClass clazz : artifact.classes().values()) {
        if (!reachableClasses.contains(clazz.className())) {
          continue;
        }

        for (DeclaredMethod method : clazz.methods().values()) {
          conflicts.addAll(checkForBrokenMethodCalls(state, artifact, clazz, method));
          conflicts.addAll(checkForBrokenFieldAccess(state, artifact, clazz, method));
        }
      }
    }
    return conflicts;
  }

  /**
   * Create a canonical mapping of which classes are kept. First come first serve in the classpath
   *
   * @param stateBuilder conflict checker state we're populating
   * @param allArtifacts maven artifacts to populate checker state with
   */
  private void createCanonicalClassMapping(
      CheckerStateBuilder stateBuilder, List<Artifact> allArtifacts) {
    for (Artifact artifact : allArtifacts) {
      for (DeclaredClass clazz : artifact.classes().values()) {
        if (stateBuilder.knownClasses().putIfAbsent(clazz.className(), clazz) == null) {
          stateBuilder.putSourceMapping(clazz.className(), artifact.name());
        }
      }
    }
  }

  private List<Conflict> checkForBrokenMethodCalls(
      CheckerState state, Artifact artifact, DeclaredClass clazz, DeclaredMethod method) {
    List<Conflict> conflicts = new ArrayList<>();

    for (CalledMethod calledMethod : method.methodCalls()) {
      final ClassTypeDescriptor owningClass = calledMethod.owner();
      final DeclaredClass calledClass = state.knownClasses().get(owningClass);

      if (calledClass == null) {
        final boolean catchesNoClassDef =
            calledMethod.caughtExceptions().stream()
                .anyMatch(c -> c.getClassName().equals("java.lang.NoClassDefFoundError"));
        if (!catchesNoClassDef) {
          conflicts.add(
              conflict(
                  ConflictCategory.CLASS_NOT_FOUND,