<commit_before>/*
 * Copyright 2016 The Error Prone Authors.
 *
 * 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.util;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.VisitorState;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.MemberEnter;
import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.Name;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;

/** A helper class to find all identifiers in scope at a given program point. */
public final class FindIdentifiers {

  /** Finds a variable declaration with the given name that is in scope at the current location. */
  public static Symbol findIdent(String name, VisitorState state) {
    return findIdent(name, state, KindSelector.VAR);
  }

  /** Finds a declaration with the given name and type that is in scope at the current location. */
  @Nullable
  public static Symbol findIdent(String name, VisitorState state, KindSelector kind) {
    ClassType enclosingClass = ASTHelpers.getType(getEnclosingClass(state.getPath()));
    Env<AttrContext> env;
    if (enclosingClass == null || enclosingClass.tsym == null) {
      env =
          Enter.instance(state.context)
              .getTopLevelEnv((JCCompilationUnit) state.getPath().getCompilationUnit());
    } else {
      env = Enter.instance(state.context).getClassEnv(enclosingClass.tsym);
      MethodTree enclosingMethod = state.findEnclosing(MethodTree.class);
      if (enclosingMethod != null) {
        env = MemberEnter.instance(state.context).getMethodEnv((JCMethodDecl) enclosingMethod, env);
      }
    }
    try {
      Symbol result = findIdent(name, state, kind, env);
      return result.exists() ? result : null;
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  // Signature was changed in Java 13: https://bugs.openjdk.java.net/browse/JDK-8223305
  private static Symbol findIdent(
      String name, VisitorState state, KindSelector kind, Env<AttrContext> env)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (RuntimeVersion.isAtLeast13()) {
      Method method =
          Resolve.class.getDeclaredMethod(
              "findIdent", DiagnosticPosition.class, Env.class, Name.class, KindSelector.class);
      method.setAccessible(true);
      return (Symbol)
          method.invoke(Resolve.instance(state.context), null, env, state.getName(name), kind);
    }
    Method method =
        Resolve.class.getDeclaredMethod("findIdent", Env.class, Name.class, KindSelector.class);
    method.setAccessible(true);
    return (Symbol) method.invoke(Resolve.instance(state.context), env, state.getName(name), kind);
  }

  @Nullable
  private static ClassTree getEnclosingClass(TreePath treePath) {
    while (treePath != null) {
      TreePath parent = treePath.getParentPath();
      if (parent == null) {
        return null;
      }
      Tree leaf = parent.getLeaf();
      if (leaf instanceof ClassTree
          && ((ClassTree) leaf).getMembers().contains(treePath.getLeaf())) {
        return (ClassTree) leaf;
      }
      treePath = parent;
    }
    return null;
  }

  /**
   * Finds the set of all bare variable identifiers in scope at the current location. Identifiers
   * are ordered by ascending distance/scope count from the current location to match shadowing
   * rules. That is, if two variables with the same simple names appear in the set, the one that
   * appears first in iteration order is the one you get if you use the bare name in the source
   * code.
   *<commit_msg>Short-circuit getEnclosingClass() if input is a ClassTree.<commit_after>/*
 * Copyright 2016 The Error Prone Authors.
 *
 * 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.util;

import static com.google.common.collect.ImmutableList.toImmutableList;
import static com.google.common.collect.ImmutableSet.toImmutableSet;
import static com.google.errorprone.util.ASTHelpers.isConsideredFinal;

import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.errorprone.VisitorState;
import com.sun.source.tree.BlockTree;
import com.sun.source.tree.CatchTree;
import com.sun.source.tree.ClassTree;
import com.sun.source.tree.CompilationUnitTree;
import com.sun.source.tree.EnhancedForLoopTree;
import com.sun.source.tree.ForLoopTree;
import com.sun.source.tree.IdentifierTree;
import com.sun.source.tree.ImportTree;
import com.sun.source.tree.LambdaExpressionTree;
import com.sun.source.tree.MemberSelectTree;
import com.sun.source.tree.MethodInvocationTree;
import com.sun.source.tree.MethodTree;
import com.sun.source.tree.NewClassTree;
import com.sun.source.tree.StatementTree;
import com.sun.source.tree.Tree;
import com.sun.source.tree.Tree.Kind;
import com.sun.source.tree.TryTree;
import com.sun.source.tree.VariableTree;
import com.sun.source.util.TreePath;
import com.sun.source.util.TreeScanner;
import com.sun.tools.javac.code.Kinds.KindSelector;
import com.sun.tools.javac.code.Scope;
import com.sun.tools.javac.code.Scope.WriteableScope;
import com.sun.tools.javac.code.Symbol;
import com.sun.tools.javac.code.Symbol.ClassSymbol;
import com.sun.tools.javac.code.Symbol.MethodSymbol;
import com.sun.tools.javac.code.Symbol.PackageSymbol;
import com.sun.tools.javac.code.Symbol.TypeSymbol;
import com.sun.tools.javac.code.Symbol.VarSymbol;
import com.sun.tools.javac.code.Type;
import com.sun.tools.javac.code.Type.ClassType;
import com.sun.tools.javac.comp.AttrContext;
import com.sun.tools.javac.comp.Enter;
import com.sun.tools.javac.comp.Env;
import com.sun.tools.javac.comp.MemberEnter;
import com.sun.tools.javac.comp.Resolve;
import com.sun.tools.javac.tree.JCTree.JCCompilationUnit;
import com.sun.tools.javac.tree.JCTree.JCMethodDecl;
import com.sun.tools.javac.util.JCDiagnostic.DiagnosticPosition;
import com.sun.tools.javac.util.Name;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import java.util.stream.StreamSupport;
import javax.annotation.Nullable;
import javax.lang.model.element.ElementKind;
import javax.lang.model.element.Modifier;

/** A helper class to find all identifiers in scope at a given program point. */
public final class FindIdentifiers {

  /** Finds a variable declaration with the given name that is in scope at the current location. */
  public static Symbol findIdent(String name, VisitorState state) {
    return findIdent(name, state, KindSelector.VAR);
  }

  /** Finds a declaration with the given name and type that is in scope at the current location. */
  @Nullable
  public static Symbol findIdent(String name, VisitorState state, KindSelector kind) {
    ClassType enclosingClass = ASTHelpers.getType(getEnclosingClass(state.getPath()));
    Env<AttrContext> env;
    if (enclosingClass == null || enclosingClass.tsym == null) {
      env =
          Enter.instance(state.context)
              .getTopLevelEnv((JCCompilationUnit) state.getPath().getCompilationUnit());
    } else {
      env = Enter.instance(state.context).getClassEnv(enclosingClass.tsym);
      MethodTree enclosingMethod = state.findEnclosing(MethodTree.class);
      if (enclosingMethod != null) {
        env = MemberEnter.instance(state.context).getMethodEnv((JCMethodDecl) enclosingMethod, env);
      }
    }
    try {
      Symbol result = findIdent(name, state, kind, env);
      return result.exists() ? result : null;
    } catch (ReflectiveOperationException e) {
      throw new LinkageError(e.getMessage(), e);
    }
  }

  // Signature was changed in Java 13: https://bugs.openjdk.java.net/browse/JDK-8223305
  private static Symbol findIdent(
      String name, VisitorState state, KindSelector kind, Env<AttrContext> env)
      throws NoSuchMethodException, IllegalAccessException, InvocationTargetException {
    if (RuntimeVersion.isAtLeast13()) {
      Method method =
          Resolve.class.getDeclaredMethod(
              "findIdent", DiagnosticPosition.class, Env.class, Name.class, KindSelector.class);
      method.setAccessible(true);
      return (Symbol)
          method.invoke(Resolve.instance(state.context), null, env, state.getName(name), kind);
    }
    Method method =
        Resolve.class.getDeclaredMethod("findIdent", Env.class, Name.class, KindSelector.class);
    method.setAccessible(true);
    return (Symbol) method.invoke(Resolve.instance(state.context), env, state.getName(name), kind);
  }

  @Nullable
  private static ClassTree getEnclosingClass(TreePath treePath) {
    if (treePath.getLeaf() instanceof ClassTree) {
      return (ClassTree) treePath.getLeaf();
    }

    while (treePath != null) {
      TreePath parent = treePath.getParentPath();
      if (parent == null) {
        return null;
      }
      Tree leaf = parent.getLeaf();
      if (leaf instanceof ClassTree
          && ((ClassTree) leaf).getMembers().contains(treePath.getLeaf())) {
        return (ClassTree) leaf;
      }
      treePath = parent;
    }
    return null;
  }

  /**
   * Finds the set of all bare variable identifiers in scope at the current location. Identifiers
   * are ordered by ascending distance/scope count from the current location to match shadowing
   * rules. That is, if two variables with the same simple names appear in the set, the one that
   * appears first in iteration order is the one you get if you use the bare name in the source
   * code.
   *
{'fraction_non_alphanumeric': 0.1046241880606248, 'fraction_numerical': 0.002938447262604392, 'mean_word_length': 4.093737692004726, 'pattern_counts': {'":': 0, '<': 7, '<?xml version=': 0, '>': 7, 'https://': 2, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '5028670', 'n_tokens_mistral': 3872, 'n_tokens_neox': 3810, 'n_words': 965}