idea: cleanup 'public', property access syntax
This commit is contained in:
+3
-3
@@ -18,11 +18,11 @@ package org.jetbrains.kotlin.idea.actions.internal
|
||||
|
||||
import com.intellij.ide.util.PropertiesComponent
|
||||
|
||||
public class KotlinInternalMode {
|
||||
public companion object Instance {
|
||||
class KotlinInternalMode {
|
||||
companion object Instance {
|
||||
val INTERNAL_MODE_PROPERTY = "kotlin.internal.mode.enabled"
|
||||
|
||||
public var enabled: Boolean
|
||||
var enabled: Boolean
|
||||
get() = PropertiesComponent.getInstance()!!.getBoolean(
|
||||
INTERNAL_MODE_PROPERTY,
|
||||
System.getProperty(INTERNAL_MODE_PROPERTY) == "true"
|
||||
|
||||
@@ -30,8 +30,7 @@ import org.jetbrains.kotlin.types.expressions.ExpressionTypingServices
|
||||
import org.jetbrains.kotlin.types.expressions.KotlinTypeInfo
|
||||
import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor
|
||||
|
||||
@JvmOverloads
|
||||
public fun KtExpression.computeTypeInfoInContext(
|
||||
@JvmOverloads fun KtExpression.computeTypeInfoInContext(
|
||||
scope: LexicalScope,
|
||||
contextExpression: KtExpression = this,
|
||||
trace: BindingTrace = BindingTraceContext(),
|
||||
@@ -44,8 +43,7 @@ public fun KtExpression.computeTypeInfoInContext(
|
||||
.getTypeInfo(scope, this, expectedType, dataFlowInfo, trace, isStatement)
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
public fun KtExpression.analyzeInContext(
|
||||
@JvmOverloads fun KtExpression.analyzeInContext(
|
||||
scope: LexicalScope,
|
||||
contextExpression: KtExpression = this,
|
||||
trace: BindingTrace = BindingTraceContext(),
|
||||
@@ -54,11 +52,10 @@ public fun KtExpression.analyzeInContext(
|
||||
isStatement: Boolean = false
|
||||
): BindingContext {
|
||||
computeTypeInfoInContext(scope, contextExpression, trace, dataFlowInfo, expectedType, isStatement)
|
||||
return trace.getBindingContext()
|
||||
return trace.bindingContext
|
||||
}
|
||||
|
||||
@JvmOverloads
|
||||
public fun KtExpression.computeTypeInContext(
|
||||
@JvmOverloads fun KtExpression.computeTypeInContext(
|
||||
scope: LexicalScope,
|
||||
contextExpression: KtExpression = this,
|
||||
trace: BindingTrace = BindingTraceContext(),
|
||||
|
||||
@@ -18,7 +18,7 @@ package org.jetbrains.kotlin.idea.caches
|
||||
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
|
||||
public data class CachedAttributeData<T: Enum<T>>(val value: T?, val timeStamp: Long)
|
||||
data class CachedAttributeData<T: Enum<T>>(val value: T?, val timeStamp: Long)
|
||||
|
||||
interface FileAttributeService {
|
||||
fun register(id: String, version: Int) {}
|
||||
|
||||
@@ -26,7 +26,7 @@ import com.intellij.util.io.URLUtil
|
||||
import org.jetbrains.kotlin.idea.util.application.runReadAction
|
||||
import java.util.concurrent.atomic.AtomicBoolean
|
||||
|
||||
public object JarUserDataManager {
|
||||
object JarUserDataManager {
|
||||
enum class State {
|
||||
INIT,
|
||||
HAS_FILE,
|
||||
@@ -37,11 +37,11 @@ public object JarUserDataManager {
|
||||
|
||||
val fileAttributeService: FileAttributeService? = ServiceManager.getService(FileAttributeService::class.java)
|
||||
|
||||
public fun register(counter: JarBooleanPropertyCounter) {
|
||||
fun register(counter: JarBooleanPropertyCounter) {
|
||||
fileAttributeService?.register(counter.key.toString(), version)
|
||||
}
|
||||
|
||||
public fun hasFileWithProperty(counter: JarBooleanPropertyCounter, file: VirtualFile): Boolean? {
|
||||
fun hasFileWithProperty(counter: JarBooleanPropertyCounter, file: VirtualFile): Boolean? {
|
||||
val localJarFile = JarFileSystemUtil.findLocalJarFile(file) ?: return null
|
||||
|
||||
val stored = localJarFile.getUserData(counter.key)
|
||||
@@ -108,19 +108,19 @@ public object JarUserDataManager {
|
||||
}
|
||||
|
||||
object JarFileSystemUtil {
|
||||
public fun findJarFileRoot(inJarFile: VirtualFile): VirtualFile? {
|
||||
if (!inJarFile.getUrl().startsWith("jar://")) return null
|
||||
fun findJarFileRoot(inJarFile: VirtualFile): VirtualFile? {
|
||||
if (!inJarFile.url.startsWith("jar://")) return null
|
||||
|
||||
var jarFile = inJarFile
|
||||
while (jarFile.getParent() != null) jarFile = jarFile.getParent()
|
||||
while (jarFile.parent != null) jarFile = jarFile.parent
|
||||
|
||||
return jarFile
|
||||
}
|
||||
|
||||
public fun findLocalJarFile(inJarFile: VirtualFile): VirtualFile? {
|
||||
if (!inJarFile.getUrl().startsWith("jar://")) return null
|
||||
fun findLocalJarFile(inJarFile: VirtualFile): VirtualFile? {
|
||||
if (!inJarFile.url.startsWith("jar://")) return null
|
||||
|
||||
val path = inJarFile.getPath()
|
||||
val path = inJarFile.path
|
||||
|
||||
val jarSeparatorIndex = path.indexOf(URLUtil.JAR_SEPARATOR)
|
||||
assert(jarSeparatorIndex >= 0) { "Path passed to JarFileSystem must have jar separator '!/': $path" }
|
||||
|
||||
@@ -34,7 +34,7 @@ import org.jetbrains.kotlin.load.java.JvmAbi
|
||||
import org.jetbrains.kotlin.name.FqName
|
||||
import java.util.*
|
||||
|
||||
public class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() {
|
||||
class KotlinShortNamesCache(private val project: Project) : PsiShortNamesCache() {
|
||||
/**
|
||||
* Return kotlin class names from project sources which should be visible from java.
|
||||
*/
|
||||
@@ -80,7 +80,7 @@ public class KotlinShortNamesCache(private val project: Project) : PsiShortNames
|
||||
}
|
||||
|
||||
override fun getAllClassNames(dest: HashSet<String>) {
|
||||
dest.addAll(getAllClassNames())
|
||||
dest.addAll(allClassNames)
|
||||
}
|
||||
|
||||
override fun getMethodsByName(name: String, scope: GlobalSearchScope): Array<PsiMethod>
|
||||
|
||||
+3
-3
@@ -28,12 +28,12 @@ import com.intellij.util.cls.ClsFormatException
|
||||
import com.intellij.util.containers.ContainerUtil
|
||||
import java.io.IOException
|
||||
|
||||
public class ClsJavaStubByVirtualFileCache {
|
||||
class ClsJavaStubByVirtualFileCache {
|
||||
private class CachedJavaStub(val modificationStamp: Long, val javaFileStub: PsiJavaFileStubImpl)
|
||||
|
||||
private val cache = ContainerUtil.createConcurrentWeakKeySoftValueMap<VirtualFile, CachedJavaStub>()
|
||||
|
||||
public fun get(classFile: VirtualFile): PsiJavaFileStubImpl? {
|
||||
fun get(classFile: VirtualFile): PsiJavaFileStubImpl? {
|
||||
val cached = cache.get(classFile)
|
||||
val fileModificationStamp = classFile.modificationStamp
|
||||
if (cached != null && cached.modificationStamp == fileModificationStamp) {
|
||||
@@ -64,7 +64,7 @@ public class ClsJavaStubByVirtualFileCache {
|
||||
companion object {
|
||||
private val LOG = Logger.getInstance(ClsJavaStubByVirtualFileCache::class.java)
|
||||
|
||||
public fun getInstance(project: Project): ClsJavaStubByVirtualFileCache {
|
||||
fun getInstance(project: Project): ClsJavaStubByVirtualFileCache {
|
||||
return ServiceManager.getService(project, ClsJavaStubByVirtualFileCache::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
+11
-11
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.types.expressions.PreliminaryDeclarationVisitor
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
|
||||
import javax.inject.Inject
|
||||
|
||||
public class CodeFragmentAnalyzer(
|
||||
class CodeFragmentAnalyzer(
|
||||
private val resolveSession: ResolveSession,
|
||||
private val qualifierResolver: QualifiedExpressionResolver,
|
||||
private val expressionTypingServices: ExpressionTypingServices,
|
||||
@@ -43,10 +43,10 @@ public class CodeFragmentAnalyzer(
|
||||
) {
|
||||
|
||||
// component dependency cycle
|
||||
public var resolveElementCache: ResolveElementCache? = null
|
||||
var resolveElementCache: ResolveElementCache? = null
|
||||
@Inject set
|
||||
|
||||
public fun analyzeCodeFragment(codeFragment: KtCodeFragment, trace: BindingTrace, bodyResolveMode: BodyResolveMode) {
|
||||
fun analyzeCodeFragment(codeFragment: KtCodeFragment, trace: BindingTrace, bodyResolveMode: BodyResolveMode) {
|
||||
val codeFragmentElement = codeFragment.getContentElement()
|
||||
|
||||
val (scopeForContextElement, dataFlowInfo) = getScopeAndDataFlowForAnalyzeFragment(codeFragment) {
|
||||
@@ -76,10 +76,10 @@ public class CodeFragmentAnalyzer(
|
||||
//TODO: this code should be moved into debugger which should set correct context for its code fragment
|
||||
private fun KtExpression.correctContextForExpression(): KtExpression {
|
||||
return when (this) {
|
||||
is KtProperty -> this.getDelegateExpressionOrInitializer()
|
||||
is KtFunctionLiteral -> this.getBodyExpression()?.getStatements()?.lastOrNull()
|
||||
is KtDeclarationWithBody -> this.getBodyExpression()
|
||||
is KtBlockExpression -> this.getStatements().lastOrNull()
|
||||
is KtProperty -> this.delegateExpressionOrInitializer
|
||||
is KtFunctionLiteral -> this.bodyExpression?.statements?.lastOrNull()
|
||||
is KtDeclarationWithBody -> this.bodyExpression
|
||||
is KtBlockExpression -> this.statements.lastOrNull()
|
||||
else -> {
|
||||
val previousSibling = this.siblings(forward = false, withItself = false).firstIsInstanceOrNull<KtExpression>()
|
||||
if (previousSibling != null) return previousSibling
|
||||
@@ -96,7 +96,7 @@ public class CodeFragmentAnalyzer(
|
||||
codeFragment: KtCodeFragment,
|
||||
resolveToElement: (KtElement) -> BindingContext
|
||||
): Pair<LexicalScope, DataFlowInfo>? {
|
||||
val context = codeFragment.getContext()
|
||||
val context = codeFragment.context
|
||||
if (context !is KtExpression) return null
|
||||
|
||||
val scopeForContextElement: LexicalScope?
|
||||
@@ -106,7 +106,7 @@ public class CodeFragmentAnalyzer(
|
||||
is KtPrimaryConstructor -> {
|
||||
val descriptor = resolveSession.getClassDescriptor(context.getContainingClassOrObject(), NoLookupLocation.FROM_IDE) as ClassDescriptorWithResolutionScopes
|
||||
|
||||
scopeForContextElement = descriptor.getScopeForInitializerResolution()
|
||||
scopeForContextElement = descriptor.scopeForInitializerResolution
|
||||
dataFlowInfo = DataFlowInfo.EMPTY
|
||||
}
|
||||
is KtSecondaryConstructor -> {
|
||||
@@ -120,7 +120,7 @@ public class CodeFragmentAnalyzer(
|
||||
is KtClassOrObject -> {
|
||||
val descriptor = resolveSession.getClassDescriptor(context, NoLookupLocation.FROM_IDE) as ClassDescriptorWithResolutionScopes
|
||||
|
||||
scopeForContextElement = descriptor.getScopeForMemberDeclarationResolution()
|
||||
scopeForContextElement = descriptor.scopeForMemberDeclarationResolution
|
||||
dataFlowInfo = DataFlowInfo.EMPTY
|
||||
}
|
||||
is KtExpression -> {
|
||||
@@ -132,7 +132,7 @@ public class CodeFragmentAnalyzer(
|
||||
dataFlowInfo = contextForElement.getDataFlowInfo(correctedContext)
|
||||
}
|
||||
is KtFile -> {
|
||||
scopeForContextElement = resolveSession.getFileScopeProvider().getFileResolutionScope(context)
|
||||
scopeForContextElement = resolveSession.fileScopeProvider.getFileResolutionScope(context)
|
||||
dataFlowInfo = DataFlowInfo.EMPTY
|
||||
}
|
||||
else -> return null
|
||||
|
||||
+2
-2
@@ -49,7 +49,7 @@ import org.jetbrains.kotlin.resolve.scopes.MemberScope
|
||||
import org.jetbrains.kotlin.utils.sure
|
||||
import java.util.*
|
||||
|
||||
public class IDELightClassGenerationSupport(private val project: Project) : LightClassGenerationSupport() {
|
||||
class IDELightClassGenerationSupport(private val project: Project) : LightClassGenerationSupport() {
|
||||
private val scopeFileComparator = JavaElementFinder.byClasspathComparator(GlobalSearchScope.allScope(project))
|
||||
private val psiManager: PsiManager = PsiManager.getInstance(project)
|
||||
|
||||
@@ -182,7 +182,7 @@ public class IDELightClassGenerationSupport(private val project: Project) : Ligh
|
||||
}
|
||||
}
|
||||
|
||||
public fun createLightClassForFileFacade(
|
||||
fun createLightClassForFileFacade(
|
||||
facadeFqName: FqName,
|
||||
facadeFiles: List<KtFile>,
|
||||
moduleInfo: IdeaModuleInfo
|
||||
|
||||
+1
-1
@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.idea.vfilefinder.KotlinModuleMappingIndex
|
||||
import org.jetbrains.kotlin.descriptors.PackagePartProvider
|
||||
import org.jetbrains.kotlin.load.kotlin.PackageParts
|
||||
|
||||
public class IDEPackagePartProvider(val scope: GlobalSearchScope) : PackagePartProvider {
|
||||
class IDEPackagePartProvider(val scope: GlobalSearchScope) : PackagePartProvider {
|
||||
|
||||
override fun findPackageParts(packageFqName: String): List<String> {
|
||||
val values: MutableList<PackageParts> = FileBasedIndex.getInstance().getValues(KotlinModuleMappingIndex.KEY, packageFqName, scope)
|
||||
|
||||
+27
-27
@@ -32,9 +32,9 @@ import org.jetbrains.kotlin.name.Name
|
||||
import org.jetbrains.kotlin.utils.emptyOrSingletonList
|
||||
import java.util.*
|
||||
|
||||
public val LIBRARY_NAME_PREFIX: String = "library "
|
||||
val LIBRARY_NAME_PREFIX: String = "library "
|
||||
|
||||
public interface IdeaModuleInfo : ModuleInfo {
|
||||
interface IdeaModuleInfo : ModuleInfo {
|
||||
fun contentScope(): GlobalSearchScope
|
||||
|
||||
val moduleOrigin: ModuleOrigin
|
||||
@@ -51,14 +51,14 @@ private fun orderEntryToModuleInfo(project: Project, orderEntry: OrderEntry, pro
|
||||
orderEntry.getOwnerModule().toInfos()
|
||||
}
|
||||
is ModuleOrderEntry -> {
|
||||
orderEntry.getModule()?.toInfos().orEmpty()
|
||||
orderEntry.module?.toInfos().orEmpty()
|
||||
}
|
||||
is LibraryOrderEntry -> {
|
||||
val library = orderEntry.getLibrary() ?: return listOf()
|
||||
val library = orderEntry.library ?: return listOf()
|
||||
emptyOrSingletonList(LibraryInfo(project, library))
|
||||
}
|
||||
is JdkOrderEntry -> {
|
||||
val sdk = orderEntry.getJdk() ?: return listOf()
|
||||
val sdk = orderEntry.jdk ?: return listOf()
|
||||
emptyOrSingletonList(SdkInfo(project, sdk))
|
||||
}
|
||||
else -> {
|
||||
@@ -68,7 +68,7 @@ private fun orderEntryToModuleInfo(project: Project, orderEntry: OrderEntry, pro
|
||||
}
|
||||
|
||||
private fun <T> Module.cached(provider: CachedValueProvider<T>): T {
|
||||
return CachedValuesManager.getManager(getProject()).getCachedValue(this, provider)
|
||||
return CachedValuesManager.getManager(project).getCachedValue(this, provider)
|
||||
}
|
||||
|
||||
fun ideaModelDependencies(module: Module, productionOnly: Boolean): List<IdeaModuleInfo> {
|
||||
@@ -80,58 +80,58 @@ fun ideaModelDependencies(module: Module, productionOnly: Boolean): List<IdeaMod
|
||||
}
|
||||
dependencyEnumerator.forEach {
|
||||
orderEntry ->
|
||||
result.addAll(orderEntryToModuleInfo(module.getProject(), orderEntry!!, productionOnly))
|
||||
result.addAll(orderEntryToModuleInfo(module.project, orderEntry!!, productionOnly))
|
||||
true
|
||||
}
|
||||
return result.toList()
|
||||
}
|
||||
|
||||
public interface ModuleSourceInfo : IdeaModuleInfo {
|
||||
interface ModuleSourceInfo : IdeaModuleInfo {
|
||||
val module: Module
|
||||
override val moduleOrigin: ModuleOrigin
|
||||
get() = ModuleOrigin.MODULE
|
||||
}
|
||||
|
||||
public data class ModuleProductionSourceInfo(override val module: Module) : ModuleSourceInfo {
|
||||
override val name = Name.special("<production sources for module ${module.getName()}>")
|
||||
data class ModuleProductionSourceInfo(override val module: Module) : ModuleSourceInfo {
|
||||
override val name = Name.special("<production sources for module ${module.name}>")
|
||||
|
||||
override fun contentScope(): GlobalSearchScope = ModuleProductionSourceScope(module)
|
||||
|
||||
override fun dependencies() = module.cached(CachedValueProvider {
|
||||
CachedValueProvider.Result(
|
||||
ideaModelDependencies(module, productionOnly = true),
|
||||
ProjectRootModificationTracker.getInstance(module.getProject()))
|
||||
ProjectRootModificationTracker.getInstance(module.project))
|
||||
})
|
||||
|
||||
override fun friends() = listOf(module.testSourceInfo())
|
||||
}
|
||||
|
||||
//TODO: (module refactoring) do not create ModuleTestSourceInfo when there are no test roots for module
|
||||
public data class ModuleTestSourceInfo(override val module: Module) : ModuleSourceInfo {
|
||||
override val name = Name.special("<test sources for module ${module.getName()}>")
|
||||
data class ModuleTestSourceInfo(override val module: Module) : ModuleSourceInfo {
|
||||
override val name = Name.special("<test sources for module ${module.name}>")
|
||||
|
||||
override fun contentScope(): GlobalSearchScope = ModuleTestSourceScope(module)
|
||||
|
||||
override fun dependencies() = module.cached(CachedValueProvider {
|
||||
CachedValueProvider.Result(
|
||||
ideaModelDependencies(module, productionOnly = false),
|
||||
ProjectRootModificationTracker.getInstance(module.getProject()))
|
||||
ProjectRootModificationTracker.getInstance(module.project))
|
||||
})
|
||||
}
|
||||
|
||||
internal fun ModuleSourceInfo.isTests() = this is ModuleTestSourceInfo
|
||||
|
||||
public fun Module.productionSourceInfo(): ModuleProductionSourceInfo = ModuleProductionSourceInfo(this)
|
||||
public fun Module.testSourceInfo(): ModuleTestSourceInfo = ModuleTestSourceInfo(this)
|
||||
fun Module.productionSourceInfo(): ModuleProductionSourceInfo = ModuleProductionSourceInfo(this)
|
||||
fun Module.testSourceInfo(): ModuleTestSourceInfo = ModuleTestSourceInfo(this)
|
||||
|
||||
private abstract class ModuleSourceScope(val module: Module) : GlobalSearchScope(module.getProject()) {
|
||||
private abstract class ModuleSourceScope(val module: Module) : GlobalSearchScope(module.project) {
|
||||
override fun compare(file1: VirtualFile, file2: VirtualFile) = 0
|
||||
override fun isSearchInModuleContent(aModule: Module) = aModule == module
|
||||
override fun isSearchInLibraries() = false
|
||||
}
|
||||
|
||||
private class ModuleProductionSourceScope(module: Module) : ModuleSourceScope(module) {
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex()
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
@@ -144,7 +144,7 @@ private class ModuleProductionSourceScope(module: Module) : ModuleSourceScope(mo
|
||||
}
|
||||
|
||||
private class ModuleTestSourceScope(module: Module) : ModuleSourceScope(module) {
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex()
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex
|
||||
|
||||
override fun equals(other: Any?): Boolean {
|
||||
if (this === other) return true
|
||||
@@ -156,11 +156,11 @@ private class ModuleTestSourceScope(module: Module) : ModuleSourceScope(module)
|
||||
override fun contains(file: VirtualFile) = moduleFileIndex.isInTestSourceContent(file)
|
||||
}
|
||||
|
||||
public data class LibraryInfo(val project: Project, val library: Library) : IdeaModuleInfo {
|
||||
data class LibraryInfo(val project: Project, val library: Library) : IdeaModuleInfo {
|
||||
override val moduleOrigin: ModuleOrigin
|
||||
get() = ModuleOrigin.LIBRARY
|
||||
|
||||
override val name: Name = Name.special("<$LIBRARY_NAME_PREFIX${library.getName()}>")
|
||||
override val name: Name = Name.special("<$LIBRARY_NAME_PREFIX${library.name}>")
|
||||
|
||||
override fun contentScope(): GlobalSearchScope = LibraryWithoutSourceScope(project, library)
|
||||
|
||||
@@ -179,14 +179,14 @@ public data class LibraryInfo(val project: Project, val library: Library) : Idea
|
||||
return result.toList()
|
||||
}
|
||||
|
||||
override fun toString() = "LibraryInfo(libraryName=${library.getName()})"
|
||||
override fun toString() = "LibraryInfo(libraryName=${library.name})"
|
||||
}
|
||||
|
||||
internal data class LibrarySourceInfo(val project: Project, val library: Library) : IdeaModuleInfo {
|
||||
override val moduleOrigin: ModuleOrigin
|
||||
get() = ModuleOrigin.OTHER
|
||||
|
||||
override val name: Name = Name.special("<sources for library ${library.getName()}>")
|
||||
override val name: Name = Name.special("<sources for library ${library.name}>")
|
||||
|
||||
override fun contentScope() = GlobalSearchScope.EMPTY_SCOPE
|
||||
|
||||
@@ -197,15 +197,15 @@ internal data class LibrarySourceInfo(val project: Project, val library: Library
|
||||
return listOf(this) + LibraryInfo(project, library).dependencies()
|
||||
}
|
||||
|
||||
override fun toString() = "LibrarySourceInfo(libraryName=${library.getName()})"
|
||||
override fun toString() = "LibrarySourceInfo(libraryName=${library.name})"
|
||||
}
|
||||
|
||||
//TODO: (module refactoring) there should be separate SdkSourceInfo but there are no kotlin source in existing sdks for now :)
|
||||
public data class SdkInfo(val project: Project, val sdk: Sdk) : IdeaModuleInfo {
|
||||
data class SdkInfo(val project: Project, val sdk: Sdk) : IdeaModuleInfo {
|
||||
override val moduleOrigin: ModuleOrigin
|
||||
get() = ModuleOrigin.LIBRARY
|
||||
|
||||
override val name: Name = Name.special("<$LIBRARY_NAME_PREFIX${sdk.getName()}>")
|
||||
override val name: Name = Name.special("<$LIBRARY_NAME_PREFIX${sdk.name}>")
|
||||
|
||||
override fun contentScope(): GlobalSearchScope = SdkScope(project, sdk)
|
||||
|
||||
@@ -234,7 +234,7 @@ private class LibraryWithoutSourceScope(project: Project, private val library: L
|
||||
|
||||
//TODO: (module refactoring) android sdk has modified scope
|
||||
private class SdkScope(project: Project, private val sdk: Sdk) :
|
||||
LibraryScopeBase(project, sdk.getRootProvider().getFiles(OrderRootType.CLASSES), arrayOf<VirtualFile>()) {
|
||||
LibraryScopeBase(project, sdk.rootProvider.getFiles(OrderRootType.CLASSES), arrayOf<VirtualFile>()) {
|
||||
|
||||
override fun equals(other: Any?) = other is SdkScope && sdk == other.sdk
|
||||
|
||||
|
||||
+7
-7
@@ -97,7 +97,7 @@ private fun JavaDescriptorResolver.resolveMethod(method: JavaMethod): FunctionDe
|
||||
}
|
||||
|
||||
private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstructor): ConstructorDescriptor? {
|
||||
return resolveClass(constructor.getContainingClass())?.getConstructors()?.findByJavaElement(constructor)
|
||||
return resolveClass(constructor.containingClass)?.constructors?.findByJavaElement(constructor)
|
||||
}
|
||||
|
||||
private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? {
|
||||
@@ -105,21 +105,21 @@ private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescr
|
||||
}
|
||||
|
||||
private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? {
|
||||
val containingClass = resolveClass(member.getContainingClass())
|
||||
return if (member.isStatic())
|
||||
containingClass?.getStaticScope()
|
||||
val containingClass = resolveClass(member.containingClass)
|
||||
return if (member.isStatic)
|
||||
containingClass?.staticScope
|
||||
else
|
||||
containingClass?.getDefaultType()?.getMemberScope()
|
||||
containingClass?.defaultType?.memberScope
|
||||
}
|
||||
|
||||
private fun <T : DeclarationDescriptorWithSource> Collection<T>.findByJavaElement(javaElement: JavaElement): T? {
|
||||
return firstOrNull { member ->
|
||||
val memberJavaElement = (member.getOriginal().getSource() as? JavaSourceElement)?.javaElement
|
||||
val memberJavaElement = (member.original.source as? JavaSourceElement)?.javaElement
|
||||
when {
|
||||
memberJavaElement == javaElement ->
|
||||
true
|
||||
memberJavaElement is JavaElementImpl<*> && javaElement is JavaElementImpl<*> ->
|
||||
memberJavaElement.getPsi().isEquivalentTo(javaElement.getPsi())
|
||||
memberJavaElement.psi.isEquivalentTo(javaElement.psi)
|
||||
else ->
|
||||
false
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ import org.jetbrains.kotlin.resolve.lazy.declarations.DeclarationProviderFactory
|
||||
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
|
||||
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
|
||||
|
||||
public object JsAnalyzerFacade : AnalyzerFacade<PlatformAnalysisParameters>() {
|
||||
object JsAnalyzerFacade : AnalyzerFacade<PlatformAnalysisParameters>() {
|
||||
|
||||
override fun <M : ModuleInfo> createResolverForModule(
|
||||
moduleInfo: M,
|
||||
@@ -55,7 +55,7 @@ public object JsAnalyzerFacade : AnalyzerFacade<PlatformAnalysisParameters>() {
|
||||
)
|
||||
|
||||
val container = createContainerForLazyResolve(moduleContext, declarationProviderFactory, BindingTraceContext(), JsPlatform, targetEnvironment)
|
||||
var packageFragmentProvider = container.get<ResolveSession>().getPackageFragmentProvider()
|
||||
var packageFragmentProvider = container.get<ResolveSession>().packageFragmentProvider
|
||||
|
||||
if (moduleInfo is LibraryInfo && KotlinJavaScriptLibraryDetectionUtil.isKotlinJavaScriptLibrary(moduleInfo.library)) {
|
||||
val providers = moduleInfo.library.getFiles(OrderRootType.CLASSES)
|
||||
|
||||
+3
-4
@@ -24,11 +24,10 @@ import com.intellij.psi.util.CachedValueProvider
|
||||
import com.intellij.openapi.roots.ProjectRootModificationTracker
|
||||
|
||||
//TODO: this should go away to support cross-platform projects
|
||||
public object JsProjectDetector {
|
||||
@JvmStatic
|
||||
public fun isJsProject(project: Project): Boolean {
|
||||
object JsProjectDetector {
|
||||
@JvmStatic fun isJsProject(project: Project): Boolean {
|
||||
return CachedValuesManager.getManager(project).getCachedValue(project) {
|
||||
val result = ModuleManager.getInstance(project).getModules().any { ProjectStructureUtil.isJsKotlinModule(it) }
|
||||
val result = ModuleManager.getInstance(project).modules.any { ProjectStructureUtil.isJsKotlinModule(it) }
|
||||
CachedValueProvider.Result(result, ProjectRootModificationTracker.getInstance(project))
|
||||
}
|
||||
}
|
||||
|
||||
+6
-8
@@ -44,17 +44,16 @@ import org.jetbrains.kotlin.utils.keysToMap
|
||||
|
||||
internal val LOG = Logger.getInstance(KotlinCacheService::class.java)
|
||||
|
||||
public class KotlinCacheService(val project: Project) {
|
||||
class KotlinCacheService(val project: Project) {
|
||||
companion object {
|
||||
@JvmStatic
|
||||
public fun getInstance(project: Project): KotlinCacheService = ServiceManager.getService(project, KotlinCacheService::class.java)!!
|
||||
@JvmStatic fun getInstance(project: Project): KotlinCacheService = ServiceManager.getService(project, KotlinCacheService::class.java)!!
|
||||
}
|
||||
|
||||
public fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade {
|
||||
fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade {
|
||||
return getFacadeToAnalyzeFiles(elements.map { it.getContainingKtFile() })
|
||||
}
|
||||
|
||||
public fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value
|
||||
fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value
|
||||
|
||||
private val globalFacadesPerPlatform = listOf(JvmPlatform, JsPlatform).keysToMap { platform -> GlobalFacade(platform) }
|
||||
|
||||
@@ -84,8 +83,7 @@ public class KotlinCacheService(val project: Project) {
|
||||
}
|
||||
}
|
||||
|
||||
@Deprecated("Use JetElement.getResolutionFacade(), please avoid introducing new usages")
|
||||
public fun <T : Any> getProjectService(platform: TargetPlatform, ideaModuleInfo: IdeaModuleInfo, serviceClass: Class<T>): T {
|
||||
@Deprecated("Use JetElement.getResolutionFacade(), please avoid introducing new usages") fun <T : Any> getProjectService(platform: TargetPlatform, ideaModuleInfo: IdeaModuleInfo, serviceClass: Class<T>): T {
|
||||
return globalFacade(platform).resolverForModuleInfo(ideaModuleInfo).componentProvider.getService(serviceClass)
|
||||
}
|
||||
|
||||
@@ -219,7 +217,7 @@ public class KotlinCacheService(val project: Project) {
|
||||
}.toSet()
|
||||
|
||||
private fun KtCodeFragment.getContextFile(): KtFile? {
|
||||
val contextElement = getContext() ?: return null
|
||||
val contextElement = context ?: return null
|
||||
val contextFile = (contextElement as? KtElement)?.getContainingKtFile()
|
||||
?: throw AssertionError("Analyzing kotlin code fragment of type $javaClass with java context of type ${contextElement.javaClass}")
|
||||
return if (contextFile is KtCodeFragment) contextFile.getContextFile() else contextFile
|
||||
|
||||
+4
-4
@@ -26,15 +26,15 @@ import org.jetbrains.kotlin.asJava.KotlinCodeBlockModificationListener
|
||||
// Synthetic file for completion can be modified without sending tree changed events and sequence of completions can lead to inconsistent
|
||||
// resolve session being cached for such a file otherwise.
|
||||
// This code is not tested. See KT-6216 for an example.
|
||||
public class KotlinOutOfBlockCompletionModificationTracker() : SimpleModificationTracker() {
|
||||
class KotlinOutOfBlockCompletionModificationTracker() : SimpleModificationTracker() {
|
||||
companion object {
|
||||
public fun getInstance(project: Project): KotlinOutOfBlockCompletionModificationTracker
|
||||
fun getInstance(project: Project): KotlinOutOfBlockCompletionModificationTracker
|
||||
= ServiceManager.getService(project, KotlinOutOfBlockCompletionModificationTracker::class.java)!!
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public fun performCompletionWithOutOfBlockTracking(completionPosition: PsiElement, body: () -> Unit) {
|
||||
fun performCompletionWithOutOfBlockTracking(completionPosition: PsiElement, body: () -> Unit) {
|
||||
if (KotlinCodeBlockModificationListener.isInsideCodeBlock(completionPosition)) {
|
||||
body()
|
||||
return
|
||||
@@ -43,6 +43,6 @@ public fun performCompletionWithOutOfBlockTracking(completionPosition: PsiElemen
|
||||
body()
|
||||
}
|
||||
finally {
|
||||
KotlinOutOfBlockCompletionModificationTracker.getInstance(completionPosition.getProject()).incModificationCount()
|
||||
KotlinOutOfBlockCompletionModificationTracker.getInstance(completionPosition.project).incModificationCount()
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -84,7 +84,7 @@ internal class PerFileAnalysisCache(val file: KtFile, val componentProvider: Com
|
||||
}
|
||||
|
||||
private fun analyze(analyzableElement: KtElement): AnalysisResult {
|
||||
val project = analyzableElement.getProject()
|
||||
val project = analyzableElement.project
|
||||
if (DumbService.isDumb(project)) {
|
||||
return AnalysisResult.EMPTY
|
||||
}
|
||||
@@ -158,7 +158,7 @@ private object KotlinResolveDataProvider {
|
||||
}
|
||||
|
||||
val resolveSession = componentProvider.get<ResolveSession>()
|
||||
val trace = DelegatingBindingTrace(resolveSession.getBindingContext(), "Trace for resolution of " + analyzableElement)
|
||||
val trace = DelegatingBindingTrace(resolveSession.bindingContext, "Trace for resolution of " + analyzableElement)
|
||||
|
||||
val targetPlatform = TargetPlatformDetector.getPlatform(analyzableElement.getContainingKtFile())
|
||||
|
||||
@@ -176,7 +176,7 @@ private object KotlinResolveDataProvider {
|
||||
listOf(analyzableElement)
|
||||
)
|
||||
return AnalysisResult.success(
|
||||
trace.getBindingContext(),
|
||||
trace.bindingContext,
|
||||
module
|
||||
)
|
||||
}
|
||||
|
||||
+6
-6
@@ -25,20 +25,20 @@ import org.jetbrains.kotlin.psi.KtClassOrObject
|
||||
class KtLightClassForDecompiledDeclaration(
|
||||
private val clsClass: ClsClassImpl,
|
||||
private val origin: KtClassOrObject?
|
||||
) : KtWrappingLightClass(clsClass.getManager()) {
|
||||
private val fqName = origin?.getFqName() ?: FqName(clsClass.getQualifiedName())
|
||||
) : KtWrappingLightClass(clsClass.manager) {
|
||||
private val fqName = origin?.fqName ?: FqName(clsClass.qualifiedName)
|
||||
|
||||
override fun copy() = this
|
||||
|
||||
override fun getOwnInnerClasses(): List<PsiClass> {
|
||||
val nestedClasses = origin?.getDeclarations()?.filterIsInstance<KtClassOrObject>() ?: emptyList()
|
||||
return clsClass.getOwnInnerClasses().map { innerClsClass ->
|
||||
val nestedClasses = origin?.declarations?.filterIsInstance<KtClassOrObject>() ?: emptyList()
|
||||
return clsClass.ownInnerClasses.map { innerClsClass ->
|
||||
KtLightClassForDecompiledDeclaration(innerClsClass as ClsClassImpl,
|
||||
nestedClasses.firstOrNull { innerClsClass.getName() == it.getName() })
|
||||
nestedClasses.firstOrNull { innerClsClass.name == it.name })
|
||||
}
|
||||
}
|
||||
|
||||
override fun getNavigationElement() = origin?.getNavigationElement() ?: super.getNavigationElement()
|
||||
override fun getNavigationElement() = origin?.navigationElement ?: super.getNavigationElement()
|
||||
|
||||
override fun getDelegate() = clsClass
|
||||
|
||||
|
||||
+10
-10
@@ -36,14 +36,14 @@ import com.intellij.openapi.projectRoots.Sdk
|
||||
import com.intellij.openapi.roots.JdkOrderEntry
|
||||
import com.intellij.openapi.roots.ModuleSourceOrderEntry
|
||||
|
||||
public class LibraryDependenciesCache(private val project: Project) {
|
||||
class LibraryDependenciesCache(private val project: Project) {
|
||||
|
||||
//NOTE: used LibraryRuntimeClasspathScope as reference
|
||||
public fun getLibrariesAndSdksUsedWith(library: Library): Pair<List<Library>, List<Sdk>> {
|
||||
fun getLibrariesAndSdksUsedWith(library: Library): Pair<List<Library>, List<Sdk>> {
|
||||
val processedModules = LinkedHashSet<Module>()
|
||||
val condition = Condition<OrderEntry>() { orderEntry ->
|
||||
if (orderEntry is ModuleOrderEntry) {
|
||||
val module = orderEntry.getModule()
|
||||
val module = orderEntry.module
|
||||
module != null && module !in processedModules
|
||||
}
|
||||
else {
|
||||
@@ -59,17 +59,17 @@ public class LibraryDependenciesCache(private val project: Project) {
|
||||
|
||||
ModuleRootManager.getInstance(module).orderEntries().recursively().satisfying(condition).process(object : RootPolicy<Unit>() {
|
||||
override fun visitModuleSourceOrderEntry(moduleSourceOrderEntry: ModuleSourceOrderEntry?, value: Unit?): Unit? {
|
||||
processedModules.addIfNotNull(moduleSourceOrderEntry?.getOwnerModule())
|
||||
processedModules.addIfNotNull(moduleSourceOrderEntry?.ownerModule)
|
||||
return Unit
|
||||
}
|
||||
|
||||
public override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry?, value: Unit?): Unit? {
|
||||
libraries.addIfNotNull(libraryOrderEntry?.getLibrary())
|
||||
override fun visitLibraryOrderEntry(libraryOrderEntry: LibraryOrderEntry?, value: Unit?): Unit? {
|
||||
libraries.addIfNotNull(libraryOrderEntry?.library)
|
||||
return Unit
|
||||
}
|
||||
|
||||
override fun visitJdkOrderEntry(jdkOrderEntry: JdkOrderEntry?, value: Unit?): Unit? {
|
||||
sdks.addIfNotNull(jdkOrderEntry?.getJdk())
|
||||
sdks.addIfNotNull(jdkOrderEntry?.jdk)
|
||||
return Unit
|
||||
}
|
||||
}, Unit)
|
||||
@@ -90,12 +90,12 @@ public class LibraryDependenciesCache(private val project: Project) {
|
||||
val modulesLibraryIsUsedIn: MultiMap<Library, Module> = MultiMap.createSet()
|
||||
|
||||
init {
|
||||
ModuleManager.getInstance(project).getModules().forEach {
|
||||
ModuleManager.getInstance(project).modules.forEach {
|
||||
module ->
|
||||
ModuleRootManager.getInstance(module).getOrderEntries().forEach {
|
||||
ModuleRootManager.getInstance(module).orderEntries.forEach {
|
||||
entry ->
|
||||
if (entry is LibraryOrderEntry) {
|
||||
val library = entry.getLibrary()
|
||||
val library = entry.library
|
||||
if (library != null) {
|
||||
modulesLibraryIsUsedIn.putValue(library, module)
|
||||
}
|
||||
|
||||
+6
-6
@@ -58,7 +58,7 @@ fun createModuleResolverProvider(
|
||||
|
||||
val jvmPlatformParameters = JvmPlatformParameters {
|
||||
javaClass: JavaClass ->
|
||||
val psiClass = (javaClass as JavaClassImpl).getPsi()
|
||||
val psiClass = (javaClass as JavaClassImpl).psi
|
||||
psiClass.getNullableModuleInfo()
|
||||
}
|
||||
|
||||
@@ -79,21 +79,21 @@ fun createModuleResolverProvider(
|
||||
}
|
||||
|
||||
private fun collectAllModuleInfosFromIdeaModel(project: Project): List<IdeaModuleInfo> {
|
||||
val ideaModules = ModuleManager.getInstance(project).getModules().toList()
|
||||
val ideaModules = ModuleManager.getInstance(project).modules.toList()
|
||||
val modulesSourcesInfos = ideaModules.flatMap { listOf(it.productionSourceInfo(), it.testSourceInfo()) }
|
||||
|
||||
//TODO: (module refactoring) include libraries that are not among dependencies of any module
|
||||
val ideaLibraries = ideaModules.flatMap {
|
||||
ModuleRootManager.getInstance(it).getOrderEntries().filterIsInstance<LibraryOrderEntry>().map {
|
||||
it.getLibrary()
|
||||
ModuleRootManager.getInstance(it).orderEntries.filterIsInstance<LibraryOrderEntry>().map {
|
||||
it.library
|
||||
}
|
||||
}.filterNotNull().toSet()
|
||||
|
||||
val librariesInfos = ideaLibraries.map { LibraryInfo(project, it) }
|
||||
|
||||
val ideaSdks = ideaModules.flatMap {
|
||||
ModuleRootManager.getInstance(it).getOrderEntries().filterIsInstance<JdkOrderEntry>().map {
|
||||
it.getJdk()
|
||||
ModuleRootManager.getInstance(it).orderEntries.filterIsInstance<JdkOrderEntry>().map {
|
||||
it.jdk
|
||||
}
|
||||
}.filterNotNull().toSet()
|
||||
|
||||
|
||||
+1
-1
@@ -67,7 +67,7 @@ internal class ProjectResolutionFacade(
|
||||
fun getAnalysisResultsForElements(elements: Collection<KtElement>): AnalysisResult {
|
||||
assert(elements.isNotEmpty()) { "elements collection should not be empty" }
|
||||
val slruCache = synchronized(analysisResults) {
|
||||
analysisResults.getValue()!!
|
||||
analysisResults.value!!
|
||||
}
|
||||
val results = elements.map {
|
||||
val perFileCache = synchronized(slruCache) {
|
||||
|
||||
@@ -26,9 +26,9 @@ class SynchronizedCachedValue<V>(project: Project, provider: () -> CachedValuePr
|
||||
trackValue
|
||||
)
|
||||
|
||||
public fun getValue(): V {
|
||||
fun getValue(): V {
|
||||
return synchronized(cachedValue) {
|
||||
cachedValue.getValue()
|
||||
cachedValue.value
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,14 +44,14 @@ fun PsiElement.getNullableModuleInfo(): IdeaModuleInfo? = this.getModuleInfo { r
|
||||
private fun PsiElement.getModuleInfo(onFailure: (String) -> IdeaModuleInfo?): IdeaModuleInfo? {
|
||||
if (this is KtLightElement<*, *>) return this.getModuleInfoForLightElement()
|
||||
|
||||
val containingJetFile = (this as? KtElement)?.getContainingFile() as? KtFile
|
||||
val containingJetFile = (this as? KtElement)?.containingFile as? KtFile
|
||||
val context = containingJetFile?.analysisContext
|
||||
if (context != null) return context.getModuleInfo()
|
||||
|
||||
val doNotAnalyze = containingJetFile?.doNotAnalyze
|
||||
if (doNotAnalyze != null) {
|
||||
return onFailure(
|
||||
"Should not analyze element: ${getText()} in file ${containingJetFile?.getName() ?: " <no file>"}\n$doNotAnalyze"
|
||||
"Should not analyze element: ${text} in file ${containingJetFile?.name ?: " <no file>"}\n$doNotAnalyze"
|
||||
)
|
||||
}
|
||||
|
||||
@@ -71,7 +71,7 @@ private fun PsiElement.getModuleInfo(onFailure: (String) -> IdeaModuleInfo?): Id
|
||||
return getModuleInfoByVirtualFile(
|
||||
project,
|
||||
virtualFile,
|
||||
isDecompiledFile = (containingFile as? KtFile)?.isCompiled() ?: false
|
||||
isDecompiledFile = (containingFile as? KtFile)?.isCompiled ?: false
|
||||
)
|
||||
}
|
||||
|
||||
@@ -82,11 +82,11 @@ private fun getModuleInfoByVirtualFile(project: Project, virtualFile: VirtualFil
|
||||
if (module != null) {
|
||||
fun warnIfDecompiled() {
|
||||
if (isDecompiledFile) {
|
||||
LOG.warn("Decompiled file for ${virtualFile.getCanonicalPath()} is in content of $module")
|
||||
LOG.warn("Decompiled file for ${virtualFile.canonicalPath} is in content of $module")
|
||||
}
|
||||
}
|
||||
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).getFileIndex()
|
||||
val moduleFileIndex = ModuleRootManager.getInstance(module).fileIndex
|
||||
if (moduleFileIndex.isInTestSourceContent(virtualFile)) {
|
||||
warnIfDecompiled()
|
||||
return module.testSourceInfo()
|
||||
@@ -102,7 +102,7 @@ private fun getModuleInfoByVirtualFile(project: Project, virtualFile: VirtualFil
|
||||
entries@ for (orderEntry in orderEntries) {
|
||||
when (orderEntry) {
|
||||
is LibraryOrderEntry -> {
|
||||
val library = orderEntry.getLibrary() ?: continue@entries
|
||||
val library = orderEntry.library ?: continue@entries
|
||||
if (ProjectRootsUtil.isLibraryClassFile(project, virtualFile) && !isDecompiledFile) {
|
||||
return LibraryInfo(project, library)
|
||||
}
|
||||
@@ -111,7 +111,7 @@ private fun getModuleInfoByVirtualFile(project: Project, virtualFile: VirtualFil
|
||||
}
|
||||
}
|
||||
is JdkOrderEntry -> {
|
||||
val sdk = orderEntry.getJdk() ?: continue@entries
|
||||
val sdk = orderEntry.jdk ?: continue@entries
|
||||
return SdkInfo(project, sdk)
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -30,7 +30,7 @@ fun GlobalContextImpl.withCompositeExceptionTrackerUnderSameLock(): GlobalContex
|
||||
|
||||
private class CompositeExceptionTracker(val delegate: ExceptionTracker) : ExceptionTracker() {
|
||||
override fun getModificationCount(): Long {
|
||||
return super.getModificationCount() + delegate.getModificationCount()
|
||||
return super.getModificationCount() + delegate.modificationCount
|
||||
}
|
||||
}
|
||||
|
||||
@@ -48,7 +48,7 @@ private class ExceptionTrackerWithProcessCanceledReport() : ExceptionTracker() {
|
||||
}
|
||||
}
|
||||
|
||||
public fun GlobalContext(logProcessCanceled: Boolean): GlobalContextImpl {
|
||||
fun GlobalContext(logProcessCanceled: Boolean): GlobalContextImpl {
|
||||
val tracker = if (logProcessCanceled) ExceptionTrackerWithProcessCanceledReport() else ExceptionTracker()
|
||||
return GlobalContextImpl(LockBasedStorageManager.createWithExceptionHandling(tracker), tracker)
|
||||
}
|
||||
|
||||
@@ -30,7 +30,7 @@ import com.intellij.openapi.roots.ProjectRootModificationTracker
|
||||
import java.util.HashSet
|
||||
|
||||
//NOTE: this is an approximation that may contain more module infos then the exact solution
|
||||
public fun ModuleSourceInfo.getDependentModules(): Set<ModuleSourceInfo> {
|
||||
fun ModuleSourceInfo.getDependentModules(): Set<ModuleSourceInfo> {
|
||||
val dependents = getDependents(module)
|
||||
if (isTests()) {
|
||||
return dependents.mapTo(HashSet<ModuleSourceInfo>()) { it.testSourceInfo() }
|
||||
@@ -47,12 +47,12 @@ private fun getDependents(module: Module): Set<Module> {
|
||||
|
||||
val processedExporting = THashSet<Module>()
|
||||
|
||||
val index = getModuleIndex(module.getProject())
|
||||
val index = getModuleIndex(module.project)
|
||||
|
||||
val walkingQueue = Queue<Module>(10)
|
||||
walkingQueue.addLast(module)
|
||||
|
||||
while (!walkingQueue.isEmpty()) {
|
||||
while (!walkingQueue.isEmpty) {
|
||||
val current = walkingQueue.pullFirst()
|
||||
processedExporting.add(current!!)
|
||||
result.addAll(index.plainUsages[current])
|
||||
@@ -74,12 +74,12 @@ private class ModuleIndex {
|
||||
private fun getModuleIndex(project: Project): ModuleIndex {
|
||||
return CachedValuesManager.getManager(project).getCachedValue(project) {
|
||||
val index = ModuleIndex()
|
||||
for (module in ModuleManager.getInstance(project).getModules()) {
|
||||
for (orderEntry in ModuleRootManager.getInstance(module).getOrderEntries()) {
|
||||
for (module in ModuleManager.getInstance(project).modules) {
|
||||
for (orderEntry in ModuleRootManager.getInstance(module).orderEntries) {
|
||||
if (orderEntry is ModuleOrderEntry) {
|
||||
val referenced = orderEntry.getModule()
|
||||
val referenced = orderEntry.module
|
||||
if (referenced != null) {
|
||||
val map = if (orderEntry.isExported()) index.exportingUsages else index.plainUsages
|
||||
val map = if (orderEntry.isExported) index.exportingUsages else index.plainUsages
|
||||
map.putValue(referenced, module)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -32,19 +32,19 @@ import org.jetbrains.kotlin.resolve.ImportPath
|
||||
import org.jetbrains.kotlin.resolve.QualifiedExpressionResolver
|
||||
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
|
||||
public fun KtElement.getResolutionFacade(): ResolutionFacade {
|
||||
return KotlinCacheService.getInstance(getProject()).getResolutionFacade(listOf(this))
|
||||
fun KtElement.getResolutionFacade(): ResolutionFacade {
|
||||
return KotlinCacheService.getInstance(project).getResolutionFacade(listOf(this))
|
||||
}
|
||||
|
||||
public fun KtDeclaration.resolveToDescriptor(): DeclarationDescriptor {
|
||||
fun KtDeclaration.resolveToDescriptor(): DeclarationDescriptor {
|
||||
return getResolutionFacade().resolveToDescriptor(this)
|
||||
}
|
||||
|
||||
public fun KtDeclaration.resolveToDescriptorIfAny(): DeclarationDescriptor? {
|
||||
fun KtDeclaration.resolveToDescriptorIfAny(): DeclarationDescriptor? {
|
||||
return analyze(BodyResolveMode.PARTIAL).get(BindingContext.DECLARATION_TO_DESCRIPTOR, this)
|
||||
}
|
||||
|
||||
public fun KtFile.resolveImportReference(fqName: FqName): Collection<DeclarationDescriptor> {
|
||||
fun KtFile.resolveImportReference(fqName: FqName): Collection<DeclarationDescriptor> {
|
||||
val facade = getResolutionFacade()
|
||||
return facade.resolveImportReference(facade.moduleDescriptor, fqName)
|
||||
}
|
||||
@@ -54,30 +54,29 @@ public fun KtFile.resolveImportReference(fqName: FqName): Collection<Declaration
|
||||
// analyze - see ResolveSessionForBodies, ResolveElementCache
|
||||
// analyzeFully - see KotlinResolveCache, KotlinResolveDataProvider
|
||||
// In the future these two approaches should be unified
|
||||
@JvmOverloads
|
||||
public fun KtElement.analyze(bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL): BindingContext {
|
||||
@JvmOverloads fun KtElement.analyze(bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL): BindingContext {
|
||||
return getResolutionFacade().analyze(this, bodyResolveMode)
|
||||
}
|
||||
|
||||
public fun KtElement.analyzeAndGetResult(): AnalysisResult {
|
||||
fun KtElement.analyzeAndGetResult(): AnalysisResult {
|
||||
val resolutionFacade = getResolutionFacade()
|
||||
return AnalysisResult.success(resolutionFacade.analyze(this), resolutionFacade.moduleDescriptor)
|
||||
}
|
||||
|
||||
public fun KtElement.findModuleDescriptor(): ModuleDescriptor {
|
||||
fun KtElement.findModuleDescriptor(): ModuleDescriptor {
|
||||
return getResolutionFacade().moduleDescriptor
|
||||
}
|
||||
|
||||
public fun KtElement.analyzeFully(): BindingContext {
|
||||
fun KtElement.analyzeFully(): BindingContext {
|
||||
return analyzeFullyAndGetResult().bindingContext
|
||||
}
|
||||
|
||||
public fun KtElement.analyzeFullyAndGetResult(vararg extraFiles: KtFile): AnalysisResult {
|
||||
return KotlinCacheService.getInstance(getProject()).getResolutionFacade(listOf(this) + extraFiles.toList()).analyzeFullyAndGetResult(listOf(this))
|
||||
fun KtElement.analyzeFullyAndGetResult(vararg extraFiles: KtFile): AnalysisResult {
|
||||
return KotlinCacheService.getInstance(project).getResolutionFacade(listOf(this) + extraFiles.toList()).analyzeFullyAndGetResult(listOf(this))
|
||||
}
|
||||
|
||||
// this method don't check visibility and collect all descriptors with given fqName
|
||||
public fun ResolutionFacade.resolveImportReference(
|
||||
fun ResolutionFacade.resolveImportReference(
|
||||
moduleDescriptor: ModuleDescriptor,
|
||||
fqName: FqName
|
||||
): Collection<DeclarationDescriptor> {
|
||||
@@ -90,7 +89,7 @@ public fun ResolutionFacade.resolveImportReference(
|
||||
//NOTE: idea default API returns module search scope for file under module but not in source or production source (for example, test data )
|
||||
// this scope can't be used to search for kotlin declarations in index in order to resolve in that case
|
||||
// see com.intellij.psi.impl.file.impl.ResolveScopeManagerImpl.getInherentResolveScope
|
||||
public fun getResolveScope(file: KtFile): GlobalSearchScope {
|
||||
fun getResolveScope(file: KtFile): GlobalSearchScope {
|
||||
if (file is KtCodeFragment) {
|
||||
file.forcedResolveScope?.let { return KotlinSourceFilterScope.sourceAndClassFiles(it, file.project) }
|
||||
}
|
||||
|
||||
+4
-4
@@ -23,19 +23,19 @@ import org.jetbrains.kotlin.idea.decompiler.navigation.findDecompiledDeclaration
|
||||
import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.sequenceOfLazyValues
|
||||
|
||||
public object DescriptorToSourceUtilsIde {
|
||||
object DescriptorToSourceUtilsIde {
|
||||
// Returns PSI element for descriptor. If there are many relevant elements (e.g. it is fake override
|
||||
// with multiple declarations), finds any of them. It can find declarations in builtins or decompiled code.
|
||||
public fun getAnyDeclaration(project: Project, descriptor: DeclarationDescriptor): PsiElement? {
|
||||
fun getAnyDeclaration(project: Project, descriptor: DeclarationDescriptor): PsiElement? {
|
||||
return getDeclarationsStream(project, descriptor).firstOrNull()
|
||||
}
|
||||
|
||||
// Returns all PSI elements for descriptor. It can find declarations in builtins or decompiled code.
|
||||
public fun getAllDeclarations(project: Project, targetDescriptor: DeclarationDescriptor): Collection<PsiElement> {
|
||||
fun getAllDeclarations(project: Project, targetDescriptor: DeclarationDescriptor): Collection<PsiElement> {
|
||||
val result = getDeclarationsStream(project, targetDescriptor).toHashSet()
|
||||
// filter out elements which are navigate to some other element of the result
|
||||
// this is needed to avoid duplicated results for references to declaration in same library source file
|
||||
return result.filter { element -> result.none { element != it && it.getNavigationElement() == element } }
|
||||
return result.filter { element -> result.none { element != it && it.navigationElement == element } }
|
||||
}
|
||||
|
||||
private fun getDeclarationsStream(project: Project, targetDescriptor: DeclarationDescriptor): Sequence<PsiElement> {
|
||||
|
||||
+8
-8
@@ -27,7 +27,7 @@ object KotlinFileReferencesResolver {
|
||||
resolveQualifiers: Boolean = true,
|
||||
resolveShortNames: Boolean = true
|
||||
): Map<KtReferenceExpression, BindingContext> {
|
||||
return (element.getContainingFile() as? KtFile)?.let { file ->
|
||||
return (element.containingFile as? KtFile)?.let { file ->
|
||||
resolve(file, listOf(element), resolveQualifiers, resolveShortNames)
|
||||
} ?: Collections.emptyMap()
|
||||
}
|
||||
@@ -52,15 +52,15 @@ object KotlinFileReferencesResolver {
|
||||
private val resolutionFacade = file.getResolutionFacade()
|
||||
private val resolveMap = LinkedHashMap<KtReferenceExpression, BindingContext>()
|
||||
|
||||
public val result: Map<KtReferenceExpression, BindingContext> = resolveMap
|
||||
val result: Map<KtReferenceExpression, BindingContext> = resolveMap
|
||||
|
||||
override fun visitUserType(userType: KtUserType) {
|
||||
if (resolveQualifiers) {
|
||||
userType.acceptChildren(this)
|
||||
}
|
||||
|
||||
if (resolveShortNames || userType.getQualifier() != null) {
|
||||
val referenceExpression = userType.getReferenceExpression()
|
||||
if (resolveShortNames || userType.qualifier != null) {
|
||||
val referenceExpression = userType.referenceExpression
|
||||
if (referenceExpression != null) {
|
||||
resolveMap[referenceExpression] = resolutionFacade.analyze(referenceExpression)
|
||||
}
|
||||
@@ -68,16 +68,16 @@ object KotlinFileReferencesResolver {
|
||||
}
|
||||
|
||||
override fun visitQualifiedExpression(expression: KtQualifiedExpression) {
|
||||
val receiverExpression = expression.getReceiverExpression()
|
||||
val receiverExpression = expression.receiverExpression
|
||||
if (resolveQualifiers || resolutionFacade.analyze(expression)[BindingContext.QUALIFIER, receiverExpression] == null) {
|
||||
receiverExpression.accept(this)
|
||||
}
|
||||
|
||||
val referenceExpression = expression.getSelectorExpression()?.referenceExpression()
|
||||
val referenceExpression = expression.selectorExpression?.referenceExpression()
|
||||
if (referenceExpression != null) {
|
||||
resolveMap[referenceExpression] = resolutionFacade.analyze(referenceExpression)
|
||||
}
|
||||
expression.getSelectorExpression()?.accept(this)
|
||||
expression.selectorExpression?.accept(this)
|
||||
}
|
||||
|
||||
override fun visitSimpleNameExpression(expression: KtSimpleNameExpression) {
|
||||
@@ -89,4 +89,4 @@ object KotlinFileReferencesResolver {
|
||||
}
|
||||
|
||||
fun KtExpression.referenceExpression(): KtReferenceExpression? =
|
||||
(if (this is KtCallExpression) getCalleeExpression() else this) as? KtReferenceExpression
|
||||
(if (this is KtCallExpression) calleeExpression else this) as? KtReferenceExpression
|
||||
|
||||
+8
-8
@@ -38,10 +38,10 @@ private var Project.elementsToShorten: MutableSet<ShorteningRequest>?
|
||||
* When one refactoring invokes another this value must be set to false so that shortening wait-set is not cleared
|
||||
* and previously collected references are processed correctly. Afterwards it must be reset to original value
|
||||
*/
|
||||
public var Project.ensureElementsToShortenIsEmptyBeforeRefactoring: Boolean
|
||||
var Project.ensureElementsToShortenIsEmptyBeforeRefactoring: Boolean
|
||||
by NotNullableUserDataProperty(Key.create("ENSURE_ELEMENTS_TO_SHORTEN_IS_EMPTY"), true)
|
||||
|
||||
public fun Project.runWithElementsToShortenIsEmptyIgnored(action: () -> Unit) {
|
||||
fun Project.runWithElementsToShortenIsEmptyIgnored(action: () -> Unit) {
|
||||
val ensureElementsToShortenIsEmpty = ensureElementsToShortenIsEmptyBeforeRefactoring
|
||||
|
||||
try {
|
||||
@@ -62,14 +62,14 @@ private fun Project.getOrCreateElementsToShorten(): MutableSet<ShorteningRequest
|
||||
return elements
|
||||
}
|
||||
|
||||
public fun KtElement.addToShorteningWaitSet(options: Options = Options.DEFAULT) {
|
||||
assert(ApplicationManager.getApplication()!!.isWriteAccessAllowed()) { "Write access needed" }
|
||||
val project = getProject()
|
||||
fun KtElement.addToShorteningWaitSet(options: Options = Options.DEFAULT) {
|
||||
assert(ApplicationManager.getApplication()!!.isWriteAccessAllowed) { "Write access needed" }
|
||||
val project = project
|
||||
val elementPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(this)
|
||||
project.getOrCreateElementsToShorten().add(ShorteningRequest(elementPointer, options))
|
||||
}
|
||||
|
||||
public fun performDelayedShortening(project: Project) {
|
||||
fun performDelayedShortening(project: Project) {
|
||||
project.elementsToShorten?.let { requests ->
|
||||
project.elementsToShorten = null
|
||||
val elementToOptions = requests.mapNotNull { req -> req.pointer.element?.let { it to req.options } }.toMap()
|
||||
@@ -79,9 +79,9 @@ public fun performDelayedShortening(project: Project) {
|
||||
}
|
||||
}
|
||||
|
||||
private val LOG = Logger.getInstance(Project::class.java.getCanonicalName())
|
||||
private val LOG = Logger.getInstance(Project::class.java.canonicalName)
|
||||
|
||||
public fun prepareElementsToShorten(project: Project) {
|
||||
fun prepareElementsToShorten(project: Project) {
|
||||
val elementsToShorten = project.elementsToShorten
|
||||
if (project.ensureElementsToShortenIsEmptyBeforeRefactoring && elementsToShorten != null && !elementsToShorten.isEmpty()) {
|
||||
LOG.warn("Waiting set for reference shortening is not empty")
|
||||
|
||||
@@ -53,7 +53,7 @@ class ModuleTypeCacheManager private constructor(project: Project) {
|
||||
|
||||
private class VfsModificationTracker(project: Project): SimpleModificationTracker() {
|
||||
init {
|
||||
val connection = project.getMessageBus().connect();
|
||||
val connection = project.messageBus.connect();
|
||||
connection.subscribe(VirtualFileManager.VFS_CHANGES, BulkVirtualFileListenerAdapter(
|
||||
object : VirtualFileAdapter() {
|
||||
override fun propertyChanged(event: VirtualFilePropertyEvent) {
|
||||
@@ -95,11 +95,11 @@ private fun computeType(module: Module) =
|
||||
private val DEFAULT_SCRIPT_NAME = "build.gradle"
|
||||
|
||||
private fun isGradleModule(module: Module): Boolean {
|
||||
val moduleFile = module.getModuleFile()
|
||||
val moduleFile = module.moduleFile
|
||||
if (moduleFile == null){
|
||||
return false
|
||||
}
|
||||
|
||||
val buildFile = moduleFile.getParent()?.findChild(DEFAULT_SCRIPT_NAME)
|
||||
val buildFile = moduleFile.parent?.findChild(DEFAULT_SCRIPT_NAME)
|
||||
return buildFile != null && buildFile.exists()
|
||||
}
|
||||
|
||||
+3
-3
@@ -35,8 +35,8 @@ class KotlinDecompiledFileViewProvider(
|
||||
private val factory: (KotlinDecompiledFileViewProvider) -> KtDecompiledFile?
|
||||
) : SingleRootFileViewProvider(manager, file, physical, KotlinLanguage.INSTANCE) {
|
||||
val content : LockedClearableLazyValue<String> = LockedClearableLazyValue(Any()) {
|
||||
val psiFile = createFile(manager.getProject(), file, KotlinFileType.INSTANCE)
|
||||
val text = psiFile?.getText() ?: ""
|
||||
val psiFile = createFile(manager.project, file, KotlinFileType.INSTANCE)
|
||||
val text = psiFile?.text ?: ""
|
||||
|
||||
DebugUtil.startPsiModification("Invalidating throw-away copy of file that was used for getting text")
|
||||
try {
|
||||
@@ -53,7 +53,7 @@ class KotlinDecompiledFileViewProvider(
|
||||
return factory(this)
|
||||
}
|
||||
|
||||
override fun createCopy(copy: VirtualFile) = KotlinDecompiledFileViewProvider(getManager(), copy, false, factory)
|
||||
override fun createCopy(copy: VirtualFile) = KotlinDecompiledFileViewProvider(manager, copy, false, factory)
|
||||
|
||||
override fun getContents() = content.get()
|
||||
}
|
||||
@@ -46,17 +46,17 @@ open class KtDecompiledFile(
|
||||
buildDecompiledText(provider.virtualFile)
|
||||
}
|
||||
|
||||
public fun getDeclarationForDescriptor(descriptor: DeclarationDescriptor): KtDeclaration? {
|
||||
val original = descriptor.getOriginal()
|
||||
fun getDeclarationForDescriptor(descriptor: DeclarationDescriptor): KtDeclaration? {
|
||||
val original = descriptor.original
|
||||
|
||||
if (original is ValueParameterDescriptor) {
|
||||
val callable = original.getContainingDeclaration()
|
||||
val callable = original.containingDeclaration
|
||||
val callableDeclaration = getDeclarationForDescriptor(callable) as? KtCallableDeclaration ?: return null
|
||||
return callableDeclaration.getValueParameters()[original.index]
|
||||
return callableDeclaration.valueParameters[original.index]
|
||||
}
|
||||
|
||||
if (original is ConstructorDescriptor && original.isPrimary()) {
|
||||
val classOrObject = getDeclarationForDescriptor(original.getContainingDeclaration()) as? KtClassOrObject
|
||||
if (original is ConstructorDescriptor && original.isPrimary) {
|
||||
val classOrObject = getDeclarationForDescriptor(original.containingDeclaration) as? KtClassOrObject
|
||||
return classOrObject?.getPrimaryConstructor() ?: classOrObject
|
||||
}
|
||||
|
||||
@@ -74,7 +74,7 @@ open class KtDecompiledFile(
|
||||
|
||||
private fun DeclarationDescriptor.findElementForDescriptor(): KtDeclaration? {
|
||||
return decompiledText.get().renderedDescriptorsToRange[descriptorToKey(this)]?.let { range ->
|
||||
PsiTreeUtil.findElementOfClassAtRange(this@KtDecompiledFile, range.getStartOffset(), range.getEndOffset(), KtDeclaration::class.java)
|
||||
PsiTreeUtil.findElementOfClassAtRange(this@KtDecompiledFile, range.startOffset, range.endOffset, KtDeclaration::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -65,7 +65,7 @@ class KotlinBuiltInDecompiler : ClassFileDecompilers.Full() {
|
||||
|
||||
private val decompilerRendererForBuiltIns = DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
|
||||
|
||||
public fun buildDecompiledTextForBuiltIns(
|
||||
fun buildDecompiledTextForBuiltIns(
|
||||
builtInFile: VirtualFile
|
||||
): DecompiledText {
|
||||
val directory = builtInFile.parent!!
|
||||
|
||||
+1
-1
@@ -30,7 +30,7 @@ import org.jetbrains.kotlin.name.FqName
|
||||
import org.jetbrains.kotlin.resolve.TargetPlatform
|
||||
import org.jetbrains.kotlin.serialization.deserialization.*
|
||||
|
||||
public class KotlinBuiltInDeserializerForDecompiler(
|
||||
class KotlinBuiltInDeserializerForDecompiler(
|
||||
packageDirectory: VirtualFile,
|
||||
packageFqName: FqName,
|
||||
private val nameResolver: NameResolver
|
||||
|
||||
+1
-1
@@ -39,7 +39,7 @@ import org.jetbrains.kotlin.serialization.deserialization.NameResolverImpl
|
||||
import org.jetbrains.kotlin.serialization.deserialization.TypeTable
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
public class KotlinBuiltInStubBuilder : ClsStubBuilder() {
|
||||
class KotlinBuiltInStubBuilder : ClsStubBuilder() {
|
||||
override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + 1
|
||||
|
||||
override fun buildFileStub(content: FileContent): PsiFileStub<*>? {
|
||||
|
||||
@@ -21,7 +21,7 @@ import com.intellij.openapi.vfs.VirtualFile
|
||||
import org.jetbrains.kotlin.builtins.BuiltInsSerializedResourcePaths
|
||||
import org.jetbrains.kotlin.idea.KotlinIcons
|
||||
|
||||
public object KotlinBuiltInClassFileType : FileType {
|
||||
object KotlinBuiltInClassFileType : FileType {
|
||||
override fun getName() = "kotlin_class"
|
||||
|
||||
override fun getDescription() = "Kotlin builtin class"
|
||||
@@ -37,7 +37,7 @@ public object KotlinBuiltInClassFileType : FileType {
|
||||
override fun getCharset(file: VirtualFile, content: ByteArray) = null
|
||||
}
|
||||
|
||||
public object KotlinBuiltInPackageFileType : FileType {
|
||||
object KotlinBuiltInPackageFileType : FileType {
|
||||
override fun getName() = "kotlin_package"
|
||||
|
||||
override fun getDescription() = "Kotlin builtin package"
|
||||
|
||||
+7
-7
@@ -29,8 +29,8 @@ import org.jetbrains.kotlin.name.Name
|
||||
/**
|
||||
* Checks if this file is a compiled Kotlin class file (not necessarily ABI-compatible with the current plugin)
|
||||
*/
|
||||
public fun isKotlinJvmCompiledFile(file: VirtualFile): Boolean {
|
||||
if (file.getExtension() != JavaClassFileType.INSTANCE!!.getDefaultExtension()) {
|
||||
fun isKotlinJvmCompiledFile(file: VirtualFile): Boolean {
|
||||
if (file.extension != JavaClassFileType.INSTANCE!!.defaultExtension) {
|
||||
return false
|
||||
}
|
||||
|
||||
@@ -45,10 +45,10 @@ public fun isKotlinJvmCompiledFile(file: VirtualFile): Boolean {
|
||||
/**
|
||||
* Checks if this file is a compiled Kotlin class file ABI-compatible with the current plugin
|
||||
*/
|
||||
public fun isKotlinWithCompatibleAbiVersion(file: VirtualFile): Boolean {
|
||||
fun isKotlinWithCompatibleAbiVersion(file: VirtualFile): Boolean {
|
||||
if (!isKotlinJvmCompiledFile(file)) return false
|
||||
|
||||
val header = KotlinBinaryClassCache.getKotlinBinaryClass(file)?.getClassHeader()
|
||||
val header = KotlinBinaryClassCache.getKotlinBinaryClass(file)?.classHeader
|
||||
return header != null && header.isCompatibleAbiVersion
|
||||
}
|
||||
|
||||
@@ -56,7 +56,7 @@ public fun isKotlinWithCompatibleAbiVersion(file: VirtualFile): Boolean {
|
||||
* Checks if this file is a compiled "internal" Kotlin class, i.e. a Kotlin class (not necessarily ABI-compatible with the current plugin)
|
||||
* which should NOT be decompiled (and, as a result, shown under the library in the Project view, be searchable via Find class, etc.)
|
||||
*/
|
||||
public fun isKotlinInternalCompiledFile(file: VirtualFile): Boolean {
|
||||
fun isKotlinInternalCompiledFile(file: VirtualFile): Boolean {
|
||||
if (!isKotlinJvmCompiledFile(file)) {
|
||||
return false
|
||||
}
|
||||
@@ -71,14 +71,14 @@ public fun isKotlinInternalCompiledFile(file: VirtualFile): Boolean {
|
||||
header.isLocalClass || header.syntheticClassKind == "PACKAGE_PART"
|
||||
}
|
||||
|
||||
public object HasCompiledKotlinInJar : JarUserDataManager.JarBooleanPropertyCounter(HasCompiledKotlinInJar::class.simpleName!!) {
|
||||
object HasCompiledKotlinInJar : JarUserDataManager.JarBooleanPropertyCounter(HasCompiledKotlinInJar::class.simpleName!!) {
|
||||
override fun hasProperty(file: VirtualFile) = isKotlinJvmCompiledFile(file)
|
||||
|
||||
fun isInNoKotlinJar(file: VirtualFile): Boolean =
|
||||
JarUserDataManager.hasFileWithProperty(HasCompiledKotlinInJar, file) == false
|
||||
}
|
||||
|
||||
public fun findMultifileClassParts(file: VirtualFile, multifileClass: KotlinJvmBinaryClass): List<KotlinJvmBinaryClass> {
|
||||
fun findMultifileClassParts(file: VirtualFile, multifileClass: KotlinJvmBinaryClass): List<KotlinJvmBinaryClass> {
|
||||
val packageFqName = multifileClass.classId.packageFqName
|
||||
val partsFinder = DirectoryBasedClassFinder(file.parent!!, packageFqName)
|
||||
val partNames = multifileClass.classHeader.filePartClassNames ?: return emptyList()
|
||||
|
||||
+7
-7
@@ -36,14 +36,14 @@ import org.jetbrains.kotlin.serialization.deserialization.DeserializationCompone
|
||||
import org.jetbrains.kotlin.serialization.deserialization.descriptors.DeserializedPackageMemberScope
|
||||
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
|
||||
|
||||
public fun DeserializerForClassfileDecompiler(classFile: VirtualFile): DeserializerForClassfileDecompiler {
|
||||
fun DeserializerForClassfileDecompiler(classFile: VirtualFile): DeserializerForClassfileDecompiler {
|
||||
val kotlinClass = KotlinBinaryClassCache.getKotlinBinaryClass(classFile)
|
||||
assert(kotlinClass != null) { "Decompiled data factory shouldn't be called on an unsupported file: " + classFile }
|
||||
val packageFqName = kotlinClass!!.classId.packageFqName
|
||||
return DeserializerForClassfileDecompiler(classFile.parent!!, packageFqName)
|
||||
}
|
||||
|
||||
public class DeserializerForClassfileDecompiler(
|
||||
class DeserializerForClassfileDecompiler(
|
||||
packageDirectory: VirtualFile,
|
||||
directoryPackageFqName: FqName
|
||||
) : DeserializerForDecompilerBase(packageDirectory, directoryPackageFqName) {
|
||||
@@ -74,7 +74,7 @@ public class DeserializerForClassfileDecompiler(
|
||||
val annotationData = header?.annotationData
|
||||
val strings = header?.strings
|
||||
if (annotationData == null || strings == null) {
|
||||
LOG.error("Could not read annotation data for $facadeFqName from ${binaryClassForPackageClass?.getClassId()}")
|
||||
LOG.error("Could not read annotation data for $facadeFqName from ${binaryClassForPackageClass?.classId}")
|
||||
return emptyList()
|
||||
}
|
||||
val (nameResolver, packageProto) = JvmProtoBufUtil.readPackageDataFrom(annotationData, strings)
|
||||
@@ -97,10 +97,10 @@ class DirectoryBasedClassFinder(
|
||||
override fun findKotlinClass(javaClass: JavaClass) = findKotlinClass(javaClass.classId)
|
||||
|
||||
override fun findKotlinClass(classId: ClassId): KotlinJvmBinaryClass? {
|
||||
if (classId.getPackageFqName() != directoryPackageFqName) {
|
||||
if (classId.packageFqName != directoryPackageFqName) {
|
||||
return null
|
||||
}
|
||||
val targetName = classId.getRelativeClassName().pathSegments().joinToString("$", postfix = ".class")
|
||||
val targetName = classId.relativeClassName.pathSegments().joinToString("$", postfix = ".class")
|
||||
val virtualFile = packageDirectory.findChild(targetName)
|
||||
if (virtualFile != null && isKotlinWithCompatibleAbiVersion(virtualFile)) {
|
||||
return KotlinBinaryClassCache.getKotlinBinaryClass(virtualFile)
|
||||
@@ -134,6 +134,6 @@ class DirectoryBasedDataFinder(
|
||||
|
||||
private val JavaClass.classId: ClassId
|
||||
get() {
|
||||
val outer = getOuterClass()
|
||||
return if (outer == null) ClassId.topLevel(getFqName()!!) else outer.classId.createNestedClassId(getName())
|
||||
val outer = outerClass
|
||||
return if (outer == null) ClassId.topLevel(fqName!!) else outer.classId.createNestedClassId(name)
|
||||
}
|
||||
|
||||
+7
-7
@@ -37,7 +37,7 @@ import org.jetbrains.kotlin.types.flexibility
|
||||
import org.jetbrains.kotlin.types.isFlexible
|
||||
import java.util.*
|
||||
|
||||
public class KotlinClassFileDecompiler : ClassFileDecompilers.Full() {
|
||||
class KotlinClassFileDecompiler : ClassFileDecompilers.Full() {
|
||||
private val stubBuilder = KotlinClsStubBuilder()
|
||||
|
||||
override fun accepts(file: VirtualFile) = isKotlinJvmCompiledFile(file)
|
||||
@@ -68,22 +68,22 @@ private val decompilerRendererForClassFiles = DescriptorRenderer.withOptions {
|
||||
private val FILE_ABI_VERSION_MARKER: String = "FILE_ABI"
|
||||
private val CURRENT_ABI_VERSION_MARKER: String = "CURRENT_ABI"
|
||||
|
||||
public val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String = "// This class file was compiled with different version of Kotlin compiler and can't be decompiled."
|
||||
public val INCOMPATIBLE_ABI_VERSION_COMMENT: String =
|
||||
val INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT: String = "// This class file was compiled with different version of Kotlin compiler and can't be decompiled."
|
||||
val INCOMPATIBLE_ABI_VERSION_COMMENT: String =
|
||||
"$INCOMPATIBLE_ABI_VERSION_GENERAL_COMMENT\n" +
|
||||
"//\n" +
|
||||
"// Current compiler ABI version is $CURRENT_ABI_VERSION_MARKER\n" +
|
||||
"// File ABI version is $FILE_ABI_VERSION_MARKER"
|
||||
|
||||
public fun buildDecompiledTextForClassFile(
|
||||
fun buildDecompiledTextForClassFile(
|
||||
classFile: VirtualFile,
|
||||
resolver: ResolverForDecompiler = DeserializerForClassfileDecompiler(classFile)
|
||||
): DecompiledText {
|
||||
val kotlinClass = KotlinBinaryClassCache.getKotlinBinaryClass(classFile)
|
||||
assert(kotlinClass != null) { "Decompiled data factory shouldn't be called on an unsupported file: " + classFile }
|
||||
val classId = kotlinClass!!.getClassId()
|
||||
val classHeader = kotlinClass.getClassHeader()
|
||||
val packageFqName = classId.getPackageFqName()
|
||||
val classId = kotlinClass!!.classId
|
||||
val classHeader = kotlinClass.classHeader
|
||||
val packageFqName = classId.packageFqName
|
||||
|
||||
return when {
|
||||
!classHeader.isCompatibleAbiVersion -> {
|
||||
|
||||
+10
-10
@@ -44,11 +44,11 @@ import org.jetbrains.kotlin.serialization.jvm.JvmProtoBuf
|
||||
import org.jetbrains.kotlin.serialization.jvm.JvmProtoBufUtil
|
||||
import org.jetbrains.kotlin.storage.LockBasedStorageManager
|
||||
|
||||
public open class KotlinClsStubBuilder : ClsStubBuilder() {
|
||||
open class KotlinClsStubBuilder : ClsStubBuilder() {
|
||||
override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + 1
|
||||
|
||||
override fun buildFileStub(content: FileContent): PsiFileStub<*>? {
|
||||
val file = content.getFile()
|
||||
val file = content.file
|
||||
|
||||
if (isKotlinInternalCompiledFile(file)) {
|
||||
return null
|
||||
@@ -59,9 +59,9 @@ public open class KotlinClsStubBuilder : ClsStubBuilder() {
|
||||
|
||||
fun doBuildFileStub(file: VirtualFile): PsiFileStub<KtFile>? {
|
||||
val kotlinBinaryClass = KotlinBinaryClassCache.getKotlinBinaryClass(file)!!
|
||||
val header = kotlinBinaryClass.getClassHeader()
|
||||
val classId = kotlinBinaryClass.getClassId()
|
||||
val packageFqName = classId.getPackageFqName()
|
||||
val header = kotlinBinaryClass.classHeader
|
||||
val classId = kotlinBinaryClass.classId
|
||||
val packageFqName = classId.packageFqName
|
||||
if (!header.isCompatibleAbiVersion) {
|
||||
return createIncompatibleAbiVersionFileStub()
|
||||
}
|
||||
@@ -74,12 +74,12 @@ public open class KotlinClsStubBuilder : ClsStubBuilder() {
|
||||
|
||||
val annotationData = header.annotationData
|
||||
if (annotationData == null) {
|
||||
LOG.error("Corrupted kotlin header for file ${file.getName()}")
|
||||
LOG.error("Corrupted kotlin header for file ${file.name}")
|
||||
return null
|
||||
}
|
||||
val strings = header.strings
|
||||
if (strings == null) {
|
||||
LOG.error("String table not found in file ${file.getName()}")
|
||||
LOG.error("String table not found in file ${file.name}")
|
||||
return null
|
||||
}
|
||||
return when {
|
||||
@@ -94,12 +94,12 @@ public open class KotlinClsStubBuilder : ClsStubBuilder() {
|
||||
val context = components.createContext(nameResolver, packageFqName, TypeTable(packageProto.typeTable))
|
||||
createFileFacadeStub(packageProto, classId.asSingleFqName(), context)
|
||||
}
|
||||
else -> throw IllegalStateException("Should have processed " + file.getPath() + " with header $header")
|
||||
else -> throw IllegalStateException("Should have processed " + file.path + " with header $header")
|
||||
}
|
||||
}
|
||||
|
||||
private fun createStubBuilderComponents(file: VirtualFile, packageFqName: FqName): ClsStubBuilderComponents {
|
||||
val classFinder = DirectoryBasedClassFinder(file.getParent()!!, packageFqName)
|
||||
val classFinder = DirectoryBasedClassFinder(file.parent!!, packageFqName)
|
||||
val classDataFinder = DirectoryBasedDataFinder(classFinder, LOG)
|
||||
val annotationLoader = AnnotationLoaderForClassFileStubBuilder(classFinder, LoggingErrorReporter(LOG))
|
||||
return ClsStubBuilderComponents(classDataFinder, annotationLoader, file)
|
||||
@@ -127,7 +127,7 @@ class AnnotationLoaderForClassFileStubBuilder(
|
||||
}
|
||||
|
||||
override fun loadTypeAnnotation(proto: ProtoBuf.Annotation, nameResolver: NameResolver): ClassId =
|
||||
nameResolver.getClassId(proto.getId())
|
||||
nameResolver.getClassId(proto.id)
|
||||
|
||||
override fun loadConstant(desc: String, initializer: Any) = null
|
||||
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.serialization.deserialization.NameResolver
|
||||
import org.jetbrains.kotlin.serialization.deserialization.ProtoContainer
|
||||
import org.jetbrains.kotlin.types.KotlinType
|
||||
|
||||
public class AnnotationLoaderForStubBuilderImpl(
|
||||
class AnnotationLoaderForStubBuilderImpl(
|
||||
private val protocol: SerializerExtensionProtocol
|
||||
) : AnnotationAndConstantLoader<ClassId, Unit, ClassIdWithTarget> {
|
||||
|
||||
|
||||
@@ -23,21 +23,21 @@ import org.jetbrains.kotlin.name.FqName
|
||||
import org.jetbrains.kotlin.serialization.js.isDefaultPackageMetafile
|
||||
import org.jetbrains.kotlin.serialization.js.isPackageClassFqName
|
||||
|
||||
public object JsMetaFileUtils {
|
||||
public fun isKotlinJsMetaFile(file: VirtualFile): Boolean = file.getFileType() == KotlinJavaScriptMetaFileType
|
||||
object JsMetaFileUtils {
|
||||
fun isKotlinJsMetaFile(file: VirtualFile): Boolean = file.fileType == KotlinJavaScriptMetaFileType
|
||||
|
||||
public fun isKotlinJavaScriptInternalCompiledFile(file: VirtualFile): Boolean =
|
||||
isKotlinJsMetaFile(file) && file.getNameWithoutExtension().contains('.')
|
||||
fun isKotlinJavaScriptInternalCompiledFile(file: VirtualFile): Boolean =
|
||||
isKotlinJsMetaFile(file) && file.nameWithoutExtension.contains('.')
|
||||
|
||||
public fun getPackageFqName(file: VirtualFile): FqName = getPackageFqName(getRelativeToRootPath(file))
|
||||
fun getPackageFqName(file: VirtualFile): FqName = getPackageFqName(getRelativeToRootPath(file))
|
||||
|
||||
public fun getClassFqName(file: VirtualFile): FqName = getClassFqName(getRelativeToRootPath(file))
|
||||
fun getClassFqName(file: VirtualFile): FqName = getClassFqName(getRelativeToRootPath(file))
|
||||
|
||||
public fun getClassId(file: VirtualFile): ClassId = getClassId(getRelativeToRootPath(file))
|
||||
fun getClassId(file: VirtualFile): ClassId = getClassId(getRelativeToRootPath(file))
|
||||
|
||||
public fun isPackageHeader(file: VirtualFile): Boolean = isPackageHeader(getRelativeToRootPath(file))
|
||||
fun isPackageHeader(file: VirtualFile): Boolean = isPackageHeader(getRelativeToRootPath(file))
|
||||
|
||||
public fun getModuleDirectory(file: VirtualFile): VirtualFile =
|
||||
fun getModuleDirectory(file: VirtualFile): VirtualFile =
|
||||
getRoot(file).findChild(getModuleName(getRelativeToRootPath(file)))!!
|
||||
|
||||
private fun getRelativeToRootPath(file: VirtualFile): String = VfsUtilCore.getRelativePath(file, getRoot(file))!!
|
||||
@@ -70,6 +70,6 @@ public object JsMetaFileUtils {
|
||||
return classFqName.isPackageClassFqName()
|
||||
}
|
||||
|
||||
private fun getRoot(file: VirtualFile): VirtualFile = if (file.getParent() == null) file else getRoot(file.getParent())
|
||||
private fun getRoot(file: VirtualFile): VirtualFile = if (file.parent == null) file else getRoot(file.parent)
|
||||
}
|
||||
|
||||
|
||||
+1
-1
@@ -32,7 +32,7 @@ import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol
|
||||
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializedResourcePaths
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
public class KotlinJavaScriptDeserializerForDecompiler(
|
||||
class KotlinJavaScriptDeserializerForDecompiler(
|
||||
classFile: VirtualFile
|
||||
) : DeserializerForDecompilerBase(classFile.parent!!, JsMetaFileUtils.getPackageFqName(classFile)) {
|
||||
|
||||
|
||||
+1
-1
@@ -58,7 +58,7 @@ class KotlinJavaScriptMetaFileDecompiler : ClassFileDecompilers.Full() {
|
||||
|
||||
private val decompilerRendererForJS = DescriptorRenderer.withOptions { defaultDecompilerRendererOptions() }
|
||||
|
||||
public fun buildDecompiledTextFromJsMetadata(
|
||||
fun buildDecompiledTextFromJsMetadata(
|
||||
classFile: VirtualFile,
|
||||
resolver: ResolverForDecompiler = KotlinJavaScriptDeserializerForDecompiler(classFile)
|
||||
): DecompiledText {
|
||||
|
||||
+1
-1
@@ -20,7 +20,7 @@ import com.intellij.openapi.fileTypes.FileType
|
||||
import com.intellij.openapi.vfs.VirtualFile
|
||||
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
|
||||
|
||||
public object KotlinJavaScriptMetaFileType : FileType {
|
||||
object KotlinJavaScriptMetaFileType : FileType {
|
||||
|
||||
override fun getName() = "KJSM"
|
||||
|
||||
|
||||
+1
-1
@@ -37,7 +37,7 @@ import org.jetbrains.kotlin.serialization.js.JsSerializerProtocol
|
||||
import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializedResourcePaths
|
||||
import java.io.ByteArrayInputStream
|
||||
|
||||
public class KotlinJavaScriptStubBuilder : ClsStubBuilder() {
|
||||
class KotlinJavaScriptStubBuilder : ClsStubBuilder() {
|
||||
override fun getStubVersion() = ClassFileStubBuilder.STUB_VERSION + 1
|
||||
|
||||
override fun buildFileStub(content: FileContent): PsiFileStub<*>? {
|
||||
|
||||
+1
-1
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.psi.KtElement
|
||||
import org.jetbrains.kotlin.psi.KtDeclaration
|
||||
import com.intellij.openapi.project.DumbService
|
||||
|
||||
public class KotlinDeclarationNavigationPolicyImpl : KotlinDeclarationNavigationPolicy {
|
||||
class KotlinDeclarationNavigationPolicyImpl : KotlinDeclarationNavigationPolicy {
|
||||
override fun getOriginalElement(declaration: KtDeclaration) =
|
||||
SourceNavigationHelper.getOriginalElement(declaration)
|
||||
override fun getNavigationElement(declaration: KtDeclaration) =
|
||||
|
||||
+6
-6
@@ -78,7 +78,7 @@ private class ClassClsStubBuilder(
|
||||
private val classOrObjectStub = createClassOrObjectStubAndModifierListStub()
|
||||
|
||||
fun build() {
|
||||
val typeConstraintListData = typeStubBuilder.createTypeParameterListStub(classOrObjectStub, classProto.getTypeParameterList())
|
||||
val typeConstraintListData = typeStubBuilder.createTypeParameterListStub(classOrObjectStub, classProto.typeParameterList)
|
||||
createConstructorStub()
|
||||
createDelegationSpecifierList()
|
||||
typeStubBuilder.createTypeConstraintListStub(classOrObjectStub, typeConstraintListData)
|
||||
@@ -105,7 +105,7 @@ private class ClassClsStubBuilder(
|
||||
ProtoBuf.Class.Kind.ANNOTATION_CLASS -> listOf(KtTokens.ANNOTATION_KEYWORD)
|
||||
else -> listOf<KtModifierKeywordToken>()
|
||||
}
|
||||
return createModifierListStubForDeclaration(parent, classProto.getFlags(), relevantFlags, additionalModifiers)
|
||||
return createModifierListStubForDeclaration(parent, classProto.flags, relevantFlags, additionalModifiers)
|
||||
}
|
||||
|
||||
private fun doCreateClassOrObjectStub(): StubElement<out PsiElement> {
|
||||
@@ -115,12 +115,12 @@ private class ClassClsStubBuilder(
|
||||
val superTypeRefs = supertypeIds.filterNot {
|
||||
//TODO: filtering function types should go away
|
||||
KotlinBuiltIns.isNumberedFunctionClassFqName(it.asSingleFqName().toUnsafe())
|
||||
}.map { it.getShortClassName().ref() }.toTypedArray()
|
||||
}.map { it.shortClassName.ref() }.toTypedArray()
|
||||
return when (classKind) {
|
||||
ProtoBuf.Class.Kind.OBJECT, ProtoBuf.Class.Kind.COMPANION_OBJECT -> {
|
||||
KotlinObjectStubImpl(
|
||||
parentStub, shortName, fqName, superTypeRefs,
|
||||
isTopLevel = !classId.isNestedClass(),
|
||||
isTopLevel = !classId.isNestedClass,
|
||||
isDefault = isCompanionObject,
|
||||
isLocal = false,
|
||||
isObjectLiteral = false
|
||||
@@ -136,7 +136,7 @@ private class ClassClsStubBuilder(
|
||||
isTrait = classKind == ProtoBuf.Class.Kind.INTERFACE,
|
||||
isEnumEntry = classKind == ProtoBuf.Class.Kind.ENUM_ENTRY,
|
||||
isLocal = false,
|
||||
isTopLevel = !classId.isNestedClass()
|
||||
isTopLevel = !classId.isNestedClass
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,7 @@ private class ClassClsStubBuilder(
|
||||
}
|
||||
|
||||
private fun createInnerAndNestedClasses(classBody: KotlinPlaceHolderStubImpl<KtClassBody>) {
|
||||
classProto.getNestedClassNameList().forEach { id ->
|
||||
classProto.nestedClassNameList.forEach { id ->
|
||||
val nestedClassName = c.nameResolver.getName(id)
|
||||
if (nestedClassName != companionObjectName) {
|
||||
val nestedClassId = classId.createNestedClassId(nestedClassName)
|
||||
|
||||
+1
-1
@@ -59,7 +59,7 @@ class TypeParametersImpl(
|
||||
typeParameterProtos: Collection<ProtoBuf.TypeParameter>,
|
||||
private val parent: TypeParameters
|
||||
) : TypeParameters {
|
||||
private val typeParametersById = typeParameterProtos.map { Pair(it.getId(), nameResolver.getName(it.getName())) }.toMap()
|
||||
private val typeParametersById = typeParameterProtos.map { Pair(it.id, nameResolver.getName(it.name)) }.toMap()
|
||||
|
||||
override fun get(id: Int): Name = typeParametersById[id] ?: parent[id]
|
||||
}
|
||||
|
||||
+6
-6
@@ -46,12 +46,12 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
|
||||
val typeReference = KotlinPlaceHolderStubImpl<KtTypeReference>(parent, KtStubElementTypes.TYPE_REFERENCE)
|
||||
|
||||
val annotations = c.components.annotationLoader.loadTypeAnnotations(type, c.nameResolver).filterNot {
|
||||
val isTopLevelClass = !it.isNestedClass()
|
||||
val isTopLevelClass = !it.isNestedClass
|
||||
isTopLevelClass && it.asSingleFqName() in JvmAnnotationNames.ANNOTATIONS_COPIED_TO_TYPES
|
||||
}
|
||||
|
||||
val effectiveParent =
|
||||
if (type.getNullable()) KotlinPlaceHolderStubImpl<KtNullableType>(typeReference, KtStubElementTypes.NULLABLE_TYPE)
|
||||
if (type.nullable) KotlinPlaceHolderStubImpl<KtNullableType>(typeReference, KtStubElementTypes.NULLABLE_TYPE)
|
||||
else typeReference
|
||||
|
||||
fun createTypeParameterStub(name: Name) {
|
||||
@@ -68,7 +68,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
|
||||
|
||||
private fun createClassReferenceTypeStub(parent: KotlinStubBaseImpl<*>, type: Type, annotations: List<ClassId>) {
|
||||
if (type.hasFlexibleTypeCapabilitiesId()) {
|
||||
val id = c.nameResolver.getString(type.getFlexibleTypeCapabilitiesId())
|
||||
val id = c.nameResolver.getString(type.flexibleTypeCapabilitiesId)
|
||||
|
||||
if (id == DynamicTypeCapabilities.id) {
|
||||
KotlinPlaceHolderStubImpl<KtDynamicType>(parent, KtStubElementTypes.DYNAMIC_TYPE)
|
||||
@@ -78,7 +78,7 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
|
||||
|
||||
val classId = c.nameResolver.getClassId(type.className)
|
||||
val shouldBuildAsFunctionType = KotlinBuiltIns.isNumberedFunctionClassFqName(classId.asSingleFqName().toUnsafe())
|
||||
&& type.getArgumentList().none { it.getProjection() == Projection.STAR }
|
||||
&& type.argumentList.none { it.projection == Projection.STAR }
|
||||
if (shouldBuildAsFunctionType) {
|
||||
val extension = annotations.any { annotation ->
|
||||
val fqName = annotation.asSingleFqName()
|
||||
@@ -233,11 +233,11 @@ class TypeClsStubBuilder(private val c: ClsStubBuilderContext) {
|
||||
typeParameterProto: ProtoBuf.TypeParameter
|
||||
) {
|
||||
val modifiers = ArrayList<KtModifierKeywordToken>()
|
||||
when (typeParameterProto.getVariance()) {
|
||||
when (typeParameterProto.variance) {
|
||||
Variance.IN -> modifiers.add(KtTokens.IN_KEYWORD)
|
||||
Variance.OUT -> modifiers.add(KtTokens.OUT_KEYWORD)
|
||||
}
|
||||
if (typeParameterProto.getReified()) {
|
||||
if (typeParameterProto.reified) {
|
||||
modifiers.add(KtTokens.REIFIED_KEYWORD)
|
||||
}
|
||||
createModifierListStub(typeParameterStub, modifiers)
|
||||
|
||||
+2
-2
@@ -137,7 +137,7 @@ fun createStubForTypeName(
|
||||
onUserTypeLevel: (KotlinUserTypeStub, Int) -> Unit = { x, y -> }
|
||||
): KotlinUserTypeStub {
|
||||
val fqName =
|
||||
if (typeClassId.isLocal()) KotlinBuiltIns.FQ_NAMES.any
|
||||
if (typeClassId.isLocal) KotlinBuiltIns.FQ_NAMES.any
|
||||
else typeClassId.asSingleFqName().toUnsafe()
|
||||
val segments = fqName.pathSegments().asReversed()
|
||||
assert(segments.isNotEmpty())
|
||||
@@ -288,7 +288,7 @@ fun createTargetedAnnotationStubs(
|
||||
val (annotationClassId, target) = annotation
|
||||
val annotationEntryStubImpl = KotlinAnnotationEntryStubImpl(
|
||||
parent,
|
||||
shortName = annotationClassId.getShortClassName().ref(),
|
||||
shortName = annotationClassId.shortClassName.ref(),
|
||||
hasValueArguments = false
|
||||
)
|
||||
if (target != null) {
|
||||
|
||||
+7
-7
@@ -38,11 +38,11 @@ private val descriptorRendererForKeys = DescriptorRenderer.COMPACT_WITH_MODIFIER
|
||||
modifiers = DescriptorRendererModifier.ALL
|
||||
}
|
||||
|
||||
public fun descriptorToKey(descriptor: DeclarationDescriptor): String {
|
||||
fun descriptorToKey(descriptor: DeclarationDescriptor): String {
|
||||
return descriptorRendererForKeys.render(descriptor)
|
||||
}
|
||||
|
||||
public data class DecompiledText(public val text: String, public val renderedDescriptorsToRange: Map<String, TextRange>)
|
||||
data class DecompiledText(val text: String, val renderedDescriptorsToRange: Map<String, TextRange>)
|
||||
|
||||
fun DescriptorRendererOptions.defaultDecompilerRendererOptions() {
|
||||
withDefinedIn = false
|
||||
@@ -53,7 +53,7 @@ fun DescriptorRendererOptions.defaultDecompilerRendererOptions() {
|
||||
alwaysRenderModifiers = true
|
||||
}
|
||||
|
||||
public fun buildDecompiledText(
|
||||
fun buildDecompiledText(
|
||||
packageFqName: FqName,
|
||||
descriptors: List<DeclarationDescriptor>,
|
||||
descriptorRenderer: DescriptorRenderer
|
||||
@@ -64,7 +64,7 @@ public fun buildDecompiledText(
|
||||
fun appendDecompiledTextAndPackageName() {
|
||||
builder.append("// IntelliJ API Decompiler stub source generated from a class file\n" + "// Implementation of methods is not available")
|
||||
builder.append("\n\n")
|
||||
if (!packageFqName.isRoot()) {
|
||||
if (!packageFqName.isRoot) {
|
||||
builder.append("package ").append(packageFqName).append("\n\n")
|
||||
}
|
||||
}
|
||||
@@ -75,7 +75,7 @@ public fun buildDecompiledText(
|
||||
|
||||
fun appendDescriptor(descriptor: DeclarationDescriptor, indent: String, lastEnumEntry: Boolean? = null) {
|
||||
if (descriptor is MissingDependencyErrorClass) {
|
||||
throw IllegalStateException("${descriptor.javaClass.getSimpleName()} cannot be rendered. FqName: ${descriptor.fullFqName}")
|
||||
throw IllegalStateException("${descriptor.javaClass.simpleName} cannot be rendered. FqName: ${descriptor.fullFqName}")
|
||||
}
|
||||
val startOffset = builder.length
|
||||
if (isEnumEntry(descriptor)) {
|
||||
@@ -93,13 +93,13 @@ public fun buildDecompiledText(
|
||||
|
||||
if (descriptor is CallableDescriptor) {
|
||||
//NOTE: assuming that only return types can be flexible
|
||||
if (descriptor.getReturnType()!!.isFlexible()) {
|
||||
if (descriptor.returnType!!.isFlexible()) {
|
||||
builder.append(" ").append(FLEXIBLE_TYPE_COMMENT)
|
||||
}
|
||||
}
|
||||
|
||||
if (descriptor is FunctionDescriptor || descriptor is PropertyDescriptor) {
|
||||
if ((descriptor as MemberDescriptor).getModality() != Modality.ABSTRACT) {
|
||||
if ((descriptor as MemberDescriptor).modality != Modality.ABSTRACT) {
|
||||
if (descriptor is FunctionDescriptor) {
|
||||
builder.append(" { ").append(DECOMPILED_CODE_COMMENT).append(" }")
|
||||
}
|
||||
|
||||
+1
-1
@@ -35,7 +35,7 @@ import org.jetbrains.kotlin.serialization.deserialization.descriptors.Deserializ
|
||||
import org.jetbrains.kotlin.storage.LockBasedStorageManager
|
||||
import org.jetbrains.kotlin.storage.StorageManager
|
||||
|
||||
public abstract class DeserializerForDecompilerBase(
|
||||
abstract class DeserializerForDecompilerBase(
|
||||
val packageDirectory: VirtualFile,
|
||||
val directoryPackageFqName: FqName
|
||||
) : ResolverForDecompiler {
|
||||
|
||||
+3
-3
@@ -21,8 +21,8 @@ import org.jetbrains.kotlin.descriptors.ClassDescriptor
|
||||
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
|
||||
import org.jetbrains.kotlin.name.ClassId
|
||||
|
||||
public interface ResolverForDecompiler {
|
||||
public fun resolveTopLevelClass(classId: ClassId): ClassDescriptor?
|
||||
interface ResolverForDecompiler {
|
||||
fun resolveTopLevelClass(classId: ClassId): ClassDescriptor?
|
||||
|
||||
public fun resolveDeclarationsInFacade(facadeFqName: FqName): List<DeclarationDescriptor>
|
||||
fun resolveDeclarationsInFacade(facadeFqName: FqName): List<DeclarationDescriptor>
|
||||
}
|
||||
|
||||
+1
-1
@@ -74,7 +74,7 @@ private class MissingDependencyErrorClassDescriptor(
|
||||
init {
|
||||
val emptyConstructor = ConstructorDescriptorImpl.create(this, Annotations.EMPTY, true, SourceElement.NO_SOURCE)
|
||||
emptyConstructor.initialize(listOf(), Visibilities.DEFAULT_VISIBILITY)
|
||||
emptyConstructor.setReturnType(createErrorType("<ERROR RETURN TYPE>"))
|
||||
emptyConstructor.returnType = createErrorType("<ERROR RETURN TYPE>")
|
||||
initialize(MemberScope.Empty, setOf(emptyConstructor), emptyConstructor)
|
||||
}
|
||||
|
||||
|
||||
+9
-9
@@ -21,20 +21,20 @@ import com.intellij.psi.PsiElement
|
||||
import com.intellij.psi.PsiNamedElement
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
|
||||
public class KotlinFindUsagesProvider : FindUsagesProvider {
|
||||
public override fun canFindUsagesFor(psiElement: PsiElement): Boolean =
|
||||
class KotlinFindUsagesProvider : FindUsagesProvider {
|
||||
override fun canFindUsagesFor(psiElement: PsiElement): Boolean =
|
||||
psiElement is KtNamedDeclaration
|
||||
|
||||
public override fun getWordsScanner() = null
|
||||
override fun getWordsScanner() = null
|
||||
|
||||
public override fun getHelpId(psiElement: PsiElement): String? = null
|
||||
override fun getHelpId(psiElement: PsiElement): String? = null
|
||||
|
||||
public override fun getType(element: PsiElement): String {
|
||||
override fun getType(element: PsiElement): String {
|
||||
return when(element) {
|
||||
is KtNamedFunction -> "function"
|
||||
is KtClass -> "class"
|
||||
is KtParameter -> "parameter"
|
||||
is KtProperty -> if (element.isLocal()) "variable" else "property"
|
||||
is KtProperty -> if (element.isLocal) "variable" else "property"
|
||||
is KtDestructuringDeclarationEntry -> "variable"
|
||||
is KtTypeParameter -> "type parameter"
|
||||
is KtSecondaryConstructor -> "constructor"
|
||||
@@ -43,10 +43,10 @@ public class KotlinFindUsagesProvider : FindUsagesProvider {
|
||||
}
|
||||
}
|
||||
|
||||
public override fun getDescriptiveName(element: PsiElement): String {
|
||||
return if (element is PsiNamedElement) element.getName() ?: "<unnamed>" else ""
|
||||
override fun getDescriptiveName(element: PsiElement): String {
|
||||
return if (element is PsiNamedElement) element.name ?: "<unnamed>" else ""
|
||||
}
|
||||
|
||||
public override fun getNodeText(element: PsiElement, useFullName: Boolean): String =
|
||||
override fun getNodeText(element: PsiElement, useFullName: Boolean): String =
|
||||
getDescriptiveName(element)
|
||||
}
|
||||
|
||||
@@ -30,8 +30,8 @@ import org.jetbrains.kotlin.psi.psiUtil.isAncestor
|
||||
import org.jetbrains.kotlin.resolve.BindingContext
|
||||
import org.jetbrains.kotlin.resolve.DescriptorUtils
|
||||
|
||||
public object UsageTypeUtils {
|
||||
public fun getUsageType(element: PsiElement?): UsageTypeEnum? {
|
||||
object UsageTypeUtils {
|
||||
fun getUsageType(element: PsiElement?): UsageTypeEnum? {
|
||||
when (element) {
|
||||
is KtForExpression -> return IMPLICIT_ITERATION
|
||||
is KtDestructuringDeclaration -> return READ
|
||||
@@ -48,7 +48,7 @@ public object UsageTypeUtils {
|
||||
return when {
|
||||
refExpr.getNonStrictParentOfType<KtImportDirective>() != null ->
|
||||
CLASS_IMPORT
|
||||
refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression>(){ getCallableReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtCallableReferenceExpression>(){ callableReference } != null ->
|
||||
CALLABLE_REFERENCE
|
||||
else -> null
|
||||
}
|
||||
@@ -60,10 +60,10 @@ public object UsageTypeUtils {
|
||||
val property = refExpr.getNonStrictParentOfType<KtProperty>()
|
||||
if (property != null) {
|
||||
when {
|
||||
property.getTypeReference().isAncestor(refExpr) ->
|
||||
return if (property.isLocal()) CLASS_LOCAL_VAR_DECLARATION else NON_LOCAL_PROPERTY_TYPE
|
||||
property.typeReference.isAncestor(refExpr) ->
|
||||
return if (property.isLocal) CLASS_LOCAL_VAR_DECLARATION else NON_LOCAL_PROPERTY_TYPE
|
||||
|
||||
property.getReceiverTypeReference().isAncestor(refExpr) ->
|
||||
property.receiverTypeReference.isAncestor(refExpr) ->
|
||||
return EXTENSION_RECEIVER_TYPE
|
||||
}
|
||||
}
|
||||
@@ -71,48 +71,48 @@ public object UsageTypeUtils {
|
||||
val function = refExpr.getNonStrictParentOfType<KtFunction>()
|
||||
if (function != null) {
|
||||
when {
|
||||
function.getTypeReference().isAncestor(refExpr) ->
|
||||
function.typeReference.isAncestor(refExpr) ->
|
||||
return FUNCTION_RETURN_TYPE
|
||||
function.getReceiverTypeReference().isAncestor(refExpr) ->
|
||||
function.receiverTypeReference.isAncestor(refExpr) ->
|
||||
return EXTENSION_RECEIVER_TYPE
|
||||
}
|
||||
}
|
||||
|
||||
return when {
|
||||
refExpr.getParentOfTypeAndBranch<KtTypeParameter>(){ getExtendsBound() } != null
|
||||
|| refExpr.getParentOfTypeAndBranch<KtTypeConstraint>(){ getBoundTypeReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtTypeParameter>(){ extendsBound } != null
|
||||
|| refExpr.getParentOfTypeAndBranch<KtTypeConstraint>(){ boundTypeReference } != null ->
|
||||
TYPE_CONSTRAINT
|
||||
|
||||
refExpr is KtSuperTypeListEntry
|
||||
|| refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry>(){ getTypeReference() } != null ->
|
||||
|| refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry>(){ typeReference } != null ->
|
||||
SUPER_TYPE
|
||||
|
||||
refExpr.getParentOfTypeAndBranch<KtTypedef>(){ getTypeReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtTypedef>(){ typeReference } != null ->
|
||||
TYPE_DEFINITION
|
||||
|
||||
refExpr.getParentOfTypeAndBranch<KtParameter>(){ getTypeReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtParameter>(){ typeReference } != null ->
|
||||
VALUE_PARAMETER_TYPE
|
||||
|
||||
refExpr.getParentOfTypeAndBranch<KtIsExpression>(){ getTypeReference() } != null
|
||||
|| refExpr.getParentOfTypeAndBranch<KtWhenConditionIsPattern>(){ getTypeReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtIsExpression>(){ typeReference } != null
|
||||
|| refExpr.getParentOfTypeAndBranch<KtWhenConditionIsPattern>(){ typeReference } != null ->
|
||||
IS
|
||||
|
||||
with(refExpr.getParentOfTypeAndBranch<KtBinaryExpressionWithTypeRHS>(){ getRight() }) {
|
||||
val opType = this?.getOperationReference()?.getReferencedNameElementType()
|
||||
with(refExpr.getParentOfTypeAndBranch<KtBinaryExpressionWithTypeRHS>(){ right }) {
|
||||
val opType = this?.operationReference?.getReferencedNameElementType()
|
||||
opType == KtTokens.AS_KEYWORD || opType == KtTokens.AS_SAFE
|
||||
} ->
|
||||
CLASS_CAST_TO
|
||||
|
||||
with(refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()) {
|
||||
if (this == null) false
|
||||
else if (getReceiverExpression() == refExpr) true
|
||||
else if (receiverExpression == refExpr) true
|
||||
else
|
||||
getSelectorExpression() == refExpr
|
||||
&& getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { getReceiverExpression() } != null
|
||||
selectorExpression == refExpr
|
||||
&& getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { receiverExpression } != null
|
||||
} ->
|
||||
CLASS_OBJECT_ACCESS
|
||||
|
||||
refExpr.getParentOfTypeAndBranch<KtSuperExpression>(){ getSuperTypeQualifier() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtSuperExpression>(){ superTypeQualifier } != null ->
|
||||
SUPER_TYPE_QUALIFIER
|
||||
|
||||
else -> null
|
||||
@@ -120,21 +120,21 @@ public object UsageTypeUtils {
|
||||
}
|
||||
|
||||
fun getVariableUsageType(): UsageTypeEnum? {
|
||||
if (refExpr.getParentOfTypeAndBranch<KtDelegatedSuperTypeEntry>(){ getDelegateExpression() } != null) {
|
||||
if (refExpr.getParentOfTypeAndBranch<KtDelegatedSuperTypeEntry>(){ delegateExpression } != null) {
|
||||
return DELEGATE
|
||||
}
|
||||
|
||||
if (refExpr.getParent() is KtValueArgumentName) return NAMED_ARGUMENT
|
||||
if (refExpr.parent is KtValueArgumentName) return NAMED_ARGUMENT
|
||||
|
||||
val dotQualifiedExpression = refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()
|
||||
|
||||
if (dotQualifiedExpression != null) {
|
||||
val parent = dotQualifiedExpression.getParent()
|
||||
val parent = dotQualifiedExpression.parent
|
||||
when {
|
||||
dotQualifiedExpression.getReceiverExpression().isAncestor(refExpr) ->
|
||||
dotQualifiedExpression.receiverExpression.isAncestor(refExpr) ->
|
||||
return RECEIVER
|
||||
|
||||
parent is KtDotQualifiedExpression && parent.getReceiverExpression().isAncestor(refExpr) ->
|
||||
parent is KtDotQualifiedExpression && parent.receiverExpression.isAncestor(refExpr) ->
|
||||
return RECEIVER
|
||||
}
|
||||
}
|
||||
@@ -158,21 +158,21 @@ public object UsageTypeUtils {
|
||||
}
|
||||
|
||||
return when {
|
||||
refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry>(){ getTypeReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtSuperTypeListEntry>(){ typeReference } != null ->
|
||||
SUPER_TYPE
|
||||
|
||||
descriptor is ConstructorDescriptor
|
||||
&& refExpr.getParentOfTypeAndBranch<KtAnnotationEntry>(){ getTypeReference() } != null ->
|
||||
&& refExpr.getParentOfTypeAndBranch<KtAnnotationEntry>(){ typeReference } != null ->
|
||||
ANNOTATION
|
||||
|
||||
with(refExpr.getParentOfTypeAndBranch<KtCallExpression>(){ getCalleeExpression() }) {
|
||||
this?.getCalleeExpression() is KtSimpleNameExpression
|
||||
with(refExpr.getParentOfTypeAndBranch<KtCallExpression>(){ calleeExpression }) {
|
||||
this?.calleeExpression is KtSimpleNameExpression
|
||||
} ->
|
||||
if (descriptor is ConstructorDescriptor) CLASS_NEW_OPERATOR else FUNCTION_CALL
|
||||
|
||||
refExpr.getParentOfTypeAndBranch<KtBinaryExpression>(){ getOperationReference() } != null ||
|
||||
refExpr.getParentOfTypeAndBranch<KtUnaryExpression>(){ getOperationReference() } != null ||
|
||||
refExpr.getParentOfTypeAndBranch<KtWhenConditionInRange>(){ getOperationReference() } != null ->
|
||||
refExpr.getParentOfTypeAndBranch<KtBinaryExpression>(){ operationReference } != null ||
|
||||
refExpr.getParentOfTypeAndBranch<KtUnaryExpression>(){ operationReference } != null ||
|
||||
refExpr.getParentOfTypeAndBranch<KtWhenConditionInRange>(){ operationReference } != null ->
|
||||
FUNCTION_CALL
|
||||
|
||||
else -> null
|
||||
|
||||
+6
-8
@@ -26,13 +26,11 @@ import org.jetbrains.kotlin.idea.caches.JarUserDataManager
|
||||
import org.jetbrains.kotlin.js.JavaScript
|
||||
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
|
||||
|
||||
public object KotlinJavaScriptLibraryDetectionUtil {
|
||||
@JvmStatic
|
||||
public fun isKotlinJavaScriptLibrary(library: Library): Boolean =
|
||||
object KotlinJavaScriptLibraryDetectionUtil {
|
||||
@JvmStatic fun isKotlinJavaScriptLibrary(library: Library): Boolean =
|
||||
isKotlinJavaScriptLibrary(library.getFiles(OrderRootType.CLASSES).toList())
|
||||
|
||||
@JvmStatic
|
||||
public fun isKotlinJavaScriptLibrary(classesRoots: List<VirtualFile>): Boolean {
|
||||
@JvmStatic fun isKotlinJavaScriptLibrary(classesRoots: List<VirtualFile>): Boolean {
|
||||
// Prevent clashing with java runtime
|
||||
if (JavaRuntimeDetectionUtil.getJavaRuntimeVersion(classesRoots) != null) return false
|
||||
|
||||
@@ -51,11 +49,11 @@ public object KotlinJavaScriptLibraryDetectionUtil {
|
||||
}
|
||||
|
||||
private fun isJsFileWithMetadata(file: VirtualFile): Boolean =
|
||||
!file.isDirectory() &&
|
||||
JavaScript.EXTENSION == file.getExtension() &&
|
||||
!file.isDirectory &&
|
||||
JavaScript.EXTENSION == file.extension &&
|
||||
KotlinJavascriptMetadataUtils.hasMetadata(String(file.contentsToByteArray(false)))
|
||||
|
||||
public object HasKotlinJSMetadataInJar : JarUserDataManager.JarBooleanPropertyCounter(HasKotlinJSMetadataInJar::class.simpleName!!) {
|
||||
object HasKotlinJSMetadataInJar : JarUserDataManager.JarBooleanPropertyCounter(HasKotlinJSMetadataInJar::class.simpleName!!) {
|
||||
override fun hasProperty(file: VirtualFile) = KotlinJavaScriptLibraryDetectionUtil.isJsFileWithMetadata(file)
|
||||
|
||||
fun hasMetadataFromCache(root: VirtualFile): Boolean? = JarUserDataManager.hasFileWithProperty(HasKotlinJSMetadataInJar, root)
|
||||
|
||||
@@ -27,65 +27,55 @@ import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
|
||||
import org.jetbrains.kotlin.resolve.jvm.diagnostics.ConflictingJvmDeclarationsData
|
||||
import org.jetbrains.kotlin.types.KotlinType
|
||||
|
||||
public object IdeRenderers {
|
||||
object IdeRenderers {
|
||||
|
||||
@JvmField
|
||||
public val HTML_AMBIGUOUS_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
|
||||
@JvmField val HTML_AMBIGUOUS_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
|
||||
calls: Collection<ResolvedCall<*>> ->
|
||||
calls
|
||||
.map { it.getResultingDescriptor() }
|
||||
.map { it.resultingDescriptor }
|
||||
.sortedWith(MemberComparator.INSTANCE)
|
||||
.joinToString("") { "<li>" + DescriptorRenderer.HTML.render(it) + "</li>" }
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_RENDER_TYPE: Renderer<KotlinType> = Renderer {
|
||||
@JvmField val HTML_RENDER_TYPE: Renderer<KotlinType> = Renderer {
|
||||
DescriptorRenderer.HTML.renderType(it)
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_NONE_APPLICABLE_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
|
||||
@JvmField val HTML_NONE_APPLICABLE_CALLS: Renderer<Collection<ResolvedCall<*>>> = Renderer {
|
||||
calls: Collection<ResolvedCall<*>> ->
|
||||
// TODO: compareBy(comparator, selector) in stdlib
|
||||
val comparator = comparator<ResolvedCall<*>> { c1, c2 -> MemberComparator.INSTANCE.compare(c1.getResultingDescriptor(), c2.getResultingDescriptor()) }
|
||||
val comparator = comparator<ResolvedCall<*>> { c1, c2 -> MemberComparator.INSTANCE.compare(c1.resultingDescriptor, c2.resultingDescriptor) }
|
||||
calls
|
||||
.sortedWith(comparator)
|
||||
.joinToString("") { "<li>" + renderResolvedCall(it) + "</li>" }
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_TYPE_INFERENCE_CONFLICTING_SUBSTITUTIONS_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
@JvmField val HTML_TYPE_INFERENCE_CONFLICTING_SUBSTITUTIONS_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
Renderers.renderConflictingSubstitutionsInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString()
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_TYPE_INFERENCE_PARAMETER_CONSTRAINT_ERROR_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
@JvmField val HTML_TYPE_INFERENCE_PARAMETER_CONSTRAINT_ERROR_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
Renderers.renderParameterConstraintError(it, HtmlTabledDescriptorRenderer.create()).toString()
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
@JvmField val HTML_TYPE_INFERENCE_NO_INFORMATION_FOR_PARAMETER_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
Renderers.renderNoInformationForParameterError(it, HtmlTabledDescriptorRenderer.create()).toString()
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_TYPE_INFERENCE_UPPER_BOUND_VIOLATED_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
@JvmField val HTML_TYPE_INFERENCE_UPPER_BOUND_VIOLATED_RENDERER: Renderer<InferenceErrorData> = Renderer {
|
||||
Renderers.renderUpperBoundViolatedInferenceError(it, HtmlTabledDescriptorRenderer.create()).toString()
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_RENDER_RETURN_TYPE: Renderer<CallableMemberDescriptor> = Renderer {
|
||||
val returnType = it.getReturnType()!!
|
||||
@JvmField val HTML_RENDER_RETURN_TYPE: Renderer<CallableMemberDescriptor> = Renderer {
|
||||
val returnType = it.returnType!!
|
||||
DescriptorRenderer.HTML.renderType(returnType)
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_COMPACT_WITH_MODIFIERS: DescriptorRenderer = DescriptorRenderer.HTML.withOptions {
|
||||
@JvmField val HTML_COMPACT_WITH_MODIFIERS: DescriptorRenderer = DescriptorRenderer.HTML.withOptions {
|
||||
withDefinedIn = false
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_CONFLICTING_JVM_DECLARATIONS_DATA: Renderer<ConflictingJvmDeclarationsData> = Renderer {
|
||||
@JvmField val HTML_CONFLICTING_JVM_DECLARATIONS_DATA: Renderer<ConflictingJvmDeclarationsData> = Renderer {
|
||||
data: ConflictingJvmDeclarationsData ->
|
||||
|
||||
val conflicts = data.signatureOrigins
|
||||
@@ -96,8 +86,7 @@ public object IdeRenderers {
|
||||
"The following declarations have the same JVM signature (<code>${data.signature.name}${data.signature.desc}</code>):<br/>\n<ul>\n$conflicts</ul>"
|
||||
}
|
||||
|
||||
@JvmField
|
||||
public val HTML_THROWABLE: Renderer<Throwable> = Renderer {
|
||||
@JvmField val HTML_THROWABLE: Renderer<Throwable> = Renderer {
|
||||
Renderers.THROWABLE.render(it).replace("\n", "<br/>")
|
||||
}
|
||||
}
|
||||
|
||||
+2
-2
@@ -36,7 +36,7 @@ import com.intellij.psi.PsiRecursiveElementVisitor
|
||||
import org.jetbrains.kotlin.idea.kdoc.KDocHighlightingVisitor
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
|
||||
public class KotlinBeforeResolveHighlightingPass(
|
||||
class KotlinBeforeResolveHighlightingPass(
|
||||
private val file: KtFile,
|
||||
document: Document
|
||||
) : TextEditorHighlightingPass(file.project, document), DumbAware {
|
||||
@@ -68,7 +68,7 @@ public class KotlinBeforeResolveHighlightingPass(
|
||||
annotationHolder = null
|
||||
}
|
||||
|
||||
public class Factory(project: Project, registrar: TextEditorHighlightingPassRegistrar) : AbstractProjectComponent(project), TextEditorHighlightingPassFactory {
|
||||
class Factory(project: Project, registrar: TextEditorHighlightingPassRegistrar) : AbstractProjectComponent(project), TextEditorHighlightingPassFactory {
|
||||
init {
|
||||
registrar.registerTextEditorHighlightingPass(this, TextEditorHighlightingPassRegistrar.Anchor.BEFORE, Pass.UPDATE_FOLDING, false, false)
|
||||
}
|
||||
|
||||
+1
-1
@@ -24,7 +24,7 @@ import com.intellij.ide.projectView.impl.ProjectRootsUtil
|
||||
class KotlinProblemHighlightFilter : ProblemHighlightFilter() {
|
||||
|
||||
override fun shouldHighlight(psiFile: PsiFile): Boolean {
|
||||
return psiFile.getFileType() != KotlinFileType.INSTANCE || !ProjectRootsUtil.isOutsideSourceRoot(psiFile)
|
||||
return psiFile.fileType != KotlinFileType.INSTANCE || !ProjectRootsUtil.isOutsideSourceRoot(psiFile)
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -54,12 +54,12 @@ import org.jetbrains.kotlin.utils.singletonOrEmptyList
|
||||
import java.lang.reflect.*
|
||||
import java.util.*
|
||||
|
||||
public open class KotlinPsiChecker : Annotator, HighlightRangeExtension {
|
||||
open class KotlinPsiChecker : Annotator, HighlightRangeExtension {
|
||||
|
||||
override fun annotate(element: PsiElement, holder: AnnotationHolder) {
|
||||
if (!(ProjectRootsUtil.isInProjectOrLibraryContent(element) || element.getContainingFile() is KtCodeFragment)) return
|
||||
if (!(ProjectRootsUtil.isInProjectOrLibraryContent(element) || element.containingFile is KtCodeFragment)) return
|
||||
|
||||
val file = element.getContainingFile() as KtFile
|
||||
val file = element.containingFile as KtFile
|
||||
|
||||
val analysisResult = file.analyzeFullyAndGetResult()
|
||||
if (analysisResult.isError()) {
|
||||
@@ -80,7 +80,7 @@ public open class KotlinPsiChecker : Annotator, HighlightRangeExtension {
|
||||
open protected fun shouldSuppressUnusedParameter(parameter: KtParameter): Boolean = false
|
||||
|
||||
fun annotateElement(element: PsiElement, holder: AnnotationHolder, diagnostics: Diagnostics) {
|
||||
if (ProjectRootsUtil.isInProjectSource(element) || element.getContainingFile() is KtCodeFragment) {
|
||||
if (ProjectRootsUtil.isInProjectSource(element) || element.containingFile is KtCodeFragment) {
|
||||
ElementAnnotator(element, holder, { param -> shouldSuppressUnusedParameter(param) }).registerDiagnosticsAnnotations(diagnostics.forElement(element))
|
||||
}
|
||||
}
|
||||
@@ -93,7 +93,7 @@ public open class KotlinPsiChecker : Annotator, HighlightRangeExtension {
|
||||
TypeKindHighlightingVisitor(holder, bindingContext)
|
||||
)
|
||||
|
||||
public fun createQuickFixes(diagnostic: Diagnostic): Collection<IntentionAction> =
|
||||
fun createQuickFixes(diagnostic: Diagnostic): Collection<IntentionAction> =
|
||||
createQuickFixes(diagnostic.singletonOrEmptyList())[diagnostic]
|
||||
}
|
||||
}
|
||||
@@ -118,7 +118,7 @@ private fun createQuickFixes(similarDiagnostics: Collection<Diagnostic>): MultiM
|
||||
}
|
||||
|
||||
for (diagnostic in similarDiagnostics) {
|
||||
actions.putValues(diagnostic, QuickFixes.getInstance().getActions(diagnostic.getFactory()))
|
||||
actions.putValues(diagnostic, QuickFixes.getInstance().getActions(diagnostic.factory))
|
||||
}
|
||||
|
||||
actions.values().forEach { NoDeclarationDescriptorsChecker.check(it.javaClass) }
|
||||
@@ -177,9 +177,9 @@ private class ElementAnnotator(private val element: PsiElement,
|
||||
if (validDiagnostics.isEmpty()) return
|
||||
|
||||
val diagnostic = diagnostics.first()
|
||||
val factory = diagnostic.getFactory()
|
||||
val factory = diagnostic.factory
|
||||
|
||||
assert(diagnostics.all { it.getPsiElement() == element && it.factory == factory })
|
||||
assert(diagnostics.all { it.psiElement == element && it.factory == factory })
|
||||
|
||||
val ranges = diagnostic.textRanges
|
||||
|
||||
@@ -191,7 +191,7 @@ private class ElementAnnotator(private val element: PsiElement,
|
||||
val reference = referenceExpression.mainReference
|
||||
if (reference is MultiRangeReference) {
|
||||
AnnotationPresentationInfo(
|
||||
ranges = reference.getRanges().map { it.shiftRight(referenceExpression.getTextOffset()) },
|
||||
ranges = reference.ranges.map { it.shiftRight(referenceExpression.textOffset) },
|
||||
highlightType = ProblemHighlightType.LIKE_UNKNOWN_SYMBOL)
|
||||
}
|
||||
else {
|
||||
@@ -202,7 +202,7 @@ private class ElementAnnotator(private val element: PsiElement,
|
||||
Errors.ILLEGAL_ESCAPE -> AnnotationPresentationInfo(ranges, textAttributes = KotlinHighlightingColors.INVALID_STRING_ESCAPE)
|
||||
|
||||
Errors.REDECLARATION -> AnnotationPresentationInfo(
|
||||
ranges = listOf(diagnostic.getTextRanges().first()), nonDefaultMessage = "")
|
||||
ranges = listOf(diagnostic.textRanges.first()), nonDefaultMessage = "")
|
||||
|
||||
else -> {
|
||||
AnnotationPresentationInfo(
|
||||
@@ -243,12 +243,12 @@ private class ElementAnnotator(private val element: PsiElement,
|
||||
|
||||
fixes.forEach { annotation.registerFix(it) }
|
||||
|
||||
if (diagnostic.getSeverity() == Severity.WARNING) {
|
||||
annotation.setProblemGroup(KotlinSuppressableWarningProblemGroup(diagnostic.getFactory()))
|
||||
if (diagnostic.severity == Severity.WARNING) {
|
||||
annotation.problemGroup = KotlinSuppressableWarningProblemGroup(diagnostic.factory)
|
||||
|
||||
if (fixes.isEmpty()) {
|
||||
// if there are no quick fixes we need to register an EmptyIntentionAction to enable 'suppress' actions
|
||||
annotation.registerFix(EmptyIntentionAction(diagnostic.getFactory().getName()))
|
||||
annotation.registerFix(EmptyIntentionAction(diagnostic.factory.name))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -262,7 +262,7 @@ private class AnnotationPresentationInfo(
|
||||
val highlightType: ProblemHighlightType? = null,
|
||||
val textAttributes: TextAttributesKey? = null) {
|
||||
|
||||
public fun create(diagnostic: Diagnostic, range: TextRange, holder: AnnotationHolder): Annotation {
|
||||
fun create(diagnostic: Diagnostic, range: TextRange, holder: AnnotationHolder): Annotation {
|
||||
val defaultMessage = nonDefaultMessage?: getDefaultMessage(diagnostic)
|
||||
|
||||
val annotation = when (diagnostic.severity) {
|
||||
@@ -286,8 +286,8 @@ private class AnnotationPresentationInfo(
|
||||
|
||||
private fun getMessage(diagnostic: Diagnostic): String {
|
||||
var message = IdeErrorMessages.render(diagnostic)
|
||||
if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode()) {
|
||||
val factoryName = diagnostic.getFactory().getName()
|
||||
if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode) {
|
||||
val factoryName = diagnostic.factory.name
|
||||
if (message.startsWith("<html>")) {
|
||||
message = "<html>[$factoryName] ${message.substring("<html>".length)}"
|
||||
}
|
||||
@@ -303,8 +303,8 @@ private class AnnotationPresentationInfo(
|
||||
|
||||
private fun getDefaultMessage(diagnostic: Diagnostic): String {
|
||||
val message = DefaultErrorMessages.render(diagnostic)
|
||||
if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode()) {
|
||||
return "[${diagnostic.getFactory().getName()}] $message"
|
||||
if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode) {
|
||||
return "[${diagnostic.factory.name}] $message"
|
||||
}
|
||||
return message
|
||||
}
|
||||
|
||||
+8
-8
@@ -32,10 +32,10 @@ class KotlinSuppressableWarningProblemGroup(
|
||||
) : SuppressableProblemGroup {
|
||||
|
||||
init {
|
||||
assert (diagnosticFactory.getSeverity() == Severity.WARNING)
|
||||
assert (diagnosticFactory.severity == Severity.WARNING)
|
||||
}
|
||||
|
||||
override fun getProblemName() = diagnosticFactory.getName()
|
||||
override fun getProblemName() = diagnosticFactory.name
|
||||
|
||||
override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction> {
|
||||
if (element == null)
|
||||
@@ -99,10 +99,10 @@ private object DeclarationKindDetector : KtVisitor<AnnotationHostKind?, Unit?>()
|
||||
|
||||
override fun visitNamedFunction(d: KtNamedFunction, data: Unit?) = detect(d, "fun")
|
||||
|
||||
override fun visitProperty(d: KtProperty, data: Unit?) = detect(d, d.getValOrVarKeyword().getText()!!)
|
||||
override fun visitProperty(d: KtProperty, data: Unit?) = detect(d, d.valOrVarKeyword.text!!)
|
||||
|
||||
override fun visitDestructuringDeclaration(d: KtDestructuringDeclaration, data: Unit?) = detect(d, d.getValOrVarKeyword()?.getText() ?: "val",
|
||||
name = d.getEntries().map { it.getName()!! }.joinToString(", ", "(", ")"))
|
||||
override fun visitDestructuringDeclaration(d: KtDestructuringDeclaration, data: Unit?) = detect(d, d.valOrVarKeyword?.text ?: "val",
|
||||
name = d.entries.map { it.name!! }.joinToString(", ", "(", ")"))
|
||||
|
||||
override fun visitTypeParameter(d: KtTypeParameter, data: Unit?) = detect(d, "type parameter", newLineNeeded = false)
|
||||
|
||||
@@ -111,11 +111,11 @@ private object DeclarationKindDetector : KtVisitor<AnnotationHostKind?, Unit?>()
|
||||
override fun visitParameter(d: KtParameter, data: Unit?) = detect(d, "parameter", newLineNeeded = false)
|
||||
|
||||
override fun visitObjectDeclaration(d: KtObjectDeclaration, data: Unit?): AnnotationHostKind? {
|
||||
if (d.isCompanion()) return detect(d, "companion object", name = "${d.getName()} of ${d.getStrictParentOfType<KtClass>()?.getName()}")
|
||||
if (d.getParent() is KtObjectLiteralExpression) return null
|
||||
if (d.isCompanion()) return detect(d, "companion object", name = "${d.name} of ${d.getStrictParentOfType<KtClass>()?.name}")
|
||||
if (d.parent is KtObjectLiteralExpression) return null
|
||||
return detect(d, "object")
|
||||
}
|
||||
|
||||
private fun detect(declaration: KtDeclaration, kind: String, name: String = declaration.getName() ?: "<anonymous>", newLineNeeded: Boolean = true)
|
||||
private fun detect(declaration: KtDeclaration, kind: String, name: String = declaration.name ?: "<anonymous>", newLineNeeded: Boolean = true)
|
||||
= AnnotationHostKind(kind, name, newLineNeeded)
|
||||
}
|
||||
|
||||
@@ -23,20 +23,20 @@ import com.intellij.psi.PsiElement
|
||||
import org.jetbrains.annotations.TestOnly
|
||||
|
||||
object NameHighlighter {
|
||||
public var namesHighlightingEnabled = true
|
||||
var namesHighlightingEnabled = true
|
||||
@TestOnly set
|
||||
|
||||
@JvmStatic
|
||||
fun highlightName(holder: AnnotationHolder, psiElement: PsiElement, attributesKey: TextAttributesKey) {
|
||||
if (namesHighlightingEnabled) {
|
||||
holder.createInfoAnnotation(psiElement, null).setTextAttributes(attributesKey)
|
||||
holder.createInfoAnnotation(psiElement, null).textAttributes = attributesKey
|
||||
}
|
||||
}
|
||||
|
||||
@JvmStatic
|
||||
fun highlightName(holder: AnnotationHolder, textRange: TextRange, attributesKey: TextAttributesKey) {
|
||||
if (namesHighlightingEnabled) {
|
||||
holder.createInfoAnnotation(textRange, null).setTextAttributes(attributesKey)
|
||||
holder.createInfoAnnotation(textRange, null).textAttributes = attributesKey
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -32,11 +32,11 @@ import org.jetbrains.kotlin.types.ErrorUtils
|
||||
private val RED_TEMPLATE = "<font color=red><b>%s</b></font>"
|
||||
private val STRONG_TEMPLATE = "<b>%s</b>"
|
||||
|
||||
public fun renderStrong(o: Any): String = STRONG_TEMPLATE.format(o)
|
||||
fun renderStrong(o: Any): String = STRONG_TEMPLATE.format(o)
|
||||
|
||||
public fun renderError(o: Any): String = RED_TEMPLATE.format(o)
|
||||
fun renderError(o: Any): String = RED_TEMPLATE.format(o)
|
||||
|
||||
public fun renderStrong(o: Any, error: Boolean): String = (if (error) RED_TEMPLATE else STRONG_TEMPLATE).format(o)
|
||||
fun renderStrong(o: Any, error: Boolean): String = (if (error) RED_TEMPLATE else STRONG_TEMPLATE).format(o)
|
||||
|
||||
private val HTML_FOR_UNINFERRED_TYPE_PARAMS: DescriptorRenderer = DescriptorRenderer.withOptions {
|
||||
uninferredTypeParameterAsName = true
|
||||
@@ -54,7 +54,7 @@ fun <D : CallableDescriptor> renderResolvedCall(resolvedCall: ResolvedCall<D>):
|
||||
|
||||
fun renderParameter(parameter: ValueParameterDescriptor): String {
|
||||
val varargElementType = parameter.varargElementType
|
||||
val parameterType = varargElementType ?: parameter.getType()
|
||||
val parameterType = varargElementType ?: parameter.type
|
||||
val renderedParameter =
|
||||
(if (varargElementType != null) "<b>vararg</b> " else "") +
|
||||
htmlRenderer.renderType(parameterType) +
|
||||
@@ -66,50 +66,50 @@ fun <D : CallableDescriptor> renderResolvedCall(resolvedCall: ResolvedCall<D>):
|
||||
}
|
||||
|
||||
fun appendTypeParametersSubstitution() {
|
||||
val parametersToArgumentsMap = resolvedCall.getTypeArguments()
|
||||
val parametersToArgumentsMap = resolvedCall.typeArguments
|
||||
fun TypeParameterDescriptor.isInferred(): Boolean {
|
||||
val typeArgument = parametersToArgumentsMap[this]
|
||||
if (typeArgument == null) return false
|
||||
return !ErrorUtils.isUninferredParameter(typeArgument)
|
||||
}
|
||||
|
||||
val typeParameters = resolvedCall.getCandidateDescriptor().getTypeParameters()
|
||||
val typeParameters = resolvedCall.candidateDescriptor.typeParameters
|
||||
val (inferredTypeParameters, notInferredTypeParameters) = typeParameters.partition { parameter -> parameter.isInferred() }
|
||||
|
||||
append("<br/>$indent<i>where</i> ")
|
||||
if (!notInferredTypeParameters.isEmpty()) {
|
||||
append(notInferredTypeParameters.map { typeParameter -> renderError(typeParameter.getName()) }.joinToString())
|
||||
append(notInferredTypeParameters.map { typeParameter -> renderError(typeParameter.name) }.joinToString())
|
||||
append("<i> cannot be inferred</i>")
|
||||
if (!inferredTypeParameters.isEmpty()) {
|
||||
append("; ")
|
||||
}
|
||||
}
|
||||
|
||||
val typeParameterToTypeArgumentMap = resolvedCall.getTypeArguments()
|
||||
val typeParameterToTypeArgumentMap = resolvedCall.typeArguments
|
||||
if (!inferredTypeParameters.isEmpty()) {
|
||||
append(inferredTypeParameters.map { typeParameter ->
|
||||
"${typeParameter.getName()} = ${htmlRenderer.renderType(typeParameterToTypeArgumentMap[typeParameter]!!)}"
|
||||
"${typeParameter.name} = ${htmlRenderer.renderType(typeParameterToTypeArgumentMap[typeParameter]!!)}"
|
||||
}.joinToString())
|
||||
}
|
||||
}
|
||||
|
||||
val resultingDescriptor = resolvedCall.getResultingDescriptor()
|
||||
val receiverParameter = resultingDescriptor.getExtensionReceiverParameter()
|
||||
val resultingDescriptor = resolvedCall.resultingDescriptor
|
||||
val receiverParameter = resultingDescriptor.extensionReceiverParameter
|
||||
if (receiverParameter != null) {
|
||||
append(htmlRenderer.renderType(receiverParameter.getType())).append(".")
|
||||
append(htmlRenderer.renderType(receiverParameter.type)).append(".")
|
||||
}
|
||||
append(resultingDescriptor.getName()).append("(")
|
||||
append(resultingDescriptor.getValueParameters().map { parameter -> renderParameter(parameter) }.joinToString())
|
||||
append(resultingDescriptor.name).append("(")
|
||||
append(resultingDescriptor.valueParameters.map { parameter -> renderParameter(parameter) }.joinToString())
|
||||
append(if (resolvedCall.hasUnmappedArguments()) renderError(")") else ")")
|
||||
|
||||
if (!resolvedCall.getCandidateDescriptor().getTypeParameters().isEmpty()) {
|
||||
if (!resolvedCall.candidateDescriptor.typeParameters.isEmpty()) {
|
||||
appendTypeParametersSubstitution()
|
||||
append("<i> for </i><br/>$indent")
|
||||
append(htmlRenderer.render(resolvedCall.getCandidateDescriptor()))
|
||||
append(htmlRenderer.render(resolvedCall.candidateDescriptor))
|
||||
}
|
||||
else {
|
||||
append(" <i>defined in</i> ")
|
||||
val containingDeclaration = resultingDescriptor.getContainingDeclaration()
|
||||
val containingDeclaration = resultingDescriptor.containingDeclaration
|
||||
val fqName = DescriptorUtils.getFqName(containingDeclaration)
|
||||
append(if (fqName.isRoot) "root package" else fqName.asString())
|
||||
}
|
||||
|
||||
+4
-4
@@ -26,15 +26,15 @@ import org.jetbrains.kotlin.diagnostics.Severity
|
||||
import org.jetbrains.kotlin.idea.highlighter.createSuppressWarningActions
|
||||
import org.jetbrains.kotlin.idea.caches.resolve.KotlinCacheService
|
||||
|
||||
public abstract class AbstractKotlinInspection: LocalInspectionTool(), CustomSuppressableInspectionTool {
|
||||
public override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction>? {
|
||||
abstract class AbstractKotlinInspection: LocalInspectionTool(), CustomSuppressableInspectionTool {
|
||||
override fun getSuppressActions(element: PsiElement?): Array<SuppressIntentionAction>? {
|
||||
if (element == null) return emptyArray()
|
||||
|
||||
return createSuppressWarningActions(element, toSeverity(defaultLevel), suppressionKey).toTypedArray()
|
||||
}
|
||||
|
||||
public override fun isSuppressedFor(element: PsiElement): Boolean {
|
||||
if (SuppressManager.getInstance()!!.isSuppressedFor(element, getID())) {
|
||||
override fun isSuppressedFor(element: PsiElement): Boolean {
|
||||
if (SuppressManager.getInstance()!!.isSuppressedFor(element, id)) {
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
+10
-10
@@ -34,8 +34,8 @@ import com.intellij.util.SmartList
|
||||
import org.jetbrains.kotlin.idea.intentions.SelfTargetingRangeIntention
|
||||
import org.jetbrains.kotlin.psi.KtElement
|
||||
|
||||
public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
public val intentions: List<IntentionBasedInspection.IntentionData<TElement>>,
|
||||
abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
val intentions: List<IntentionBasedInspection.IntentionData<TElement>>,
|
||||
protected val problemText: String?,
|
||||
protected val elementType: Class<TElement>
|
||||
) : AbstractKotlinInspection() {
|
||||
@@ -43,7 +43,7 @@ public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
constructor(intention: SelfTargetingRangeIntention<TElement>, additionalChecker: (TElement) -> Boolean = { true })
|
||||
: this(listOf(IntentionData(intention, additionalChecker)), null, intention.elementType)
|
||||
|
||||
public data class IntentionData<TElement : KtElement>(
|
||||
data class IntentionData<TElement : KtElement>(
|
||||
val intention: SelfTargetingRangeIntention<TElement>,
|
||||
val additionalChecker: (TElement) -> Boolean = { true }
|
||||
)
|
||||
@@ -51,7 +51,7 @@ public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean, session: LocalInspectionToolSession): PsiElementVisitor {
|
||||
return object : PsiElementVisitor() {
|
||||
override fun visitElement(element: PsiElement) {
|
||||
if (!elementType.isInstance(element) || element.getTextLength() == 0) return
|
||||
if (!elementType.isInstance(element) || element.textLength == 0) return
|
||||
|
||||
@Suppress("UNCHECKED_CAST")
|
||||
val targetElement = element as TElement
|
||||
@@ -62,9 +62,9 @@ public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
for ((intention, additionalChecker) in intentions) {
|
||||
synchronized(intention) {
|
||||
val range = intention.applicabilityRange(targetElement)?.let { range ->
|
||||
val elementRange = targetElement.getTextRange()
|
||||
val elementRange = targetElement.textRange
|
||||
assert(range in elementRange) { "Wrong applicabilityRange() result for $intention - should be within element's range" }
|
||||
range.shiftRight(-elementRange.getStartOffset())
|
||||
range.shiftRight(-elementRange.startOffset)
|
||||
}
|
||||
|
||||
if (range != null && additionalChecker(targetElement)) {
|
||||
@@ -96,13 +96,13 @@ public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
) : LocalQuickFixOnPsiElement(targetElement), IntentionAction {
|
||||
|
||||
// store text into variable because intention instance is shared and may change its text later
|
||||
override fun getFamilyName() = intention.getFamilyName()
|
||||
override fun getFamilyName() = intention.familyName
|
||||
|
||||
override fun getText(): String = text
|
||||
|
||||
override fun startInWriteAction() = true
|
||||
|
||||
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = isAvailable()
|
||||
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?) = isAvailable
|
||||
|
||||
override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement): Boolean {
|
||||
assert(startElement == endElement)
|
||||
@@ -119,13 +119,13 @@ public abstract class IntentionBasedInspection<TElement : KtElement>(
|
||||
if (!isAvailable(project, file, startElement, endElement)) return
|
||||
|
||||
startElement.getOrCreateEditor()?.let { editor ->
|
||||
editor.getCaretModel().moveToOffset(startElement.getTextOffset())
|
||||
editor.caretModel.moveToOffset(startElement.textOffset)
|
||||
intention.applyTo(startElement as TElement, editor)
|
||||
}
|
||||
}
|
||||
|
||||
private fun PsiElement.getOrCreateEditor(): Editor? {
|
||||
val file = getContainingFile()?.getVirtualFile() ?: return null
|
||||
val file = containingFile?.virtualFile ?: return null
|
||||
val document = FileDocumentManager.getInstance().getDocument(file) ?: return null
|
||||
|
||||
val editorFactory = EditorFactory.getInstance()
|
||||
|
||||
+31
-31
@@ -31,11 +31,11 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
|
||||
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
|
||||
public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, "Replace overloaded operator with function call") {
|
||||
class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(KtExpression::class.java, "Replace overloaded operator with function call") {
|
||||
companion object {
|
||||
private fun isApplicablePrefix(element: KtPrefixExpression, caretOffset: Int): Boolean {
|
||||
val opRef = element.getOperationReference()
|
||||
if (!opRef.getTextRange().containsOffset(caretOffset)) return false
|
||||
val opRef = element.operationReference
|
||||
if (!opRef.textRange.containsOffset(caretOffset)) return false
|
||||
return when (opRef.getReferencedNameElementType()) {
|
||||
KtTokens.PLUS, KtTokens.MINUS, KtTokens.PLUSPLUS, KtTokens.MINUSMINUS, KtTokens.EXCL -> true
|
||||
else -> false
|
||||
@@ -43,9 +43,9 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
}
|
||||
|
||||
private fun isApplicablePostfix(element: KtPostfixExpression, caretOffset: Int): Boolean {
|
||||
val opRef = element.getOperationReference()
|
||||
if (!opRef.getTextRange().containsOffset(caretOffset)) return false
|
||||
if (element.getBaseExpression() == null) return false
|
||||
val opRef = element.operationReference
|
||||
if (!opRef.textRange.containsOffset(caretOffset)) return false
|
||||
if (element.baseExpression == null) return false
|
||||
return when (opRef.getReferencedNameElementType()) {
|
||||
KtTokens.PLUSPLUS, KtTokens.MINUSMINUS -> true
|
||||
else -> false
|
||||
@@ -53,37 +53,37 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
}
|
||||
|
||||
private fun isApplicableBinary(element: KtBinaryExpression, caretOffset: Int): Boolean {
|
||||
val opRef = element.getOperationReference()
|
||||
if (!opRef.getTextRange().containsOffset(caretOffset)) return false
|
||||
val opRef = element.operationReference
|
||||
if (!opRef.textRange.containsOffset(caretOffset)) return false
|
||||
return when (opRef.getReferencedNameElementType()) {
|
||||
KtTokens.PLUS, KtTokens.MINUS, KtTokens.MUL, KtTokens.DIV, KtTokens.PERC, KtTokens.RANGE, KtTokens.IN_KEYWORD, KtTokens.NOT_IN, KtTokens.PLUSEQ, KtTokens.MINUSEQ, KtTokens.MULTEQ, KtTokens.DIVEQ, KtTokens.PERCEQ, KtTokens.EQEQ, KtTokens.EXCLEQ, KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ -> true
|
||||
KtTokens.EQ -> element.getLeft() is KtArrayAccessExpression
|
||||
KtTokens.EQ -> element.left is KtArrayAccessExpression
|
||||
else -> false
|
||||
}
|
||||
}
|
||||
|
||||
private fun isApplicableArrayAccess(element: KtArrayAccessExpression, caretOffset: Int): Boolean {
|
||||
val lbracket = element.getLeftBracket() ?: return false
|
||||
val rbracket = element.getRightBracket() ?: return false
|
||||
val lbracket = element.leftBracket ?: return false
|
||||
val rbracket = element.rightBracket ?: return false
|
||||
|
||||
val access = element.readWriteAccess(useResolveForReadWrite = true)
|
||||
if (access == ReferenceAccess.READ_WRITE) return false // currently not supported
|
||||
|
||||
return lbracket.getTextRange().containsOffset(caretOffset) || rbracket.getTextRange().containsOffset(caretOffset)
|
||||
return lbracket.textRange.containsOffset(caretOffset) || rbracket.textRange.containsOffset(caretOffset)
|
||||
}
|
||||
|
||||
private fun isApplicableCall(element: KtCallExpression, caretOffset: Int): Boolean {
|
||||
val lbrace = (element.getValueArgumentList()?.getLeftParenthesis()
|
||||
?: element.getLambdaArguments().firstOrNull()?.getLambdaExpression()?.getLeftCurlyBrace()
|
||||
val lbrace = (element.valueArgumentList?.leftParenthesis
|
||||
?: element.lambdaArguments.firstOrNull()?.getLambdaExpression()?.leftCurlyBrace
|
||||
?: return false) as PsiElement
|
||||
if (!lbrace.getTextRange().containsOffset(caretOffset)) return false
|
||||
if (!lbrace.textRange.containsOffset(caretOffset)) return false
|
||||
|
||||
val resolvedCall = element.getResolvedCall(element.analyze())
|
||||
val descriptor = resolvedCall?.getResultingDescriptor()
|
||||
val descriptor = resolvedCall?.resultingDescriptor
|
||||
if (descriptor is FunctionDescriptor && descriptor.getName() == OperatorNameConventions.INVOKE) {
|
||||
if (element.getParent() is KtDotQualifiedExpression &&
|
||||
element.getCalleeExpression()?.getText() == OperatorNameConventions.INVOKE.asString()) return false
|
||||
return element.getValueArgumentList() != null || element.getLambdaArguments().isNotEmpty()
|
||||
if (element.parent is KtDotQualifiedExpression &&
|
||||
element.calleeExpression?.text == OperatorNameConventions.INVOKE.asString()) return false
|
||||
return element.valueArgumentList != null || element.lambdaArguments.isNotEmpty()
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -104,7 +104,7 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
}
|
||||
|
||||
private fun convertPostFix(element: KtPostfixExpression): KtExpression {
|
||||
val op = element.getOperationReference().getReferencedNameElementType()
|
||||
val op = element.operationReference.getReferencedNameElementType()
|
||||
val operatorName = when (op) {
|
||||
KtTokens.PLUSPLUS -> OperatorNameConventions.INC
|
||||
KtTokens.MINUSMINUS -> OperatorNameConventions.DEC
|
||||
@@ -130,7 +130,7 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
|
||||
val context = element.analyze(BodyResolveMode.PARTIAL)
|
||||
val functionCandidate = element.getResolvedCall(context)
|
||||
val functionName = functionCandidate?.getCandidateDescriptor()?.getName().toString()
|
||||
val functionName = functionCandidate?.candidateDescriptor?.name.toString()
|
||||
val elemType = context.getType(left)
|
||||
|
||||
val pattern = when (op) {
|
||||
@@ -194,11 +194,11 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
|
||||
//TODO: don't use creation by plain text
|
||||
private fun convertCall(element: KtCallExpression): KtExpression {
|
||||
val callee = element.getCalleeExpression()!!
|
||||
val arguments = element.getValueArgumentList()
|
||||
val argumentString = arguments?.getText()?.removeSurrounding("(", ")")
|
||||
val funcLitArgs = element.getLambdaArguments()
|
||||
val calleeText = callee.getText()
|
||||
val callee = element.calleeExpression!!
|
||||
val arguments = element.valueArgumentList
|
||||
val argumentString = arguments?.text?.removeSurrounding("(", ")")
|
||||
val funcLitArgs = element.lambdaArguments
|
||||
val calleeText = callee.text
|
||||
val transformation = "$calleeText.${OperatorNameConventions.INVOKE.asString()}" +
|
||||
(if (argumentString == null) "()" else "($argumentString)")
|
||||
val transformed = KtPsiFactory(element).createExpression(transformation)
|
||||
@@ -209,10 +209,10 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
callExpression.valueArgumentList?.delete()
|
||||
}
|
||||
}
|
||||
return callee.getParent()!!.replace(transformed) as KtExpression
|
||||
return callee.parent!!.replace(transformed) as KtExpression
|
||||
}
|
||||
|
||||
public fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> {
|
||||
fun convert(element: KtExpression): Pair<KtExpression, KtSimpleNameExpression> {
|
||||
var elementToBeReplaced = element
|
||||
if (element is KtArrayAccessExpression && isAssignmentLeftSide(element)) {
|
||||
elementToBeReplaced = element.parent as KtExpression
|
||||
@@ -240,12 +240,12 @@ public class OperatorToFunctionIntention : SelfTargetingIntention<KtExpression>(
|
||||
return when (result) {
|
||||
is KtBinaryExpression -> {
|
||||
if (KtPsiUtil.isAssignment(result))
|
||||
findCallName(result.getRight()!!)
|
||||
findCallName(result.right!!)
|
||||
else
|
||||
findCallName(result.getLeft()!!)
|
||||
findCallName(result.left!!)
|
||||
}
|
||||
|
||||
is KtUnaryExpression -> findCallName(result.getBaseExpression()!!)
|
||||
is KtUnaryExpression -> findCallName(result.baseExpression!!)
|
||||
|
||||
else -> result.getQualifiedElementSelector() as KtSimpleNameExpression?
|
||||
}
|
||||
|
||||
+11
-11
@@ -34,8 +34,8 @@ import org.jetbrains.kotlin.psi.psiUtil.containsInside
|
||||
import org.jetbrains.kotlin.psi.psiUtil.parentsWithSelf
|
||||
import java.util.*
|
||||
|
||||
public abstract class SelfTargetingIntention<TElement : KtElement>(
|
||||
public val elementType: Class<TElement>,
|
||||
abstract class SelfTargetingIntention<TElement : KtElement>(
|
||||
val elementType: Class<TElement>,
|
||||
private var text: String,
|
||||
private val familyName: String = text
|
||||
) : IntentionAction {
|
||||
@@ -49,12 +49,12 @@ public abstract class SelfTargetingIntention<TElement : KtElement>(
|
||||
final override fun getText() = text
|
||||
final override fun getFamilyName() = familyName
|
||||
|
||||
public abstract fun isApplicableTo(element: TElement, caretOffset: Int): Boolean
|
||||
abstract fun isApplicableTo(element: TElement, caretOffset: Int): Boolean
|
||||
|
||||
public abstract fun applyTo(element: TElement, editor: Editor)
|
||||
abstract fun applyTo(element: TElement, editor: Editor)
|
||||
|
||||
private fun getTarget(editor: Editor, file: PsiFile): TElement? {
|
||||
val offset = editor.getCaretModel().getOffset()
|
||||
val offset = editor.caretModel.offset
|
||||
val leaf1 = file.findElementAt(offset)
|
||||
val leaf2 = file.findElementAt(offset - 1)
|
||||
val commonParent = if (leaf1 != null && leaf2 != null) PsiTreeUtil.findCommonParent(leaf1, leaf2) else null
|
||||
@@ -75,7 +75,7 @@ public abstract class SelfTargetingIntention<TElement : KtElement>(
|
||||
if (elementType.isInstance(element) && isApplicableTo(element as TElement, offset)) {
|
||||
return element
|
||||
}
|
||||
if (!allowCaretInsideElement(element) && element.getTextRange().containsInside(offset)) break
|
||||
if (!allowCaretInsideElement(element) && element.textRange.containsInside(offset)) break
|
||||
}
|
||||
return null
|
||||
}
|
||||
@@ -131,13 +131,13 @@ public abstract class SelfTargetingIntention<TElement : KtElement>(
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class SelfTargetingRangeIntention<TElement : KtElement>(
|
||||
abstract class SelfTargetingRangeIntention<TElement : KtElement>(
|
||||
elementType: Class<TElement>,
|
||||
text: String,
|
||||
familyName: String = text
|
||||
) : SelfTargetingIntention<TElement>(elementType, text, familyName) {
|
||||
|
||||
public abstract fun applicabilityRange(element: TElement): TextRange?
|
||||
abstract fun applicabilityRange(element: TElement): TextRange?
|
||||
|
||||
override final fun isApplicableTo(element: TElement, caretOffset: Int): Boolean {
|
||||
val range = applicabilityRange(element) ?: return false
|
||||
@@ -145,15 +145,15 @@ public abstract class SelfTargetingRangeIntention<TElement : KtElement>(
|
||||
}
|
||||
}
|
||||
|
||||
public abstract class SelfTargetingOffsetIndependentIntention<TElement : KtElement>(
|
||||
abstract class SelfTargetingOffsetIndependentIntention<TElement : KtElement>(
|
||||
elementType: Class<TElement>,
|
||||
text: String,
|
||||
familyName: String = text
|
||||
) : SelfTargetingRangeIntention<TElement>(elementType, text, familyName) {
|
||||
|
||||
public abstract fun isApplicableTo(element: TElement): Boolean
|
||||
abstract fun isApplicableTo(element: TElement): Boolean
|
||||
|
||||
override final fun applicabilityRange(element: TElement): TextRange? {
|
||||
return if (isApplicableTo(element)) element.getTextRange() else null
|
||||
return if (isApplicableTo(element)) element.textRange else null
|
||||
}
|
||||
}
|
||||
|
||||
@@ -25,13 +25,13 @@ import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getChildOfType
|
||||
|
||||
class KDocElementFactory(val project: Project) {
|
||||
public fun createKDocFromText(text: String): KDoc {
|
||||
fun createKDocFromText(text: String): KDoc {
|
||||
val fileText = text + " fun foo { }"
|
||||
val function = KtPsiFactory(project).createDeclaration<KtFunction>(fileText)
|
||||
return PsiTreeUtil.findChildOfType(function, KDoc::class.java)!!
|
||||
}
|
||||
|
||||
public fun createNameFromText(text: String): KDocName {
|
||||
fun createNameFromText(text: String): KDocName {
|
||||
val kdoc = createKDocFromText("/** @param $text foo*/")
|
||||
val section = kdoc.getDefaultSection()
|
||||
val tag = section.findTagByName("param")
|
||||
|
||||
@@ -28,14 +28,14 @@ import org.jetbrains.kotlin.resolve.source.PsiSourceElement
|
||||
object KDocFinder {
|
||||
fun findKDoc(declaration: DeclarationDescriptor): KDocTag? {
|
||||
if (declaration is DeclarationDescriptorWithSource) {
|
||||
var psiDeclaration = (declaration.getSource() as? PsiSourceElement)?.psi?.getNavigationElement()
|
||||
var psiDeclaration = (declaration.source as? PsiSourceElement)?.psi?.navigationElement
|
||||
// KDoc for primary constructor is located inside of its class KDoc
|
||||
if (psiDeclaration is KtPrimaryConstructor) {
|
||||
psiDeclaration = psiDeclaration.getContainingClassOrObject()
|
||||
}
|
||||
|
||||
if (psiDeclaration is KtDeclaration) {
|
||||
val kdoc = psiDeclaration.getDocComment()
|
||||
val kdoc = psiDeclaration.docComment
|
||||
if (kdoc != null) {
|
||||
if (declaration is ConstructorDescriptor) {
|
||||
// ConstructorDescriptor resolves to the same JetDeclaration
|
||||
@@ -50,7 +50,7 @@ object KDocFinder {
|
||||
}
|
||||
|
||||
if (declaration is PropertyDescriptor) {
|
||||
val containingClassDescriptor = declaration.getContainingDeclaration() as? ClassDescriptor
|
||||
val containingClassDescriptor = declaration.containingDeclaration as? ClassDescriptor
|
||||
if (containingClassDescriptor != null) {
|
||||
val classKDoc = findKDoc(containingClassDescriptor)?.getParentOfType<KDoc>(false)
|
||||
if (classKDoc != null) {
|
||||
@@ -64,8 +64,8 @@ object KDocFinder {
|
||||
}
|
||||
|
||||
if (declaration is CallableDescriptor) {
|
||||
for (baseDescriptor in declaration.getOverriddenDescriptors()) {
|
||||
val baseKDoc = findKDoc(baseDescriptor.getOriginal())
|
||||
for (baseDescriptor in declaration.overriddenDescriptors) {
|
||||
val baseKDoc = findKDoc(baseDescriptor.original)
|
||||
if (baseKDoc != null) {
|
||||
return baseKDoc
|
||||
}
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.kdoc.psi.impl.KDocLink
|
||||
class KDocHighlightingVisitor(private val holder: AnnotationHolder): PsiElementVisitor() {
|
||||
override fun visitElement(element: PsiElement) {
|
||||
if (element is KDocLink) {
|
||||
holder.createInfoAnnotation(element, null).setTextAttributes(KotlinHighlightingColors.KDOC_LINK)
|
||||
holder.createInfoAnnotation(element, null).textAttributes = KotlinHighlightingColors.KDOC_LINK
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,7 +36,7 @@ import org.jetbrains.kotlin.resolve.scopes.utils.collectDescriptorsFiltered
|
||||
import org.jetbrains.kotlin.resolve.scopes.utils.memberScopeAsImportingScope
|
||||
import org.jetbrains.kotlin.resolve.source.PsiSourceElement
|
||||
|
||||
public class KDocReference(element: KDocName): KtMultiReference<KDocName>(element) {
|
||||
class KDocReference(element: KDocName): KtMultiReference<KDocName>(element) {
|
||||
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
|
||||
val declaration = element.getContainingDoc().getOwner() ?: return arrayListOf()
|
||||
val declarationDescriptor = context[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] ?: return arrayListOf()
|
||||
@@ -64,7 +64,7 @@ public class KDocReference(element: KDocName): KtMultiReference<KDocName>(elemen
|
||||
override fun getCanonicalText(): String = element.getNameText()
|
||||
}
|
||||
|
||||
public fun resolveKDocLink(resolutionFacade: ResolutionFacade,
|
||||
fun resolveKDocLink(resolutionFacade: ResolutionFacade,
|
||||
fromDescriptor: DeclarationDescriptor,
|
||||
fromSubjectOfTag: KDocTag?,
|
||||
qualifiedName: List<String>): Collection<DeclarationDescriptor> {
|
||||
@@ -98,7 +98,7 @@ private fun resolveInLocalScope(fromDescriptor: DeclarationDescriptor,
|
||||
}
|
||||
}
|
||||
|
||||
public fun getParamDescriptors(fromDescriptor: DeclarationDescriptor): List<DeclarationDescriptor> {
|
||||
fun getParamDescriptors(fromDescriptor: DeclarationDescriptor): List<DeclarationDescriptor> {
|
||||
// TODO resolve parameters of functions passed as parameters
|
||||
when (fromDescriptor) {
|
||||
is CallableDescriptor ->
|
||||
@@ -151,7 +151,7 @@ private fun getClassInnerScope(outerScope: LexicalScope, descriptor: ClassDescri
|
||||
scopeChain)
|
||||
}
|
||||
|
||||
public fun getResolutionScope(resolutionFacade: ResolutionFacade, descriptor: DeclarationDescriptor): LexicalScope {
|
||||
fun getResolutionScope(resolutionFacade: ResolutionFacade, descriptor: DeclarationDescriptor): LexicalScope {
|
||||
return when (descriptor) {
|
||||
is PackageFragmentDescriptor ->
|
||||
LexicalScope.empty(getPackageInnerScope(descriptor).memberScopeAsImportingScope(), descriptor)
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ import com.intellij.psi.PsiElement
|
||||
import org.jetbrains.kotlin.idea.references.mainReference
|
||||
import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
|
||||
|
||||
public class KDocUnresolvedReferenceInspection(): AbstractKotlinInspection() {
|
||||
class KDocUnresolvedReferenceInspection(): AbstractKotlinInspection() {
|
||||
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor =
|
||||
KDocUnresolvedReferenceVisitor(holder)
|
||||
|
||||
|
||||
@@ -24,10 +24,10 @@ import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade
|
||||
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
|
||||
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
|
||||
|
||||
public object AnalyzerFacadeProvider {
|
||||
object AnalyzerFacadeProvider {
|
||||
//NOTE: it's convenient that JS backend doesn't have platform parameters (for now)
|
||||
// otherwise we would be forced to add casts on the call site of setupResolverForProject
|
||||
public fun getAnalyzerFacade(targetPlatform: TargetPlatform): AnalyzerFacade<JvmPlatformParameters> {
|
||||
fun getAnalyzerFacade(targetPlatform: TargetPlatform): AnalyzerFacade<JvmPlatformParameters> {
|
||||
return when (targetPlatform) {
|
||||
JvmPlatform -> JvmAnalyzerFacade
|
||||
JsPlatform -> JsAnalyzerFacade
|
||||
|
||||
@@ -20,7 +20,7 @@ import org.jetbrains.kotlin.container.StorageComponentContainer
|
||||
import org.jetbrains.kotlin.container.useImpl
|
||||
import org.jetbrains.kotlin.resolve.TargetEnvironment
|
||||
|
||||
public object IdeaEnvironment : TargetEnvironment("Idea") {
|
||||
object IdeaEnvironment : TargetEnvironment("Idea") {
|
||||
override fun configure(container: StorageComponentContainer) {
|
||||
container.useImpl<ResolveElementCache>()
|
||||
container.useImpl<IdeaLocalDescriptorResolver>()
|
||||
|
||||
+1
-1
@@ -23,7 +23,7 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
import org.jetbrains.kotlin.resolve.lazy.LocalDescriptorResolver
|
||||
import org.jetbrains.kotlin.resolve.lazy.NoDescriptorForDeclarationException
|
||||
|
||||
public class IdeaLocalDescriptorResolver(
|
||||
class IdeaLocalDescriptorResolver(
|
||||
private val resolveElementCache: ResolveElementCache
|
||||
): LocalDescriptorResolver {
|
||||
override fun resolveLocalDeclaration(declaration: KtDeclaration): DeclarationDescriptor {
|
||||
|
||||
@@ -47,7 +47,7 @@ import org.jetbrains.kotlin.resolve.lazy.descriptors.LazyScriptDescriptor
|
||||
import org.jetbrains.kotlin.resolve.scopes.LexicalScope
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.check
|
||||
|
||||
public class ResolveElementCache(
|
||||
class ResolveElementCache(
|
||||
private val resolveSession: ResolveSession,
|
||||
private val project: Project,
|
||||
private val targetPlatform: TargetPlatform,
|
||||
@@ -114,7 +114,7 @@ public class ResolveElementCache(
|
||||
override fun resolveFunctionBody(function: KtNamedFunction)
|
||||
= getElementAdditionalResolve(function, function, BodyResolveMode.FULL)
|
||||
|
||||
public fun resolvePrimaryConstructorParametersDefaultValues(ktClass: KtClass): BindingContext {
|
||||
fun resolvePrimaryConstructorParametersDefaultValues(ktClass: KtClass): BindingContext {
|
||||
return constructorAdditionalResolve(resolveSession, ktClass, ktClass.getContainingKtFile()).bindingContext
|
||||
}
|
||||
|
||||
@@ -179,7 +179,7 @@ public class ResolveElementCache(
|
||||
}
|
||||
}
|
||||
|
||||
public fun resolveToElement(element: KtElement, bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL): BindingContext {
|
||||
fun resolveToElement(element: KtElement, bodyResolveMode: BodyResolveMode = BodyResolveMode.FULL): BindingContext {
|
||||
var contextElement = element
|
||||
|
||||
val elementOfAdditionalResolve = findElementOfAdditionalResolve(contextElement)
|
||||
@@ -198,7 +198,7 @@ public class ResolveElementCache(
|
||||
resolveSession.resolveToDescriptor(declaration)
|
||||
}
|
||||
|
||||
return resolveSession.getBindingContext()
|
||||
return resolveSession.bindingContext
|
||||
}
|
||||
|
||||
private fun findElementOfAdditionalResolve(element: KtElement): KtElement? {
|
||||
@@ -313,11 +313,11 @@ public class ResolveElementCache(
|
||||
}
|
||||
}
|
||||
|
||||
val controlFlowTrace = DelegatingBindingTrace(trace.getBindingContext(), "Element control flow resolve", resolveElement)
|
||||
val controlFlowTrace = DelegatingBindingTrace(trace.bindingContext, "Element control flow resolve", resolveElement)
|
||||
ControlFlowInformationProvider(resolveElement, controlFlowTrace).checkDeclaration()
|
||||
controlFlowTrace.addOwnDataTo(trace, null, false)
|
||||
|
||||
return Pair(trace.getBindingContext(), statementFilterUsed)
|
||||
return Pair(trace.bindingContext, statementFilterUsed)
|
||||
}
|
||||
|
||||
private fun packageRefAdditionalResolve(resolveSession: ResolveSession, ktElement: KtElement): BindingTrace {
|
||||
@@ -327,7 +327,7 @@ public class ResolveElementCache(
|
||||
val header = ktElement.getParentOfType<KtPackageDirective>(true)!!
|
||||
|
||||
if (Name.isValidIdentifier(ktElement.getReferencedName())) {
|
||||
if (trace.getBindingContext()[BindingContext.REFERENCE_TARGET, ktElement] == null) {
|
||||
if (trace.bindingContext[BindingContext.REFERENCE_TARGET, ktElement] == null) {
|
||||
val fqName = header.getFqName(ktElement)
|
||||
val packageDescriptor = resolveSession.moduleDescriptor.getPackage(fqName)
|
||||
trace.record(BindingContext.REFERENCE_TARGET, ktElement, packageDescriptor)
|
||||
@@ -372,7 +372,7 @@ public class ResolveElementCache(
|
||||
if (fileAnnotationList != null) {
|
||||
doResolveAnnotations(resolveSession.getFileAnnotations(fileAnnotationList.getContainingKtFile()))
|
||||
}
|
||||
if (modifierList != null && modifierList.getParent() is KtFile) {
|
||||
if (modifierList != null && modifierList.parent is KtFile) {
|
||||
doResolveAnnotations(resolveSession.getDanglingAnnotations(modifierList.getContainingKtFile()))
|
||||
}
|
||||
}
|
||||
@@ -388,16 +388,16 @@ public class ResolveElementCache(
|
||||
var descriptor = resolveSession.resolveToDescriptor(declaration)
|
||||
if (declaration is KtClass) {
|
||||
if (modifierList == declaration.getPrimaryConstructorModifierList()) {
|
||||
descriptor = (descriptor as ClassDescriptor).getUnsubstitutedPrimaryConstructor()
|
||||
descriptor = (descriptor as ClassDescriptor).unsubstitutedPrimaryConstructor
|
||||
?: error("No constructor found: ${declaration.getText()}")
|
||||
}
|
||||
}
|
||||
|
||||
if (declaration is KtClassOrObject && modifierList.getParent() == declaration.getBody() && descriptor is LazyClassDescriptor) {
|
||||
return descriptor.getDanglingAnnotations()
|
||||
if (declaration is KtClassOrObject && modifierList.parent == declaration.getBody() && descriptor is LazyClassDescriptor) {
|
||||
return descriptor.danglingAnnotations
|
||||
}
|
||||
|
||||
return descriptor.getAnnotations()
|
||||
return descriptor.annotations
|
||||
}
|
||||
|
||||
private fun typeParameterAdditionalResolve(analyzer: KotlinCodeAnalyzer, typeParameter: KtTypeParameter): BindingTrace {
|
||||
@@ -412,15 +412,15 @@ public class ResolveElementCache(
|
||||
val descriptor = resolveSession.resolveToDescriptor(classOrObject) as LazyClassDescriptor
|
||||
|
||||
// Activate resolving of supertypes
|
||||
ForceResolveUtil.forceResolveAllContents(descriptor.getTypeConstructor().getSupertypes())
|
||||
ForceResolveUtil.forceResolveAllContents(descriptor.typeConstructor.supertypes)
|
||||
|
||||
val bodyResolver = createBodyResolver(resolveSession, trace, file, StatementFilter.NONE)
|
||||
bodyResolver.resolveSuperTypeEntryList(DataFlowInfo.EMPTY,
|
||||
classOrObject,
|
||||
descriptor,
|
||||
descriptor.getUnsubstitutedPrimaryConstructor(),
|
||||
descriptor.unsubstitutedPrimaryConstructor,
|
||||
descriptor.scopeForConstructorHeaderResolution,
|
||||
descriptor.getScopeForMemberDeclarationResolution())
|
||||
descriptor.scopeForMemberDeclarationResolution)
|
||||
|
||||
return trace
|
||||
}
|
||||
@@ -433,7 +433,7 @@ public class ResolveElementCache(
|
||||
ForceResolveUtil.forceResolveAllContents(descriptor)
|
||||
|
||||
val bodyResolveContext = BodyResolveContextForLazy(TopDownAnalysisMode.LocalDeclarations, { declaration ->
|
||||
assert(declaration.getParent() == property || declaration == property) {
|
||||
assert(declaration.parent == property || declaration == property) {
|
||||
"Must be called only for property accessors or for property, but called for $declaration"
|
||||
}
|
||||
resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(declaration)
|
||||
@@ -443,7 +443,7 @@ public class ResolveElementCache(
|
||||
|
||||
forceResolveAnnotationsInside(property)
|
||||
|
||||
for (accessor in property.getAccessors()) {
|
||||
for (accessor in property.accessors) {
|
||||
ControlFlowInformationProvider(accessor, trace).checkDeclaration()
|
||||
}
|
||||
|
||||
@@ -485,7 +485,7 @@ public class ResolveElementCache(
|
||||
val scope = resolveSession.declarationScopeProvider.getResolutionScopeForDeclaration(klass)
|
||||
|
||||
val classDescriptor = resolveSession.resolveToDescriptor(klass) as ClassDescriptor
|
||||
val constructorDescriptor = classDescriptor.getUnsubstitutedPrimaryConstructor()
|
||||
val constructorDescriptor = classDescriptor.unsubstitutedPrimaryConstructor
|
||||
?: error("Can't get primary constructor for descriptor '$classDescriptor' in from class '${klass.getElementTextWithContext()}'")
|
||||
|
||||
val bodyResolver = createBodyResolver(resolveSession, trace, file, StatementFilter.NONE)
|
||||
@@ -521,10 +521,10 @@ public class ResolveElementCache(
|
||||
file: KtFile,
|
||||
statementFilter: StatementFilter
|
||||
): BodyResolver {
|
||||
val globalContext = SimpleGlobalContext(resolveSession.storageManager, resolveSession.getExceptionTracker())
|
||||
val globalContext = SimpleGlobalContext(resolveSession.storageManager, resolveSession.exceptionTracker)
|
||||
val module = resolveSession.moduleDescriptor
|
||||
return createContainerForBodyResolve(
|
||||
globalContext.withProject(file.getProject()).withModule(module),
|
||||
globalContext.withProject(file.project).withModule(module),
|
||||
trace,
|
||||
targetPlatform,
|
||||
statementFilter
|
||||
@@ -534,7 +534,7 @@ public class ResolveElementCache(
|
||||
// All additional resolve should be done to separate trace
|
||||
private fun createDelegatingTrace(resolveElement: KtElement): BindingTrace {
|
||||
return resolveSession.storageManager.createSafeTrace(
|
||||
DelegatingBindingTrace(resolveSession.getBindingContext(), "trace to resolve element", resolveElement))
|
||||
DelegatingBindingTrace(resolveSession.bindingContext, "trace to resolve element", resolveElement))
|
||||
}
|
||||
|
||||
private class BodyResolveContextForLazy(
|
||||
|
||||
+4
-4
@@ -21,7 +21,7 @@ import org.jetbrains.kotlin.diagnostics.Diagnostic
|
||||
import org.jetbrains.kotlin.psi.KtCodeFragment
|
||||
import org.jetbrains.kotlin.utils.singletonOrEmptyList
|
||||
|
||||
public abstract class KotlinIntentionActionsFactory {
|
||||
abstract class KotlinIntentionActionsFactory {
|
||||
protected open fun isApplicableForCodeFragment(): Boolean = false
|
||||
|
||||
protected abstract fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction>
|
||||
@@ -29,17 +29,17 @@ public abstract class KotlinIntentionActionsFactory {
|
||||
protected open fun doCreateActionsForAllProblems(
|
||||
sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> = emptyList()
|
||||
|
||||
public fun createActions(diagnostic: Diagnostic): List<IntentionAction> =
|
||||
fun createActions(diagnostic: Diagnostic): List<IntentionAction> =
|
||||
createActions(diagnostic.singletonOrEmptyList(), false)
|
||||
|
||||
public fun createActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> =
|
||||
fun createActionsForAllProblems(sameTypeDiagnostics: Collection<Diagnostic>): List<IntentionAction> =
|
||||
createActions(sameTypeDiagnostics, true)
|
||||
|
||||
private fun createActions(sameTypeDiagnostics: Collection<Diagnostic>, createForAll: Boolean): List<IntentionAction> {
|
||||
if (sameTypeDiagnostics.isEmpty()) return emptyList()
|
||||
val first = sameTypeDiagnostics.first()
|
||||
|
||||
if (first.psiElement.getContainingFile() is KtCodeFragment && !isApplicableForCodeFragment()) {
|
||||
if (first.psiElement.containingFile is KtCodeFragment && !isApplicableForCodeFragment()) {
|
||||
return emptyList()
|
||||
}
|
||||
|
||||
|
||||
+13
-13
@@ -44,7 +44,7 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
override fun getFamilyName() = KotlinBundle.message("suppress.warnings.family")
|
||||
override fun getText() = KotlinBundle.message("suppress.warning.for", suppressKey, kind.kind, kind.name)
|
||||
|
||||
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid()
|
||||
override fun isAvailable(project: Project, editor: Editor?, element: PsiElement) = element.isValid
|
||||
|
||||
override fun invoke(project: Project, editor: Editor?, element: PsiElement) {
|
||||
val id = "\"$suppressKey\""
|
||||
@@ -88,7 +88,7 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
}
|
||||
|
||||
private fun suppressAtModifierListOwner(suppressAt: KtModifierListOwner, id: String) {
|
||||
val modifierList = suppressAt.getModifierList()
|
||||
val modifierList = suppressAt.modifierList
|
||||
val psiFactory = KtPsiFactory(suppressAt)
|
||||
if (modifierList == null) {
|
||||
// create a modifier list from scratch
|
||||
@@ -102,7 +102,7 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
if (entry == null) {
|
||||
// no [suppress] annotation
|
||||
val newAnnotation = psiFactory.createAnnotationEntry(suppressAnnotationText(id))
|
||||
val addedAnnotation = modifierList.addBefore(newAnnotation, modifierList.getFirstChild())
|
||||
val addedAnnotation = modifierList.addBefore(newAnnotation, modifierList.firstChild)
|
||||
val whiteSpace = psiFactory.createWhiteSpace(kind)
|
||||
modifierList.addAfter(whiteSpace, addedAnnotation)
|
||||
}
|
||||
@@ -136,8 +136,8 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
val copy = suppressAt.copy()!!
|
||||
|
||||
val afterReplace = suppressAt.replace(annotatedExpression) as KtAnnotatedExpression
|
||||
val toReplace = afterReplace.findElementAt(afterReplace.getTextLength() - 2)!!
|
||||
assert (toReplace.getText() == placeholderText)
|
||||
val toReplace = afterReplace.findElementAt(afterReplace.textLength - 2)!!
|
||||
assert (toReplace.text == placeholderText)
|
||||
val result = toReplace.replace(copy)!!
|
||||
|
||||
caretBox.positionCaretInCopy(result)
|
||||
@@ -145,19 +145,19 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
|
||||
private fun addArgumentToSuppressAnnotation(entry: KtAnnotationEntry, id: String) {
|
||||
// add new arguments to an existing entry
|
||||
val args = entry.getValueArgumentList()
|
||||
val args = entry.valueArgumentList
|
||||
val psiFactory = KtPsiFactory(entry)
|
||||
val newArgList = psiFactory.createCallArguments("($id)")
|
||||
if (args == null) {
|
||||
// new argument list
|
||||
entry.addAfter(newArgList, entry.getLastChild())
|
||||
entry.addAfter(newArgList, entry.lastChild)
|
||||
}
|
||||
else if (args.getArguments().isEmpty()) {
|
||||
else if (args.arguments.isEmpty()) {
|
||||
// replace '()' with a new argument list
|
||||
args.replace(newArgList)
|
||||
}
|
||||
else {
|
||||
args.addArgument(newArgList.getArguments()[0])
|
||||
args.addArgument(newArgList.arguments[0])
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +165,7 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
|
||||
private fun findSuppressAnnotation(annotated: KtAnnotated): KtAnnotationEntry? {
|
||||
val context = annotated.analyze()
|
||||
return findSuppressAnnotation(context, annotated.getAnnotationEntries())
|
||||
return findSuppressAnnotation(context, annotated.annotationEntries)
|
||||
}
|
||||
|
||||
private fun findSuppressAnnotation(annotationList: KtFileAnnotationList): KtAnnotationEntry? {
|
||||
@@ -184,7 +184,7 @@ class KotlinSuppressIntentionAction private constructor(
|
||||
}
|
||||
}
|
||||
|
||||
public class AnnotationHostKind(val kind: String, val name: String, val newLineNeeded: Boolean)
|
||||
class AnnotationHostKind(val kind: String, val name: String, val newLineNeeded: Boolean)
|
||||
|
||||
private fun KtPsiFactory.createWhiteSpace(kind: AnnotationHostKind): PsiElement {
|
||||
return if (kind.newLineNeeded) createNewLine() else createWhiteSpace()
|
||||
@@ -194,10 +194,10 @@ private class CaretBox<out E: KtExpression>(
|
||||
val expression: E,
|
||||
private val editor: Editor?
|
||||
) {
|
||||
private val offsetInExpression: Int = (editor?.getCaretModel()?.getOffset() ?: 0) - expression.getTextRange()!!.getStartOffset()
|
||||
private val offsetInExpression: Int = (editor?.caretModel?.offset ?: 0) - expression.textRange!!.startOffset
|
||||
|
||||
fun positionCaretInCopy(copy: PsiElement) {
|
||||
if (editor == null) return
|
||||
editor.getCaretModel().moveToOffset(copy.getTextOffset() + offsetInExpression)
|
||||
editor.caretModel.moveToOffset(copy.textOffset + offsetInExpression)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ import com.intellij.openapi.extensions.ExtensionPointName
|
||||
import com.intellij.openapi.extensions.Extensions
|
||||
import org.jetbrains.kotlin.diagnostics.DiagnosticFactory
|
||||
|
||||
public class QuickFixes {
|
||||
class QuickFixes {
|
||||
private val factories: Multimap<DiagnosticFactory<*>, KotlinIntentionActionsFactory> = HashMultimap.create<DiagnosticFactory<*>, KotlinIntentionActionsFactory>()
|
||||
private val actions: Multimap<DiagnosticFactory<*>, IntentionAction> = HashMultimap.create<DiagnosticFactory<*>, IntentionAction>()
|
||||
|
||||
@@ -32,32 +32,32 @@ public class QuickFixes {
|
||||
Extensions.getExtensions(QuickFixContributor.EP_NAME).forEach { it.registerQuickFixes(this) }
|
||||
}
|
||||
|
||||
public fun register(diagnosticFactory: DiagnosticFactory<*>, vararg factory: KotlinIntentionActionsFactory) {
|
||||
fun register(diagnosticFactory: DiagnosticFactory<*>, vararg factory: KotlinIntentionActionsFactory) {
|
||||
factories.putAll(diagnosticFactory, factory.toList())
|
||||
}
|
||||
|
||||
public fun register(diagnosticFactory: DiagnosticFactory<*>, vararg action: IntentionAction) {
|
||||
fun register(diagnosticFactory: DiagnosticFactory<*>, vararg action: IntentionAction) {
|
||||
actions.putAll(diagnosticFactory, action.toList())
|
||||
}
|
||||
|
||||
public fun getActionFactories(diagnosticFactory: DiagnosticFactory<*>): Collection<KotlinIntentionActionsFactory> {
|
||||
fun getActionFactories(diagnosticFactory: DiagnosticFactory<*>): Collection<KotlinIntentionActionsFactory> {
|
||||
return factories.get(diagnosticFactory)
|
||||
}
|
||||
|
||||
public fun getActions(diagnosticFactory: DiagnosticFactory<*>): Collection<IntentionAction> {
|
||||
fun getActions(diagnosticFactory: DiagnosticFactory<*>): Collection<IntentionAction> {
|
||||
return actions.get(diagnosticFactory)
|
||||
}
|
||||
|
||||
public fun getDiagnostics(factory: KotlinIntentionActionsFactory): Collection<DiagnosticFactory<*>> {
|
||||
fun getDiagnostics(factory: KotlinIntentionActionsFactory): Collection<DiagnosticFactory<*>> {
|
||||
return factories.keySet().filter { factory in factories.get(it) }
|
||||
}
|
||||
|
||||
companion object {
|
||||
public fun getInstance(): QuickFixes = ServiceManager.getService(QuickFixes::class.java)
|
||||
fun getInstance(): QuickFixes = ServiceManager.getService(QuickFixes::class.java)
|
||||
}
|
||||
}
|
||||
|
||||
public interface QuickFixContributor {
|
||||
interface QuickFixContributor {
|
||||
companion object {
|
||||
val EP_NAME: ExtensionPointName<QuickFixContributor> = ExtensionPointName.create("org.jetbrains.kotlin.quickFixContributor")
|
||||
}
|
||||
|
||||
@@ -34,7 +34,7 @@ import org.jetbrains.kotlin.psi.psiUtil.siblings
|
||||
import org.jetbrains.kotlin.psi.psiUtil.startOffset
|
||||
import org.jetbrains.kotlin.utils.ifEmpty
|
||||
|
||||
public fun moveCaretIntoGeneratedElement(editor: Editor, element: PsiElement) {
|
||||
fun moveCaretIntoGeneratedElement(editor: Editor, element: PsiElement) {
|
||||
val project = element.project
|
||||
val pointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(element)
|
||||
|
||||
@@ -47,22 +47,22 @@ private fun moveCaretIntoGeneratedElementDocumentUnblocked(editor: Editor, eleme
|
||||
// Inspired by GenerateMembersUtils.positionCaret()
|
||||
|
||||
if (element is KtDeclarationWithBody && element.hasBody()) {
|
||||
val expression = element.getBodyExpression()
|
||||
val expression = element.bodyExpression
|
||||
if (expression is KtBlockExpression) {
|
||||
val lBrace = expression.getLBrace()
|
||||
val rBrace = expression.getRBrace()
|
||||
val lBrace = expression.lBrace
|
||||
val rBrace = expression.rBrace
|
||||
|
||||
if (lBrace != null && rBrace != null) {
|
||||
val firstInBlock = lBrace.siblings(forward = true, withItself = false).first { it !is PsiWhiteSpace }
|
||||
val lastInBlock = rBrace.siblings(forward = false, withItself = false).first { it !is PsiWhiteSpace }
|
||||
|
||||
val start = firstInBlock.getTextRange()!!.getStartOffset()
|
||||
val end = lastInBlock.getTextRange()!!.getEndOffset()
|
||||
val start = firstInBlock.textRange!!.startOffset
|
||||
val end = lastInBlock.textRange!!.endOffset
|
||||
|
||||
editor.moveCaret(Math.min(start, end))
|
||||
|
||||
if (start < end) {
|
||||
editor.getSelectionModel().setSelection(start, end)
|
||||
editor.selectionModel.setSelection(start, end)
|
||||
}
|
||||
|
||||
return true
|
||||
@@ -71,24 +71,24 @@ private fun moveCaretIntoGeneratedElementDocumentUnblocked(editor: Editor, eleme
|
||||
}
|
||||
|
||||
if (element is KtWithExpressionInitializer && element.hasInitializer()) {
|
||||
val expression = element.getInitializer()
|
||||
val expression = element.initializer
|
||||
if (expression == null) throw AssertionError()
|
||||
|
||||
val initializerRange = expression.getTextRange()
|
||||
val initializerRange = expression.textRange
|
||||
|
||||
val offset = initializerRange?.getStartOffset() ?: element.getTextOffset()
|
||||
val offset = initializerRange?.startOffset ?: element.getTextOffset()
|
||||
|
||||
editor.moveCaret(offset)
|
||||
|
||||
if (initializerRange != null) {
|
||||
editor.getSelectionModel().setSelection(initializerRange.getStartOffset(), initializerRange.getEndOffset())
|
||||
editor.selectionModel.setSelection(initializerRange.startOffset, initializerRange.endOffset)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
if (element is KtProperty) {
|
||||
for (accessor in element.getAccessors()) {
|
||||
for (accessor in element.accessors) {
|
||||
if (moveCaretIntoGeneratedElementDocumentUnblocked(editor, accessor)) {
|
||||
return true
|
||||
}
|
||||
@@ -98,9 +98,9 @@ private fun moveCaretIntoGeneratedElementDocumentUnblocked(editor: Editor, eleme
|
||||
return false
|
||||
}
|
||||
|
||||
public fun Editor.moveCaret(offset: Int, scrollType: ScrollType = ScrollType.RELATIVE) {
|
||||
getCaretModel().moveToOffset(offset)
|
||||
getScrollingModel().scrollToCaret(scrollType)
|
||||
fun Editor.moveCaret(offset: Int, scrollType: ScrollType = ScrollType.RELATIVE) {
|
||||
caretModel.moveToOffset(offset)
|
||||
scrollingModel.scrollToCaret(scrollType)
|
||||
}
|
||||
|
||||
private fun findInsertAfterAnchor(editor: Editor?, body: KtClassBody): PsiElement? {
|
||||
@@ -145,7 +145,7 @@ private fun removeAfterOffset(offset: Int, whiteSpace: PsiWhiteSpace): PsiElemen
|
||||
return whiteSpace
|
||||
}
|
||||
|
||||
public fun <T : KtDeclaration> insertMembersAfter(
|
||||
fun <T : KtDeclaration> insertMembersAfter(
|
||||
editor: Editor?,
|
||||
classOrObject: KtClassOrObject,
|
||||
members: Collection<T>,
|
||||
@@ -201,6 +201,6 @@ public fun <T : KtDeclaration> insertMembersAfter(
|
||||
}
|
||||
}
|
||||
|
||||
public fun <T : KtDeclaration> insertMember(editor: Editor, classOrObject: KtClassOrObject, declaration: T): T {
|
||||
fun <T : KtDeclaration> insertMember(editor: Editor, classOrObject: KtClassOrObject, declaration: T): T {
|
||||
return insertMembersAfter(editor, classOrObject, listOf(declaration)).single()
|
||||
}
|
||||
@@ -28,30 +28,30 @@ import org.jetbrains.kotlin.resolve.ImportPath
|
||||
/**
|
||||
* Returns FqName for given declaration (either Java or Kotlin)
|
||||
*/
|
||||
public fun PsiElement.getKotlinFqName(): FqName? {
|
||||
fun PsiElement.getKotlinFqName(): FqName? {
|
||||
val element = namedUnwrappedElement
|
||||
return when (element) {
|
||||
is PsiPackage -> FqName(element.getQualifiedName())
|
||||
is PsiClass -> element.getQualifiedName()?.let { FqName(it) }
|
||||
is PsiPackage -> FqName(element.qualifiedName)
|
||||
is PsiClass -> element.qualifiedName?.let { FqName(it) }
|
||||
is PsiMember -> element.getName()?.let { name ->
|
||||
val prefix = element.getContainingClass()?.getQualifiedName()
|
||||
val prefix = element.containingClass?.qualifiedName
|
||||
FqName(if (prefix != null) "$prefix.$name" else name)
|
||||
}
|
||||
is KtNamedDeclaration -> element.getFqName()
|
||||
is KtNamedDeclaration -> element.fqName
|
||||
else -> null
|
||||
}
|
||||
}
|
||||
|
||||
public fun FqName.isImported(importPath: ImportPath, skipAliasedImports: Boolean = true): Boolean {
|
||||
fun FqName.isImported(importPath: ImportPath, skipAliasedImports: Boolean = true): Boolean {
|
||||
return when {
|
||||
skipAliasedImports && importPath.hasAlias() -> false
|
||||
importPath.isAllUnder() && !isRoot() -> importPath.fqnPart() == this.parent()
|
||||
importPath.isAllUnder && !isRoot -> importPath.fqnPart() == this.parent()
|
||||
else -> importPath.fqnPart() == this
|
||||
}
|
||||
}
|
||||
|
||||
public fun ImportPath.isImported(alreadyImported: ImportPath): Boolean {
|
||||
return if (isAllUnder() || hasAlias()) this == alreadyImported else fqnPart().isImported(alreadyImported)
|
||||
fun ImportPath.isImported(alreadyImported: ImportPath): Boolean {
|
||||
return if (isAllUnder || hasAlias()) this == alreadyImported else fqnPart().isImported(alreadyImported)
|
||||
}
|
||||
|
||||
public fun ImportPath.isImported(imports: Iterable<ImportPath>): Boolean = imports.any { isImported(it) }
|
||||
fun ImportPath.isImported(imports: Iterable<ImportPath>): Boolean = imports.any { isImported(it) }
|
||||
|
||||
+2
-2
@@ -24,8 +24,8 @@ import org.jetbrains.kotlin.kdoc.psi.impl.KDocName
|
||||
import org.jetbrains.kotlin.lexer.KtTokens
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
|
||||
public class KotlinReferenceContributor() : PsiReferenceContributor() {
|
||||
public override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
|
||||
class KotlinReferenceContributor() : PsiReferenceContributor() {
|
||||
override fun registerReferenceProviders(registrar: PsiReferenceRegistrar) {
|
||||
with(registrar) {
|
||||
registerProvider(KtSimpleNameExpression::class.java) {
|
||||
KtSimpleNameReference(it)
|
||||
|
||||
+6
-6
@@ -27,21 +27,21 @@ import org.jetbrains.kotlin.resolve.BindingContext
|
||||
|
||||
class KtDestructuringDeclarationReference(element: KtDestructuringDeclaration) : KtMultiReference<KtDestructuringDeclaration>(element) {
|
||||
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
|
||||
return expression.getEntries().mapNotNull { entry ->
|
||||
context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry)?.getCandidateDescriptor()
|
||||
return expression.entries.mapNotNull { entry ->
|
||||
context.get(BindingContext.COMPONENT_RESOLVED_CALL, entry)?.candidateDescriptor
|
||||
}
|
||||
}
|
||||
|
||||
override fun getRangeInElement(): TextRange? {
|
||||
val start = expression.getLPar()
|
||||
val end = expression.getRPar()
|
||||
val start = expression.lPar
|
||||
val end = expression.rPar
|
||||
if (start == null || end == null) return TextRange.EMPTY_RANGE
|
||||
return TextRange(start.getStartOffsetInParent(), end.getStartOffsetInParent())
|
||||
return TextRange(start.startOffsetInParent, end.startOffsetInParent)
|
||||
}
|
||||
|
||||
override fun canRename(): Boolean {
|
||||
val bindingContext = expression.analyze() //TODO: should it use full body resolve?
|
||||
return resolveToDescriptors(bindingContext).all { it is CallableMemberDescriptor && it.getKind() == CallableMemberDescriptor.Kind.SYNTHESIZED}
|
||||
return resolveToDescriptors(bindingContext).all { it is CallableMemberDescriptor && it.kind == CallableMemberDescriptor.Kind.SYNTHESIZED}
|
||||
}
|
||||
|
||||
override fun handleElementRename(newElementName: String?): PsiElement? {
|
||||
|
||||
@@ -22,23 +22,23 @@ import org.jetbrains.kotlin.psi.KtForExpression
|
||||
import org.jetbrains.kotlin.resolve.BindingContext
|
||||
import java.util.*
|
||||
|
||||
public class KtForLoopInReference(element: KtForExpression) : KtMultiReference<KtForExpression>(element) {
|
||||
class KtForLoopInReference(element: KtForExpression) : KtMultiReference<KtForExpression>(element) {
|
||||
|
||||
override fun getRangeInElement(): TextRange {
|
||||
val inKeywordNode = expression.getInKeywordNode()
|
||||
val inKeywordNode = expression.inKeywordNode
|
||||
if (inKeywordNode == null)
|
||||
return TextRange.EMPTY_RANGE
|
||||
|
||||
val offset = inKeywordNode.getPsi()!!.getStartOffsetInParent()
|
||||
return TextRange(offset, offset + inKeywordNode.getTextLength())
|
||||
val offset = inKeywordNode.psi!!.startOffsetInParent
|
||||
return TextRange(offset, offset + inKeywordNode.textLength)
|
||||
}
|
||||
|
||||
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
|
||||
val loopRange = expression.getLoopRange()
|
||||
val loopRange = expression.loopRange
|
||||
if (loopRange == null) {
|
||||
return Collections.emptyList()
|
||||
}
|
||||
return LOOP_RANGE_KEYS.mapNotNull { key -> context.get(key, loopRange)?.getCandidateDescriptor() }
|
||||
return LOOP_RANGE_KEYS.mapNotNull { key -> context.get(key, loopRange)?.candidateDescriptor }
|
||||
}
|
||||
|
||||
companion object {
|
||||
|
||||
+7
-7
@@ -25,12 +25,12 @@ import org.jetbrains.kotlin.resolve.BindingContext
|
||||
import java.util.Collections
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
|
||||
|
||||
public class KtPropertyDelegationMethodsReference(element: KtPropertyDelegate) : KtMultiReference<KtPropertyDelegate>(element) {
|
||||
class KtPropertyDelegationMethodsReference(element: KtPropertyDelegate) : KtMultiReference<KtPropertyDelegate>(element) {
|
||||
|
||||
override fun getRangeInElement(): TextRange {
|
||||
val byKeywordNode = expression.getByKeywordNode()
|
||||
val offset = byKeywordNode.getPsi()!!.getStartOffsetInParent()
|
||||
return TextRange(offset, offset + byKeywordNode.getTextLength())
|
||||
val byKeywordNode = expression.byKeywordNode
|
||||
val offset = byKeywordNode.psi!!.startOffsetInParent
|
||||
return TextRange(offset, offset + byKeywordNode.textLength)
|
||||
}
|
||||
|
||||
override fun getTargetDescriptors(context: BindingContext): Collection<DeclarationDescriptor> {
|
||||
@@ -42,9 +42,9 @@ public class KtPropertyDelegationMethodsReference(element: KtPropertyDelegate) :
|
||||
if (descriptor !is PropertyDescriptor) {
|
||||
return Collections.emptyList()
|
||||
}
|
||||
return (descriptor.getAccessors().mapNotNull {
|
||||
return (descriptor.accessors.mapNotNull {
|
||||
accessor ->
|
||||
context.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor)?.getCandidateDescriptor()
|
||||
} + listOfNotNull(context.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, descriptor)?.getCandidateDescriptor()))
|
||||
context.get(BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor)?.candidateDescriptor
|
||||
} + listOfNotNull(context.get(BindingContext.DELEGATED_PROPERTY_PD_RESOLVED_CALL, descriptor)?.candidateDescriptor))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -30,17 +30,17 @@ import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
|
||||
import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList
|
||||
import java.util.*
|
||||
|
||||
public interface KtReference : PsiPolyVariantReference {
|
||||
interface KtReference : PsiPolyVariantReference {
|
||||
fun resolveToDescriptors(bindingContext: BindingContext): Collection<DeclarationDescriptor>
|
||||
|
||||
override fun getElement(): KtElement
|
||||
}
|
||||
|
||||
public abstract class AbstractKtReference<T : KtElement>(element: T)
|
||||
abstract class AbstractKtReference<T : KtElement>(element: T)
|
||||
: PsiPolyVariantReferenceBase<T>(element), KtReference {
|
||||
|
||||
public val expression: T
|
||||
get() = getElement()
|
||||
val expression: T
|
||||
get() = element
|
||||
|
||||
override fun multiResolve(incompleteCode: Boolean): Array<ResolveResult> {
|
||||
return PsiElementResolveResult.createResults(resolveToPsiElements())
|
||||
@@ -60,7 +60,7 @@ public abstract class AbstractKtReference<T : KtElement>(element: T)
|
||||
|
||||
override fun getCanonicalText(): String = "<TBD>"
|
||||
|
||||
public open fun canRename(): Boolean = false
|
||||
open fun canRename(): Boolean = false
|
||||
override fun handleElementRename(newElementName: String?): PsiElement? = throw IncorrectOperationException()
|
||||
|
||||
override fun bindToElement(element: PsiElement): PsiElement = throw IncorrectOperationException()
|
||||
@@ -94,12 +94,12 @@ public abstract class AbstractKtReference<T : KtElement>(element: T)
|
||||
|
||||
private fun resolveToPsiElements(targetDescriptor: DeclarationDescriptor): Collection<PsiElement> {
|
||||
if (targetDescriptor is PackageViewDescriptor) {
|
||||
val psiFacade = JavaPsiFacade.getInstance(expression.getProject())
|
||||
val psiFacade = JavaPsiFacade.getInstance(expression.project)
|
||||
val fqName = targetDescriptor.fqName.asString()
|
||||
return psiFacade.findPackage(fqName).singletonOrEmptyList()
|
||||
}
|
||||
else {
|
||||
return DescriptorToSourceUtilsIde.getAllDeclarations(expression.getProject(), targetDescriptor)
|
||||
return DescriptorToSourceUtilsIde.getAllDeclarations(expression.project, targetDescriptor)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -117,11 +117,11 @@ public abstract class AbstractKtReference<T : KtElement>(element: T)
|
||||
return context[BindingContext.AMBIGUOUS_LABEL_TARGET, reference]
|
||||
}
|
||||
|
||||
override fun toString() = javaClass.getSimpleName() + ": " + expression.getText()
|
||||
override fun toString() = javaClass.simpleName + ": " + expression.text
|
||||
}
|
||||
|
||||
public abstract class KtSimpleReference<T : KtReferenceExpression>(expression: T) : AbstractKtReference<T>(expression) {
|
||||
abstract class KtSimpleReference<T : KtReferenceExpression>(expression: T) : AbstractKtReference<T>(expression) {
|
||||
override fun getTargetDescriptors(context: BindingContext) = expression.getReferenceTargets(context)
|
||||
}
|
||||
|
||||
public abstract class KtMultiReference<T : KtElement>(expression: T) : AbstractKtReference<T>(expression)
|
||||
abstract class KtMultiReference<T : KtElement>(expression: T) : AbstractKtReference<T>(expression)
|
||||
|
||||
+13
-13
@@ -84,13 +84,13 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
}
|
||||
|
||||
override fun getRangeInElement(): TextRange {
|
||||
val element = getElement().getReferencedNameElement()
|
||||
val element = element.getReferencedNameElement()
|
||||
val startOffset = getElement().startOffset
|
||||
return element.getTextRange().shiftRight(-startOffset)
|
||||
return element.textRange.shiftRight(-startOffset)
|
||||
}
|
||||
|
||||
override fun canRename(): Boolean {
|
||||
if (expression.getParentOfTypeAndBranch<KtWhenConditionInRange>(strict = true){ getOperationReference() } != null) return false
|
||||
if (expression.getParentOfTypeAndBranch<KtWhenConditionInRange>(strict = true){ operationReference } != null) return false
|
||||
|
||||
val elementType = expression.getReferencedNameElementType()
|
||||
if (elementType == KtTokens.PLUSPLUS || elementType == KtTokens.MINUSMINUS) return false
|
||||
@@ -103,7 +103,7 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
if (newElementName == null) return expression;
|
||||
|
||||
// Do not rename if the reference corresponds to synthesized component function
|
||||
val expressionText = expression.getText()
|
||||
val expressionText = expression.text
|
||||
if (expressionText != null && Name.isValidIdentifier(expressionText)) {
|
||||
if (isComponentLike(Name.identifier(expressionText)) && resolve() is KtParameter) {
|
||||
return expression
|
||||
@@ -111,16 +111,16 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
}
|
||||
|
||||
val psiFactory = KtPsiFactory(expression)
|
||||
val element = Extensions.getArea(expression.getProject()).getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions
|
||||
val element = Extensions.getArea(expression.project).getExtensionPoint(SimpleNameReferenceExtension.EP_NAME).extensions
|
||||
.asSequence()
|
||||
.map { it.handleElementRename(this, psiFactory, newElementName) }
|
||||
.firstOrNull { it != null } ?: psiFactory.createNameIdentifier(newElementName)
|
||||
|
||||
val nameElement = expression.getReferencedNameElement()
|
||||
|
||||
val elementType = nameElement.getNode().getElementType()
|
||||
val elementType = nameElement.node.elementType
|
||||
if (elementType is KtToken && OperatorConventions.getNameForOperationSymbol(elementType) != null) {
|
||||
val opExpression = expression.getParent() as? KtOperationExpression
|
||||
val opExpression = expression.parent as? KtOperationExpression
|
||||
if (opExpression != null) {
|
||||
val (newExpression, newNameElement) = OperatorToFunctionIntention.convert(opExpression)
|
||||
newNameElement.replace(element)
|
||||
@@ -132,7 +132,7 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
return expression
|
||||
}
|
||||
|
||||
public enum class ShorteningMode {
|
||||
enum class ShorteningMode {
|
||||
NO_SHORTENING,
|
||||
DELAYED_SHORTENING,
|
||||
FORCED_SHORTENING
|
||||
@@ -178,13 +178,13 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
* Note that FqName may not be empty
|
||||
*/
|
||||
private fun KtNameReferenceExpression.changeQualifiedName(fqName: FqName): KtElement {
|
||||
assert(!fqName.isRoot()) { "Can't set empty FqName for element $this" }
|
||||
assert(!fqName.isRoot) { "Can't set empty FqName for element $this" }
|
||||
|
||||
val shortName = fqName.shortName().render()
|
||||
val psiFactory = KtPsiFactory(this)
|
||||
val fqNameBase = (getParent() as? KtCallExpression)?.let { parent ->
|
||||
val fqNameBase = (parent as? KtCallExpression)?.let { parent ->
|
||||
val callCopy = parent.copy() as KtCallExpression
|
||||
callCopy.getCalleeExpression()!!.replace(psiFactory.createSimpleName(shortName)).getParent()!!.getText()
|
||||
callCopy.calleeExpression!!.replace(psiFactory.createSimpleName(shortName)).parent!!.text
|
||||
} ?: shortName
|
||||
|
||||
val text = if (!fqName.isOneSegmentFQN()) "${fqName.parent().render()}.$fqNameBase" else fqNameBase
|
||||
@@ -192,12 +192,12 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
|
||||
val elementToReplace = getQualifiedElement()
|
||||
return when (elementToReplace) {
|
||||
is KtUserType -> {
|
||||
val typeText = "$text${elementToReplace.getTypeArgumentList()?.getText() ?: ""}"
|
||||
val typeText = "$text${elementToReplace.typeArgumentList?.text ?: ""}"
|
||||
elementToReplace.replace(psiFactory.createType(typeText).typeElement!!)
|
||||
}
|
||||
else -> elementToReplace.replace(psiFactory.createExpression(text))
|
||||
} as KtElement
|
||||
}
|
||||
|
||||
override fun getCanonicalText(): String = expression.getText()
|
||||
override fun getCanonicalText(): String = expression.text
|
||||
}
|
||||
|
||||
+4
-4
@@ -47,7 +47,7 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre
|
||||
return result
|
||||
}
|
||||
|
||||
override fun getRangeInElement() = TextRange(0, expression.getTextLength())
|
||||
override fun getRangeInElement() = TextRange(0, expression.textLength)
|
||||
|
||||
override fun canRename() = true
|
||||
|
||||
@@ -65,11 +65,11 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre
|
||||
}
|
||||
if (newName == null) return expression //TODO: handle the case when get/set becomes ordinary method
|
||||
|
||||
val nameIdentifier = KtPsiFactory(expression).createNameIdentifier(newName.getIdentifier())
|
||||
val nameIdentifier = KtPsiFactory(expression).createNameIdentifier(newName.identifier)
|
||||
expression.getReferencedNameElement().replace(nameIdentifier)
|
||||
return expression
|
||||
}
|
||||
|
||||
public class Getter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, true)
|
||||
public class Setter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, false)
|
||||
class Getter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, true)
|
||||
class Setter(expression: KtNameReferenceExpression) : SyntheticPropertyAccessorReference(expression, false)
|
||||
}
|
||||
|
||||
@@ -44,10 +44,10 @@ import java.util.*
|
||||
|
||||
// Navigation element of the resolved reference
|
||||
// For property accessor return enclosing property
|
||||
public val PsiReference.unwrappedTargets: Set<PsiElement>
|
||||
val PsiReference.unwrappedTargets: Set<PsiElement>
|
||||
get() {
|
||||
fun PsiElement.adjust(): PsiElement? {
|
||||
val target = unwrapped?.getOriginalElement()
|
||||
val target = unwrapped?.originalElement
|
||||
return when {
|
||||
target is KtPropertyAccessor -> target.getNonStrictParentOfType<KtProperty>()
|
||||
else -> target
|
||||
@@ -55,22 +55,22 @@ public val PsiReference.unwrappedTargets: Set<PsiElement>
|
||||
}
|
||||
|
||||
return when (this) {
|
||||
is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet<PsiElement>()) { it.getElement()?.adjust() }
|
||||
is PsiPolyVariantReference -> multiResolve(false).mapNotNullTo(HashSet<PsiElement>()) { it.element?.adjust() }
|
||||
else -> emptyOrSingletonList(resolve()?.adjust()).toSet()
|
||||
}
|
||||
}
|
||||
|
||||
//
|
||||
public fun PsiReference.canBeReferenceTo(candidateTarget: PsiElement): Boolean {
|
||||
fun PsiReference.canBeReferenceTo(candidateTarget: PsiElement): Boolean {
|
||||
// optimization
|
||||
return getElement().getContainingFile() == candidateTarget.getContainingFile()
|
||||
|| ProjectRootsUtil.isInProjectOrLibSource(getElement())
|
||||
return element.containingFile == candidateTarget.containingFile
|
||||
|| ProjectRootsUtil.isInProjectOrLibSource(element)
|
||||
}
|
||||
|
||||
public fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
|
||||
fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
|
||||
if (!canBeReferenceTo(candidateTarget)) return false
|
||||
|
||||
val unwrappedCandidate = candidateTarget.unwrapped?.getOriginalElement() ?: return false
|
||||
val unwrappedCandidate = candidateTarget.unwrapped?.originalElement ?: return false
|
||||
|
||||
// Optimizations
|
||||
when (this) {
|
||||
@@ -95,7 +95,7 @@ public fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
|
||||
}
|
||||
// TODO: Workaround for Kotlin constructor search in Java code. To be removed after refactoring of the search API
|
||||
else if (this is PsiJavaCodeReferenceElement && unwrappedCandidate is KtConstructor<*>) {
|
||||
var parent = getElement().getParent()
|
||||
var parent = getElement().parent
|
||||
if (parent is PsiAnonymousClass) {
|
||||
parent = parent.getParent()
|
||||
}
|
||||
@@ -104,10 +104,10 @@ public fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
|
||||
if (this is PsiJavaCodeReferenceElement && candidateTarget is KtObjectDeclaration && unwrappedTargets.size == 1) {
|
||||
val referredClass = unwrappedTargets.first()
|
||||
if (referredClass is KtClass && candidateTarget in referredClass.getCompanionObjects()) {
|
||||
if (getParent() is PsiImportStaticStatement) return true
|
||||
if (parent is PsiImportStaticStatement) return true
|
||||
|
||||
return getParent().getReference()?.unwrappedTargets?.any {
|
||||
(it is KtProperty || it is KtNamedFunction) && it.getParent()?.getParent() == candidateTarget
|
||||
return parent.reference?.unwrappedTargets?.any {
|
||||
(it is KtProperty || it is KtNamedFunction) && it.parent?.parent == candidateTarget
|
||||
} ?: false
|
||||
}
|
||||
}
|
||||
@@ -116,8 +116,8 @@ public fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
|
||||
|
||||
private fun PsiElement.isConstructorOf(unwrappedCandidate: PsiElement) =
|
||||
// call to Java constructor
|
||||
(this is PsiMethod && isConstructor() && getContainingClass() == unwrappedCandidate) ||
|
||||
// call to Kotlin constructor
|
||||
(this is PsiMethod && isConstructor && containingClass == unwrappedCandidate) ||
|
||||
// call to Kotlin constructor
|
||||
(this is KtConstructor<*> && getContainingClassOrObject() == unwrappedCandidate)
|
||||
|
||||
fun AbstractKtReference<out KtExpression>.renameImplicitConventionalCall(newName: String?): KtExpression {
|
||||
@@ -129,30 +129,30 @@ fun AbstractKtReference<out KtExpression>.renameImplicitConventionalCall(newName
|
||||
}
|
||||
|
||||
val KtSimpleNameExpression.mainReference: KtSimpleNameReference
|
||||
get() = getReferences().firstIsInstance()
|
||||
get() = references.firstIsInstance()
|
||||
|
||||
val KtReferenceExpression.mainReference: KtReference
|
||||
get() = if (this is KtSimpleNameExpression) mainReference else getReferences().firstIsInstance<KtReference>()
|
||||
get() = if (this is KtSimpleNameExpression) mainReference else references.firstIsInstance<KtReference>()
|
||||
|
||||
val KDocName.mainReference: KDocReference
|
||||
get() = getReferences().firstIsInstance()
|
||||
get() = references.firstIsInstance()
|
||||
|
||||
val KtElement.mainReference: KtReference?
|
||||
get() {
|
||||
return when {
|
||||
this is KtReferenceExpression -> mainReference
|
||||
this is KDocName -> mainReference
|
||||
else -> getReferences().firstIsInstanceOrNull<KtReference>()
|
||||
else -> references.firstIsInstanceOrNull<KtReference>()
|
||||
}
|
||||
}
|
||||
|
||||
// ----------- Read/write access -----------------------------------------------------------------------------------------------------------------------
|
||||
|
||||
public enum class ReferenceAccess(val isRead: Boolean, val isWrite: Boolean) {
|
||||
enum class ReferenceAccess(val isRead: Boolean, val isWrite: Boolean) {
|
||||
READ(true, false), WRITE(false, true), READ_WRITE(true, true)
|
||||
}
|
||||
|
||||
public fun KtExpression.readWriteAccess(useResolveForReadWrite: Boolean): ReferenceAccess {
|
||||
fun KtExpression.readWriteAccess(useResolveForReadWrite: Boolean): ReferenceAccess {
|
||||
var expression = getQualifiedExpressionForSelectorOrThis()
|
||||
loop@ while (true) {
|
||||
val parent = expression.parent
|
||||
@@ -187,7 +187,7 @@ public fun KtExpression.readWriteAccess(useResolveForReadWrite: Boolean): Refere
|
||||
ReferenceAccess.READ
|
||||
}
|
||||
|
||||
public fun KtReference.canBeResolvedViaImport(target: DeclarationDescriptor): Boolean {
|
||||
fun KtReference.canBeResolvedViaImport(target: DeclarationDescriptor): Boolean {
|
||||
if (!target.canBeReferencedViaImport()) return false
|
||||
if (target.isExtension) return true // assume that any type of reference can use imports when resolved to extension
|
||||
val referenceExpression = this.element as? KtNameReferenceExpression ?: return false
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import org.jetbrains.kotlin.lexer.KotlinLexer
|
||||
import org.jetbrains.kotlin.lexer.KtTokens
|
||||
import org.jetbrains.kotlin.psi.KtFile
|
||||
|
||||
public class KotlinIndexPatternBuilder: IndexPatternBuilder {
|
||||
class KotlinIndexPatternBuilder: IndexPatternBuilder {
|
||||
private val TODO_COMMENT_TOKENS = TokenSet.orSet(KtTokens.COMMENTS, TokenSet.create(KDocTokens.KDOC))
|
||||
|
||||
override fun getCommentTokenSet(file: PsiFile): TokenSet? {
|
||||
|
||||
+1
-1
@@ -26,7 +26,7 @@ import com.intellij.psi.PsiElement
|
||||
import com.intellij.psi.search.searches.ClassInheritorsSearch
|
||||
import com.intellij.util.EmptyQuery
|
||||
|
||||
public fun HierarchySearchRequest<*>.searchInheritors(): Query<PsiClass> {
|
||||
fun HierarchySearchRequest<*>.searchInheritors(): Query<PsiClass> {
|
||||
val psiClass: PsiClass? = when (originalElement) {
|
||||
is KtClassOrObject -> LightClassUtil.getPsiClass(originalElement)
|
||||
is PsiClass -> originalElement
|
||||
|
||||
+4
-4
@@ -34,9 +34,9 @@ interface DeclarationSearchRequest<in T> {
|
||||
val searchScope: SearchScope
|
||||
}
|
||||
|
||||
public interface SearchRequestWithElement<T : PsiElement> : DeclarationSearchRequest<T> {
|
||||
interface SearchRequestWithElement<T : PsiElement> : DeclarationSearchRequest<T> {
|
||||
val originalElement: T
|
||||
override val project: Project get() = originalElement.getProject()
|
||||
override val project: Project get() = originalElement.project
|
||||
}
|
||||
|
||||
abstract class DeclarationsSearch<T: PsiElement, R: DeclarationSearchRequest<T>>: QueryFactory<T, R>() {
|
||||
@@ -56,7 +56,7 @@ abstract class DeclarationsSearch<T: PsiElement, R: DeclarationSearchRequest<T>>
|
||||
fun search(request: R): Query<T> = if (isApplicable(request)) createUniqueResultsQuery(request) else EmptyQuery.getEmptyQuery<T>()
|
||||
}
|
||||
|
||||
public class HierarchySearchRequest<T: PsiElement> (
|
||||
class HierarchySearchRequest<T: PsiElement> (
|
||||
override val originalElement: T,
|
||||
override val searchScope: SearchScope,
|
||||
val searchDeeply: Boolean = true
|
||||
@@ -110,7 +110,7 @@ abstract class HierarchySearch<T: PsiElement>(
|
||||
|
||||
protected abstract fun doSearchDirect(request: HierarchySearchRequest<T>, consumer: Processor<T>)
|
||||
|
||||
protected override fun doSearch(request: HierarchySearchRequest<T>, consumer: Processor<T>) {
|
||||
override fun doSearch(request: HierarchySearchRequest<T>, consumer: Processor<T>) {
|
||||
if (request.searchDeeply) {
|
||||
doSearchAll(request, consumer)
|
||||
}
|
||||
|
||||
+5
-5
@@ -38,7 +38,7 @@ fun PsiElement.isOverridableElement(): Boolean = when (this) {
|
||||
else -> false
|
||||
}
|
||||
|
||||
public fun HierarchySearchRequest<*>.searchOverriders(): Query<PsiMethod> {
|
||||
fun HierarchySearchRequest<*>.searchOverriders(): Query<PsiMethod> {
|
||||
val psiMethods = runReadAction { originalElement.toLightMethods() }
|
||||
if (psiMethods.isEmpty()) return EmptyQuery.getEmptyQuery()
|
||||
|
||||
@@ -47,17 +47,17 @@ public fun HierarchySearchRequest<*>.searchOverriders(): Query<PsiMethod> {
|
||||
.reduce { query1, query2 -> MergeQuery(query1, query2)}
|
||||
}
|
||||
|
||||
public object KotlinPsiMethodOverridersSearch : HierarchySearch<PsiMethod>(PsiMethodOverridingHierarchyTraverser) {
|
||||
object KotlinPsiMethodOverridersSearch : HierarchySearch<PsiMethod>(PsiMethodOverridingHierarchyTraverser) {
|
||||
fun searchDirectOverriders(psiMethod: PsiMethod): Iterable<PsiMethod> {
|
||||
fun PsiMethod.isAcceptable(inheritor: PsiClass, baseMethod: PsiMethod, baseClass: PsiClass): Boolean =
|
||||
when {
|
||||
hasModifierProperty(PsiModifier.STATIC) -> false
|
||||
baseMethod.hasModifierProperty(PsiModifier.PACKAGE_LOCAL) ->
|
||||
JavaPsiFacade.getInstance(getProject()).arePackagesTheSame(baseClass, inheritor)
|
||||
JavaPsiFacade.getInstance(project).arePackagesTheSame(baseClass, inheritor)
|
||||
else -> true
|
||||
}
|
||||
|
||||
val psiClass = psiMethod.getContainingClass()
|
||||
val psiClass = psiMethod.containingClass
|
||||
if (psiClass == null) return Collections.emptyList()
|
||||
|
||||
val classToMethod = HashMap<PsiClass, PsiMethod>()
|
||||
@@ -65,7 +65,7 @@ public object KotlinPsiMethodOverridersSearch : HierarchySearch<PsiMethod>(PsiMe
|
||||
override fun nextElements(current: PsiClass): Iterable<PsiClass> =
|
||||
DirectClassInheritorsSearch.search(
|
||||
current,
|
||||
current.getProject().allScope(),
|
||||
current.project.allScope(),
|
||||
/* checkInheritance = */ true,
|
||||
/* includeAnonymous = */ true
|
||||
)
|
||||
|
||||
+1
-1
@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.load.java.JvmAbi
|
||||
import org.jetbrains.kotlin.psi.*
|
||||
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
|
||||
|
||||
public class KotlinReadWriteAccessDetector : ReadWriteAccessDetector() {
|
||||
class KotlinReadWriteAccessDetector : ReadWriteAccessDetector() {
|
||||
override fun isReadWriteAccessible(element: PsiElement) = element is KtVariableDeclaration || element is KtParameter
|
||||
|
||||
override fun isDeclarationWriteAccess(element: PsiElement) = isReadWriteAccessible(element)
|
||||
|
||||
+12
-12
@@ -47,7 +47,7 @@ data class KotlinReferencesSearchOptions(val acceptCallableOverrides: Boolean =
|
||||
}
|
||||
}
|
||||
|
||||
public class KotlinReferencesSearchParameters(elementToSearch: PsiElement,
|
||||
class KotlinReferencesSearchParameters(elementToSearch: PsiElement,
|
||||
scope: SearchScope = runReadAction { elementToSearch.project.allScope() },
|
||||
ignoreAccessScope: Boolean = false,
|
||||
optimizer: SearchRequestCollector? = null,
|
||||
@@ -55,10 +55,10 @@ public class KotlinReferencesSearchParameters(elementToSearch: PsiElement,
|
||||
: ReferencesSearch.SearchParameters(elementToSearch, scope, ignoreAccessScope, optimizer) {
|
||||
}
|
||||
|
||||
public class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() {
|
||||
class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, ReferencesSearch.SearchParameters>() {
|
||||
|
||||
override fun processQuery(queryParameters: ReferencesSearch.SearchParameters, consumer: Processor<PsiReference>) {
|
||||
val element = queryParameters.getElementToSearch()
|
||||
val element = queryParameters.elementToSearch
|
||||
|
||||
val unwrappedElement = element.namedUnwrappedElement ?: return
|
||||
|
||||
@@ -171,8 +171,8 @@ public class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, Referenc
|
||||
}
|
||||
|
||||
companion object {
|
||||
public fun processKtClassOrObject(element: KtClassOrObject, queryParameters: ReferencesSearch.SearchParameters) {
|
||||
val className = element.getName()
|
||||
fun processKtClassOrObject(element: KtClassOrObject, queryParameters: ReferencesSearch.SearchParameters) {
|
||||
val className = element.name
|
||||
if (className != null) {
|
||||
val lightClass = runReadAction { LightClassUtil.getPsiClass(element) }
|
||||
if (lightClass != null) {
|
||||
@@ -242,7 +242,7 @@ public class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, Referenc
|
||||
is KtClassOrObject -> processKtClassOrObject(element, queryParameters)
|
||||
is KtNamedFunction, is KtSecondaryConstructor -> {
|
||||
val function = element as KtFunction
|
||||
val name = runReadAction { function.getName() }
|
||||
val name = runReadAction { function.name }
|
||||
if (name != null) {
|
||||
val methods = runReadAction { LightClassUtil.getLightClassMethods(function) }
|
||||
for (method in methods) {
|
||||
@@ -304,22 +304,22 @@ public class KotlinReferencesSearcher : QueryExecutorBase<PsiReference, Referenc
|
||||
|
||||
private fun isOnlyKotlinSearch(searchScope: SearchScope) =
|
||||
searchScope is LocalSearchScope && runReadAction {
|
||||
searchScope.getScope().all { it.getContainingFile().getFileType() == KotlinFileType.INSTANCE }
|
||||
searchScope.scope.all { it.containingFile.fileType == KotlinFileType.INSTANCE }
|
||||
}
|
||||
|
||||
private fun searchNamedElement(queryParameters: ReferencesSearch.SearchParameters,
|
||||
element: PsiNamedElement?,
|
||||
name: String? = element?.getName()) {
|
||||
name: String? = element?.name) {
|
||||
if (name != null && element != null) {
|
||||
val scope = runReadAction { queryParameters.getEffectiveSearchScope() }
|
||||
val scope = runReadAction { queryParameters.effectiveSearchScope }
|
||||
val context = UsageSearchContext.IN_CODE + UsageSearchContext.IN_FOREIGN_LANGUAGES + UsageSearchContext.IN_COMMENTS
|
||||
val kotlinOptions = (queryParameters as? KotlinReferencesSearchParameters)?.kotlinOptions
|
||||
?: KotlinReferencesSearchOptions.Empty
|
||||
val resultProcessor = MyRequestResultProcessor(element,
|
||||
queryParameters.getElementToSearch().namedUnwrappedElement ?: element,
|
||||
queryParameters.elementToSearch.namedUnwrappedElement ?: element,
|
||||
options = kotlinOptions)
|
||||
queryParameters.getOptimizer().searchWord(name, scope, context.toShort(), true, element,
|
||||
resultProcessor)
|
||||
queryParameters.optimizer.searchWord(name, scope, context.toShort(), true, element,
|
||||
resultProcessor)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,13 +29,13 @@ infix fun SearchScope.or(otherScope: SearchScope): SearchScope = union(otherScop
|
||||
operator fun SearchScope.minus(otherScope: GlobalSearchScope): SearchScope = this and !otherScope
|
||||
operator fun GlobalSearchScope.not(): GlobalSearchScope = GlobalSearchScope.notScope(this)
|
||||
|
||||
public fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this)
|
||||
fun Project.allScope(): GlobalSearchScope = GlobalSearchScope.allScope(this)
|
||||
|
||||
public fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this)
|
||||
fun Project.projectScope(): GlobalSearchScope = GlobalSearchScope.projectScope(this)
|
||||
|
||||
public fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this)
|
||||
fun PsiFile.fileScope(): GlobalSearchScope = GlobalSearchScope.fileScope(this)
|
||||
|
||||
public fun SearchScope.restrictToKotlinSources(): SearchScope {
|
||||
fun SearchScope.restrictToKotlinSources(): SearchScope {
|
||||
return when (this) {
|
||||
is GlobalSearchScope -> GlobalSearchScope.getScopeRestrictedByFileTypes(this, KotlinFileType.INSTANCE)
|
||||
is LocalSearchScope -> {
|
||||
|
||||
@@ -25,7 +25,7 @@ import org.jetbrains.kotlin.resolve.dataClassUtils.isComponentLike
|
||||
import org.jetbrains.kotlin.types.expressions.OperatorConventions.*
|
||||
import org.jetbrains.kotlin.util.OperatorNameConventions
|
||||
|
||||
public val ALL_SEARCHABLE_OPERATIONS: ImmutableSet<KtToken> = ImmutableSet
|
||||
val ALL_SEARCHABLE_OPERATIONS: ImmutableSet<KtToken> = ImmutableSet
|
||||
.builder<KtToken>()
|
||||
.addAll(UNARY_OPERATION_NAMES.keys)
|
||||
.addAll(BINARY_OPERATION_NAMES.keys)
|
||||
@@ -38,15 +38,15 @@ public val ALL_SEARCHABLE_OPERATIONS: ImmutableSet<KtToken> = ImmutableSet
|
||||
.add(KtTokens.BY_KEYWORD)
|
||||
.build()
|
||||
|
||||
public val INDEXING_OPERATION_NAMES = setOf(OperatorNameConventions.GET, OperatorNameConventions.SET)
|
||||
val INDEXING_OPERATION_NAMES = setOf(OperatorNameConventions.GET, OperatorNameConventions.SET)
|
||||
|
||||
public val DELEGATE_ACCESSOR_NAMES = setOf(Name.identifier("getValue"), Name.identifier("setValue"))
|
||||
val DELEGATE_ACCESSOR_NAMES = setOf(Name.identifier("getValue"), Name.identifier("setValue"))
|
||||
|
||||
public val IN_OPERATIONS_TO_SEARCH = setOf(KtTokens.IN_KEYWORD)
|
||||
val IN_OPERATIONS_TO_SEARCH = setOf(KtTokens.IN_KEYWORD)
|
||||
|
||||
public val COMPARISON_OPERATIONS_TO_SEARCH = setOf(KtTokens.LT, KtTokens.GT)
|
||||
val COMPARISON_OPERATIONS_TO_SEARCH = setOf(KtTokens.LT, KtTokens.GT)
|
||||
|
||||
public fun Name.getOperationSymbolsToSearch(): Set<KtToken> {
|
||||
fun Name.getOperationSymbolsToSearch(): Set<KtToken> {
|
||||
when (this) {
|
||||
OperatorNameConventions.COMPARE_TO -> return COMPARISON_OPERATIONS_TO_SEARCH
|
||||
OperatorNameConventions.EQUALS -> return EQUALS_OPERATIONS
|
||||
|
||||
+8
-8
@@ -36,8 +36,8 @@ fun PsiNamedElement.getAccessorNames(readable: Boolean = true, writable: Boolean
|
||||
val setter = setter
|
||||
|
||||
val result = ArrayList<String>()
|
||||
if (readable && getter != null) result.add(getter.getName())
|
||||
if (writable && setter != null) result.add(setter.getName())
|
||||
if (readable && getter != null) result.add(getter.name)
|
||||
if (writable && setter != null) result.add(setter.name)
|
||||
return result
|
||||
}
|
||||
|
||||
@@ -55,25 +55,25 @@ fun PsiNamedElement.getAccessorNames(readable: Boolean = true, writable: Boolean
|
||||
return Collections.emptyList()
|
||||
}
|
||||
|
||||
public fun PsiNamedElement.getClassNameForCompanionObject(): String? {
|
||||
fun PsiNamedElement.getClassNameForCompanionObject(): String? {
|
||||
return if (this is KtObjectDeclaration && this.isCompanion()) {
|
||||
getNonStrictParentOfType<KtClass>()?.getName()
|
||||
getNonStrictParentOfType<KtClass>()?.name
|
||||
} else {
|
||||
null
|
||||
}
|
||||
}
|
||||
|
||||
public fun PsiNamedElement.getSpecialNamesToSearch(): List<String> {
|
||||
val name = getName()
|
||||
fun PsiNamedElement.getSpecialNamesToSearch(): List<String> {
|
||||
val name = name
|
||||
return when {
|
||||
name == null || !Name.isValidIdentifier(name) -> Collections.emptyList<String>()
|
||||
this is KtParameter -> {
|
||||
val componentFunctionName = this.dataClassComponentFunction()?.name
|
||||
if (componentFunctionName == null) return Collections.emptyList<String>()
|
||||
|
||||
return listOf(componentFunctionName.asString(), KtTokens.LPAR.getValue())
|
||||
return listOf(componentFunctionName.asString(), KtTokens.LPAR.value)
|
||||
}
|
||||
else -> Name.identifier(name).getOperationSymbolsToSearch().map { (it as KtSingleValueToken).getValue() }
|
||||
else -> Name.identifier(name).getOperationSymbolsToSearch().map { (it as KtSingleValueToken).value }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -47,7 +47,7 @@ val KtDeclaration.constructor: ConstructorDescriptor?
|
||||
get() {
|
||||
val context = this.analyze()
|
||||
return when (this) {
|
||||
is KtClassOrObject -> context[BindingContext.CLASS, this]?.getUnsubstitutedPrimaryConstructor()
|
||||
is KtClassOrObject -> context[BindingContext.CLASS, this]?.unsubstitutedPrimaryConstructor
|
||||
is KtFunction -> context[BindingContext.CONSTRUCTOR, this]
|
||||
else -> null
|
||||
}
|
||||
@@ -70,12 +70,12 @@ fun PsiReference.checkUsageVsOriginalDescriptor(
|
||||
}
|
||||
|
||||
fun PsiReference.isImportUsage(): Boolean =
|
||||
getElement()!!.getNonStrictParentOfType<KtImportDirective>() != null
|
||||
element!!.getNonStrictParentOfType<KtImportDirective>() != null
|
||||
|
||||
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean = with (getElement()!!) {
|
||||
fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean = with (element!!) {
|
||||
fun checkJavaUsage(): Boolean {
|
||||
val call = getNonStrictParentOfType<PsiConstructorCall>()
|
||||
return call == getParent() && call?.resolveConstructor()?.getContainingClass()?.getNavigationElement() == ktClassOrObject
|
||||
return call == parent && call?.resolveConstructor()?.containingClass?.navigationElement == ktClassOrObject
|
||||
}
|
||||
|
||||
fun checkKotlinUsage(): Boolean {
|
||||
@@ -84,7 +84,7 @@ fun PsiReference.isConstructorUsage(ktClassOrObject: KtClassOrObject): Boolean =
|
||||
val descriptor = getConstructorCallDescriptor()
|
||||
if (descriptor !is ConstructorDescriptor) return false
|
||||
|
||||
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.getContainingDeclaration())
|
||||
val declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.containingDeclaration)
|
||||
return declaration == ktClassOrObject || (declaration is KtConstructor<*> && declaration.getContainingClassOrObject() == ktClassOrObject)
|
||||
}
|
||||
|
||||
@@ -95,12 +95,12 @@ private fun KtElement.getConstructorCallDescriptor(): DeclarationDescriptor? {
|
||||
val bindingContext = this.analyze()
|
||||
val constructorCalleeExpression = getNonStrictParentOfType<KtConstructorCalleeExpression>()
|
||||
if (constructorCalleeExpression != null) {
|
||||
return bindingContext.get(BindingContext.REFERENCE_TARGET, constructorCalleeExpression.getConstructorReferenceExpression())
|
||||
return bindingContext.get(BindingContext.REFERENCE_TARGET, constructorCalleeExpression.constructorReferenceExpression)
|
||||
}
|
||||
|
||||
val callExpression = getNonStrictParentOfType<KtCallElement>()
|
||||
if (callExpression != null) {
|
||||
val callee = callExpression.getCalleeExpression()
|
||||
val callee = callExpression.calleeExpression
|
||||
if (callee is KtReferenceExpression) {
|
||||
return bindingContext.get(BindingContext.REFERENCE_TARGET, callee)
|
||||
}
|
||||
@@ -109,7 +109,7 @@ private fun KtElement.getConstructorCallDescriptor(): DeclarationDescriptor? {
|
||||
return null
|
||||
}
|
||||
|
||||
public fun PsiElement.processDelegationCallConstructorUsages(scope: SearchScope, process: (KtCallElement) -> Boolean): Boolean {
|
||||
fun PsiElement.processDelegationCallConstructorUsages(scope: SearchScope, process: (KtCallElement) -> Boolean): Boolean {
|
||||
if (!processDelegationCallKotlinConstructorUsages(scope, process)) return false
|
||||
return processDelegationCallJavaConstructorUsages(scope, process)
|
||||
}
|
||||
@@ -135,8 +135,8 @@ private fun PsiElement.processDelegationCallJavaConstructorUsages(scope: SearchS
|
||||
if (this is KtLightElement<*, *>) return true
|
||||
// TODO: Temporary hack to avoid NPE while KotlinNoOriginLightMethod is around
|
||||
if (this is KtLightMethod && this.getOrigin() == null) return true
|
||||
if (!(this is PsiMethod && isConstructor())) return true
|
||||
val klass = getContainingClass() ?: return true
|
||||
if (!(this is PsiMethod && isConstructor)) return true
|
||||
val klass = containingClass ?: return true
|
||||
val descriptor = getJavaMethodDescriptor() as? ConstructorDescriptor ?: return true
|
||||
return processInheritorsDelegatingCallToSpecifiedConstructor(klass, scope, descriptor, process)
|
||||
}
|
||||
@@ -188,8 +188,8 @@ fun PsiReference.isExtensionOfDeclarationClassUsage(declaration: KtNamedDeclarat
|
||||
usageDescriptor !is FunctionDescriptor -> false
|
||||
else -> {
|
||||
val receiverDescriptor =
|
||||
usageDescriptor.getExtensionReceiverParameter()?.getType()?.getConstructor()?.getDeclarationDescriptor()
|
||||
val containingDescriptor = targetDescriptor.getContainingDeclaration()
|
||||
usageDescriptor.extensionReceiverParameter?.type?.constructor?.declarationDescriptor
|
||||
val containingDescriptor = targetDescriptor.containingDeclaration
|
||||
|
||||
containingDescriptor == receiverDescriptor
|
||||
|| (containingDescriptor is ClassDescriptor
|
||||
@@ -206,7 +206,7 @@ fun PsiReference.isUsageInContainingDeclaration(declaration: KtNamedDeclaration)
|
||||
val descriptor = declaration.descriptor ?: return false
|
||||
return checkUsageVsOriginalDescriptor(descriptor) { usageDescriptor, targetDescriptor ->
|
||||
usageDescriptor != targetDescriptor
|
||||
&& usageDescriptor.getContainingDeclaration() == targetDescriptor.getContainingDeclaration()
|
||||
&& usageDescriptor.containingDeclaration == targetDescriptor.containingDeclaration
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user