Extract ChangedClassName and JVM name helpers
diff --git a/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/IncrementalContextBase.kt b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/IncrementalContextBase.kt index be6a921..df50f83 100644 --- a/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/IncrementalContextBase.kt +++ b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/IncrementalContextBase.kt
@@ -19,6 +19,11 @@ import com.google.devtools.ksp.IncrementalContextLoggingOptions import com.google.devtools.ksp.buildApiFeatures +import com.google.devtools.ksp.common.jvm.ChangedClassName +import com.google.devtools.ksp.common.jvm.dotPrefixesOf +import com.google.devtools.ksp.common.jvm.isClassAffectedBy +import com.google.devtools.ksp.common.jvm.normalizeJvmDollars +import com.google.devtools.ksp.common.jvm.withRootScopeAliases import com.google.devtools.ksp.impl.symbol.kotlin.separateQualifierAndName import com.google.devtools.ksp.symbol.KSClassDeclaration import com.google.devtools.ksp.symbol.KSDeclaration @@ -105,6 +110,8 @@ protected val classQueries = ClassQueries(File(cachesDir, "classQueries")) protected val packageQueries = PackageQueries(File(cachesDir, "packageQueries")) + private val changedClassNames: List<ChangedClassName> = changedClasses.map(::ChangedClassName) + private val cachesUpToDateFile = File(cachesDir, "caches.uptodate") // Missing query cache files mean the caches were written by an older KSP that didn't record Resolver API // queries; reprocess all sources once so queries issued per file are populated. @@ -295,7 +302,7 @@ // A missing key means the caches were written by an older KSP that didn't record outputs without sources // (Dependencies(false)). We can't prove there are none, and they'd be lost if we exited early. if (unassociatedOutputsKey !in sourceToOutputsMap) return false - if (classQueries.isAffectedBy(changedClasses) || packageQueries.isAffectedBy(changedClasses)) return false + if (classQueries.isAffectedBy(changedClassNames) || packageQueries.isAffectedBy(changedClassNames)) return false // Nothing to propagate from means calcDirtyFiles would return no files. Newly defined symbols can be ignored: // they only come from modified files. if (initialDirtyFiles().isNotEmpty()) return false @@ -326,83 +333,21 @@ private fun cleanOutputs(): Set<File> = sourceToOutputsMap.values.flatten().toSet() // Files in this module that looked up a class that changed on the classpath. - private fun dirtyFilesByClasspath(): Set<File> = buildSet { - for (rawFqn in changedClasses) { - val (rawScope, rawName) = separateQualifierAndName(rawFqn) - addDirtyFilesForSymbol(rawScope, rawName) - if (rawScope == "<anonymous>") { - addDirtyFilesForSymbol("", rawName) - } - val pkgPrefix = rawFqn.substringBeforeLast('.', "") - if ('$' in pkgPrefix) { - addDirtyFilesForSymbol(pkgPrefix.replace('$', '.'), rawName) - } - var dollar = rawName.indexOf('$') - while (dollar != -1) { - val rawOuterPart = rawName.substring(0, dollar) - val innerName = rawName.substring(dollar + 1) - if (rawOuterPart.isNotEmpty() && innerName.isNotEmpty()) { - for (outerCandidate in outerScopeCandidates(rawOuterPart)) { - val nestedScope = if (pkgPrefix.isEmpty()) outerCandidate else "$pkgPrefix.$outerCandidate" - addDirtyFilesForSymbol(nestedScope, innerName) - if ('$' in pkgPrefix) { - addDirtyFilesForSymbol("${pkgPrefix.replace('$', '.')}.$outerCandidate", innerName) - } - } - } - dollar = rawName.indexOf('$', dollar + 1) - } - } - } - - private fun outerScopeCandidates(rawOuterPart: String): Set<String> { - val dollarPositions = buildList { - var idx = rawOuterPart.indexOf('$') - while (idx != -1) { - if (idx > 0 && idx < rawOuterPart.length - 1) add(idx) - idx = rawOuterPart.indexOf('$', idx + 1) - } - } - val candidates = mutableSetOf(rawOuterPart) - val allDots = rawOuterPart.replace('$', '.') - if (!allDots.startsWith('.') && !allDots.endsWith('.') && ".." !in allDots) { - candidates.add(allDots) - } - if (dollarPositions.size in 1..4) { - val maskCount = 1 shl dollarPositions.size - for (mask in 1 until maskCount) { - val chars = rawOuterPart.toCharArray() - var valid = true - for (bit in dollarPositions.indices) { - if ((mask and (1 shl bit)) != 0) { - val pos = dollarPositions[bit] - if (chars[pos - 1] == '.') { - valid = false - break - } - chars[pos] = '.' - } - } - if (valid) candidates.add(String(chars)) - } - } - return candidates - } - - private fun MutableSet<File>.addDirtyFilesForSymbol(scope: String, name: String) { - val symbol = LookupSymbolWrapper(name, scope) - classLookupCache[symbol].mapTo(this) { it.toRelativeFile() } - symbolLookupCache[symbol].mapTo(this) { it.toRelativeFile() } - } + private fun dirtyFilesByClasspath(): Set<File> = + changedClassNames + .asSequence() + .flatMap { it.lookupSymbols } + .flatMap { sym -> classLookupCache[sym] + symbolLookupCache[sym] } + .mapTo(mutableSetOf()) { it.toRelativeFile() } private fun noSourceFilesOfChangedClasses(): Set<File> { - if (changedClasses.isEmpty()) return emptySet() - val normalizedChanged = changedClasses.mapTo(mutableSetOf()) { it.replace('$', '.') } + if (changedClassNames.isEmpty()) return emptySet() + val normalizedChanged = changedClassNames.mapTo(mutableSetOf()) { it.normalizedFqn } val changedEnclosingPrefixes = dotPrefixesOf(normalizedChanged) return sourceToOutputsMap.keys.filterTo(mutableSetOf()) { key -> NoSourceFile.isSyntheticFile(key.name) && isClassAffectedBy( - stripSyntheticFileNameModifiers(key.name).replace('$', '.'), + stripSyntheticFileNameModifiers(key.name).normalizeJvmDollars(), normalizedChanged, changedEnclosingPrefixes, ) @@ -446,13 +391,7 @@ } val dirtyFilesByNewSyms = newSyms.flatMap { newSym -> - val direct = symbolLookupCache[newSym] - val anon = if (newSym.scope.isEmpty()) { - symbolLookupCache[LookupSymbolWrapper(newSym.name, "<anonymous>")] - } else { - emptyList() - } - (direct + anon).map { it.toRelativeFile() } + newSym.withRootScopeAliases().flatMap { symbolLookupCache[it] }.map { it.toRelativeFile() } } val dirtyFilesBySealed = sealedMap.keys @@ -797,7 +736,7 @@ return // Normalize '$' to '.' so recorded class queries match dot-normalized changedClasses entries. - updatedClassQueries.add(fqn.replace('$', '.')) + updatedClassQueries.add(fqn.normalizeJvmDollars()) } fun recordPackageQuery(packageName: String) { @@ -805,7 +744,7 @@ return // Normalize '$' to '.' so package queries and includeTopLevel owner qualifiers match normalized lookups. - updatedPackageQueries.add(packageName.replace('$', '.')) + updatedPackageQueries.add(packageName.normalizeJvmDollars()) } protected open fun logBeforeCacheFlush(outputs: Set<File>, sourceToOutputs: Map<File, Set<File>>) { @@ -853,10 +792,8 @@ lookupCache[sym].forEach { visit(File(it)) } - if (sym.scope.isEmpty()) { - visit(LookupSymbolWrapper(sym.name, "<anonymous>")) - } else if (sym.scope == "<anonymous>") { - visit(LookupSymbolWrapper(sym.name, "")) + sym.withRootScopeAliases().forEach { alias -> + if (alias != sym) visit(alias) } }
diff --git a/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/PersistentSet.kt b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/PersistentSet.kt index d1a0688..3b30018 100644 --- a/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/PersistentSet.kt +++ b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/PersistentSet.kt
@@ -17,6 +17,9 @@ package com.google.devtools.ksp.common +import com.google.devtools.ksp.common.jvm.ChangedClassName +import com.google.devtools.ksp.common.jvm.dotPrefixesOf +import com.google.devtools.ksp.common.jvm.isClassAffectedBy import java.io.BufferedInputStream import java.io.File import kotlinx.serialization.ExperimentalSerializationApi @@ -62,34 +65,6 @@ } } -internal fun dotPrefixesOf(fqns: Iterable<String>): Set<String> = buildSet { - for (fqn in fqns) { - var dot = fqn.indexOf('.') - while (dot != -1) { - add(fqn.substring(0, dot)) - dot = fqn.indexOf('.', dot + 1) - } - } -} - -internal fun hasDotPrefixIn(fqn: String, candidates: Set<String>): Boolean { - var dot = fqn.indexOf('.') - while (dot != -1) { - if (fqn.substring(0, dot) in candidates) return true - dot = fqn.indexOf('.', dot + 1) - } - return false -} - -internal fun isClassAffectedBy( - targetFqn: String, - changedClasses: Set<String>, - changedEnclosingPrefixes: Set<String>, -): Boolean = - targetFqn in changedClasses || - targetFqn in changedEnclosingPrefixes || - hasDotPrefixIn(targetFqn, changedClasses) - /** * Class FQNs queried by processors via `Resolver` APIs (e.g. `getClassDeclarationByName`, member lookups in * `getFunctionDeclarationsByName` / `getPropertyDeclarationByName`, and library classes yielded by @@ -103,14 +78,20 @@ class ClassQueries( storage: File, ) : PersistentSet<String>(stringSetSerializer, storage, deserialize(stringSetSerializer, storage)) { - fun isAffectedBy(changedClasses: Collection<String>): Boolean { + /** + * Returns `true` if any class in [changedClasses] affects a recorded class query — either by + * matching it directly, being nested inside a queried outer class, or enclosing a queried + * nested class or enum entry. + */ + internal fun isAffectedBy(changedClasses: Collection<ChangedClassName>): Boolean { if (isEmpty() || changedClasses.isEmpty()) return false + // Local single-threaded cache of dot-separated prefixes; NONE avoids synchronization overhead. + // Note: isClassAffectedBy evaluates its argument eagerly on the first element. val enclosingPrefixes by lazy(LazyThreadSafetyMode.NONE) { dotPrefixesOf(this@ClassQueries) } - return changedClasses.any { rawFqn -> - val fqn = rawFqn.replace('$', '.') - fqn in this || hasDotPrefixIn(fqn, this) || fqn in enclosingPrefixes + return changedClasses.any { changed -> + isClassAffectedBy(changed.normalizedFqn, this, enclosingPrefixes) } } } @@ -121,23 +102,30 @@ * Persisted across incremental runs. * * Entries in `changedClasses` use `.` for package separators while preserving `$` inside class and file-facade names. - * Thus `rawFqn.substringBeforeLast('.', "")` extracts the exact package without confusing `$`-containing class names - * (`hints.Bar$Generated`, `hints.My$UtilKt`) with subpackages (`hints.Bar.Generated`). Also checks `dotNormalizedFqn` - * and `enclosingPrefixes` so `includeTopLevel = true` callable lookups on a previously missing owner or enclosing - * subclass match when that class is added, without matching subpackages or sibling classes. + * Thus [ChangedClassName.normalizedPackageName] extracts the exact package without confusing `$`-containing class names + * (`hints.Bar$Generated`, `hints.My$UtilKt`) with subpackages (`hints.Bar.Generated`). Also checks + * [ChangedClassName.normalizedFqn] and `enclosingPrefixes` so `includeTopLevel = true` callable lookups on a previously + * missing owner or enclosing subclass match when that class is added, without matching subpackages or sibling classes. */ class PackageQueries( storage: File, ) : PersistentSet<String>(stringSetSerializer, storage, deserialize(stringSetSerializer, storage)) { - fun isAffectedBy(changedClasses: Collection<String>): Boolean { + /** + * Returns `true` if any class in [changedClasses] affects a recorded package query — either by + * belonging to a queried package ([ChangedClassName.normalizedPackageName]) or by matching or + * enclosing a queried owner FQN ([ChangedClassName.normalizedFqn]) from an + * `includeTopLevel = true` callable lookup. + */ + internal fun isAffectedBy(changedClasses: Collection<ChangedClassName>): Boolean { if (isEmpty() || changedClasses.isEmpty()) return false + // Computed on demand if the earlier `||` checks miss; local single-threaded use makes NONE safe. val enclosingPrefixes by lazy(LazyThreadSafetyMode.NONE) { dotPrefixesOf(this@PackageQueries) } - return changedClasses.any { rawFqn -> - val pkg = rawFqn.substringBeforeLast('.', "").replace('$', '.') - val dotNormalizedFqn = rawFqn.replace('$', '.') - pkg in this || dotNormalizedFqn in this || dotNormalizedFqn in enclosingPrefixes + return changedClasses.any { changed -> + changed.normalizedPackageName in this || + changed.normalizedFqn in this || + changed.normalizedFqn in enclosingPrefixes } } }
diff --git a/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassName.kt b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassName.kt new file mode 100644 index 0000000..aef556d --- /dev/null +++ b/kotlin-analysis-api/src/main/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassName.kt
@@ -0,0 +1,189 @@ +/* + * Copyright 2026 Google LLC + * Copyright 2010-2026 JetBrains s.r.o. and Kotlin Programming Language contributors. + * + * 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.ksp.common.jvm + +import com.google.devtools.ksp.common.LookupSymbolWrapper + +internal const val ANONYMOUS_ROOT_SCOPE = "<anonymous>" + +/** + * Structured representation of a JVM classpath-change class name where `.` separates package + * segments (or already-normalized nested segments) and `$` may be either a JVM nested-class + * separator or a literal `$` character in a class or package name. + * + * Identity (`equals`, `hashCode`, `toString`) is determined solely by [raw]; derived views are + * lazily computed and cached on the instance. + */ +internal data class ChangedClassName(val raw: String) { + val packageName: String by lazy { raw.substringBeforeLast('.', "") } + + val binarySimpleName: String by lazy { raw.substringAfterLast('.') } + + /** Package name with `$` normalized to `.` (for `PackageQueries`). */ + val normalizedPackageName: String by lazy { packageName.normalizeJvmDollars() } + + /** Fully dot-normalized FQN (for `ClassQueries` and `NoSourceFile` matching). */ + val normalizedFqn: String by lazy { raw.normalizeJvmDollars() } + + /** + * All candidate [LookupSymbolWrapper] keys that could refer to this class in lookup caches, + * accounting for: + * - root-package `""` vs `"<anonymous>"` scope aliases, + * - `$` inside package names, and + * - `$` inside [binarySimpleName] being either a literal character or a nested-class separator. + */ + val lookupSymbols: Set<LookupSymbolWrapper> by lazy { + buildSet { + // 1. Top-level interpretation: treat any `$` in binarySimpleName as literal. + for (scope in packageScopeVariants(packageName)) { + add(LookupSymbolWrapper(binarySimpleName, scope)) + } + + // 2. Nested-class interpretations: split binarySimpleName at each `$` into (outerPart, innerName). + val pkgPrefixes = packagePrefixVariants(packageName) + for ((rawOuterPart, innerName) in splitBinaryNestedNames(binarySimpleName)) { + for (outerScope in expandNestedOuterScopes(rawOuterPart)) { + for (pkg in pkgPrefixes) { + val fullScope = if (pkg.isEmpty()) outerScope else "$pkg.$outerScope" + add(LookupSymbolWrapper(innerName, fullScope)) + } + } + } + } + } + + companion object { + /** + * Converts a JVM internal name (`/` package separators, `$` nested or literal class-name + * characters) into a [ChangedClassName] while keeping `$` intact so package and class + * boundaries stay distinct. + */ + fun fromInternalName(internalName: String): ChangedClassName = + ChangedClassName(internalName.replace('/', '.')) + } +} + +/** Normalizes JVM `$` characters to `.` for dot-normalized FQN comparisons. */ +internal fun String.normalizeJvmDollars(): String = replace('$', '.') + +/** + * Returns [scope] together with its root-package alias (`""` ↔ `"<anonymous>"`) when [scope] + * represents the root package; otherwise returns `listOf(scope)`. + */ +internal fun rootScopeAliases(scope: String): List<String> = when (scope) { + "" -> listOf("", ANONYMOUS_ROOT_SCOPE) + ANONYMOUS_ROOT_SCOPE -> listOf(ANONYMOUS_ROOT_SCOPE, "") + else -> listOf(scope) +} + +/** + * Returns [this] together with its root-package alias (`""` ↔ `"<anonymous>"`) if it resides in + * the root package; otherwise returns `listOf(this)`. + */ +internal fun LookupSymbolWrapper.withRootScopeAliases(): List<LookupSymbolWrapper> = + rootScopeAliases(scope).map { aliasScope -> + if (aliasScope == scope) this else LookupSymbolWrapper(name, aliasScope) + } + +/** Returns all strict dot-separated prefixes of every FQN in [fqns]. */ +internal fun dotPrefixesOf(fqns: Iterable<String>): Set<String> = buildSet { + for (fqn in fqns) { + var dot = fqn.indexOf('.') + while (dot != -1) { + add(fqn.substring(0, dot)) + dot = fqn.indexOf('.', dot + 1) + } + } +} + +/** Returns `true` if any strict dot-separated prefix of [fqn] is in [candidates]. */ +internal fun hasDotPrefixIn(fqn: String, candidates: Set<String>): Boolean { + var dot = fqn.indexOf('.') + while (dot != -1) { + if (fqn.substring(0, dot) in candidates) return true + dot = fqn.indexOf('.', dot + 1) + } + return false +} + +/** + * Returns `true` if [targetFqn] is directly in [changedClasses], is an enclosing class of a + * changed class (in [changedEnclosingPrefixes]), or is nested inside a changed class. + */ +internal fun isClassAffectedBy( + targetFqn: String, + changedClasses: Set<String>, + changedEnclosingPrefixes: Set<String>, +): Boolean = + targetFqn in changedClasses || + targetFqn in changedEnclosingPrefixes || + hasDotPrefixIn(targetFqn, changedClasses) + +private fun packagePrefixVariants(packageName: String): List<String> = + if ('$' in packageName) listOf(packageName, packageName.normalizeJvmDollars()) else listOf(packageName) + +private fun packageScopeVariants(packageName: String): List<String> = + if (packageName.isEmpty()) rootScopeAliases("") else packagePrefixVariants(packageName) + +private fun splitBinaryNestedNames(binarySimpleName: String): List<Pair<String, String>> = buildList { + var dollar = binarySimpleName.indexOf('$') + while (dollar != -1) { + val rawOuterPart = binarySimpleName.substring(0, dollar) + val innerName = binarySimpleName.substring(dollar + 1) + if (rawOuterPart.isNotEmpty() && innerName.isNotEmpty()) { + add(rawOuterPart to innerName) + } + dollar = binarySimpleName.indexOf('$', dollar + 1) + } +} + +private const val MAX_COMBINATORIAL_DOLLARS = 4 + +private fun expandNestedOuterScopes(rawOuterPart: String): Set<String> { + val dollarPositions = buildList { + var idx = rawOuterPart.indexOf('$') + while (idx != -1) { + if (idx > 0 && idx < rawOuterPart.length - 1) add(idx) + idx = rawOuterPart.indexOf('$', idx + 1) + } + } + val candidates = mutableSetOf(rawOuterPart) + val allDots = rawOuterPart.normalizeJvmDollars() + if (!allDots.startsWith('.') && !allDots.endsWith('.') && ".." !in allDots) { + candidates.add(allDots) + } + if (dollarPositions.size in 1..MAX_COMBINATORIAL_DOLLARS) { + val maskCount = 1 shl dollarPositions.size + for (mask in 1 until maskCount) { + val chars = rawOuterPart.toCharArray() + var valid = true + for (bit in dollarPositions.indices) { + if ((mask and (1 shl bit)) != 0) { + val pos = dollarPositions[bit] + if (chars[pos - 1] == '.') { + valid = false + break + } + chars[pos] = '.' + } + } + if (valid) candidates.add(String(chars)) + } + } + return candidates +}
diff --git a/kotlin-analysis-api/src/test/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassNameTest.kt b/kotlin-analysis-api/src/test/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassNameTest.kt new file mode 100644 index 0000000..0cf6a99 --- /dev/null +++ b/kotlin-analysis-api/src/test/kotlin/com/google/devtools/ksp/common/jvm/ChangedClassNameTest.kt
@@ -0,0 +1,167 @@ +/* + * Copyright 2026 Google LLC + * Copyright 2010-2026 JetBrains s.r.o. and Kotlin Programming Language contributors. + * + * 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.ksp.common.jvm + +import com.google.devtools.ksp.common.LookupSymbolWrapper +import org.junit.jupiter.api.Assertions.assertEquals +import org.junit.jupiter.api.Assertions.assertFalse +import org.junit.jupiter.api.Assertions.assertSame +import org.junit.jupiter.api.Assertions.assertTrue +import org.junit.jupiter.api.Test + +class ChangedClassNameTest { + @Test + fun `parses package and binary simple name`() { + val nested = ChangedClassName.fromInternalName("p1/Outer\$Inner") + assertEquals("p1.Outer\$Inner", nested.raw) + assertEquals("p1", nested.packageName) + assertEquals("Outer\$Inner", nested.binarySimpleName) + assertEquals("p1", nested.normalizedPackageName) + assertEquals("p1.Outer.Inner", nested.normalizedFqn) + + val root = ChangedClassName.fromInternalName("Root\$Generated") + assertEquals("", root.packageName) + assertEquals("Root\$Generated", root.binarySimpleName) + assertEquals("", root.normalizedPackageName) + assertEquals("Root.Generated", root.normalizedFqn) + + val dollarPkg = ChangedClassName.fromInternalName("pkg\$1/My\$UtilKt") + assertEquals("pkg\$1", dollarPkg.packageName) + assertEquals("My\$UtilKt", dollarPkg.binarySimpleName) + assertEquals("pkg.1", dollarPkg.normalizedPackageName) + assertEquals("pkg.1.My.UtilKt", dollarPkg.normalizedFqn) + } + + @Test + fun `equality depends only on raw and derived properties are cached`() { + val a = ChangedClassName("p1.Outer\$Inner") + val b = ChangedClassName("p1.Outer\$Inner") + assertEquals(a, b) + assertEquals(a.hashCode(), b.hashCode()) + assertSame(a.lookupSymbols, a.lookupSymbols) + assertSame(a.normalizedFqn, a.normalizedFqn) + } + + @Test + fun `expands lookup symbols for nested, dollar-named, and root-package classes`() { + assertEquals( + setOf( + LookupSymbolWrapper("Outer\$Inner", "p1"), + LookupSymbolWrapper("Inner", "p1.Outer"), + ), + ChangedClassName("p1.Outer\$Inner").lookupSymbols, + ) + + assertEquals( + setOf( + LookupSymbolWrapper("Root\$Inner", ""), + LookupSymbolWrapper("Root\$Inner", ANONYMOUS_ROOT_SCOPE), + LookupSymbolWrapper("Inner", "Root"), + ), + ChangedClassName("Root\$Inner").lookupSymbols, + ) + + assertEquals( + setOf( + LookupSymbolWrapper("Outer\$Gen\$Inner", "pkg\$1"), + LookupSymbolWrapper("Outer\$Gen\$Inner", "pkg.1"), + LookupSymbolWrapper("Gen\$Inner", "pkg\$1.Outer"), + LookupSymbolWrapper("Gen\$Inner", "pkg.1.Outer"), + LookupSymbolWrapper("Inner", "pkg\$1.Outer\$Gen"), + LookupSymbolWrapper("Inner", "pkg\$1.Outer.Gen"), + LookupSymbolWrapper("Inner", "pkg.1.Outer\$Gen"), + LookupSymbolWrapper("Inner", "pkg.1.Outer.Gen"), + ), + ChangedClassName("pkg\$1.Outer\$Gen\$Inner").lookupSymbols, + ) + + assertEquals( + setOf( + LookupSymbolWrapper("\$Outer\$Inner", "p1"), + LookupSymbolWrapper("Inner", "p1.\$Outer"), + ), + ChangedClassName("p1.\$Outer\$Inner").lookupSymbols, + ) + + assertEquals( + setOf( + LookupSymbolWrapper("User\$\$serializer", "lib"), + LookupSymbolWrapper("\$serializer", "lib.User"), + LookupSymbolWrapper("serializer", "lib.User\$"), + ), + ChangedClassName("lib.User\$\$serializer").lookupSymbols, + ) + + assertEquals( + setOf( + LookupSymbolWrapper("A\$\$B\$Inner", "p1"), + LookupSymbolWrapper("\$B\$Inner", "p1.A"), + LookupSymbolWrapper("B\$Inner", "p1.A\$"), + LookupSymbolWrapper("Inner", "p1.A\$\$B"), + LookupSymbolWrapper("Inner", "p1.A.\$B"), + LookupSymbolWrapper("Inner", "p1.A\$.B"), + ), + ChangedClassName("p1.A\$\$B\$Inner").lookupSymbols, + ) + + assertEquals( + setOf(LookupSymbolWrapper("Foo\$", "p1")), + ChangedClassName("p1.Foo\$").lookupSymbols, + ) + assertEquals( + setOf(LookupSymbolWrapper("\$Foo", "p1")), + ChangedClassName("p1.\$Foo").lookupSymbols, + ) + + // When rawOuterPart has more than MAX_COMBINATORIAL_DOLLARS (4) internal '$', only the raw + // and all-dots outer scopes are emitted (no partial combinations). + assertEquals( + setOf( + LookupSymbolWrapper("Inner", "p1.A\$B\$C\$D\$E\$F"), + LookupSymbolWrapper("Inner", "p1.A.B.C.D.E.F"), + ), + ChangedClassName("p1.A\$B\$C\$D\$E\$F\$Inner").lookupSymbols + .filter { it.name == "Inner" } + .toSet(), + ) + } + + @Test + fun `root scope aliases and dot-prefix matching`() { + assertEquals( + listOf(LookupSymbolWrapper("Foo", ""), LookupSymbolWrapper("Foo", ANONYMOUS_ROOT_SCOPE)), + LookupSymbolWrapper("Foo", "").withRootScopeAliases(), + ) + assertEquals( + listOf(LookupSymbolWrapper("Foo", ANONYMOUS_ROOT_SCOPE), LookupSymbolWrapper("Foo", "")), + LookupSymbolWrapper("Foo", ANONYMOUS_ROOT_SCOPE).withRootScopeAliases(), + ) + assertEquals( + listOf(LookupSymbolWrapper("Foo", "p1")), + LookupSymbolWrapper("Foo", "p1").withRootScopeAliases(), + ) + + val changed = setOf("p1.Outer.Inner", "p2.Foo") + val prefixes = dotPrefixesOf(changed) + assertEquals(setOf("p1", "p1.Outer", "p2"), prefixes) + assertTrue(isClassAffectedBy("p1.Outer.Inner", changed, prefixes)) + assertTrue(isClassAffectedBy("p1.Outer", changed, prefixes)) + assertTrue(isClassAffectedBy("p1.Outer.Inner.Deep", changed, prefixes)) + assertFalse(isClassAffectedBy("p1.Other", changed, prefixes)) + } +}