Skip to content

Commit

Permalink
Merge pull request #502 from scalacenter/find-and-format-local-methods
Browse files Browse the repository at this point in the history
find-and-format-local-methods
  • Loading branch information
adpi2 authored Jul 14, 2023
2 parents 9ec2eb1 + 2ddea8f commit 9eaa603
Show file tree
Hide file tree
Showing 33 changed files with 352 additions and 237 deletions.
10 changes: 10 additions & 0 deletions .scalafmt.conf
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,13 @@ assumeStandardLibraryStripMargin = true
lineEndings = unix
runner.dialect = scala3
maxColumn = 120
rewrite.rules = [RedundantBraces]
rewrite.redundantBraces.generalExpressions = true
rewrite.redundantBraces.stringInterpolation = true
rewrite.redundantBraces.defnBodies = none
fileOverride {
"glob:**/modules/unpickler/**.scala" {
rewrite.scala3.convertToNewSyntax = yes
rewrite.scala3.removeOptionalBraces = yes
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ private class ClassEntryLookUp(
cachedSourceLines.getOrElse(line, Seq.empty) :+ classFile
)
}
} finally {
inputStream.close()
}
} finally inputStream.close()
}
}

Expand Down Expand Up @@ -315,9 +313,7 @@ private object ClassEntryLookUp {
isValueClass,
classSystem
)
} finally {
inputStream.close()
}
} finally inputStream.close()
}

private def findPackage(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -227,11 +227,10 @@ private[debugadapter] final class DebugSession private (
}

override def sendEvent(event: Events.DebugEvent): Unit = {
try {
try
super.sendEvent(event)
} finally {
finally
if (event.`type` == "terminated") terminatedEvent.trySuccess(())
}
}

private def name = debuggee.name
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ object DebugTools {
def resolveCompilerClassLoader(scalaVersion: ScalaVersion): Option[ClassLoader] =
resolver
.resolveExpressionCompiler(scalaVersion)
.warnFailure(logger, s"Cannot fetch expression compiler of Scala ${scalaVersion}")
.warnFailure(logger, s"Cannot fetch expression compiler of Scala $scalaVersion")

val scala3Loader = if (scala3Entries.isEmpty) None else resolveCompilerClassLoader(scala3Version)
val scala2Loader = if (scala2Entries.isEmpty) None else resolveCompilerClassLoader(scala2Version)
Expand All @@ -114,7 +114,7 @@ object DebugTools {
classLoader <- if (entry.isScala2) scala2Loader else if (entry.isScala3) scala3Loader else None
scalaVersion <- entry.scalaVersion
compiler <- ExpressionCompiler(scalaVersion, scalacOptions, classPath, classLoader)
.warnFailure(logger, s"Cannot load expression compiler of Scala ${scalaVersion}")
.warnFailure(logger, s"Cannot load expression compiler of Scala $scalaVersion")
} yield entry -> compiler
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -204,7 +204,7 @@ private[internal] class EvaluationProvider(
private def evaluationBlock[T](f: => T): T = {
isEvaluating.set(true)
try f
finally { isEvaluating.set(false) }
finally isEvaluating.set(false)
}

override def clearState(thread: ThreadReference): Unit = {}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,8 @@ private[debugadapter] final class SourceLookUpProvider(

val classSearch =
classPathEntries
.flatMap { _.fullyQualifiedNames.filterNot { _.contains("$$anon$") } }
.groupBy { SourceLookUpProvider.getScalaClassName }
.flatMap(_.fullyQualifiedNames.filterNot(_.contains("$$anon$")))
.groupBy(SourceLookUpProvider.getScalaClassName)

override def supportsRealtimeBreakpointVerification(): Boolean = true

Expand Down Expand Up @@ -92,9 +92,9 @@ private[debugadapter] object SourceLookUpProvider {

def getScalaClassName(className: String): String = {
val lastDot = className.lastIndexOf('.') + 1
val decoded = NameTransformer.decode { className.drop(lastDot) }
val decoded = NameTransformer.decode(className.drop(lastDot))
val lastDollar = decoded.stripSuffix("$").lastIndexOf('$') + 1
decoded.drop { lastDollar }
decoded.drop(lastDollar)
}

def apply(entries: Seq[ClassEntry], logger: Logger): SourceLookUpProvider = {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,9 +37,7 @@ private[evaluator] class JdiObject(
for {
exception <- Safe(invocationException.exception).map(JdiObject(_, thread))
message <- exception.invoke("toString", List()).map(_.asString.stringValue).recover { case _ => "" }
} yield {
throw new MethodInvocationFailed(message, Some(exception))
}
} yield throw new MethodInvocationFailed(message, Some(exception))
}

// we use a Seq instead of a Map because the ScalaEvaluator rely on the order of the fields
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ class RuntimeDefaultEvaluator(val frame: JdiFrame, implicit val logger: Logger)
}

def evaluateStaticField(tree: StaticFieldTree): Safe[JdiValue] =
Safe { JdiValue(tree.on.getValue(tree.field), frame.thread) }
Safe(JdiValue(tree.on.getValue(tree.field), frame.thread))

/* -------------------------------------------------------------------------- */
/* Method evaluation */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
validateWithClass(qual).transform {
case qual: Valid[?] =>
validateName(name.value, qual)
.orElse { validateClass(name.value, qual) }
.orElse(validateClass(name.value, qual))
case _: Invalid =>
searchClassesQCN(qual.toString + "." + name.value)
}
Expand Down Expand Up @@ -84,7 +84,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
lazy val thisTree: Validation[RuntimeEvaluableTree] =
Validation.fromOption {
frame.thisObject
.map { ths => ThisTree(ths.reference.referenceType().asInstanceOf[ClassType]) }
.map(ths => ThisTree(ths.reference.referenceType().asInstanceOf[ClassType]))
}

/* -------------------------------------------------------------------------- */
Expand All @@ -99,7 +99,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
// We might sometimes need to access a 'private' attribute of a class
private def fieldLookup(name: String, ref: ReferenceType) =
Option(ref.fieldByName(name))
.orElse { ref.visibleFields().asScala.find(_.name().endsWith("$" + name)) }
.orElse(ref.visibleFields().asScala.find(_.name().endsWith("$" + name)))

def fieldTreeByName(
of: Validation[RuntimeTree],
Expand All @@ -108,7 +108,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
of match {
case ReferenceTree(ref) =>
for {
field <- Validation.fromOption { fieldLookup(name, ref) }
field <- Validation.fromOption(fieldLookup(name, ref))
_ = loadClassOnNeed(field)
fieldTree <- toStaticIfNeeded(field, of.get)
} yield fieldTree
Expand All @@ -131,7 +131,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
val isInModule = inCompanion(ofName, moduleName)

(isInModule, moduleCls, of) match {
case (true, _, _) => CompilerRecoverable(s"Cannot access module ${name} from ${ofName}")
case (true, _, _) => CompilerRecoverable(s"Cannot access module $name from $ofName")
case (_, Module(_), _) => Valid(TopLevelModuleTree(moduleCls))
case (_, cls, Some(instance: RuntimeEvaluableTree)) =>
if (cls.name.startsWith(instance.`type`.name()))
Expand Down Expand Up @@ -180,7 +180,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
.orElse {
of match {
case Valid(_: ThisTree) | _: Recoverable => localVarTreeByName(name)
case _ => Recoverable(s"${value} is not a local variable")
case _ => Recoverable(s"$value is not a local variable")
}
}
}
Expand All @@ -193,7 +193,7 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
args: Seq[RuntimeEvaluableTree]
): Validation[RuntimeEvaluableTree] =
methodTreeByNameAndArgs(on, "apply", args)
.orElse { ArrayElemTree(on, args) }
.orElse(ArrayElemTree(on, args))

def validateIndirectApply(
on: Validation[RuntimeTree],
Expand All @@ -218,9 +218,9 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
args: Seq[RuntimeEvaluableTree]
): Validation[RuntimeEvaluableTree] =
methodTreeByNameAndArgs(tree, name, args)
.orElse { validateIndirectApply(Valid(tree), name, args) }
.orElse { validateApply(tree, args) }
.orElse { validateOuter(tree).flatMap(findMethod(_, name, args)) }
.orElse(validateIndirectApply(Valid(tree), name, args))
.orElse(validateApply(tree, args))
.orElse(validateOuter(tree).flatMap(findMethod(_, name, args)))

def validateMethod(call: Call): Validation[RuntimeEvaluableTree] = {
lazy val preparedCall = call.fun match {
Expand All @@ -239,8 +239,8 @@ class RuntimeDefaultValidator(val frame: JdiFrame, val sourceLookUp: SourceLookU
lhs <- preparedCall.qual
methodTree <-
PrimitiveUnaryOpTree(lhs, preparedCall.name)
.orElse { PrimitiveBinaryOpTree(lhs, args, preparedCall.name) }
.orElse { findMethod(lhs, preparedCall.name, args) }
.orElse(PrimitiveBinaryOpTree(lhs, args, preparedCall.name))
.orElse(findMethod(lhs, preparedCall.name, args))
} yield methodTree

call.fun match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -102,10 +102,10 @@ private[evaluator] class RuntimeEvaluationHelpers(frame: JdiFrame, sourceLookup:
): Validation[Method] = {
val candidates = ref.methodsByName(encodedName).asScala

val unboxedCandidates = candidates.filter { argsMatch(_, args, boxing = false) }
val unboxedCandidates = candidates.filter(argsMatch(_, args, boxing = false))

val boxedCandidates = unboxedCandidates.size match {
case 0 => candidates.filter { argsMatch(_, args, boxing = true) }
case 0 => candidates.filter(argsMatch(_, args, boxing = true))
case _ => unboxedCandidates
}

Expand All @@ -121,7 +121,7 @@ private[evaluator] class RuntimeEvaluationHelpers(frame: JdiFrame, sourceLookup:

finalCandidates
.validateSingle(s"Cannot find a proper method $encodedName with args types $args on $ref")
.map { loadClassOnNeed }
.map(loadClassOnNeed)
}

private def zeroArgMethodByName(ref: ReferenceType, funName: String, encode: Boolean = true): Validation[Method] = {
Expand Down Expand Up @@ -157,7 +157,7 @@ private[evaluator] class RuntimeEvaluationHelpers(frame: JdiFrame, sourceLookup:
case ReferenceTree(ref) =>
if (!args.isEmpty)
methodsByNameAndArgs(ref, NameTransformer.encode(funName), args.map(_.`type`))
.flatMap { toStaticIfNeeded(_, args, tree) }
.flatMap(toStaticIfNeeded(_, args, tree))
else zeroArgMethodTreeByName(tree, NameTransformer.encode(funName))
case _ => Recoverable(new IllegalArgumentException(s"Cannot find method $funName on $tree"))
}
Expand Down Expand Up @@ -329,7 +329,7 @@ private[evaluator] class RuntimeEvaluationHelpers(frame: JdiFrame, sourceLookup:
}

def searchClasses(name: String, in: Option[String]): Validation[ClassType] = {
def baseName = in.getOrElse { frame.current().location().declaringType().name() }
def baseName = in.getOrElse(frame.current().location().declaringType().name())

val candidates = sourceLookup.classesByName(name)

Expand All @@ -343,14 +343,14 @@ private[evaluator] class RuntimeEvaluationHelpers(frame: JdiFrame, sourceLookup:

bestMatch
.validateSingle(s"Cannot find class $name")
.flatMap { loadClass }
.flatMap(loadClass)
}

def searchClassesQCN(partialClassName: String): Validation[RuntimeTree] = {
val name = SourceLookUpProvider.getScalaClassName(partialClassName)
searchClasses(name + "$", Some(partialClassName))
.map { TopLevelModuleTree(_) }
.orElse { searchClasses(name, Some(partialClassName)).map { ClassTree(_) } }
.map(TopLevelModuleTree(_))
.orElse(searchClasses(name, Some(partialClassName)).map(ClassTree(_)))
}

/* -------------------------------------------------------------------------- */
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ case class NestedModuleTree(
override def prettyPrint(depth: Int): String = {
val indent = "\t" * (depth + 1)
s"""|NestedModuleTree(
|${indent}mod= ${module}
|${indent}mod= $module
|${indent}init= ${init.prettyPrint(depth + 1)}
|${indent.dropRight(1)})""".stripMargin
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -90,7 +90,7 @@ object Validation {
case e @ (_: InvalidStackFrameException | _: AbsentInformationException) => Fatal(e)
case e @ (_: InvocationException | _: VMOutOfMemoryException) => Fatal(e)
case e: Exception =>
logger.warn(s"\u001b[35mUnexpected error while validating: ${e}\u001b[0m")
logger.warn(s"Unexpected error while validating: $e")
CompilerRecoverable(e)
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -122,9 +122,8 @@ private[internal] object Decompiler {
}

// Print classes
for (symbol <- symbols) {
for (symbol <- symbols)
printer.printSymbol(symbol)
}

Some(printer.result)
} catch {
Expand All @@ -148,9 +147,8 @@ private[internal] object Decompiler {
innerIdx < arrayLength && text(
wordStartIdx + innerIdx
) == ScalaSigBytes(innerIdx)
) {
)
innerIdx += 1
}
if (innerIdx == arrayLength) return true
else {
wordStartIdx += 1
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,9 +27,9 @@ object Parser {
className: String,
logger: Logger
): ScalaSig = {
try {
try
new Builder(bytes).readAll()
} catch {
catch {
case ex: IOException =>
throw ex
case ex: Throwable =>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ class ScalaSigPrinter(builder: StringBuilder) {
filterFirstCons: Boolean = false
): Unit = {
var firstConsFiltered = !filterFirstCons
for (child <- symbol.children) {
for (child <- symbol.children)
if (child.isParam && child.isType) {} // do nothing
else if (!firstConsFiltered)
child match {
Expand All @@ -160,7 +160,6 @@ class ScalaSigPrinter(builder: StringBuilder) {
case _ => printSymbol(level + 1, child)
}
else printSymbol(level + 1, child)
}
}

def printWithIndent(level: Int, s: String): Unit = {
Expand Down Expand Up @@ -251,9 +250,7 @@ class ScalaSigPrinter(builder: StringBuilder) {
print("\n")
printChildren(level, c, !c.isTrait)
printWithIndent(level, "}\n")
} finally {
for (param <- typeParams) removeTypeParameter(param.get)
}
} finally for (param <- typeParams) removeTypeParameter(param.get)
}
}

Expand Down Expand Up @@ -358,10 +355,10 @@ class ScalaSigPrinter(builder: StringBuilder) {

def _pmt(mt: FunctionType): Unit = {

val paramEntries = mt.paramSymbols.map({
val paramEntries = mt.paramSymbols.map {
case ms: MethodSymbol => pe(ms)
case _ => "^___^"
})
}

// Print parameter clauses
print(
Expand Down Expand Up @@ -398,11 +395,10 @@ class ScalaSigPrinter(builder: StringBuilder) {
val typeParams = pt.paramSymbols
for (param <- typeParams) addTypeParameter(param)
print(typeParamString(typeParams))
try {
try
printMethodType(pt.typeRef.get, printResult)({})
} finally {
finally
for (param <- typeParams) removeTypeParameter(param)
}
// todo consider another method types
case x => print(" : "); printType(x)
}
Expand Down Expand Up @@ -1014,9 +1010,8 @@ object ScalaSigPrinter {

def lastIdentifierCharIdx(s: String): Int = {
var idx = -1
while (idx + 1 < s.length && isIdentifierPart(s.charAt(idx + 1))) {
while (idx + 1 < s.length && isIdentifierPart(s.charAt(idx + 1)))
idx += 1
}
idx
}

Expand Down
Loading

0 comments on commit 9eaa603

Please sign in to comment.