<commit_before>package dotty.tools.dotc
package transform

import core._
import Names._
import StdNames.nme
import Types._
import dotty.tools.dotc.transform.MegaPhase._
import ast.Trees._
import Flags._
import Contexts.Context
import Symbols._
import Constants._
import Decorators._
import Denotations._, SymDenotations._
import Decorators.StringInterpolators
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Annotations.ConcreteAnnotation
import scala.collection.mutable
import DenotTransformers._
import Names.Name
import NameOps._
import TypeUtils._

/** A transformer that removes repeated parameters (T*) from all types, replacing
 *  them with Seq types.
 */
class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase =>
  import ast.tpd._

  override def phaseName = "elimRepeated"

  override def changesMembers = true // the phase adds vararg bridges

  def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type =
    elimRepeated(tp)

  override def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation =
    super.transform(ref) match {
      case ref1: SymDenotation if (ref1 ne ref) && overridesJava(ref1.symbol) =>
        // This method won't override the corresponding Java method at the end of this phase,
        // only the bridge added by `addVarArgsBridge` will.
        ref1.copySymDenotation(initFlags = ref1.flags &~ Override)
      case ref1 =>
        ref1
    }

  override def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym is Method

  private def overridesJava(sym: Symbol)(implicit ctx: Context) = sym.allOverriddenSymbols.exists(_ is JavaDefined)

  private def elimRepeated(tp: Type)(implicit ctx: Context): Type = tp.stripTypeVar match {
    case tp @ MethodTpe(paramNames, paramTypes, resultType) =>
      val resultType1 = elimRepeated(resultType)
      val paramTypes1 =
        if (paramTypes.nonEmpty && paramTypes.last.isRepeatedParam) {
          val last = paramTypes.last.underlyingIfRepeated(tp.isJavaMethod)
          paramTypes.init :+ last
        } else paramTypes
      tp.derivedLambdaType(paramNames, paramTypes1, resultType1)
    case tp: PolyType =>
      tp.derivedLambdaType(tp.paramNames, tp.paramInfos, elimRepeated(tp.resultType))
    case tp =>
      tp
  }

  def transformTypeOfTree(tree: Tree)(implicit ctx: Context): Tree =
    tree.withType(elimRepeated(tree.tpe))

  override def transformIdent(tree: Ident)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  override def transformSelect(tree: Select)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  override def transformApply(tree: Apply)(implicit ctx: Context): Tree = {
    val formals =
      ctx.atPhase(thisPhase) { implicit ctx =>
        tree.fun.tpe.widen.asInstanceOf[MethodType].paramInfos
      }
    val args1 = tree.args.zipWithConserve(formals) { (arg, formal) =>
      arg match {
        case arg: Typed if isWildcardStarArg(arg) =>
          if (tree.fun.symbol.is(JavaDefined) && arg.expr.tpe.derivesFrom(defn.SeqClass))
            seqToArray(arg.expr, formal.translateParameterized(defn.RepeatedParamClass, defn.ArrayClass))
          else arg.expr
        case arg => arg
      }
    }
    transformTypeOfTree(cpy.Apply(tree)(tree.fun, args1))
  }

  /** Convert sequence argument to Java array of type `pt` */
  private def seqToArray(tree: Tree, pt: Type)(implicit ctx: Context): Tree = tree match {
    case SeqLiteral(elems, elemtpt) =>
      JavaSeqLiteral(elems, elemtpt)
    case _ =>
      val elemType = tree.tpe.elemType
      var elemClass = elemType.classSymbol
      if (defn.NotRuntimeClasses contains elemClass) elemClass = defn.ObjectClass
      ref(defn.DottyArraysModule)
        .select(nme.seqToArray)
        .appliedToType(elemType)
        .appliedTo(tree, Literal(Constant(elemClass.typeRef)))
        .ensureConforms(pt)
          // Because of phantomclasses, the Java array's type might not conform to the return type
  }

  override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  /** If method overrides a Java varargs method, add a varargs bridge.
   *  Also transform trees inside method annotation
   */<commit_msg>Fix #3675: don't unnecessarily wrap arrays when eliminating java varargs<commit_after>package dotty.tools.dotc
package transform

import core._
import Names._
import StdNames.nme
import Types._
import dotty.tools.dotc.transform.MegaPhase._
import ast.Trees._
import Flags._
import Contexts.Context
import Symbols._
import Constants._
import Decorators._
import Denotations._, SymDenotations._
import Decorators.StringInterpolators
import dotty.tools.dotc.ast.tpd
import dotty.tools.dotc.core.Annotations.ConcreteAnnotation
import scala.collection.mutable
import DenotTransformers._
import Names.Name
import NameOps._
import TypeUtils._

/** A transformer that removes repeated parameters (T*) from all types, replacing
 *  them with Seq types.
 */
class ElimRepeated extends MiniPhase with InfoTransformer { thisPhase =>
  import ast.tpd._

  override def phaseName = "elimRepeated"

  override def changesMembers = true // the phase adds vararg bridges

  def transformInfo(tp: Type, sym: Symbol)(implicit ctx: Context): Type =
    elimRepeated(tp)

  override def transform(ref: SingleDenotation)(implicit ctx: Context): SingleDenotation =
    super.transform(ref) match {
      case ref1: SymDenotation if (ref1 ne ref) && overridesJava(ref1.symbol) =>
        // This method won't override the corresponding Java method at the end of this phase,
        // only the bridge added by `addVarArgsBridge` will.
        ref1.copySymDenotation(initFlags = ref1.flags &~ Override)
      case ref1 =>
        ref1
    }

  override def mayChange(sym: Symbol)(implicit ctx: Context): Boolean = sym is Method

  private def overridesJava(sym: Symbol)(implicit ctx: Context) = sym.allOverriddenSymbols.exists(_ is JavaDefined)

  private def elimRepeated(tp: Type)(implicit ctx: Context): Type = tp.stripTypeVar match {
    case tp @ MethodTpe(paramNames, paramTypes, resultType) =>
      val resultType1 = elimRepeated(resultType)
      val paramTypes1 =
        if (paramTypes.nonEmpty && paramTypes.last.isRepeatedParam) {
          val last = paramTypes.last.underlyingIfRepeated(tp.isJavaMethod)
          paramTypes.init :+ last
        } else paramTypes
      tp.derivedLambdaType(paramNames, paramTypes1, resultType1)
    case tp: PolyType =>
      tp.derivedLambdaType(tp.paramNames, tp.paramInfos, elimRepeated(tp.resultType))
    case tp =>
      tp
  }

  def transformTypeOfTree(tree: Tree)(implicit ctx: Context): Tree =
    tree.withType(elimRepeated(tree.tpe))

  override def transformIdent(tree: Ident)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  override def transformSelect(tree: Select)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  override def transformApply(tree: Apply)(implicit ctx: Context): Tree = {
    val formals =
      ctx.atPhase(thisPhase) { implicit ctx =>
        tree.fun.tpe.widen.asInstanceOf[MethodType].paramInfos
      }
    val args1 = tree.args.zipWithConserve(formals) { (arg, formal) =>
      arg match {
        case arg: Typed if isWildcardStarArg(arg) =>
          if (tree.fun.symbol.is(JavaDefined) && arg.expr.tpe.derivesFrom(defn.SeqClass))
            seqToArray(arg.expr, formal.translateParameterized(defn.RepeatedParamClass, defn.ArrayClass))
          else arg.expr
        case arg => arg
      }
    }
    transformTypeOfTree(cpy.Apply(tree)(tree.fun, args1))
  }

  /** Convert sequence argument to Java array of type `pt` */
  private def seqToArray(tree: Tree, pt: Type)(implicit ctx: Context): Tree = tree match {
    case SeqLiteral(elems, elemtpt) =>
      JavaSeqLiteral(elems, elemtpt)
    case app@Apply(fun, args) if isWrappedArray(app) =>
      args.head // There's only one argument: the wrapped array
    case _ =>
      val elemType = tree.tpe.elemType
      var elemClass = elemType.classSymbol
      if (defn.NotRuntimeClasses contains elemClass) elemClass = defn.ObjectClass
      ref(defn.DottyArraysModule)
        .select(nme.seqToArray)
        .appliedToType(elemType)
        .appliedTo(tree, Literal(Constant(elemClass.typeRef)))
        .ensureConforms(pt)
          // Because of phantomclasses, the Java array's type might not conform to the return type
  }

  /** Determines whether the given `tree` represents a wrapped array */
  private def isWrappedArray(tree: Apply)(implicit ctx: Context): Boolean = {
    val elemTpe = tree.tpe.elemType
    val wrapMethodName = TreeGen.wrapArrayMethodName(elemTpe)
    val wrapMethodSym = defn.ScalaPredefModuleRef.denot.requiredMethod(wrapMethodName)
    tree.fun.symbol == wrapMethodSym
  }

  override def transformTypeApply(tree: TypeApply)(implicit ctx: Context): Tree =
    transformTypeOfTree(tree)

  /** If method overrides a Java varargs method, add a varargs bridge.
   *  Also transform trees inside method annotation
   */
{'fraction_non_alphanumeric': 0.09229747675962816, 'fraction_numerical': 0.0033200531208499337, 'mean_word_length': 3.6994279771190848, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 28, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '3831908', 'n_tokens_mistral': 2715, 'n_tokens_neox': 2665, 'n_words': 727}