Cleanup: apply "Use synthetic property access syntax"

This commit is contained in:
Mikhail Glukhikh
2017-02-17 15:39:05 +03:00
parent 1375267996
commit d0cc1635db
163 changed files with 344 additions and 344 deletions
@@ -103,5 +103,5 @@ abstract class DataClassMethodGenerator(private val declaration: KtClassOrObject
.map { bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, it)!! } .map { bindingContext.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, it)!! }
private val primaryConstructorParameters: List<KtParameter> private val primaryConstructorParameters: List<KtParameter>
get() = (declaration as? KtClass)?.getPrimaryConstructorParameters().orEmpty() get() = (declaration as? KtClass)?.primaryConstructorParameters.orEmpty()
} }
@@ -54,7 +54,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
contextKind: OwnerKind, contextKind: OwnerKind,
classOrObject: KtPureClassOrObject classOrObject: KtPureClassOrObject
) { ) {
val methodElement = classOrObject.getPrimaryConstructor() ?: classOrObject val methodElement = classOrObject.primaryConstructor ?: classOrObject
if (generateOverloadsIfNeeded(methodElement, constructorDescriptor, constructorDescriptor, contextKind, classBuilder, memberCodegen)) { if (generateOverloadsIfNeeded(methodElement, constructorDescriptor, constructorDescriptor, contextKind, classBuilder, memberCodegen)) {
return return
@@ -251,7 +251,7 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
val classDescriptor = constructorDescriptor.constructedClass val classDescriptor = constructorDescriptor.constructedClass
if (classDescriptor.kind != ClassKind.CLASS) return false if (classDescriptor.kind != ClassKind.CLASS) return false
if (classOrObject.isLocal()) return false if (classOrObject.isLocal) return false
if (CodegenBinding.canHaveOuter(state.bindingContext, classDescriptor)) return false if (CodegenBinding.canHaveOuter(state.bindingContext, classDescriptor)) return false
@@ -265,6 +265,6 @@ class DefaultParameterValueSubstitutor(val state: GenerationState) {
} }
private fun hasSecondaryConstructorsWithNoParameters(klass: KtClass) = private fun hasSecondaryConstructorsWithNoParameters(klass: KtClass) =
klass.getSecondaryConstructors().any { it.valueParameters.isEmpty() } klass.secondaryConstructors.any { it.valueParameters.isEmpty() }
} }
@@ -33,10 +33,10 @@ abstract class DelegatingClassBuilderFactory(
abstract override fun newClassBuilder(origin: JvmDeclarationOrigin): DelegatingClassBuilder abstract override fun newClassBuilder(origin: JvmDeclarationOrigin): DelegatingClassBuilder
override fun asBytes(builder: ClassBuilder?): ByteArray? { override fun asBytes(builder: ClassBuilder?): ByteArray? {
return delegate.asBytes((builder as DelegatingClassBuilder).getDelegate()) return delegate.asBytes((builder as DelegatingClassBuilder).delegate)
} }
override fun asText(builder: ClassBuilder?): String? { override fun asText(builder: ClassBuilder?): String? {
return delegate.asText((builder as DelegatingClassBuilder).getDelegate()) return delegate.asText((builder as DelegatingClassBuilder).delegate)
} }
} }
@@ -34,7 +34,7 @@ data class SourceInfo(val source: String, val pathOrCleanFQN: String, val linesI
val isTopLevel = element is KtFile || (element is KtNamedFunction && element.getParent() is KtFile) val isTopLevel = element is KtFile || (element is KtNamedFunction && element.getParent() is KtFile)
val cleanedClassFqName = if (!isTopLevel) internalClassName else internalClassName.substringBefore('$') val cleanedClassFqName = if (!isTopLevel) internalClassName else internalClassName.substringBefore('$')
return SourceInfo(element.getContainingKtFile().name, cleanedClassFqName, lineNumbers!!) return SourceInfo(element.containingKtFile.name, cleanedClassFqName, lineNumbers!!)
} }
} }
@@ -58,7 +58,7 @@ object JavaClassProperty : IntrinsicPropertyGetter() {
} }
override fun toCallable(fd: FunctionDescriptor, isSuper: Boolean, resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): Callable { override fun toCallable(fd: FunctionDescriptor, isSuper: Boolean, resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): Callable {
val classType = codegen.getState().typeMapper.mapType(resolvedCall.call.dispatchReceiver!!.type) val classType = codegen.state.typeMapper.mapType(resolvedCall.call.dispatchReceiver!!.type)
return object : IntrinsicCallable(getType(Class::class.java), listOf(), classType, null) { return object : IntrinsicCallable(getType(Class::class.java), listOf(), classType, null) {
override fun invokeIntrinsic(v: InstructionAdapter) { override fun invokeIntrinsic(v: InstructionAdapter) {
if (isPrimitive(classType)) { if (isPrimitive(classType)) {
@@ -26,7 +26,7 @@ import org.jetbrains.org.objectweb.asm.commons.InstructionAdapter
class NewArray : IntrinsicMethod() { class NewArray : IntrinsicMethod() {
override fun toCallable(fd: FunctionDescriptor, isSuper: Boolean, resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): Callable { override fun toCallable(fd: FunctionDescriptor, isSuper: Boolean, resolvedCall: ResolvedCall<*>, codegen: ExpressionCodegen): Callable {
val jetType = resolvedCall.resultingDescriptor.returnType!! val jetType = resolvedCall.resultingDescriptor.returnType!!
val type = codegen.getState().typeMapper.mapType(jetType) val type = codegen.state.typeMapper.mapType(jetType)
return object : IntrinsicCallable(type, listOf(Type.INT_TYPE), null, null) { return object : IntrinsicCallable(type, listOf(Type.INT_TYPE), null, null) {
override fun invokeIntrinsic(v: InstructionAdapter) { override fun invokeIntrinsic(v: InstructionAdapter) {
codegen.newArrayInstruction(jetType) codegen.newArrayInstruction(jetType)
@@ -177,8 +177,8 @@ val AbstractInsnNode.intConstant: Int? get() =
fun insnListOf(vararg insns: AbstractInsnNode) = InsnList().apply { insns.forEach { add(it) } } fun insnListOf(vararg insns: AbstractInsnNode) = InsnList().apply { insns.forEach { add(it) } }
fun AbstractInsnNode.isStoreOperation(): Boolean = getOpcode() in Opcodes.ISTORE..Opcodes.ASTORE fun AbstractInsnNode.isStoreOperation(): Boolean = opcode in Opcodes.ISTORE..Opcodes.ASTORE
fun AbstractInsnNode.isLoadOperation(): Boolean = getOpcode() in Opcodes.ILOAD..Opcodes.ALOAD fun AbstractInsnNode.isLoadOperation(): Boolean = opcode in Opcodes.ILOAD..Opcodes.ALOAD
val AbstractInsnNode?.insnText get() = InlineCodegenUtil.getInsnText(this) val AbstractInsnNode?.insnText get() = InlineCodegenUtil.getInsnText(this)
val AbstractInsnNode?.debugText get() = val AbstractInsnNode?.debugText get() =
@@ -44,7 +44,7 @@ class JvmStringTable(private val typeMapper: KotlinTypeMapper) : StringTable {
val lastRecord = records.lastOrNull() val lastRecord = records.lastOrNull()
if (lastRecord != null && lastRecord.isTrivial()) { if (lastRecord != null && lastRecord.isTrivial()) {
lastRecord.setRange(lastRecord.range + 1) lastRecord.range = lastRecord.range + 1
} }
else records.add(Record.newBuilder()) else records.add(Record.newBuilder())
} }
@@ -93,12 +93,12 @@ class JvmStringTable(private val typeMapper: KotlinTypeMapper) : StringTable {
else { else {
val predefinedIndex = JvmNameResolver.getPredefinedStringIndex(string) val predefinedIndex = JvmNameResolver.getPredefinedStringIndex(string)
if (predefinedIndex != null) { if (predefinedIndex != null) {
record.setPredefinedIndex(predefinedIndex) record.predefinedIndex = predefinedIndex
// TODO: move all records with predefined names to the end and do not write associated strings for them (since they are ignored) // TODO: move all records with predefined names to the end and do not write associated strings for them (since they are ignored)
strings.add("") strings.add("")
} }
else { else {
record.setOperation(Record.Operation.DESC_TO_CLASS_ID) record.operation = Record.Operation.DESC_TO_CLASS_ID
strings.add("L${string.replace('.', '$')};") strings.add("L${string.replace('.', '$')};")
} }
} }
@@ -67,7 +67,7 @@ class ModuleVisibilityHelperImpl : ModuleVisibilityHelper {
private fun findModule(descriptor: DeclarationDescriptor, modules: Collection<Module>): Module? { private fun findModule(descriptor: DeclarationDescriptor, modules: Collection<Module>): Module? {
val sourceElement = getSourceElement(descriptor) val sourceElement = getSourceElement(descriptor)
if (sourceElement is KotlinSourceElement) { if (sourceElement is KotlinSourceElement) {
return modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.getContainingKtFile().virtualFile.path in it.getSourceFiles() } return modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.containingKtFile.virtualFile.path in it.getSourceFiles() }
} }
else { else {
return modules.firstOrNull { module -> return modules.firstOrNull { module ->
@@ -98,7 +98,7 @@ object JvmFileClassUtil {
@JvmStatic fun isFromMultifileClass(declarationElement: KtElement, descriptor: DeclarationDescriptor): Boolean { @JvmStatic fun isFromMultifileClass(declarationElement: KtElement, descriptor: DeclarationDescriptor): Boolean {
if (DescriptorUtils.isTopLevelDeclaration(descriptor)) { if (DescriptorUtils.isTopLevelDeclaration(descriptor)) {
val fileClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(declarationElement.getContainingKtFile()) val fileClassInfo = JvmFileClassUtil.getFileClassInfoNoResolve(declarationElement.containingKtFile)
return fileClassInfo.withJvmMultifileClass return fileClassInfo.withJvmMultifileClass
} }
return false return false
@@ -118,6 +118,6 @@ val KtFile.javaFileFacadeFqName: FqName
} }
fun KtDeclaration.isInsideJvmMultifileClassFile() = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve( fun KtDeclaration.isInsideJvmMultifileClassFile() = JvmFileClassUtil.findAnnotationEntryOnFileNoResolve(
getContainingKtFile(), containingKtFile,
JvmFileClassUtil.JVM_MULTIFILE_CLASS_SHORT JvmFileClassUtil.JVM_MULTIFILE_CLASS_SHORT
) != null ) != null
@@ -88,7 +88,7 @@ class PlatformStaticAnnotationChecker : SimpleDeclarationChecker {
else -> declaration else -> declaration
} }
if (insideObject && checkDeclaration.getModifierList()?.hasModifier(KtTokens.OVERRIDE_KEYWORD) == true) { if (insideObject && checkDeclaration.modifierList?.hasModifier(KtTokens.OVERRIDE_KEYWORD) == true) {
diagnosticHolder.report(ErrorsJvm.OVERRIDE_CANNOT_BE_STATIC.on(declaration)) diagnosticHolder.report(ErrorsJvm.OVERRIDE_CANNOT_BE_STATIC.on(declaration))
} }
@@ -124,7 +124,7 @@ open class PartialAnalysisHandlerExtension : AnalysisHandlerExtension {
} }
if (declaration is KtClass && declaration.isAnnotation()) { if (declaration is KtClass && declaration.isAnnotation()) {
declaration.getPrimaryConstructorParameters().forEach { doForEachDeclaration(it, f) } declaration.primaryConstructorParameters.forEach { doForEachDeclaration(it, f) }
} }
} }
@@ -1326,7 +1326,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) {
} }
private fun generateHeaderDelegationSpecifiers(classOrObject: KtClassOrObject) { private fun generateHeaderDelegationSpecifiers(classOrObject: KtClassOrObject) {
for (specifier in classOrObject.getSuperTypeListEntries()) { for (specifier in classOrObject.superTypeListEntries) {
generateInstructions(specifier) generateInstructions(specifier)
} }
} }
@@ -1351,7 +1351,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) {
override fun visitClass(klass: KtClass) { override fun visitClass(klass: KtClass) {
if (klass.hasPrimaryConstructor()) { if (klass.hasPrimaryConstructor()) {
processParameters(klass.getPrimaryConstructorParameters()) processParameters(klass.primaryConstructorParameters)
// delegation specifiers of primary constructor, anonymous class and property initializers // delegation specifiers of primary constructor, anonymous class and property initializers
generateHeaderDelegationSpecifiers(klass) generateHeaderDelegationSpecifiers(klass)
@@ -1379,7 +1379,7 @@ class ControlFlowProcessor(private val trace: BindingTrace) {
} }
private fun generateDeclarationForLocalClassOrObjectIfNeeded(classOrObject: KtClassOrObject) { private fun generateDeclarationForLocalClassOrObjectIfNeeded(classOrObject: KtClassOrObject) {
if (classOrObject.isLocal()) { if (classOrObject.isLocal) {
for (declaration in classOrObject.declarations) { for (declaration in classOrObject.declarations) {
if (declaration is KtSecondaryConstructor || if (declaration is KtSecondaryConstructor ||
declaration is KtProperty || declaration is KtProperty ||
@@ -54,17 +54,17 @@ import org.jetbrains.kotlin.types.TypeUtils
import java.util.* import java.util.*
fun getReceiverTypePredicate(resolvedCall: ResolvedCall<*>, receiverValue: ReceiverValue): TypePredicate? { fun getReceiverTypePredicate(resolvedCall: ResolvedCall<*>, receiverValue: ReceiverValue): TypePredicate? {
val callableDescriptor = resolvedCall.getResultingDescriptor() ?: return null val callableDescriptor = resolvedCall.resultingDescriptor ?: return null
when (receiverValue) { when (receiverValue) {
resolvedCall.getExtensionReceiver() -> { resolvedCall.extensionReceiver -> {
val receiverParameter = callableDescriptor.getExtensionReceiverParameter() val receiverParameter = callableDescriptor.extensionReceiverParameter
if (receiverParameter != null) return receiverParameter.getType().getSubtypesPredicate() if (receiverParameter != null) return receiverParameter.type.getSubtypesPredicate()
} }
resolvedCall.getDispatchReceiver() -> { resolvedCall.dispatchReceiver -> {
val rootCallableDescriptors = callableDescriptor.findTopMostOverriddenDescriptors() val rootCallableDescriptors = callableDescriptor.findTopMostOverriddenDescriptors()
return or(rootCallableDescriptors.mapNotNull { return or(rootCallableDescriptors.mapNotNull {
it.getDispatchReceiverParameter()?.getType()?.let { TypeUtils.makeNullableIfNeeded(it, resolvedCall.call.isSafeCall()) }?.getSubtypesPredicate() it.dispatchReceiverParameter?.type?.let { TypeUtils.makeNullableIfNeeded(it, resolvedCall.call.isSafeCall()) }?.getSubtypesPredicate()
}) })
} }
} }
@@ -90,14 +90,14 @@ fun getExpectedTypePredicate(
fun getTypePredicateForUnresolvedCallArgument(to: KtElement, inputValueIndex: Int): TypePredicate? { fun getTypePredicateForUnresolvedCallArgument(to: KtElement, inputValueIndex: Int): TypePredicate? {
if (inputValueIndex < 0) return null if (inputValueIndex < 0) return null
val call = to.getCall(bindingContext) ?: return null val call = to.getCall(bindingContext) ?: return null
val callee = call.getCalleeExpression() ?: return null val callee = call.calleeExpression ?: return null
val candidates = callee.getReferenceTargets(bindingContext) val candidates = callee.getReferenceTargets(bindingContext)
.filterIsInstance<FunctionDescriptor>() .filterIsInstance<FunctionDescriptor>()
.sortedBy { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) } .sortedBy { DescriptorRenderer.FQ_NAMES_IN_TYPES.render(it) }
if (candidates.isEmpty()) return null if (candidates.isEmpty()) return null
val explicitReceiver = call.getExplicitReceiver() val explicitReceiver = call.explicitReceiver
val argValueOffset = if (explicitReceiver != null) 1 else 0 val argValueOffset = if (explicitReceiver != null) 1 else 0
val predicates = ArrayList<TypePredicate>() val predicates = ArrayList<TypePredicate>()
@@ -120,10 +120,10 @@ fun getExpectedTypePredicate(
TracingStrategy.EMPTY, TracingStrategy.EMPTY,
candidateCall, candidateCall,
LinkedHashSet()) LinkedHashSet())
if (!status.isSuccess()) continue if (!status.isSuccess) continue
val candidateArgumentMap = candidateCall.getValueArguments() val candidateArgumentMap = candidateCall.valueArguments
val callArguments = call.getValueArguments() val callArguments = call.valueArguments
val i = inputValueIndex - argValueOffset val i = inputValueIndex - argValueOffset
if (i < 0 || i >= callArguments.size) continue if (i < 0 || i >= callArguments.size) continue
@@ -135,7 +135,7 @@ fun getExpectedTypePredicate(
val expectedType = if (resolvedArgument is VarargValueArgument) val expectedType = if (resolvedArgument is VarargValueArgument)
candidateParameter.varargElementType candidateParameter.varargElementType
else else
candidateParameter.getType() candidateParameter.type
predicates.add(if (expectedType != null) AllSubtypes(expectedType) else AllTypes) predicates.add(if (expectedType != null) AllSubtypes(expectedType) else AllTypes)
} }
@@ -152,14 +152,14 @@ fun getExpectedTypePredicate(
is KtReturnExpression -> returnElement.getTargetFunctionDescriptor(bindingContext) is KtReturnExpression -> returnElement.getTargetFunctionDescriptor(bindingContext)
else -> bindingContext[DECLARATION_TO_DESCRIPTOR, pseudocode.correspondingElement] else -> bindingContext[DECLARATION_TO_DESCRIPTOR, pseudocode.correspondingElement]
} }
addSubtypesOf((functionDescriptor as? CallableDescriptor)?.getReturnType()) addSubtypesOf((functionDescriptor as? CallableDescriptor)?.returnType)
} }
is ConditionalJumpInstruction -> is ConditionalJumpInstruction ->
addSubtypesOf(builtIns.getBooleanType()) addSubtypesOf(builtIns.booleanType)
is ThrowExceptionInstruction -> is ThrowExceptionInstruction ->
addSubtypesOf(builtIns.getThrowable().getDefaultType()) addSubtypesOf(builtIns.throwable.defaultType)
is MergeInstruction -> is MergeInstruction ->
addTypePredicates(it.outputValue) addTypePredicates(it.outputValue)
@@ -190,11 +190,11 @@ fun getExpectedTypePredicate(
} }
else { else {
it.arguments[value]?.let { parameter -> it.arguments[value]?.let { parameter ->
val expectedType = when (it.resolvedCall.getValueArguments()[parameter]) { val expectedType = when (it.resolvedCall.valueArguments[parameter]) {
is VarargValueArgument -> is VarargValueArgument ->
parameter.varargElementType parameter.varargElementType
else -> else ->
parameter.getType() parameter.type
} }
addSubtypesOf(expectedType) addSubtypesOf(expectedType)
} }
@@ -203,7 +203,7 @@ fun getExpectedTypePredicate(
is MagicInstruction -> @Suppress("NON_EXHAUSTIVE_WHEN") when (it.kind) { is MagicInstruction -> @Suppress("NON_EXHAUSTIVE_WHEN") when (it.kind) {
AND, OR -> AND, OR ->
addSubtypesOf(builtIns.getBooleanType()) addSubtypesOf(builtIns.booleanType)
LOOP_RANGE_ITERATION -> LOOP_RANGE_ITERATION ->
addByExplicitReceiver(bindingContext[LOOP_RANGE_ITERATOR_RESOLVED_CALL, value.element as? KtExpression]) addByExplicitReceiver(bindingContext[LOOP_RANGE_ITERATOR_RESOLVED_CALL, value.element as? KtExpression])
@@ -211,18 +211,18 @@ fun getExpectedTypePredicate(
VALUE_CONSUMER -> { VALUE_CONSUMER -> {
val element = it.element val element = it.element
when { when {
element.getStrictParentOfType<KtWhileExpression>()?.getCondition() == element -> element.getStrictParentOfType<KtWhileExpression>()?.condition == element ->
addSubtypesOf(builtIns.getBooleanType()) addSubtypesOf(builtIns.booleanType)
element is KtProperty -> { element is KtProperty -> {
val propertyDescriptor = bindingContext[DECLARATION_TO_DESCRIPTOR, element] as? PropertyDescriptor val propertyDescriptor = bindingContext[DECLARATION_TO_DESCRIPTOR, element] as? PropertyDescriptor
propertyDescriptor?.getAccessors()?.map { propertyDescriptor?.accessors?.map {
addByExplicitReceiver(bindingContext[DELEGATED_PROPERTY_RESOLVED_CALL, it]) addByExplicitReceiver(bindingContext[DELEGATED_PROPERTY_RESOLVED_CALL, it])
} }
} }
element is KtDelegatedSuperTypeEntry -> element is KtDelegatedSuperTypeEntry ->
addSubtypesOf(bindingContext[TYPE, element.getTypeReference()]) addSubtypesOf(bindingContext[TYPE, element.typeReference])
} }
} }
@@ -256,7 +256,7 @@ fun Instruction.calcSideEffectFree(): Boolean {
return when (this) { return when (this) {
is ReadValueInstruction -> target.let { is ReadValueInstruction -> target.let {
when (it) { when (it) {
is AccessTarget.Call -> when (it.resolvedCall.getResultingDescriptor()) { is AccessTarget.Call -> when (it.resolvedCall.resultingDescriptor) {
is LocalVariableDescriptor, is ValueParameterDescriptor, is ReceiverParameterDescriptor -> true is LocalVariableDescriptor, is ValueParameterDescriptor, is ReceiverParameterDescriptor -> true
else -> false else -> false
} }
@@ -61,7 +61,7 @@ object PositioningStrategies {
is KtObjectDeclaration -> { is KtObjectDeclaration -> {
return markRange( return markRange(
element.getObjectKeyword()!!, element.getObjectKeyword()!!,
element.getNameIdentifier() ?: element.getObjectKeyword()!! element.nameIdentifier ?: element.getObjectKeyword()!!
) )
} }
is KtConstructorDelegationCall -> { is KtConstructorDelegationCall -> {
@@ -86,7 +86,7 @@ object PositioningStrategies {
private fun getElementToMark(declaration: KtDeclaration): PsiElement { private fun getElementToMark(declaration: KtDeclaration): PsiElement {
val (returnTypeRef, nameIdentifierOrPlaceholder) = when (declaration) { val (returnTypeRef, nameIdentifierOrPlaceholder) = when (declaration) {
is KtCallableDeclaration -> Pair(declaration.typeReference, declaration.nameIdentifier) is KtCallableDeclaration -> Pair(declaration.typeReference, declaration.nameIdentifier)
is KtPropertyAccessor -> Pair(declaration.getReturnTypeReference(), declaration.getNamePlaceholder()) is KtPropertyAccessor -> Pair(declaration.returnTypeReference, declaration.namePlaceholder)
else -> Pair(null, null) else -> Pair(null, null)
} }
@@ -127,9 +127,9 @@ object PositioningStrategies {
} }
is KtFunction -> { is KtFunction -> {
val endOfSignatureElement = val endOfSignatureElement =
element.getTypeReference() element.typeReference
?: element.getValueParameterList() ?: element.valueParameterList
?: element.getNameIdentifier() ?: element.nameIdentifier
?: element ?: element
val startElement val startElement
= if (element is KtFunctionLiteral) { = if (element is KtFunctionLiteral) {
@@ -141,19 +141,19 @@ object PositioningStrategies {
return markRange(startElement, endOfSignatureElement) return markRange(startElement, endOfSignatureElement)
} }
is KtProperty -> { is KtProperty -> {
val endOfSignatureElement = element.getTypeReference() ?: element.getNameIdentifier() ?: element val endOfSignatureElement = element.typeReference ?: element.nameIdentifier ?: element
return markRange(element, endOfSignatureElement) return markRange(element, endOfSignatureElement)
} }
is KtPropertyAccessor -> { is KtPropertyAccessor -> {
val endOfSignatureElement = val endOfSignatureElement =
element.getReturnTypeReference() element.returnTypeReference
?: element.getRightParenthesis()?.getPsi() ?: element.rightParenthesis?.psi
?: element.getNamePlaceholder() ?: element.namePlaceholder
return markRange(element, endOfSignatureElement) return markRange(element, endOfSignatureElement)
} }
is KtClass -> { is KtClass -> {
val nameAsDeclaration = element.getNameIdentifier() ?: return markElement(element) val nameAsDeclaration = element.nameIdentifier ?: return markElement(element)
val primaryConstructorParameterList = element.getPrimaryConstructorParameterList() ?: return markElement(nameAsDeclaration) val primaryConstructorParameterList = element.getPrimaryConstructorParameterList() ?: return markElement(nameAsDeclaration)
return markRange(nameAsDeclaration, primaryConstructorParameterList) return markRange(nameAsDeclaration, primaryConstructorParameterList)
} }
@@ -212,7 +212,7 @@ object PositioningStrategies {
override fun mark(element: PsiElement): List<TextRange> { override fun mark(element: PsiElement): List<TextRange> {
val nameIdentifier = when (element) { val nameIdentifier = when (element) {
is KtNamedDeclaration -> element.nameIdentifier is KtNamedDeclaration -> element.nameIdentifier
is KtFile -> element.packageDirective!!.getNameIdentifier() is KtFile -> element.packageDirective!!.nameIdentifier
else -> null else -> null
} }
@@ -260,7 +260,7 @@ object PositioningStrategies {
val visibilityTokens = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.PUBLIC_KEYWORD, KtTokens.INTERNAL_KEYWORD) val visibilityTokens = listOf(KtTokens.PRIVATE_KEYWORD, KtTokens.PROTECTED_KEYWORD, KtTokens.PUBLIC_KEYWORD, KtTokens.INTERNAL_KEYWORD)
val modifierList = element.modifierList val modifierList = element.modifierList
val result = visibilityTokens.mapNotNull { modifierList?.getModifier(it)?.getTextRange() } val result = visibilityTokens.mapNotNull { modifierList?.getModifier(it)?.textRange }
if (!result.isEmpty()) return result if (!result.isEmpty()) return result
// Try to resolve situation when there's no visibility modifiers written before element // Try to resolve situation when there's no visibility modifiers written before element
@@ -273,10 +273,10 @@ object PositioningStrategies {
val elementToMark = when (element) { val elementToMark = when (element) {
is KtObjectDeclaration -> element.getObjectKeyword()!! is KtObjectDeclaration -> element.getObjectKeyword()!!
is KtPropertyAccessor -> element.getNamePlaceholder() is KtPropertyAccessor -> element.namePlaceholder
is KtAnonymousInitializer -> element is KtAnonymousInitializer -> element
else -> throw IllegalArgumentException( else -> throw IllegalArgumentException(
"Can't find text range for element '${element.javaClass.getCanonicalName()}' with the text '${element.getText()}'") "Can't find text range for element '${element.javaClass.canonicalName}' with the text '${element.text}'")
} }
return markElement(elementToMark) return markElement(elementToMark)
} }
@@ -284,13 +284,13 @@ object PositioningStrategies {
@JvmField val VARIANCE_IN_PROJECTION: PositioningStrategy<KtTypeProjection> = object : PositioningStrategy<KtTypeProjection>() { @JvmField val VARIANCE_IN_PROJECTION: PositioningStrategy<KtTypeProjection> = object : PositioningStrategy<KtTypeProjection>() {
override fun mark(element: KtTypeProjection): List<TextRange> { override fun mark(element: KtTypeProjection): List<TextRange> {
return markElement(element.getProjectionToken()!!) return markElement(element.projectionToken!!)
} }
} }
@JvmField val PARAMETER_DEFAULT_VALUE: PositioningStrategy<KtParameter> = object : PositioningStrategy<KtParameter>() { @JvmField val PARAMETER_DEFAULT_VALUE: PositioningStrategy<KtParameter> = object : PositioningStrategy<KtParameter>() {
override fun mark(element: KtParameter): List<TextRange> { override fun mark(element: KtParameter): List<TextRange> {
return markNode(element.getDefaultValue()!!.node) return markNode(element.defaultValue!!.node)
} }
} }
@@ -309,7 +309,7 @@ object PositioningStrategies {
@JvmField val DECLARATION_WITH_BODY: PositioningStrategy<KtDeclarationWithBody> = object : PositioningStrategy<KtDeclarationWithBody>() { @JvmField val DECLARATION_WITH_BODY: PositioningStrategy<KtDeclarationWithBody> = object : PositioningStrategy<KtDeclarationWithBody>() {
override fun mark(element: KtDeclarationWithBody): List<TextRange> { override fun mark(element: KtDeclarationWithBody): List<TextRange> {
val lastBracketRange = (element.bodyExpression as? KtBlockExpression)?.getLastBracketRange() val lastBracketRange = (element.bodyExpression as? KtBlockExpression)?.lastBracketRange
return if (lastBracketRange != null) return if (lastBracketRange != null)
markRange(lastBracketRange) markRange(lastBracketRange)
else else
@@ -317,7 +317,7 @@ object PositioningStrategies {
} }
override fun isValid(element: KtDeclarationWithBody): Boolean { override fun isValid(element: KtDeclarationWithBody): Boolean {
return super.isValid(element) && (element.bodyExpression as? KtBlockExpression)?.getLastBracketRange() != null return super.isValid(element) && (element.bodyExpression as? KtBlockExpression)?.lastBracketRange != null
} }
} }
@@ -361,14 +361,14 @@ object PositioningStrategies {
@JvmField val NULLABLE_TYPE: PositioningStrategy<KtNullableType> = object : PositioningStrategy<KtNullableType>() { @JvmField val NULLABLE_TYPE: PositioningStrategy<KtNullableType> = object : PositioningStrategy<KtNullableType>() {
override fun mark(element: KtNullableType): List<TextRange> { override fun mark(element: KtNullableType): List<TextRange> {
return markNode(element.getQuestionMarkNode()) return markNode(element.questionMarkNode)
} }
} }
@JvmField val CALL_EXPRESSION: PositioningStrategy<PsiElement> = object : PositioningStrategy<PsiElement>() { @JvmField val CALL_EXPRESSION: PositioningStrategy<PsiElement> = object : PositioningStrategy<PsiElement>() {
override fun mark(element: PsiElement): List<TextRange> { override fun mark(element: PsiElement): List<TextRange> {
if (element is KtCallExpression) { if (element is KtCallExpression) {
return markRange(element, element.getTypeArgumentList() ?: element.getCalleeExpression() ?: element) return markRange(element, element.typeArgumentList ?: element.calleeExpression ?: element)
} }
return markElement(element) return markElement(element)
} }
@@ -387,7 +387,7 @@ object PositioningStrategies {
return markElement(valueParameterList) return markElement(valueParameterList)
} }
if (element is KtFunctionLiteral) { if (element is KtFunctionLiteral) {
return markNode(element.getLBrace().node) return markNode(element.lBrace.node)
} }
return DECLARATION_SIGNATURE_OR_DEFAULT.mark(element) return DECLARATION_SIGNATURE_OR_DEFAULT.mark(element)
} }
@@ -419,7 +419,7 @@ object PositioningStrategies {
@JvmField val UNREACHABLE_CODE: PositioningStrategy<PsiElement> = object : PositioningStrategy<PsiElement>() { @JvmField val UNREACHABLE_CODE: PositioningStrategy<PsiElement> = object : PositioningStrategy<PsiElement>() {
override fun markDiagnostic(diagnostic: ParametrizedDiagnostic<out PsiElement>): List<TextRange> { override fun markDiagnostic(diagnostic: ParametrizedDiagnostic<out PsiElement>): List<TextRange> {
return Errors.UNREACHABLE_CODE.cast(diagnostic).getA() return Errors.UNREACHABLE_CODE.cast(diagnostic).a
} }
} }
@@ -443,8 +443,8 @@ object PositioningStrategies {
override fun mark(element: KtConstructorDelegationCall): List<TextRange> { override fun mark(element: KtConstructorDelegationCall): List<TextRange> {
if (element.isImplicit) { if (element.isImplicit) {
val constructor = element.getStrictParentOfType<KtSecondaryConstructor>()!! val constructor = element.getStrictParentOfType<KtSecondaryConstructor>()!!
val valueParameterList = constructor.getValueParameterList() ?: return markElement(constructor) val valueParameterList = constructor.valueParameterList ?: return markElement(constructor)
return markRange(constructor.getConstructorKeyword(), valueParameterList.getLastChild()) return markRange(constructor.getConstructorKeyword(), valueParameterList.lastChild)
} }
return markElement(element.calleeExpression ?: element) return markElement(element.calleeExpression ?: element)
} }
@@ -452,7 +452,7 @@ object PositioningStrategies {
@JvmField val DELEGATOR_SUPER_CALL: PositioningStrategy<KtEnumEntry> = object: PositioningStrategy<KtEnumEntry>() { @JvmField val DELEGATOR_SUPER_CALL: PositioningStrategy<KtEnumEntry> = object: PositioningStrategy<KtEnumEntry>() {
override fun mark(element: KtEnumEntry): List<TextRange> { override fun mark(element: KtEnumEntry): List<TextRange> {
val specifiers = element.getSuperTypeListEntries() val specifiers = element.superTypeListEntries
return markElement(if (specifiers.isEmpty()) element else specifiers[0]) return markElement(if (specifiers.isEmpty()) element else specifiers[0])
} }
} }
@@ -120,7 +120,7 @@ object Renderers {
@JvmField val RENDER_CLASS_OR_OBJECT = Renderer { @JvmField val RENDER_CLASS_OR_OBJECT = Renderer {
classOrObject: KtClassOrObject -> classOrObject: KtClassOrObject ->
val name = if (classOrObject.getName() != null) " '" + classOrObject.getName() + "'" else "" val name = if (classOrObject.name != null) " '" + classOrObject.name + "'" else ""
if (classOrObject is KtClass) "Class" + name else "Object" + name if (classOrObject is KtClass) "Class" + name else "Object" + name
} }
@@ -27,7 +27,7 @@ class KotlinLookupLocation(val element: KtElement) : LookupLocation {
override val location: LocationInfo? override val location: LocationInfo?
get() { get() {
val containingJetFile = element.getContainingKtFile() val containingJetFile = element.containingKtFile
if (containingJetFile.doNotAnalyze != null) return null if (containingJetFile.doNotAnalyze != null) return null
@@ -42,13 +42,13 @@ class KDocImpl(buffer: CharSequence?) : LazyParseablePsiElement(KDocTokens.KDOC,
override fun getDefaultSection(): KDocSection = getChildOfType<KDocSection>()!! override fun getDefaultSection(): KDocSection = getChildOfType<KDocSection>()!!
override fun findSectionByName(name: String): KDocSection? = override fun findSectionByName(name: String): KDocSection? =
getChildrenOfType<KDocSection>().firstOrNull { it.getName() == name } getChildrenOfType<KDocSection>().firstOrNull { it.name == name }
override fun findSectionByTag(tag: KDocKnownTag): KDocSection? = override fun findSectionByTag(tag: KDocKnownTag): KDocSection? =
findSectionByName(tag.name.toLowerCase()) findSectionByName(tag.name.toLowerCase())
override fun findSectionByTag(tag: KDocKnownTag, subjectName: String): KDocSection? = override fun findSectionByTag(tag: KDocKnownTag, subjectName: String): KDocSection? =
getChildrenOfType<KDocSection>().firstOrNull { getChildrenOfType<KDocSection>().firstOrNull {
it.getName() == tag.name.toLowerCase() && it.getSubjectName() == subjectName it.name == tag.name.toLowerCase() && it.getSubjectName() == subjectName
} }
} }
@@ -41,7 +41,7 @@ class KDocSection(node: ASTNode) : KDocTag(node) {
(firstChild as? KDocTag)?.getContent() ?: super.getContent() (firstChild as? KDocTag)?.getContent() ?: super.getContent()
fun findTagsByName(name: String): List<KDocTag> { fun findTagsByName(name: String): List<KDocTag> {
return getChildrenOfType<KDocTag>().filter { it.getName() == name } return getChildrenOfType<KDocTag>().filter { it.name == name }
} }
fun findTagByName(name: String): KDocTag? fun findTagByName(name: String): KDocTag?
@@ -203,7 +203,7 @@ private object DebugTextBuildingVisitor : KtVisitor<String, Unit>() {
append("class ") append("class ")
appendInn(klass.nameAsName) appendInn(klass.nameAsName)
appendInn(klass.typeParameterList) appendInn(klass.typeParameterList)
appendInn(klass.getPrimaryConstructorModifierList(), prefix = " ", suffix = " ") appendInn(klass.primaryConstructorModifierList, prefix = " ", suffix = " ")
appendInn(klass.getPrimaryConstructorParameterList()) appendInn(klass.getPrimaryConstructorParameterList())
appendInn(klass.getSuperTypeList(), prefix = " : ") appendInn(klass.getSuperTypeList(), prefix = " : ")
} }
@@ -104,7 +104,7 @@ abstract class KtClassOrObject :
override fun hasPrimaryConstructor(): Boolean = hasExplicitPrimaryConstructor() || !hasSecondaryConstructors() override fun hasPrimaryConstructor(): Boolean = hasExplicitPrimaryConstructor() || !hasSecondaryConstructors()
private fun hasSecondaryConstructors(): Boolean = !getSecondaryConstructors().isEmpty() private fun hasSecondaryConstructors(): Boolean = !secondaryConstructors.isEmpty()
override fun getSecondaryConstructors(): List<KtSecondaryConstructor> = getBody()?.secondaryConstructors.orEmpty() override fun getSecondaryConstructors(): List<KtSecondaryConstructor> = getBody()?.secondaryConstructors.orEmpty()
@@ -160,12 +160,12 @@ abstract class KtCodeFragment(
} }
fun getContextContainingFile(): KtFile? { fun getContextContainingFile(): KtFile? {
return (getOriginalContext() as? KtElement)?.getContainingKtFile() return (getOriginalContext() as? KtElement)?.containingKtFile
} }
fun getOriginalContext(): KtElement? { fun getOriginalContext(): KtElement? {
val contextElement = getContext() as? KtElement val contextElement = getContext() as? KtElement
val contextFile = contextElement?.getContainingKtFile() val contextFile = contextElement?.containingKtFile
if (contextFile is KtCodeFragment) { if (contextFile is KtCodeFragment) {
return contextFile.getOriginalContext() return contextFile.getOriginalContext()
} }
@@ -173,7 +173,7 @@ fun <TElement : KtElement> createByPattern(pattern: String, vararg args: Any, fa
for ((pointer, n) in pointers) { for ((pointer, n) in pointers) {
var element = pointer.element!! var element = pointer.element!!
if (element is KtFunctionLiteral) { if (element is KtFunctionLiteral) {
element = element.getParent() as KtLambdaExpression element = element.parent as KtLambdaExpression
} }
@Suppress("UNCHECKED_CAST") @Suppress("UNCHECKED_CAST")
val argumentType = argumentTypes[n] as PsiElementPlaceholderArgumentType<in Any, in PsiElement> val argumentType = argumentTypes[n] as PsiElementPlaceholderArgumentType<in Any, in PsiElement>
@@ -102,7 +102,7 @@ fun KtSimpleNameExpression.getReceiverExpression(): KtExpression? {
parent is KtCallExpression -> { parent is KtCallExpression -> {
//This is in case `a().b()` //This is in case `a().b()`
val callExpression = parent val callExpression = parent
val grandParent = callExpression.getParent() val grandParent = callExpression.parent
if (grandParent is KtQualifiedExpression) { if (grandParent is KtQualifiedExpression) {
val parentsReceiver = grandParent.receiverExpression val parentsReceiver = grandParent.receiverExpression
if (parentsReceiver != callExpression) { if (parentsReceiver != callExpression) {
@@ -226,7 +226,7 @@ fun StubBasedPsiElementBase<out KotlinClassOrObjectStub<out KtClassOrObject>>.ge
return stub.getSuperNames() return stub.getSuperNames()
} }
val specifiers = (this as KtClassOrObject).getSuperTypeListEntries() val specifiers = (this as KtClassOrObject).superTypeListEntries
if (specifiers.isEmpty()) return Collections.emptyList<String>() if (specifiers.isEmpty()) return Collections.emptyList<String>()
val result = ArrayList<String>() val result = ArrayList<String>()
@@ -488,7 +488,7 @@ fun KtElement.containingClass(): KtClass? = getStrictParentOfType()
fun KtClassOrObject.findPropertyByName(name: String): KtNamedDeclaration? { fun KtClassOrObject.findPropertyByName(name: String): KtNamedDeclaration? {
return declarations.firstOrNull { it is KtProperty && it.name == name } as KtNamedDeclaration? return declarations.firstOrNull { it is KtProperty && it.name == name } as KtNamedDeclaration?
?: getPrimaryConstructorParameters().firstOrNull { it.hasValOrVar() && it.name == name } ?: primaryConstructorParameters.firstOrNull { it.hasValOrVar() && it.name == name }
} }
fun isTypeConstructorReference(e: PsiElement): Boolean { fun isTypeConstructorReference(e: PsiElement): Boolean {
@@ -296,7 +296,7 @@ class DeclarationsChecker(
private fun checkTypesInClassHeader(classOrObject: KtClassOrObject) { private fun checkTypesInClassHeader(classOrObject: KtClassOrObject) {
fun KtTypeReference.type(): KotlinType? = trace.bindingContext.get(TYPE, this) fun KtTypeReference.type(): KotlinType? = trace.bindingContext.get(TYPE, this)
for (delegationSpecifier in classOrObject.getSuperTypeListEntries()) { for (delegationSpecifier in classOrObject.superTypeListEntries) {
val typeReference = delegationSpecifier.typeReference ?: continue val typeReference = delegationSpecifier.typeReference ?: continue
typeReference.type()?.let { DescriptorResolver.checkBounds(typeReference, it, trace) } typeReference.type()?.let { DescriptorResolver.checkBounds(typeReference, it, trace) }
} }
@@ -397,7 +397,7 @@ class DeclarationsChecker(
private fun checkObject(declaration: KtObjectDeclaration, classDescriptor: ClassDescriptorWithResolutionScopes) { private fun checkObject(declaration: KtObjectDeclaration, classDescriptor: ClassDescriptorWithResolutionScopes) {
checkOpenMembers(classDescriptor) checkOpenMembers(classDescriptor)
if (declaration.isLocal() && !declaration.isCompanion() && !declaration.isObjectLiteral()) { if (declaration.isLocal && !declaration.isCompanion() && !declaration.isObjectLiteral()) {
trace.report(LOCAL_OBJECT_NOT_ALLOWED.on(declaration, classDescriptor)) trace.report(LOCAL_OBJECT_NOT_ALLOWED.on(declaration, classDescriptor))
} }
} }
@@ -412,7 +412,7 @@ class DeclarationsChecker(
if (aClass.isInterface()) { if (aClass.isInterface()) {
checkConstructorInInterface(aClass) checkConstructorInInterface(aClass)
checkMethodsOfAnyInInterface(classDescriptor) checkMethodsOfAnyInInterface(classDescriptor)
if (aClass.isLocal() && classDescriptor.containingDeclaration !is ClassDescriptor) { if (aClass.isLocal && classDescriptor.containingDeclaration !is ClassDescriptor) {
trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor)) trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor))
} }
} }
@@ -427,7 +427,7 @@ class DeclarationsChecker(
private fun checkPrimaryConstructor(classOrObject: KtClassOrObject, classDescriptor: ClassDescriptor) { private fun checkPrimaryConstructor(classOrObject: KtClassOrObject, classDescriptor: ClassDescriptor) {
val primaryConstructor = classDescriptor.unsubstitutedPrimaryConstructor ?: return val primaryConstructor = classDescriptor.unsubstitutedPrimaryConstructor ?: return
val declaration = classOrObject.getPrimaryConstructor() ?: return val declaration = classOrObject.primaryConstructor ?: return
for (parameter in declaration.valueParameters) { for (parameter in declaration.valueParameters) {
trace.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, parameter)?.let { trace.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, parameter)?.let {
@@ -471,7 +471,7 @@ class DeclarationsChecker(
} }
private fun checkConstructorInInterface(klass: KtClass) { private fun checkConstructorInInterface(klass: KtClass) {
klass.getPrimaryConstructor()?.let { trace.report(CONSTRUCTOR_IN_INTERFACE.on(it)) } klass.primaryConstructor?.let { trace.report(CONSTRUCTOR_IN_INTERFACE.on(it)) }
} }
private fun checkMethodsOfAnyInInterface(classDescriptor: ClassDescriptorWithResolutionScopes) { private fun checkMethodsOfAnyInInterface(classDescriptor: ClassDescriptorWithResolutionScopes) {
@@ -494,7 +494,7 @@ class DeclarationsChecker(
} }
private fun checkValOnAnnotationParameter(aClass: KtClass) { private fun checkValOnAnnotationParameter(aClass: KtClass) {
for (parameter in aClass.getPrimaryConstructorParameters()) { for (parameter in aClass.primaryConstructorParameters) {
if (!parameter.hasValOrVar()) { if (!parameter.hasValOrVar()) {
trace.report(MISSING_VAL_ON_ANNOTATION_PARAMETER.on(parameter)) trace.report(MISSING_VAL_ON_ANNOTATION_PARAMETER.on(parameter))
} }
@@ -44,7 +44,7 @@ class DelegationResolver<T : CallableMemberDescriptor> private constructor(
private fun generateDelegatedMembers(): Collection<T> { private fun generateDelegatedMembers(): Collection<T> {
val delegatedMembers = hashSetOf<T>() val delegatedMembers = hashSetOf<T>()
for (delegationSpecifier in classOrObject.getSuperTypeListEntries()) { for (delegationSpecifier in classOrObject.superTypeListEntries) {
if (delegationSpecifier !is KtDelegatedSuperTypeEntry) { if (delegationSpecifier !is KtDelegatedSuperTypeEntry) {
continue continue
} }
@@ -32,7 +32,7 @@ class ExposedVisibilityChecker(private val trace: DiagnosticSink = DO_NOTHING) {
var result = checkSupertypes(klass, classDescriptor) var result = checkSupertypes(klass, classDescriptor)
result = result and checkParameterBounds(klass, classDescriptor) result = result and checkParameterBounds(klass, classDescriptor)
val constructor = klass.getPrimaryConstructor() ?: return result val constructor = klass.primaryConstructor ?: return result
val constructorDescriptor = classDescriptor.unsubstitutedPrimaryConstructor ?: return result val constructorDescriptor = classDescriptor.unsubstitutedPrimaryConstructor ?: return result
return result and checkFunction(constructor, constructorDescriptor) return result and checkFunction(constructor, constructorDescriptor)
} }
@@ -122,7 +122,7 @@ class ExposedVisibilityChecker(private val trace: DiagnosticSink = DO_NOTHING) {
private fun checkSupertypes(klass: KtClassOrObject, classDescriptor: ClassDescriptor): Boolean { private fun checkSupertypes(klass: KtClassOrObject, classDescriptor: ClassDescriptor): Boolean {
val classVisibility = classDescriptor.effectiveVisibility() val classVisibility = classDescriptor.effectiveVisibility()
val isInterface = classDescriptor.kind == ClassKind.INTERFACE val isInterface = classDescriptor.kind == ClassKind.INTERFACE
val delegationList = klass.getSuperTypeListEntries() val delegationList = klass.superTypeListEntries
var result = true var result = true
classDescriptor.typeConstructor.supertypes.forEachIndexed { i, superType -> classDescriptor.typeConstructor.supertypes.forEachIndexed { i, superType ->
if (i >= delegationList.size) return result if (i >= delegationList.size) return result
@@ -100,8 +100,8 @@ class FunctionDescriptorResolver(
): SimpleFunctionDescriptor { ): SimpleFunctionDescriptor {
val functionDescriptor = functionConstructor( val functionDescriptor = functionConstructor(
containingDescriptor, containingDescriptor,
annotationResolver.resolveAnnotationsWithoutArguments(scope, function.getModifierList(), trace), annotationResolver.resolveAnnotationsWithoutArguments(scope, function.modifierList, trace),
function.getNameAsSafeName(), function.nameAsSafeName,
CallableMemberDescriptor.Kind.DECLARATION, CallableMemberDescriptor.Kind.DECLARATION,
function.toSourceElement() function.toSourceElement()
) )
@@ -119,8 +119,8 @@ class FunctionDescriptorResolver(
dataFlowInfo: DataFlowInfo dataFlowInfo: DataFlowInfo
) { ) {
if (functionDescriptor.returnType != null) return if (functionDescriptor.returnType != null) return
assert(function.getTypeReference() == null) { assert(function.typeReference == null) {
"Return type must be initialized early for function: " + function.getText() + ", at: " + DiagnosticUtils.atLocation(function) } "Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) }
val returnType = if (function.hasBlockBody()) { val returnType = if (function.hasBlockBody()) {
builtIns.unitType builtIns.unitType
@@ -251,14 +251,14 @@ class FunctionDescriptorResolver(
classElement: KtPureClassOrObject, classElement: KtPureClassOrObject,
trace: BindingTrace trace: BindingTrace
): ClassConstructorDescriptorImpl? { ): ClassConstructorDescriptorImpl? {
if (classDescriptor.getKind() == ClassKind.ENUM_ENTRY || !classElement.hasPrimaryConstructor()) return null if (classDescriptor.kind == ClassKind.ENUM_ENTRY || !classElement.hasPrimaryConstructor()) return null
return createConstructorDescriptor( return createConstructorDescriptor(
scope, scope,
classDescriptor, classDescriptor,
true, true,
classElement.getPrimaryConstructorModifierList(), classElement.primaryConstructorModifierList,
classElement.getPrimaryConstructor() ?: classElement, classElement.primaryConstructor ?: classElement,
classElement.getPrimaryConstructorParameters(), classElement.primaryConstructorParameters,
trace trace
) )
} }
@@ -273,9 +273,9 @@ class FunctionDescriptorResolver(
scope, scope,
classDescriptor, classDescriptor,
false, false,
constructor.getModifierList(), constructor.modifierList,
constructor, constructor,
constructor.getValueParameters(), constructor.valueParameters,
trace trace
) )
} }
@@ -102,7 +102,7 @@ class LazyTopDownAnalyzer(
} }
override fun visitImportDirective(importDirective: KtImportDirective) { override fun visitImportDirective(importDirective: KtImportDirective) {
val importResolver = fileScopeProvider.getImportResolver(importDirective.getContainingKtFile()) val importResolver = fileScopeProvider.getImportResolver(importDirective.containingKtFile)
importResolver.forceResolveImport(importDirective) importResolver.forceResolveImport(importDirective)
} }
@@ -143,7 +143,7 @@ class LazyTopDownAnalyzer(
} }
private fun registerPrimaryConstructorParameters(klass: KtClass) { private fun registerPrimaryConstructorParameters(klass: KtClass) {
for (jetParameter in klass.getPrimaryConstructorParameters()) { for (jetParameter in klass.primaryConstructorParameters) {
if (jetParameter.hasValOrVar()) { if (jetParameter.hasValOrVar()) {
c.primaryConstructorParameterProperties.put(jetParameter, lazyDeclarationResolver.resolveToDescriptor(jetParameter) as PropertyDescriptor) c.primaryConstructorParameterProperties.put(jetParameter, lazyDeclarationResolver.resolveToDescriptor(jetParameter) as PropertyDescriptor)
} }
@@ -222,7 +222,7 @@ class LazyTopDownAnalyzer(
} }
private fun resolveImportsInAllFiles(c: TopDownAnalysisContext) { private fun resolveImportsInAllFiles(c: TopDownAnalysisContext) {
for (file in c.files + c.scripts.keys.map { it.getContainingKtFile() }) { for (file in c.files + c.scripts.keys.map { it.containingKtFile }) {
fileScopeProvider.getImportResolver(file).forceResolveAllImports() fileScopeProvider.getImportResolver(file).forceResolveAllImports()
} }
} }
@@ -182,7 +182,7 @@ class QualifiedExpressionResolver {
when { when {
importDirective.suppressDiagnosticsInDebugMode() -> null importDirective.suppressDiagnosticsInDebugMode() -> null
packageFragmentForVisibilityCheck is DeclarationDescriptorWithSource && packageFragmentForVisibilityCheck.source == SourceElement.NO_SOURCE -> { packageFragmentForVisibilityCheck is DeclarationDescriptorWithSource && packageFragmentForVisibilityCheck.source == SourceElement.NO_SOURCE -> {
PackageFragmentWithCustomSource(packageFragmentForVisibilityCheck, KotlinSourceElement(importDirective.getContainingKtFile())) PackageFragmentWithCustomSource(packageFragmentForVisibilityCheck, KotlinSourceElement(importDirective.containingKtFile))
} }
else -> packageFragmentForVisibilityCheck else -> packageFragmentForVisibilityCheck
} }
@@ -601,7 +601,7 @@ class QualifiedExpressionResolver {
if (descriptor is DeclarationDescriptorWithVisibility) { if (descriptor is DeclarationDescriptorWithVisibility) {
val fromToCheck = val fromToCheck =
if (shouldBeVisibleFrom is PackageFragmentDescriptor && shouldBeVisibleFrom.source == SourceElement.NO_SOURCE && referenceExpression.containingFile !is DummyHolder) { if (shouldBeVisibleFrom is PackageFragmentDescriptor && shouldBeVisibleFrom.source == SourceElement.NO_SOURCE && referenceExpression.containingFile !is DummyHolder) {
PackageFragmentWithCustomSource(shouldBeVisibleFrom, KotlinSourceElement(referenceExpression.getContainingKtFile())) PackageFragmentWithCustomSource(shouldBeVisibleFrom, KotlinSourceElement(referenceExpression.containingKtFile))
} }
else { else {
shouldBeVisibleFrom shouldBeVisibleFrom
@@ -101,11 +101,11 @@ class TypeResolver(
private fun resolveType(c: TypeResolutionContext, typeReference: KtTypeReference): KotlinType { private fun resolveType(c: TypeResolutionContext, typeReference: KtTypeReference): KotlinType {
assert(!c.allowBareTypes) { "Use resolvePossiblyBareType() when bare types are allowed" } assert(!c.allowBareTypes) { "Use resolvePossiblyBareType() when bare types are allowed" }
return resolvePossiblyBareType(c, typeReference).getActualType() return resolvePossiblyBareType(c, typeReference).actualType
} }
fun resolvePossiblyBareType(c: TypeResolutionContext, typeReference: KtTypeReference): PossiblyBareType { fun resolvePossiblyBareType(c: TypeResolutionContext, typeReference: KtTypeReference): PossiblyBareType {
val cachedType = c.trace.getBindingContext().get(BindingContext.TYPE, typeReference) val cachedType = c.trace.bindingContext.get(BindingContext.TYPE, typeReference)
if (cachedType != null) return type(cachedType) if (cachedType != null) return type(cachedType)
val resolvedTypeSlice = if (c.abbreviated) BindingContext.ABBREVIATED_TYPE else BindingContext.TYPE val resolvedTypeSlice = if (c.abbreviated) BindingContext.ABBREVIATED_TYPE else BindingContext.TYPE
@@ -120,15 +120,15 @@ class TypeResolver(
// Bare types can be allowed only inside expressions; lazy type resolution is only relevant for declarations // Bare types can be allowed only inside expressions; lazy type resolution is only relevant for declarations
val lazyKotlinType = LazyWrappedType(storageManager) { val lazyKotlinType = LazyWrappedType(storageManager) {
doResolvePossiblyBareType(c, typeReference).getActualType() doResolvePossiblyBareType(c, typeReference).actualType
} }
c.trace.record(resolvedTypeSlice, typeReference, lazyKotlinType) c.trace.record(resolvedTypeSlice, typeReference, lazyKotlinType)
return type(lazyKotlinType) return type(lazyKotlinType)
} }
val type = doResolvePossiblyBareType(c, typeReference) val type = doResolvePossiblyBareType(c, typeReference)
if (!type.isBare()) { if (!type.isBare) {
c.trace.record(resolvedTypeSlice, typeReference, type.getActualType()) c.trace.record(resolvedTypeSlice, typeReference, type.actualType)
} }
return type return type
} }
@@ -820,7 +820,7 @@ class TypeResolver(
} }
} }
else { else {
val type = resolveType(c.noBareTypes(), argumentElement.getTypeReference()!!) val type = resolveType(c.noBareTypes(), argumentElement.typeReference!!)
val kind = resolveProjectionKind(projectionKind) val kind = resolveProjectionKind(projectionKind)
if (constructor.parameters.size > i) { if (constructor.parameters.size > i) {
val parameterDescriptor = constructor.parameters[i] val parameterDescriptor = constructor.parameters[i]
@@ -65,7 +65,7 @@ class VarianceCheckerCore(
if (klass is KtClass) { if (klass is KtClass) {
if (!checkClassHeader(klass)) return false if (!checkClassHeader(klass)) return false
} }
for (member in klass.declarations + klass.getPrimaryConstructorParameters()) { for (member in klass.declarations + klass.primaryConstructorParameters) {
val descriptor = when (member) { val descriptor = when (member) {
is KtParameter -> context.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, member) is KtParameter -> context.get(BindingContext.PRIMARY_CONSTRUCTOR_PARAMETER, member)
is KtDeclaration -> context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, member) is KtDeclaration -> context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, member)
@@ -93,7 +93,7 @@ class VarianceCheckerCore(
private fun checkClassHeader(klass: KtClass): Boolean { private fun checkClassHeader(klass: KtClass): Boolean {
var noError = true var noError = true
for (specifier in klass.getSuperTypeListEntries()) { for (specifier in klass.superTypeListEntries) {
noError = noError and specifier.typeReference?.checkTypePosition(context, OUT_VARIANCE) noError = noError and specifier.typeReference?.checkTypePosition(context, OUT_VARIANCE)
} }
return noError and klass.checkTypeParameters(context, OUT_VARIANCE) return noError and klass.checkTypeParameters(context, OUT_VARIANCE)
@@ -146,7 +146,7 @@ fun KtElement.getCall(context: BindingContext): Call? {
val parent = element.parent val parent = element.parent
val reference: KtExpression? = when { val reference: KtExpression? = when {
parent is KtInstanceExpressionWithLabel -> parent parent is KtInstanceExpressionWithLabel -> parent
parent is KtUserType -> parent.getParent()?.getParent() as? KtConstructorCalleeExpression parent is KtUserType -> parent.parent?.parent as? KtConstructorCalleeExpression
else -> element.getCalleeExpressionIfAny() else -> element.getCalleeExpressionIfAny()
} }
if (reference != null) { if (reference != null) {
@@ -38,7 +38,7 @@ class DataClassDeclarationChecker : SimpleDeclarationChecker {
if (descriptor.unsubstitutedPrimaryConstructor == null && descriptor.constructors.isNotEmpty()) { if (descriptor.unsubstitutedPrimaryConstructor == null && descriptor.constructors.isNotEmpty()) {
declaration.nameIdentifier?.let { diagnosticHolder.report(Errors.PRIMARY_CONSTRUCTOR_REQUIRED_FOR_DATA_CLASS.on(it)) } declaration.nameIdentifier?.let { diagnosticHolder.report(Errors.PRIMARY_CONSTRUCTOR_REQUIRED_FOR_DATA_CLASS.on(it)) }
} }
val primaryConstructor = declaration.getPrimaryConstructor() val primaryConstructor = declaration.primaryConstructor
val parameters = primaryConstructor?.valueParameters ?: emptyList() val parameters = primaryConstructor?.valueParameters ?: emptyList()
if (parameters.isEmpty()) { if (parameters.isEmpty()) {
(primaryConstructor?.valueParameterList ?: declaration.nameIdentifier)?.let { (primaryConstructor?.valueParameterList ?: declaration.nameIdentifier)?.let {
@@ -58,7 +58,7 @@ class ReifiedTypeParameterAnnotationChecker : SimpleDeclarationChecker {
diagnosticHolder.report( diagnosticHolder.report(
Errors.REIFIED_TYPE_PARAMETER_NO_INLINE.on( Errors.REIFIED_TYPE_PARAMETER_NO_INLINE.on(
typeParameterDeclaration.getModifierList()!!.getModifier(KtTokens.REIFIED_KEYWORD)!! typeParameterDeclaration.modifierList!!.getModifier(KtTokens.REIFIED_KEYWORD)!!
) )
) )
} }
@@ -45,19 +45,19 @@ interface IndexedImports {
} }
class AllUnderImportsIndexed(allImports: Collection<KtImportDirective>) : IndexedImports { class AllUnderImportsIndexed(allImports: Collection<KtImportDirective>) : IndexedImports {
override val imports = allImports.filter { it.isAllUnder() } override val imports = allImports.filter { it.isAllUnder }
override fun importsForName(name: Name) = imports override fun importsForName(name: Name) = imports
} }
class ExplicitImportsIndexed(allImports: Collection<KtImportDirective>) : IndexedImports { class ExplicitImportsIndexed(allImports: Collection<KtImportDirective>) : IndexedImports {
override val imports = allImports.filter { !it.isAllUnder() } override val imports = allImports.filter { !it.isAllUnder }
private val nameToDirectives: ListMultimap<Name, KtImportDirective> by lazy { private val nameToDirectives: ListMultimap<Name, KtImportDirective> by lazy {
val builder = ImmutableListMultimap.builder<Name, KtImportDirective>() val builder = ImmutableListMultimap.builder<Name, KtImportDirective>()
for (directive in imports) { for (directive in imports) {
val path = directive.getImportPath() ?: continue // parse error val path = directive.importPath ?: continue // parse error
val importedName = path.getImportedName() ?: continue // parse error val importedName = path.importedName ?: continue // parse error
builder.put(importedName, directive) builder.put(importedName, directive)
} }
@@ -241,8 +241,8 @@ class LazyImportScope(
return importResolver.storageManager.compute { return importResolver.storageManager.compute {
val descriptors = LinkedHashSet<DeclarationDescriptor>() val descriptors = LinkedHashSet<DeclarationDescriptor>()
for (directive in importResolver.indexedImports.imports) { for (directive in importResolver.indexedImports.imports) {
val importPath = directive.getImportPath() ?: continue val importPath = directive.importPath ?: continue
val importedName = importPath.getImportedName() val importedName = importPath.importedName
if (importedName == null || nameFilter(importedName)) { if (importedName == null || nameFilter(importedName)) {
descriptors.addAll(importResolver.getImportScope(directive).getContributedDescriptors(kindFilter, nameFilter)) descriptors.addAll(importResolver.getImportScope(directive).getContributedDescriptors(kindFilter, nameFilter))
} }
@@ -33,6 +33,6 @@ class KtScriptInfo(
override fun getTypeParameterList() = null override fun getTypeParameterList() = null
override fun getPrimaryConstructorParameters() = listOf<KtParameter>() override fun getPrimaryConstructorParameters() = listOf<KtParameter>()
override fun getClassKind() = ClassKind.CLASS override fun getClassKind() = ClassKind.CLASS
override fun getDeclarations() = script.getDeclarations() override fun getDeclarations() = script.declarations
override fun getDanglingAnnotations() = listOf<KtAnnotationEntry>() override fun getDanglingAnnotations() = listOf<KtAnnotationEntry>()
} }
@@ -358,7 +358,7 @@ open class LazyClassMemberScope(
private fun resolveSecondaryConstructors(): Collection<ClassConstructorDescriptor> { private fun resolveSecondaryConstructors(): Collection<ClassConstructorDescriptor> {
val classOrObject = declarationProvider.correspondingClassOrObject ?: return emptyList() val classOrObject = declarationProvider.correspondingClassOrObject ?: return emptyList()
return classOrObject.getSecondaryConstructors().map { constructor -> return classOrObject.secondaryConstructors.map { constructor ->
val descriptor = c.functionDescriptorResolver.resolveSecondaryConstructorDescriptor( val descriptor = c.functionDescriptorResolver.resolveSecondaryConstructorDescriptor(
thisDescriptor.scopeForConstructorHeaderResolution, thisDescriptor, constructor, trace thisDescriptor.scopeForConstructorHeaderResolution, thisDescriptor, constructor, trace
) )
@@ -368,7 +368,7 @@ open class LazyClassMemberScope(
} }
protected fun setDeferredReturnType(descriptor: ClassConstructorDescriptorImpl) { protected fun setDeferredReturnType(descriptor: ClassConstructorDescriptorImpl) {
descriptor.returnType = DeferredType.create(c.storageManager, trace, { thisDescriptor.getDefaultType() }) descriptor.returnType = DeferredType.create(c.storageManager, trace, { thisDescriptor.defaultType })
} }
override fun recordLookup(name: Name, from: LookupLocation) { override fun recordLookup(name: Name, from: LookupLocation) {
@@ -60,7 +60,7 @@ class LazyScriptDescriptor(
val scriptDefinition: KotlinScriptDefinition val scriptDefinition: KotlinScriptDefinition
by lazy { by lazy {
val file = scriptInfo.script.getContainingKtFile() val file = scriptInfo.script.containingKtFile
getScriptDefinition(file) ?: throw RuntimeException("file ${file.name} is not a script") getScriptDefinition(file) ?: throw RuntimeException("file ${file.name} is not a script")
} }
@@ -65,19 +65,19 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
): KotlinTypeInfo { ): KotlinTypeInfo {
if (!isDeclaration) { if (!isDeclaration) {
// function expression // function expression
if (!function.getTypeParameters().isEmpty()) { if (!function.typeParameters.isEmpty()) {
context.trace.report(TYPE_PARAMETERS_NOT_ALLOWED.on(function)) context.trace.report(TYPE_PARAMETERS_NOT_ALLOWED.on(function))
} }
if (function.getName() != null) { if (function.name != null) {
context.trace.report(ANONYMOUS_FUNCTION_WITH_NAME.on(function.nameIdentifier!!)) context.trace.report(ANONYMOUS_FUNCTION_WITH_NAME.on(function.nameIdentifier!!))
} }
for (parameter in function.getValueParameters()) { for (parameter in function.valueParameters) {
if (parameter.hasDefaultValue()) { if (parameter.hasDefaultValue()) {
context.trace.report(ANONYMOUS_FUNCTION_PARAMETER_WITH_DEFAULT_VALUE.on(parameter)) context.trace.report(ANONYMOUS_FUNCTION_PARAMETER_WITH_DEFAULT_VALUE.on(parameter))
} }
if (parameter.isVarArg()) { if (parameter.isVarArg) {
context.trace.report(USELESS_VARARG_ON_PARAMETER.on(parameter)) context.trace.report(USELESS_VARARG_ON_PARAMETER.on(parameter))
} }
} }
@@ -88,7 +88,7 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
functionDescriptor = components.functionDescriptorResolver.resolveFunctionDescriptor( functionDescriptor = components.functionDescriptorResolver.resolveFunctionDescriptor(
context.scope.ownerDescriptor, context.scope, function, context.trace, context.dataFlowInfo) context.scope.ownerDescriptor, context.scope, function, context.trace, context.dataFlowInfo)
assert(statementScope != null) { assert(statementScope != null) {
"statementScope must be not null for function: " + function.getName() + " at location " + DiagnosticUtils.atLocation(function) "statementScope must be not null for function: " + function.name + " at location " + DiagnosticUtils.atLocation(function)
} }
statementScope!!.addFunctionDescriptor(functionDescriptor) statementScope!!.addFunctionDescriptor(functionDescriptor)
} }
@@ -112,7 +112,7 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
} }
components.valueParameterResolver.resolveValueParameters( components.valueParameterResolver.resolveValueParameters(
function.getValueParameters(), functionDescriptor.valueParameters, context.scope, context.dataFlowInfo, context.trace function.valueParameters, functionDescriptor.valueParameters, context.scope, context.dataFlowInfo, context.trace
) )
components.modifiersChecker.withTrace(context.trace).checkModifiersForLocalDeclaration(function, functionDescriptor) components.modifiersChecker.withTrace(context.trace).checkModifiersForLocalDeclaration(function, functionDescriptor)
@@ -252,7 +252,7 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
if (returnedExpression != null) { if (returnedExpression != null) {
val type = context.trace.getType(returnedExpression) val type = context.trace.getType(returnedExpression)
if (type == null || !KotlinBuiltIns.isUnit(type)) { if (type == null || !KotlinBuiltIns.isUnit(type)) {
context.trace.report(RETURN_TYPE_MISMATCH.on(returnedExpression, components.builtIns.getUnitType())) context.trace.report(RETURN_TYPE_MISMATCH.on(returnedExpression, components.builtIns.unitType))
} }
} }
} }
@@ -74,7 +74,7 @@ class LocalClassifierAnalyzer(
classOrObject: KtClassOrObject classOrObject: KtClassOrObject
) { ) {
val module = DescriptorUtils.getContainingModule(containingDeclaration) val module = DescriptorUtils.getContainingModule(containingDeclaration)
val project = classOrObject.getProject() val project = classOrObject.project
val moduleContext = globalContext.withProject(project).withModule(module) val moduleContext = globalContext.withProject(project).withModule(module)
val container = createContainerForLazyLocalClassifierAnalyzer( val container = createContainerForLazyLocalClassifierAnalyzer(
moduleContext, moduleContext,
@@ -58,7 +58,7 @@ class ValueParameterResolver(
context: ExpressionTypingContext context: ExpressionTypingContext
) { ) {
if (!valueParameterDescriptor.declaresDefaultValue()) return if (!valueParameterDescriptor.declaresDefaultValue()) return
val defaultValue = jetParameter.getDefaultValue() ?: return val defaultValue = jetParameter.defaultValue ?: return
expressionTypingServices.getTypeInfo(defaultValue, context.replaceExpectedType(valueParameterDescriptor.type)) expressionTypingServices.getTypeInfo(defaultValue, context.replaceExpectedType(valueParameterDescriptor.type))
if (DescriptorUtils.isAnnotationClass(DescriptorResolver.getContainingClass(context.scope))) { if (DescriptorUtils.isAnnotationClass(DescriptorResolver.getContainingClass(context.scope))) {
val constant = constantExpressionEvaluator.evaluateExpression(defaultValue, context.trace, valueParameterDescriptor.type) val constant = constantExpressionEvaluator.evaluateExpression(defaultValue, context.trace, valueParameterDescriptor.type)
@@ -403,7 +403,7 @@ class ExpressionCodegen(
val spreadBuilderClassName = AsmUtil.asmPrimitiveTypeToLangPrimitiveType(elementType)!!.typeName.identifier + "SpreadBuilder" val spreadBuilderClassName = AsmUtil.asmPrimitiveTypeToLangPrimitiveType(elementType)!!.typeName.identifier + "SpreadBuilder"
owner = "kotlin/jvm/internal/" + spreadBuilderClassName owner = "kotlin/jvm/internal/" + spreadBuilderClassName
addDescriptor = "(" + elementType.descriptor + ")V" addDescriptor = "(" + elementType.descriptor + ")V"
toArrayDescriptor = "()" + type.getDescriptor() toArrayDescriptor = "()" + type.descriptor
} }
mv.anew(Type.getObjectType(owner)) mv.anew(Type.getObjectType(owner))
mv.dup() mv.dup()
@@ -91,7 +91,7 @@ class FunctionCodegen(val irFunction: IrFunction, val classCodegen: ClassCodegen
val defaultValue = this val defaultValue = this
val constant = org.jetbrains.kotlin.codegen.ExpressionCodegen.getCompileTimeConstant( val constant = org.jetbrains.kotlin.codegen.ExpressionCodegen.getCompileTimeConstant(
defaultValue, state.bindingContext, true, state.shouldInlineConstVals) defaultValue, state.bindingContext, true, state.shouldInlineConstVals)
assert(!state.classBuilderMode.generateBodies || constant != null) { "Default value for annotation parameter should be compile time value: " + defaultValue.getText() } assert(!state.classBuilderMode.generateBodies || constant != null) { "Default value for annotation parameter should be compile time value: " + defaultValue.text }
if (constant != null) { if (constant != null) {
val annotationCodegen = AnnotationCodegen.forAnnotationDefaultValue(methodVisitor, classCodegen, state.typeMapper) val annotationCodegen = AnnotationCodegen.forAnnotationDefaultValue(methodVisitor, classCodegen, state.typeMapper)
annotationCodegen.generateAnnotationDefaultValue(constant, descriptor.returnType!!) annotationCodegen.generateAnnotationDefaultValue(constant, descriptor.returnType!!)
@@ -212,7 +212,7 @@ class ClassGenerator(val declarationGenerator: DeclarationGenerator) : Generator
primaryConstructorDescriptor) primaryConstructorDescriptor)
val bodyGenerator = BodyGenerator(primaryConstructorDescriptor, context) val bodyGenerator = BodyGenerator(primaryConstructorDescriptor, context)
ktClassOrObject.getPrimaryConstructor()?.valueParameterList?.let { ktValueParameterList -> ktClassOrObject.primaryConstructor?.valueParameterList?.let { ktValueParameterList ->
bodyGenerator.generateDefaultParameters(ktValueParameterList, irPrimaryConstructor) bodyGenerator.generateDefaultParameters(ktValueParameterList, irPrimaryConstructor)
} }
irPrimaryConstructor.body = bodyGenerator.generatePrimaryConstructorBody(ktClassOrObject) irPrimaryConstructor.body = bodyGenerator.generatePrimaryConstructorBody(ktClassOrObject)
@@ -221,7 +221,7 @@ class ClassGenerator(val declarationGenerator: DeclarationGenerator) : Generator
} }
private fun generatePropertiesDeclaredInPrimaryConstructor(irClass: IrClassImpl, ktClassOrObject: KtClassOrObject) { private fun generatePropertiesDeclaredInPrimaryConstructor(irClass: IrClassImpl, ktClassOrObject: KtClassOrObject) {
ktClassOrObject.getPrimaryConstructor()?.let { ktPrimaryConstructor -> ktClassOrObject.primaryConstructor?.let { ktPrimaryConstructor ->
for (ktParameter in ktPrimaryConstructor.valueParameters) { for (ktParameter in ktPrimaryConstructor.valueParameters) {
if (ktParameter.hasValOrVar()) { if (ktParameter.hasValOrVar()) {
val irProperty = PropertyGenerator(declarationGenerator).generatePropertyForPrimaryConstructorParameter(ktParameter) val irProperty = PropertyGenerator(declarationGenerator).generatePropertyForPrimaryConstructorParameter(ktParameter)
@@ -34,7 +34,7 @@ object LightClassUtil {
fun findClass(stub: StubElement<*>, predicate: (PsiClassStub<*>) -> Boolean): PsiClass? { fun findClass(stub: StubElement<*>, predicate: (PsiClassStub<*>) -> Boolean): PsiClass? {
if (stub is PsiClassStub<*> && predicate(stub)) { if (stub is PsiClassStub<*> && predicate(stub)) {
return stub.getPsi() return stub.psi
} }
if (stub is PsiClassStub<*> || stub is PsiFileStub<*>) { if (stub is PsiClassStub<*> || stub is PsiFileStub<*>) {
@@ -165,9 +165,9 @@ class LightClassDataProviderForClassOrObject(private val classOrObject: KtClassO
LightClassDataProvider<WithFileStubAndExtraDiagnostics>(classOrObject.project) { LightClassDataProvider<WithFileStubAndExtraDiagnostics>(classOrObject.project) {
private val file: KtFile private val file: KtFile
get() = classOrObject.getContainingKtFile() get() = classOrObject.containingKtFile
override val isLocal: Boolean get() = classOrObject.isLocal() override val isLocal: Boolean get() = classOrObject.isLocal
override fun getContext(files: Collection<KtFile>): LightClassConstructionContext { override fun getContext(files: Collection<KtFile>): LightClassConstructionContext {
return LightClassGenerationSupport.getInstance(classOrObject.project).getContextForClassOrObject(classOrObject) return LightClassGenerationSupport.getInstance(classOrObject.project).getContextForClassOrObject(classOrObject)
@@ -237,7 +237,7 @@ class LightClassDataProviderForClassOrObject(private val classOrObject: KtClassO
// TODO: current method will process local classes in irrelevant declarations, it should be fixed. // TODO: current method will process local classes in irrelevant declarations, it should be fixed.
// We generate all enclosing classes // We generate all enclosing classes
if (classOrObject.isLocal() && processingClassOrObject.isLocal()) { if (classOrObject.isLocal && processingClassOrObject.isLocal) {
val commonParent = PsiTreeUtil.findCommonParent(classOrObject, processingClassOrObject) val commonParent = PsiTreeUtil.findCommonParent(classOrObject, processingClassOrObject)
return commonParent != null && commonParent !is PsiFile return commonParent != null && commonParent !is PsiFile
} }
@@ -252,7 +252,7 @@ class LightClassDataProviderForClassOrObject(private val classOrObject: KtClassO
override fun generate(state: GenerationState, files: Collection<KtFile>) { override fun generate(state: GenerationState, files: Collection<KtFile>) {
val packageCodegen = state.factory.forPackage(packageFqName, files) val packageCodegen = state.factory.forPackage(packageFqName, files)
val file = classOrObject.getContainingKtFile() val file = classOrObject.containingKtFile
val packagePartType = state.fileClassesProvider.getFileClassType(file) val packagePartType = state.fileClassesProvider.getFileClassType(file)
val context = state.rootContext.intoPackagePart(packageCodegen.packageFragment, packagePartType, file) val context = state.rootContext.intoPackagePart(packageCodegen.packageFragment, packagePartType, file)
packageCodegen.generateClassOrObject(classOrObject, context) packageCodegen.generateClassOrObject(classOrObject, context)
@@ -194,7 +194,7 @@ class KtLightClassForFacade private constructor(
override fun isValid() = files.all { it.isValid && fileHasTopLevelCallables(it) && facadeClassFqName == it.javaFileFacadeFqName } override fun isValid() = files.all { it.isValid && fileHasTopLevelCallables(it) && facadeClassFqName == it.javaFileFacadeFqName }
override fun copy() = KtLightClassForFacade(getManager(), facadeClassFqName, lightClassDataCache, files) override fun copy() = KtLightClassForFacade(manager, facadeClassFqName, lightClassDataCache, files)
override val clsDelegate: PsiClass override val clsDelegate: PsiClass
get() { get() {
@@ -216,7 +216,7 @@ class KtLightClassForFacade private constructor(
override fun getNavigationElement() = files.iterator().next() override fun getNavigationElement() = files.iterator().next()
override fun isEquivalentTo(another: PsiElement?): Boolean { override fun isEquivalentTo(another: PsiElement?): Boolean {
return another is PsiClass && Comparing.equal(another.qualifiedName, getQualifiedName()) return another is PsiClass && Comparing.equal(another.qualifiedName, qualifiedName)
} }
override fun getElementIcon(flags: Int): Icon? = throw UnsupportedOperationException("This should be done by JetIconProvider") override fun getElementIcon(flags: Int): Icon? = throw UnsupportedOperationException("This should be done by JetIconProvider")
@@ -240,7 +240,7 @@ class KtLightClassForFacade private constructor(
override fun hashCode() = hashCode override fun hashCode() = hashCode
private fun computeHashCode(): Int { private fun computeHashCode(): Int {
var result = getManager().hashCode() var result = manager.hashCode()
result = 31 * result + files.hashCode() result = 31 * result + files.hashCode()
result = 31 * result + facadeClassFqName.hashCode() result = 31 * result + facadeClassFqName.hashCode()
return result return result
@@ -255,7 +255,7 @@ class KtLightClassForFacade private constructor(
if (this === other) return true if (this === other) return true
if (this.hashCode != lightClass.hashCode) return false if (this.hashCode != lightClass.hashCode) return false
if (getManager() != lightClass.getManager()) return false if (manager != lightClass.manager) return false
if (files != lightClass.files) return false if (files != lightClass.files) return false
if (facadeClassFqName != lightClass.facadeClassFqName) return false if (facadeClassFqName != lightClass.facadeClassFqName) return false
@@ -121,7 +121,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
classOrObject.containingFile.virtualFile ?: error("No virtual file for " + classOrObject.text) classOrObject.containingFile.virtualFile ?: error("No virtual file for " + classOrObject.text)
object : FakeFileForLightClass( object : FakeFileForLightClass(
classOrObject.getContainingKtFile(), classOrObject.containingKtFile,
{ if (classOrObject.isTopLevel()) this else create(getOutermostClassOrObject(classOrObject))!! }, { if (classOrObject.isTopLevel()) this else create(getOutermostClassOrObject(classOrObject))!! },
{ getJavaFileStub() } { getJavaFileStub() }
) { ) {
@@ -352,7 +352,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
fun create(classOrObject: KtClassOrObject): KtLightClassForSourceDeclaration? { fun create(classOrObject: KtClassOrObject): KtLightClassForSourceDeclaration? {
if (classOrObject.getContainingKtFile().isScript || classOrObject.hasModifier(KtTokens.HEADER_KEYWORD)) { if (classOrObject.containingKtFile.isScript || classOrObject.hasModifier(KtTokens.HEADER_KEYWORD)) {
return null return null
} }
@@ -366,7 +366,7 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
return null return null
} }
if (classOrObject.isLocal()) { if (classOrObject.isLocal) {
if (classOrObject.containingFile.virtualFile == null) return null if (classOrObject.containingFile.virtualFile == null) return null
return KtLightClassForLocalDeclaration(classOrObject) return KtLightClassForLocalDeclaration(classOrObject)
@@ -91,12 +91,12 @@ class FilteredJvmDiagnostics(val jvmDiagnostics: Diagnostics, val otherDiagnosti
val higherPriority = setOf<DiagnosticFactory<*>>( val higherPriority = setOf<DiagnosticFactory<*>>(
CONFLICTING_OVERLOADS, REDECLARATION, NOTHING_TO_OVERRIDE, MANY_IMPL_MEMBER_NOT_IMPLEMENTED) CONFLICTING_OVERLOADS, REDECLARATION, NOTHING_TO_OVERRIDE, MANY_IMPL_MEMBER_NOT_IMPLEMENTED)
return otherDiagnostics.forElement(psiElement).any { it.factory in higherPriority } return otherDiagnostics.forElement(psiElement).any { it.factory in higherPriority }
|| psiElement is KtPropertyAccessor && alreadyReported(psiElement.getParent()!!) || psiElement is KtPropertyAccessor && alreadyReported(psiElement.parent!!)
} }
override fun forElement(psiElement: PsiElement): Collection<Diagnostic> { override fun forElement(psiElement: PsiElement): Collection<Diagnostic> {
val jvmDiagnosticFactories = setOf(CONFLICTING_JVM_DECLARATIONS, ACCIDENTAL_OVERRIDE, CONFLICTING_INHERITED_JVM_DECLARATIONS) val jvmDiagnosticFactories = setOf(CONFLICTING_JVM_DECLARATIONS, ACCIDENTAL_OVERRIDE, CONFLICTING_INHERITED_JVM_DECLARATIONS)
fun Diagnostic.data() = cast(this, jvmDiagnosticFactories).getA() fun Diagnostic.data() = cast(this, jvmDiagnosticFactories).a
val (conflicting, other) = jvmDiagnostics.forElement(psiElement).partition { it.factory in jvmDiagnosticFactories } val (conflicting, other) = jvmDiagnostics.forElement(psiElement).partition { it.factory in jvmDiagnosticFactories }
if (alreadyReported(psiElement)) { if (alreadyReported(psiElement)) {
// CONFLICTING_OVERLOADS already reported, no need to duplicate it // CONFLICTING_OVERLOADS already reported, no need to duplicate it
@@ -70,7 +70,7 @@ fun PsiElement.toLightMethods(): List<PsiMethod> =
is KtProperty -> LightClassUtil.getLightClassPropertyMethods(this).toList() is KtProperty -> LightClassUtil.getLightClassPropertyMethods(this).toList()
is KtParameter -> LightClassUtil.getLightClassPropertyMethods(this).toList() is KtParameter -> LightClassUtil.getLightClassPropertyMethods(this).toList()
is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethods(this) is KtPropertyAccessor -> LightClassUtil.getLightClassAccessorMethods(this)
is KtClass -> toLightClass()?.getConstructors()?.firstOrNull().singletonOrEmptyList() is KtClass -> toLightClass()?.constructors?.firstOrNull().singletonOrEmptyList()
is PsiMethod -> this.singletonList() is PsiMethod -> this.singletonList()
else -> listOf() else -> listOf()
} }
@@ -88,8 +88,8 @@ fun PsiElement.getRepresentativeLightMethod(): PsiMethod? =
fun KtParameter.toPsiParameters(): Collection<PsiParameter> { fun KtParameter.toPsiParameters(): Collection<PsiParameter> {
val paramList = getNonStrictParentOfType<KtParameterList>() ?: return emptyList() val paramList = getNonStrictParentOfType<KtParameterList>() ?: return emptyList()
val paramIndex = paramList.getParameters().indexOf(this) val paramIndex = paramList.parameters.indexOf(this)
val owner = paramList.getParent() val owner = paramList.parent
val lightParamIndex = if (owner is KtDeclaration && owner.isExtensionDeclaration()) paramIndex + 1 else paramIndex val lightParamIndex = if (owner is KtDeclaration && owner.isExtensionDeclaration()) paramIndex + 1 else paramIndex
val methods: Collection<PsiMethod> = val methods: Collection<PsiMethod> =
@@ -77,8 +77,8 @@ class LazyJavaAnnotationDescriptor(
val nameToArg = javaAnnotation.arguments.associateBy { it.name } val nameToArg = javaAnnotation.arguments.associateBy { it.name }
return constructors.first().valueParameters.keysToMapExceptNulls { valueParameter -> return constructors.first().valueParameters.keysToMapExceptNulls { valueParameter ->
var javaAnnotationArgument = nameToArg[valueParameter.getName()] var javaAnnotationArgument = nameToArg[valueParameter.name]
if (javaAnnotationArgument == null && valueParameter.getName() == DEFAULT_ANNOTATION_MEMBER_NAME) { if (javaAnnotationArgument == null && valueParameter.name == DEFAULT_ANNOTATION_MEMBER_NAME) {
javaAnnotationArgument = nameToArg[null] javaAnnotationArgument = nameToArg[null]
} }
@@ -240,7 +240,7 @@ class LazyJavaClassDescriptor(
override fun getDeclarationDescriptor() = this@LazyJavaClassDescriptor override fun getDeclarationDescriptor() = this@LazyJavaClassDescriptor
override fun toString(): String = getName().asString() override fun toString(): String = name.asString()
} }
// Only needed when calculating built-ins member scope // Only needed when calculating built-ins member scope
@@ -183,7 +183,7 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS
val name = if (function.name.asString() == "equals" && val name = if (function.name.asString() == "equals" &&
jValueParameters.size == 1 && jValueParameters.size == 1 &&
c.module.builtIns.getNullableAnyType() == outType) { c.module.builtIns.nullableAnyType == outType) {
// This is a hack to prevent numerous warnings on Kotlin classes that inherit Java classes: if you override "equals" in such // This is a hack to prevent numerous warnings on Kotlin classes that inherit Java classes: if you override "equals" in such
// class without this hack, you'll be warned that in the superclass the name is "p0" (regardless of the fact that it's // class without this hack, you'll be warned that in the superclass the name is "p0" (regardless of the fact that it's
// "other" in Any) // "other" in Any)
@@ -258,7 +258,7 @@ abstract class LazyJavaScope(protected val c: LazyJavaResolverContext) : MemberS
propertyDescriptor.setType(propertyType, listOf(), getDispatchReceiverParameter(), null as KotlinType?) propertyDescriptor.setType(propertyType, listOf(), getDispatchReceiverParameter(), null as KotlinType?)
if (DescriptorUtils.shouldRecordInitializerForProperty(propertyDescriptor, propertyDescriptor.getType())) { if (DescriptorUtils.shouldRecordInitializerForProperty(propertyDescriptor, propertyDescriptor.type)) {
propertyDescriptor.setCompileTimeInitializer( propertyDescriptor.setCompileTimeInitializer(
c.storageManager.createNullableLazyValue { c.storageManager.createNullableLazyValue {
c.components.javaPropertyInitializerEvaluator.getInitializerConstant(field, propertyDescriptor) c.components.javaPropertyInitializerEvaluator.getInitializerConstant(field, propertyDescriptor)
@@ -108,7 +108,7 @@ class AnnotationDeserializer(private val module: ModuleDescriptor, private val n
// In the case of empty array, no element has the element type, so we fall back to the expected type, if any. // In the case of empty array, no element has the element type, so we fall back to the expected type, if any.
// This is not very accurate when annotation class has been changed without recompiling clients, // This is not very accurate when annotation class has been changed without recompiling clients,
// but should not in fact matter because the value is empty anyway // but should not in fact matter because the value is empty anyway
if (expectedIsArray) expectedType else builtIns.getArrayType(Variance.INVARIANT, builtIns.getAnyType()) if (expectedIsArray) expectedType else builtIns.getArrayType(Variance.INVARIANT, builtIns.anyType)
} }
val expectedElementType = builtIns.getArrayElementType(if (expectedIsArray) expectedType else actualArrayType) val expectedElementType = builtIns.getArrayElementType(if (expectedIsArray) expectedType else actualArrayType)
@@ -147,15 +147,15 @@ class AnnotationDeserializer(private val module: ModuleDescriptor, private val n
private fun resolveArrayElementType(value: Value, nameResolver: NameResolver): SimpleType = private fun resolveArrayElementType(value: Value, nameResolver: NameResolver): SimpleType =
with(builtIns) { with(builtIns) {
when (value.type) { when (value.type) {
Type.BYTE -> getByteType() Type.BYTE -> byteType
Type.CHAR -> getCharType() Type.CHAR -> charType
Type.SHORT -> getShortType() Type.SHORT -> shortType
Type.INT -> getIntType() Type.INT -> intType
Type.LONG -> getLongType() Type.LONG -> longType
Type.FLOAT -> getFloatType() Type.FLOAT -> floatType
Type.DOUBLE -> getDoubleType() Type.DOUBLE -> doubleType
Type.BOOLEAN -> getBooleanType() Type.BOOLEAN -> booleanType
Type.STRING -> getStringType() Type.STRING -> stringType
Type.CLASS -> error("Arrays of class literals are not supported yet") // TODO: support arrays of class literals Type.CLASS -> error("Arrays of class literals are not supported yet") // TODO: support arrays of class literals
Type.ENUM -> resolveClass(nameResolver.getClassId(value.classId)).defaultType Type.ENUM -> resolveClass(nameResolver.getClassId(value.classId)).defaultType
Type.ANNOTATION -> resolveClass(nameResolver.getClassId(value.annotation.id)).defaultType Type.ANNOTATION -> resolveClass(nameResolver.getClassId(value.annotation.id)).defaultType
@@ -35,7 +35,7 @@ fun main(args: Array<String>) {
val jar = JarFile(file) val jar = JarFile(file)
try { try {
for (jarEntry in jar.entries()) { for (jarEntry in jar.entries()) {
result[jarEntry.getName()] = Pair(jarEntry, jar.getInputStream(jarEntry).readBytes()) result[jarEntry.name] = Pair(jarEntry, jar.getInputStream(jarEntry).readBytes())
} }
} }
finally { finally {
@@ -50,7 +50,7 @@ fun loadVersions(library: File): String {
val jarFile = JarFile(library) val jarFile = JarFile(library)
try { try {
for (entry in jarFile.entries()) { for (entry in jarFile.entries()) {
if (entry.getName().endsWith(".class")) { if (entry.name.endsWith(".class")) {
val classBytes = jarFile.getInputStream(entry).readBytes() val classBytes = jarFile.getInputStream(entry).readBytes()
loadClassVersions(classBytes)?.let { loadClassVersions(classBytes)?.let {
val (metadata, bytecode) = it val (metadata, bytecode) = it
@@ -68,13 +68,13 @@ fun main(args: Array<String>) {
try { try {
for (entry in inJar.entries()) { for (entry in inJar.entries()) {
val inBytes = inJar.getInputStream(entry).readBytes() val inBytes = inJar.getInputStream(entry).readBytes()
val outBytes = transform(entry.getName(), inBytes) val outBytes = transform(entry.name, inBytes)
if (inBytes.size < outBytes.size) { if (inBytes.size < outBytes.size) {
error("Size increased for ${entry.getName()}: was ${inBytes.size} bytes, became ${outBytes.size} bytes") error("Size increased for ${entry.name}: was ${inBytes.size} bytes, became ${outBytes.size} bytes")
} }
entry.setCompressedSize(-1L) entry.compressedSize = -1L
outJar.putNextEntry(entry) outJar.putNextEntry(entry)
outJar.write(outBytes) outJar.write(outBytes)
outJar.closeEntry() outJar.closeEntry()
@@ -37,7 +37,7 @@ fun KtFunctionLiteral.findLabelAndCall(): Pair<Name?, KtCallExpression?> {
when (literalParent) { when (literalParent) {
is KtLabeledExpression -> { is KtLabeledExpression -> {
val callExpression = (literalParent.getParent() as? KtValueArgument)?.callExpression() val callExpression = (literalParent.parent as? KtValueArgument)?.callExpression()
return Pair(literalParent.getLabelNameAsName(), callExpression) return Pair(literalParent.getLabelNameAsName(), callExpression)
} }
@@ -598,7 +598,7 @@ class KotlinPsiUnifier(
} }
fun getDelegationOrderInfo(cls: KtClassOrObject): OrderInfo<KtSuperTypeListEntry> { fun getDelegationOrderInfo(cls: KtClassOrObject): OrderInfo<KtSuperTypeListEntry> {
val (orderInsensitive, orderSensitive) = cls.getSuperTypeListEntries().partition { it is KtSuperTypeEntry } val (orderInsensitive, orderSensitive) = cls.superTypeListEntries.partition { it is KtSuperTypeEntry }
return OrderInfo(orderSensitive, orderInsensitive) return OrderInfo(orderSensitive, orderInsensitive)
} }
@@ -539,7 +539,7 @@ class PartialBodyResolveFilter(
is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent) is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent)
is KtContainerNode -> { //TODO - not quite correct is KtContainerNode -> { //TODO - not quite correct
val pparent = parent.getParent() as? KtExpression val pparent = parent.parent as? KtExpression
pparent != null && isValueNeeded(pparent) pparent != null && isValueNeeded(pparent)
} }
@@ -559,7 +559,7 @@ class PartialBodyResolveFilter(
private fun KtBlockExpression.lastStatement(): KtExpression? private fun KtBlockExpression.lastStatement(): KtExpression?
= lastChild?.siblings(forward = false)?.firstIsInstanceOrNull<KtExpression>() = lastChild?.siblings(forward = false)?.firstIsInstanceOrNull<KtExpression>()
private fun PsiElement.isStatement() = this is KtExpression && getParent() is KtBlockExpression private fun PsiElement.isStatement() = this is KtExpression && parent is KtBlockExpression
private fun KtTypeReference?.containsProbablyNothing() private fun KtTypeReference?.containsProbablyNothing()
= this?.typeElement?.anyDescendantOfType<KtUserType> { it.isProbablyNothing() } ?: false = this?.typeElement?.anyDescendantOfType<KtUserType> { it.isProbablyNothing() } ?: false
@@ -64,7 +64,7 @@ class IDELightClassGenerationSupport(private val project: Project) : LightClassG
private val psiManager: PsiManager = PsiManager.getInstance(project) private val psiManager: PsiManager = PsiManager.getInstance(project)
override fun getContextForClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext { override fun getContextForClassOrObject(classOrObject: KtClassOrObject): LightClassConstructionContext {
if (classOrObject.isLocal()) { if (classOrObject.isLocal) {
return getContextForLocalClassOrObject(classOrObject) return getContextForLocalClassOrObject(classOrObject)
} }
else { else {
@@ -312,12 +312,12 @@ class IDELightClassGenerationSupport(private val project: Project) : LightClassG
val relativeFqName = getClassRelativeName(decompiledClassOrObject) val relativeFqName = getClassRelativeName(decompiledClassOrObject)
val iterator = relativeFqName.pathSegments().iterator() val iterator = relativeFqName.pathSegments().iterator()
val base = iterator.next() val base = iterator.next()
assert(rootLightClassForDecompiledFile.name == base.asString()) { "Light class for file:\n" + decompiledClassOrObject.getContainingKtFile().virtualFile.canonicalPath + "\nwas expected to have name: " + base.asString() + "\n Actual: " + rootLightClassForDecompiledFile.name } assert(rootLightClassForDecompiledFile.name == base.asString()) { "Light class for file:\n" + decompiledClassOrObject.containingKtFile.virtualFile.canonicalPath + "\nwas expected to have name: " + base.asString() + "\n Actual: " + rootLightClassForDecompiledFile.name }
var current: KtLightClassForDecompiledDeclaration = rootLightClassForDecompiledFile var current: KtLightClassForDecompiledDeclaration = rootLightClassForDecompiledFile
while (iterator.hasNext()) { while (iterator.hasNext()) {
val name = iterator.next() val name = iterator.next()
val innerClass = current.findInnerClassByName(name.asString(), false).sure { val innerClass = current.findInnerClassByName(name.asString(), false).sure {
"Could not find corresponding inner/nested class " + relativeFqName + " in class " + decompiledClassOrObject.fqName + "\n" + "File: " + decompiledClassOrObject.getContainingKtFile().virtualFile.name "Could not find corresponding inner/nested class " + relativeFqName + " in class " + decompiledClassOrObject.fqName + "\n" + "File: " + decompiledClassOrObject.containingKtFile.virtualFile.name
} }
current = innerClass as KtLightClassForDecompiledDeclaration current = innerClass as KtLightClassForDecompiledDeclaration
} }
@@ -55,7 +55,7 @@ internal val LOG = Logger.getInstance(KotlinCacheService::class.java)
class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService { class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade { override fun getResolutionFacade(elements: List<KtElement>): ResolutionFacade {
return getFacadeToAnalyzeFiles(elements.map { it.getContainingKtFile() }) return getFacadeToAnalyzeFiles(elements.map { it.containingKtFile })
} }
override fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value override fun getSuppressionCache(): KotlinSuppressCache = kotlinSuppressCache.value
@@ -350,7 +350,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
private fun KtCodeFragment.getContextFile(): KtFile? { private fun KtCodeFragment.getContextFile(): KtFile? {
val contextElement = context ?: return null val contextElement = context ?: return null
val contextFile = (contextElement as? KtElement)?.getContainingKtFile() val contextFile = (contextElement as? KtElement)?.containingKtFile
?: throw AssertionError("Analyzing kotlin code fragment of type $javaClass with java context of type ${contextElement.javaClass}") ?: 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 return if (contextFile is KtCodeFragment) contextFile.getContextFile() else contextFile
} }
@@ -68,7 +68,7 @@ internal class PerFileAnalysisCache(val file: KtFile, val componentProvider: Com
} }
fun getAnalysisResults(element: KtElement): AnalysisResult { fun getAnalysisResults(element: KtElement): AnalysisResult {
assert (element.getContainingKtFile() == file) { "Wrong file. Expected $file, but was ${element.getContainingKtFile()}" } assert (element.containingKtFile == file) { "Wrong file. Expected $file, but was ${element.containingKtFile}" }
val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element) val analyzableParent = KotlinResolveDataProvider.findAnalyzableParent(element)
@@ -146,7 +146,7 @@ private object KotlinResolveDataProvider {
// if none of the above worked, take the outermost declaration // if none of the above worked, take the outermost declaration
?: PsiTreeUtil.getTopmostParentOfType(element, KtDeclaration::class.java) ?: PsiTreeUtil.getTopmostParentOfType(element, KtDeclaration::class.java)
// if even that didn't work, take the whole file // if even that didn't work, take the whole file
?: element.getContainingKtFile() ?: element.containingKtFile
} }
fun analyze(project: Project, componentProvider: ComponentProvider, analyzableElement: KtElement): AnalysisResult { fun analyze(project: Project, componentProvider: ComponentProvider, analyzableElement: KtElement): AnalysisResult {
@@ -156,7 +156,7 @@ private object KotlinResolveDataProvider {
return AnalysisResult.success(analyzeExpressionCodeFragment(componentProvider, analyzableElement), module) return AnalysisResult.success(analyzeExpressionCodeFragment(componentProvider, analyzableElement), module)
} }
val file = analyzableElement.getContainingKtFile() val file = analyzableElement.containingKtFile
if (file.getModuleInfo() is LibrarySourceInfo) { if (file.getModuleInfo() is LibrarySourceInfo) {
// Library sources: mark file to skip // Library sources: mark file to skip
file.putUserData(LibrarySourceHacks.SKIP_TOP_LEVEL_MEMBERS, true) file.putUserData(LibrarySourceHacks.SKIP_TOP_LEVEL_MEMBERS, true)
@@ -165,7 +165,7 @@ private object KotlinResolveDataProvider {
val resolveSession = componentProvider.get<ResolveSession>() val resolveSession = componentProvider.get<ResolveSession>()
val trace = DelegatingBindingTrace(resolveSession.bindingContext, "Trace for resolution of " + analyzableElement) val trace = DelegatingBindingTrace(resolveSession.bindingContext, "Trace for resolution of " + analyzableElement)
val targetPlatform = TargetPlatformDetector.getPlatform(analyzableElement.getContainingKtFile()) val targetPlatform = TargetPlatformDetector.getPlatform(analyzableElement.containingKtFile)
val lazyTopDownAnalyzer = createContainerForLazyBodyResolve( val lazyTopDownAnalyzer = createContainerForLazyBodyResolve(
//TODO: should get ModuleContext //TODO: should get ModuleContext
@@ -73,7 +73,7 @@ internal class ProjectResolutionFacade(
} }
val results = elements.map { val results = elements.map {
val perFileCache = synchronized(slruCache) { val perFileCache = synchronized(slruCache) {
slruCache[it.getContainingKtFile()] slruCache[it.containingKtFile]
} }
perFileCache.getAnalysisResults(it) perFileCache.getAnalysisResults(it)
} }
@@ -145,7 +145,7 @@ object ByDescriptorIndexer : DecompiledTextIndexer<String> {
if (original is ConstructorDescriptor && original.isPrimary) { if (original is ConstructorDescriptor && original.isPrimary) {
val classOrObject = getDeclarationForDescriptor(original.containingDeclaration, file) as? KtClassOrObject val classOrObject = getDeclarationForDescriptor(original.containingDeclaration, file) as? KtClassOrObject
return classOrObject?.getPrimaryConstructor() ?: classOrObject return classOrObject?.primaryConstructor ?: classOrObject
} }
val descriptorKey = original.toStringKey() val descriptorKey = original.toStringKey()
@@ -69,7 +69,7 @@ open class KotlinPsiChecker : Annotator, HighlightRangeExtension {
getAfterAnalysisVisitor(holder, bindingContext).forEach { visitor -> element.accept(visitor) } getAfterAnalysisVisitor(holder, bindingContext).forEach { visitor -> element.accept(visitor) }
annotateElement(element, holder, bindingContext.getDiagnostics()) annotateElement(element, holder, bindingContext.diagnostics)
} }
override fun isForceHighlightParents(file: PsiFile): Boolean { override fun isForceHighlightParents(file: PsiFile): Boolean {
@@ -117,7 +117,7 @@ class ResolveElementCache(
= getElementsAdditionalResolve(function, null, BodyResolveMode.FULL) = getElementsAdditionalResolve(function, null, BodyResolveMode.FULL)
fun resolvePrimaryConstructorParametersDefaultValues(ktClass: KtClass): BindingContext { fun resolvePrimaryConstructorParametersDefaultValues(ktClass: KtClass): BindingContext {
return constructorAdditionalResolve(resolveSession, ktClass, ktClass.getContainingKtFile(), BindingTraceFilter.NO_DIAGNOSTICS).bindingContext return constructorAdditionalResolve(resolveSession, ktClass, ktClass.containingKtFile, BindingTraceFilter.NO_DIAGNOSTICS).bindingContext
} }
@Deprecated("Use getElementsAdditionalResolve") @Deprecated("Use getElementsAdditionalResolve")
@@ -278,7 +278,7 @@ class ResolveElementCache(
assert(bodyResolveMode == BodyResolveMode.FULL) assert(bodyResolveMode == BodyResolveMode.FULL)
} }
val file = resolveElement.getContainingKtFile() val file = resolveElement.containingKtFile
var statementFilterUsed = StatementFilter.NONE var statementFilterUsed = StatementFilter.NONE
@@ -403,10 +403,10 @@ class ResolveElementCache(
else { else {
val fileAnnotationList = ktAnnotationEntry.getParentOfType<KtFileAnnotationList>(true) val fileAnnotationList = ktAnnotationEntry.getParentOfType<KtFileAnnotationList>(true)
if (fileAnnotationList != null) { if (fileAnnotationList != null) {
doResolveAnnotations(resolveSession.getFileAnnotations(fileAnnotationList.getContainingKtFile())) doResolveAnnotations(resolveSession.getFileAnnotations(fileAnnotationList.containingKtFile))
} }
if (modifierList != null && modifierList.parent is KtFile) { if (modifierList != null && modifierList.parent is KtFile) {
doResolveAnnotations(resolveSession.getDanglingAnnotations(modifierList.getContainingKtFile())) doResolveAnnotations(resolveSession.getDanglingAnnotations(modifierList.containingKtFile))
} }
} }
@@ -420,7 +420,7 @@ class ResolveElementCache(
private fun getAnnotationsByDeclaration(resolveSession: ResolveSession, modifierList: KtModifierList, declaration: KtDeclaration): Annotations { private fun getAnnotationsByDeclaration(resolveSession: ResolveSession, modifierList: KtModifierList, declaration: KtDeclaration): Annotations {
var descriptor = resolveSession.resolveToDescriptor(declaration) var descriptor = resolveSession.resolveToDescriptor(declaration)
if (declaration is KtClass) { if (declaration is KtClass) {
if (modifierList == declaration.getPrimaryConstructorModifierList()) { if (modifierList == declaration.primaryConstructorModifierList) {
descriptor = (descriptor as ClassDescriptor).unsubstitutedPrimaryConstructor descriptor = (descriptor as ClassDescriptor).unsubstitutedPrimaryConstructor
?: error("No constructor found: ${declaration.getText()}") ?: error("No constructor found: ${declaration.getText()}")
} }
@@ -532,7 +532,7 @@ class ResolveElementCache(
"in from class '${klass.getElementTextWithContext()}'") "in from class '${klass.getElementTextWithContext()}'")
ForceResolveUtil.forceResolveAllContents(constructorDescriptor) ForceResolveUtil.forceResolveAllContents(constructorDescriptor)
val primaryConstructor = klass.getPrimaryConstructor() val primaryConstructor = klass.primaryConstructor
if (primaryConstructor != null) { if (primaryConstructor != null) {
val bodyResolver = createBodyResolver(resolveSession, trace, file, StatementFilter.NONE) val bodyResolver = createBodyResolver(resolveSession, trace, file, StatementFilter.NONE)
bodyResolver.resolveConstructorParameterDefaultValues(DataFlowInfo.EMPTY, trace, primaryConstructor, constructorDescriptor, scope) bodyResolver.resolveConstructorParameterDefaultValues(DataFlowInfo.EMPTY, trace, primaryConstructor, constructorDescriptor, scope)
@@ -103,7 +103,7 @@ fun PsiReference.matchesTarget(candidateTarget: PsiElement): Boolean {
} }
if (this is PsiJavaCodeReferenceElement && candidateTarget is KtObjectDeclaration && unwrappedTargets.size == 1) { if (this is PsiJavaCodeReferenceElement && candidateTarget is KtObjectDeclaration && unwrappedTargets.size == 1) {
val referredClass = unwrappedTargets.first() val referredClass = unwrappedTargets.first()
if (referredClass is KtClass && candidateTarget in referredClass.getCompanionObjects()) { if (referredClass is KtClass && candidateTarget in referredClass.companionObjects) {
if (parent is PsiImportStaticStatement) return true if (parent is PsiImportStaticStatement) return true
return parent.reference?.unwrappedTargets?.any { return parent.reference?.unwrappedTargets?.any {
@@ -603,7 +603,7 @@ class ExpressionsOfTypeProcessor(
runReadAction { runReadAction {
if (!scope.isValid) return@runReadAction if (!scope.isValid) return@runReadAction
val file = scope.getContainingKtFile() val file = scope.containingKtFile
val restricted = LocalSearchScope(scope).intersectWith(searchScope) val restricted = LocalSearchScope(scope).intersectWith(searchScope)
if (restricted is LocalSearchScope) { if (restricted is LocalSearchScope) {
ScopeLoop@ ScopeLoop@
@@ -175,7 +175,7 @@ private fun processInheritorsDelegatingCallToSpecifiedConstructor(
private fun processClassDelegationCallsToSpecifiedConstructor( private fun processClassDelegationCallsToSpecifiedConstructor(
klass: KtClass, constructor: DeclarationDescriptor, process: (KtCallElement) -> Boolean klass: KtClass, constructor: DeclarationDescriptor, process: (KtCallElement) -> Boolean
): Boolean { ): Boolean {
for (secondaryConstructor in klass.getSecondaryConstructors()) { for (secondaryConstructor in klass.secondaryConstructors) {
val delegationCallDescriptor = secondaryConstructor.getDelegationCall().getConstructorCallDescriptor() val delegationCallDescriptor = secondaryConstructor.getDelegationCall().getConstructorCallDescriptor()
if (constructor == delegationCallDescriptor) { if (constructor == delegationCallDescriptor) {
if (!process(secondaryConstructor.getDelegationCall())) return false if (!process(secondaryConstructor.getDelegationCall())) return false
@@ -184,7 +184,7 @@ private fun processClassDelegationCallsToSpecifiedConstructor(
if (!klass.isEnum()) return true if (!klass.isEnum()) return true
for (declaration in klass.declarations) { for (declaration in klass.declarations) {
if (declaration is KtEnumEntry) { if (declaration is KtEnumEntry) {
val delegationCall = declaration.getSuperTypeListEntries().firstOrNull() val delegationCall = declaration.superTypeListEntries.firstOrNull()
if (delegationCall is KtSuperTypeCallEntry && constructor == delegationCall.calleeExpression.getConstructorCallDescriptor()) { if (delegationCall is KtSuperTypeCallEntry && constructor == delegationCall.calleeExpression.getConstructorCallDescriptor()) {
if (!process(delegationCall)) return false if (!process(delegationCall)) return false
} }
@@ -43,11 +43,11 @@ class KotlinInheritedMembersNodeProvider: InheritedMembersNodeProvider<TreeEleme
val children = ArrayList<TreeElement>() val children = ArrayList<TreeElement>()
val defaultType = descriptor.getDefaultType() val defaultType = descriptor.defaultType
for (memberDescriptor in defaultType.memberScope.getContributedDescriptors()) { for (memberDescriptor in defaultType.memberScope.getContributedDescriptors()) {
if (memberDescriptor !is CallableMemberDescriptor) continue if (memberDescriptor !is CallableMemberDescriptor) continue
when (memberDescriptor.getKind()) { when (memberDescriptor.kind) {
CallableMemberDescriptor.Kind.FAKE_OVERRIDE, CallableMemberDescriptor.Kind.FAKE_OVERRIDE,
CallableMemberDescriptor.Kind.DELEGATION -> { CallableMemberDescriptor.Kind.DELEGATION -> {
val superTypeMember = DescriptorToSourceUtilsIde.getAnyDeclaration(project, memberDescriptor) val superTypeMember = DescriptorToSourceUtilsIde.getAnyDeclaration(project, memberDescriptor)
@@ -116,5 +116,5 @@ class KotlinStructureViewElement(val element: NavigatablePsiElement,
get() = (descriptor as? DeclarationDescriptorWithVisibility)?.visibility == Visibilities.PUBLIC get() = (descriptor as? DeclarationDescriptorWithVisibility)?.visibility == Visibilities.PUBLIC
} }
fun KtClassOrObject.getStructureDeclarations() = getPrimaryConstructorParameters().filter { it.hasValOrVar() } + declarations fun KtClassOrObject.getStructureDeclarations() = primaryConstructorParameters.filter { it.hasValOrVar() } + declarations
@@ -283,7 +283,7 @@ fun breakOrContinueExpressionItems(position: KtElement, breakOrContinue: String)
result.add(createKeywordElement(breakOrContinue)) result.add(createKeywordElement(breakOrContinue))
} }
val label = (parent.getParent() as? KtLabeledExpression)?.getLabelNameAsName() val label = (parent.parent as? KtLabeledExpression)?.getLabelNameAsName()
if (label != null) { if (label != null) {
result.add(createKeywordElement(breakOrContinue, tail = label.labelNameToTail())) result.add(createKeywordElement(breakOrContinue, tail = label.labelNameToTail()))
} }
@@ -45,7 +45,7 @@ class WithExpressionPrefixInsertHandler(val prefix: String) : InsertHandler<Look
var parent = expression.getParent() var parent = expression.getParent()
if (parent is KtCallExpression && expression == parent.calleeExpression) { if (parent is KtCallExpression && expression == parent.calleeExpression) {
expression = parent expression = parent
parent = parent.getParent() parent = parent.parent
} }
if (parent is KtDotQualifiedExpression && expression == parent.selectorExpression) { if (parent is KtDotQualifiedExpression && expression == parent.selectorExpression) {
expression = parent expression = parent
@@ -127,7 +127,7 @@ class SmartCompletion(
} }
is KtWhenConditionWithExpression -> { is KtWhenConditionWithExpression -> {
val entry = parent.getParent() as KtWhenEntry val entry = parent.parent as KtWhenEntry
val whenExpression = entry.parent as KtWhenExpression val whenExpression = entry.parent as KtWhenExpression
val subject = whenExpression.subjectExpression ?: return@lazy emptySet() val subject = whenExpression.subjectExpression ?: return@lazy emptySet()
@@ -472,7 +472,7 @@ class KotlinIndicesHelper(
private fun KtNamedDeclaration.resolveToDescriptorsWithHack( private fun KtNamedDeclaration.resolveToDescriptorsWithHack(
psiFilter: (KtDeclaration) -> Boolean): Collection<DeclarationDescriptor> { psiFilter: (KtDeclaration) -> Boolean): Collection<DeclarationDescriptor> {
if (getContainingKtFile().isCompiled) { //TODO: it's temporary while resolveToDescriptor does not work for compiled declarations if (containingKtFile.isCompiled) { //TODO: it's temporary while resolveToDescriptor does not work for compiled declarations
return resolutionFacade.resolveImportReference(moduleDescriptor, fqName!!).filterIsInstance<DeclarationDescriptor>() return resolutionFacade.resolveImportReference(moduleDescriptor, fqName!!).filterIsInstance<DeclarationDescriptor>()
} }
else { else {
@@ -102,7 +102,7 @@ fun ImplicitReceiver.asExpression(resolutionScope: LexicalScope, psiFactory: KtP
fun KtImportDirective.targetDescriptors(resolutionFacade: ResolutionFacade = this.getResolutionFacade()): Collection<DeclarationDescriptor> { fun KtImportDirective.targetDescriptors(resolutionFacade: ResolutionFacade = this.getResolutionFacade()): Collection<DeclarationDescriptor> {
// For codeFragments imports are created in dummy file // For codeFragments imports are created in dummy file
if (this.getContainingKtFile().doNotAnalyze != null) return emptyList() if (this.containingKtFile.doNotAnalyze != null) return emptyList()
val nameExpression = importedReference?.getQualifiedElementSelector() as? KtSimpleNameExpression ?: return emptyList() val nameExpression = importedReference?.getQualifiedElementSelector() as? KtSimpleNameExpression ?: return emptyList()
return nameExpression.mainReference.resolveToDescriptors(resolutionFacade.analyze(nameExpression)) return nameExpression.mainReference.resolveToDescriptors(resolutionFacade.analyze(nameExpression))
} }
@@ -170,7 +170,7 @@ fun PsiElement.deleteSingle() {
} }
fun KtClass.getOrCreateCompanionObject() : KtObjectDeclaration { fun KtClass.getOrCreateCompanionObject() : KtObjectDeclaration {
getCompanionObjects().firstOrNull()?.let { return it } companionObjects.firstOrNull()?.let { return it }
return addDeclaration(KtPsiFactory(this).createCompanionObject()) return addDeclaration(KtPsiFactory(this).createCompanionObject())
} }
@@ -183,7 +183,7 @@ class KotlinMavenPluginPhaseInspection : DomElementsInspection<MavenDomProjectMo
private class AddJavaExecutionsLocalFix(val module: Module, val file: XmlFile, val kotlinPlugin: MavenDomPlugin) : LocalQuickFix { private class AddJavaExecutionsLocalFix(val module: Module, val file: XmlFile, val kotlinPlugin: MavenDomPlugin) : LocalQuickFix {
override fun getName() = "Configure maven-compiler-plugin executions in the right order" override fun getName() = "Configure maven-compiler-plugin executions in the right order"
override fun getFamilyName() = getName() override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) { override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
PomFile.forFileOrNull(file)?.addJavacExecutions(module, kotlinPlugin) PomFile.forFileOrNull(file)?.addJavacExecutions(module, kotlinPlugin)
@@ -64,7 +64,7 @@ class KotlinMavenUnresolvedReferenceQuickFixProvider : UnresolvedReferenceQuickF
val typeReference = expression.getParentOfType<KtTypeReference>(true) val typeReference = expression.getParentOfType<KtTypeReference>(true)
val referenced = typeReference?.text ?: expression.getReferencedName() val referenced = typeReference?.text ?: expression.getReferencedName()
expression.getContainingKtFile() expression.containingKtFile
.importDirectives .importDirectives
.firstOrNull { !it.isAllUnder && it.aliasName == referenced || it.importedFqName?.shortName()?.asString() == referenced } .firstOrNull { !it.isAllUnder && it.aliasName == referenced || it.importedFqName?.shortName()?.asString() == referenced }
?.let { it.importedFqName?.asString() } ?.let { it.importedFqName?.asString() }
@@ -104,9 +104,9 @@ internal fun createGroupedImportsAction(
autoImportDescription: String, autoImportDescription: String,
fqNames: Collection<FqName> fqNames: Collection<FqName>
): KotlinAddImportAction { ): KotlinAddImportAction {
val prioritizer = DescriptorGroupPrioritizer(element.getContainingKtFile()) val prioritizer = DescriptorGroupPrioritizer(element.containingKtFile)
val file = element.getContainingKtFile() val file = element.containingKtFile
val variants = fqNames val variants = fqNames
.groupBy { it.parentOrNull() ?: FqName.ROOT } .groupBy { it.parentOrNull() ?: FqName.ROOT }
.map { .map {
@@ -204,7 +204,7 @@ class KotlinAddImportAction internal constructor(
project.executeWriteCommand(QuickFixBundle.message("add.import")) { project.executeWriteCommand(QuickFixBundle.message("add.import")) {
if (!element.isValid) return@executeWriteCommand if (!element.isValid) return@executeWriteCommand
val file = element.getContainingKtFile() val file = element.containingKtFile
variant.declarationToImport(project)?.let { variant.declarationToImport(project)?.let {
val location = ProximityLocation(element, ModuleUtilCore.findModuleForPsiElement(element)) val location = ProximityLocation(element, ModuleUtilCore.findModuleForPsiElement(element))
@@ -62,7 +62,7 @@ abstract class KotlinGenerateTestSupportActionBase(
companion object { companion object {
private fun findTargetClass(editor: Editor, file: PsiFile): KtClassOrObject? { private fun findTargetClass(editor: Editor, file: PsiFile): KtClassOrObject? {
val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return null val elementAtCaret = file.findElementAt(editor.caretModel.offset) ?: return null
return elementAtCaret.parentsWithSelf.filterIsInstance<KtClassOrObject>().firstOrNull { !it.isLocal() } return elementAtCaret.parentsWithSelf.filterIsInstance<KtClassOrObject>().firstOrNull { !it.isLocal }
} }
private fun chooseAndPerform(editor: Editor, frameworks: List<TestFramework>, consumer: (TestFramework) -> Unit) { private fun chooseAndPerform(editor: Editor, frameworks: List<TestFramework>, consumer: (TestFramework) -> Unit) {
@@ -49,7 +49,7 @@ tailrec fun ClassDescriptor.findDeclaredFunction(
fun getPropertiesToUseInGeneratedMember(classOrObject: KtClassOrObject): List<KtNamedDeclaration> { fun getPropertiesToUseInGeneratedMember(classOrObject: KtClassOrObject): List<KtNamedDeclaration> {
return ArrayList<KtNamedDeclaration>().apply { return ArrayList<KtNamedDeclaration>().apply {
classOrObject.getPrimaryConstructorParameters().filterTo(this) { it.hasValOrVar() } classOrObject.primaryConstructorParameters.filterTo(this) { it.hasValOrVar() }
classOrObject.declarations.filterIsInstance<KtProperty>().filterTo(this) { classOrObject.declarations.filterIsInstance<KtProperty>().filterTo(this) {
val descriptor = it.resolveToDescriptor() val descriptor = it.resolveToDescriptor()
when (descriptor) { when (descriptor) {
@@ -61,7 +61,7 @@ class CheckComponentsUsageSearchAction : AnAction() {
progressIndicator?.text = "Checking data class ${i + 1} of ${dataClasses.size}..." progressIndicator?.text = "Checking data class ${i + 1} of ${dataClasses.size}..."
progressIndicator?.text2 = dataClass.fqName?.asString() ?: "" progressIndicator?.text2 = dataClass.fqName?.asString() ?: ""
val parameter = dataClass.getPrimaryConstructor()?.valueParameters?.firstOrNull() val parameter = dataClass.primaryConstructor?.valueParameters?.firstOrNull()
if (parameter != null) { if (parameter != null) {
try { try {
var smartRefsCount = 0 var smartRefsCount = 0
@@ -193,7 +193,7 @@ class CheckPartialBodyResolveAction : AnAction() {
is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent) is KtBlockExpression -> expression == parent.lastStatement() && isValueNeeded(parent)
is KtContainerNode -> { //TODO - not quite correct is KtContainerNode -> { //TODO - not quite correct
val pparent = parent.getParent() as? KtExpression val pparent = parent.parent as? KtExpression
pparent != null && isValueNeeded(pparent) pparent != null && isValueNeeded(pparent)
} }
@@ -58,7 +58,7 @@ class CodeInliner<TCallElement : KtElement>(
fun doInline(): KtElement? { fun doInline(): KtElement? {
val descriptor = resolvedCall.resultingDescriptor val descriptor = resolvedCall.resultingDescriptor
val file = nameExpression.getContainingKtFile() val file = nameExpression.containingKtFile
val elementToBeReplaced = when (callElement) { val elementToBeReplaced = when (callElement) {
is KtExpression -> callElement.getQualifiedExpressionForSelectorOrThis() is KtExpression -> callElement.getQualifiedExpressionForSelectorOrThis()
@@ -136,7 +136,7 @@ class KotlinBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() {
return buildString { return buildString {
append("object") append("object")
val superTypeEntries = getSuperTypeListEntries() val superTypeEntries = superTypeListEntries
if (superTypeEntries.isNotEmpty()) { if (superTypeEntries.isNotEmpty()) {
append(" : ") append(" : ")
@@ -120,7 +120,7 @@ object DebuggerUtils {
toProcess.add(file) toProcess.add(file)
for (collectedElement in analyzedElements) { for (collectedElement in analyzedElements) {
val containingFile = collectedElement.getContainingKtFile() val containingFile = collectedElement.containingKtFile
toProcess.add(containingFile) toProcess.add(containingFile)
} }
@@ -140,12 +140,12 @@ class KotlinPositionManager(private val myDebugProcess: DebugProcess) : MultiReq
val methodName = location.method().name() val methodName = location.method().name()
return when { return when {
JvmAbi.isGetterName(methodName) -> { JvmAbi.isGetterName(methodName) -> {
val parameterForGetter = contextElement.getPrimaryConstructor()?.valueParameters?.firstOrNull() { val parameterForGetter = contextElement.primaryConstructor?.valueParameters?.firstOrNull() {
it.hasValOrVar() && it.name != null && JvmAbi.getterName(it.name!!) == methodName it.hasValOrVar() && it.name != null && JvmAbi.getterName(it.name!!) == methodName
} ?: return null } ?: return null
parameterForGetter parameterForGetter
} }
methodName == "<init>" -> contextElement.getPrimaryConstructor() methodName == "<init>" -> contextElement.primaryConstructor
else -> null else -> null
} }
} }
@@ -90,7 +90,7 @@ class KotlinFieldBreakpointType : JavaBreakpointType<KotlinPropertyBreakpointPro
} }
is KtLightClassForSourceDeclaration -> { is KtLightClassForSourceDeclaration -> {
val jetClass = psiClass.kotlinOrigin val jetClass = psiClass.kotlinOrigin
createBreakpointIfPropertyExists(jetClass, jetClass.getContainingKtFile(), className, fieldName) createBreakpointIfPropertyExists(jetClass, jetClass.containingKtFile, className, fieldName)
} }
else -> null else -> null
} }
@@ -386,7 +386,7 @@ class KotlinEvaluator(val codeFragment: KtCodeFragment, val sourcePosition: Sour
val generateClassFilter = object : GenerationState.GenerateClassFilter() { val generateClassFilter = object : GenerationState.GenerateClassFilter() {
override fun shouldGeneratePackagePart(jetFile: KtFile) = jetFile == fileForDebugger override fun shouldGeneratePackagePart(jetFile: KtFile) = jetFile == fileForDebugger
override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true override fun shouldAnnotateClass(processingClassOrObject: KtClassOrObject) = true
override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.getContainingKtFile() == fileForDebugger override fun shouldGenerateClass(processingClassOrObject: KtClassOrObject) = processingClassOrObject.containingKtFile == fileForDebugger
override fun shouldGenerateScript(script: KtScript) = false override fun shouldGenerateScript(script: KtScript) = false
} }
@@ -84,7 +84,7 @@ fun getFunctionForExtractedFragment(
val newDebugExpressions = addDebugExpressionIntoTmpFileForExtractFunction(originalFile, codeFragment, breakpointLine) val newDebugExpressions = addDebugExpressionIntoTmpFileForExtractFunction(originalFile, codeFragment, breakpointLine)
if (newDebugExpressions.isEmpty()) return null if (newDebugExpressions.isEmpty()) return null
val tmpFile = newDebugExpressions.first().getContainingKtFile() val tmpFile = newDebugExpressions.first().containingKtFile
if (LOG.isDebugEnabled) { if (LOG.isDebugEnabled) {
LOG.debug("TMP_FILE:\n${runReadAction { tmpFile.text }}") LOG.debug("TMP_FILE:\n${runReadAction { tmpFile.text }}")
@@ -63,7 +63,7 @@ class KotlinRecursiveCallLineMarkerProvider : LineMarkerProvider {
when (parent) { when (parent) {
is KtFunctionLiteral -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null is KtFunctionLiteral -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null
is KtNamedFunction -> { is KtNamedFunction -> {
when (parent.getParent()) { when (parent.parent) {
is KtBlockExpression, is KtClassBody, is KtFile, is KtScript -> return parent is KtBlockExpression, is KtClassBody, is KtFile, is KtScript -> return parent
else -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null else -> if (stopOnNonInlinedLambdas && !InlineUtil.isInlinedArgument(parent, parent.analyze(), false)) return null
} }
@@ -35,7 +35,7 @@ class ArrayInDataClassInspection : AbstractKotlinInspection() {
return object : KtVisitorVoid() { return object : KtVisitorVoid() {
override fun visitClass(klass: KtClass) { override fun visitClass(klass: KtClass) {
if (!klass.isData()) return if (!klass.isData()) return
val constructor = klass.getPrimaryConstructor() ?: return val constructor = klass.primaryConstructor ?: return
if (hasOverriddenEqualsAndHashCode(klass)) return if (hasOverriddenEqualsAndHashCode(klass)) return
val context = constructor.analyze(BodyResolveMode.PARTIAL) val context = constructor.analyze(BodyResolveMode.PARTIAL)
for (parameter in constructor.valueParameters) { for (parameter in constructor.valueParameters) {
@@ -81,7 +81,7 @@ class EqualsOrHashCodeInspection : AbstractKotlinInspection() {
when (classDescriptor.kind) { when (classDescriptor.kind) {
ClassKind.OBJECT -> { ClassKind.OBJECT -> {
if (classOrObject.getSuperTypeListEntries().isNotEmpty()) return if (classOrObject.superTypeListEntries.isNotEmpty()) return
holder.registerProblem(nameIdentifier, "equals()/hashCode() in object declaration", DeleteEqualsAndHashCodeFix) holder.registerProblem(nameIdentifier, "equals()/hashCode() in object declaration", DeleteEqualsAndHashCodeFix)
} }
ClassKind.CLASS -> { ClassKind.CLASS -> {
@@ -69,7 +69,7 @@ class AddJvmOverloadsIntention : SelfTargetingIntention<KtModifierListOwner>(
text = "Add '@JvmOverloads' annotation to $targetName" text = "Add '@JvmOverloads' annotation to $targetName"
return TargetPlatformDetector.getPlatform(element.getContainingKtFile()) == JvmPlatform return TargetPlatformDetector.getPlatform(element.containingKtFile) == JvmPlatform
&& parameters.any { it.hasDefaultValue() } && parameters.any { it.hasDefaultValue() }
&& element.findAnnotation(annotationFqName) == null && element.findAnnotation(annotationFqName) == null
} }
@@ -87,7 +87,7 @@ class ConvertPrimaryConstructorToSecondaryIntention : SelfTargetingIntention<KtP
valueParameter.typeReference?.text ?: "", valueParameter.defaultValue?.text) valueParameter.typeReference?.text ?: "", valueParameter.defaultValue?.text)
} }
noReturnType() noReturnType()
for (superTypeEntry in klass.getSuperTypeListEntries()) { for (superTypeEntry in klass.superTypeListEntries) {
if (superTypeEntry is KtSuperTypeCallEntry) { if (superTypeEntry is KtSuperTypeCallEntry) {
superDelegation(superTypeEntry.valueArgumentList?.text ?: "") superDelegation(superTypeEntry.valueArgumentList?.text ?: "")
superTypeEntry.replace(factory.createSuperTypeEntry(superTypeEntry.typeReference!!.text)) superTypeEntry.replace(factory.createSuperTypeEntry(superTypeEntry.typeReference!!.text))
@@ -57,7 +57,7 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention<KtClass>(K
} ?: return } ?: return
val inconvertibleSubclasses = subclasses.filter { val inconvertibleSubclasses = subclasses.filter {
it !is KtObjectDeclaration || it.containingClassOrObject != element || it.getSuperTypeListEntries().size != 1 it !is KtObjectDeclaration || it.containingClassOrObject != element || it.superTypeListEntries.size != 1
} }
if (inconvertibleSubclasses.isNotEmpty()) { if (inconvertibleSubclasses.isNotEmpty()) {
val message = buildString { val message = buildString {
@@ -75,14 +75,14 @@ class ConvertSealedClassToEnumIntention : SelfTargetingRangeIntention<KtClass>(K
val comma = psiFactory.createComma() val comma = psiFactory.createComma()
val semicolon = psiFactory.createSemicolon() val semicolon = psiFactory.createSemicolon()
val constructorCallNeeded = element.hasExplicitPrimaryConstructor() || element.getSecondaryConstructors().isNotEmpty() val constructorCallNeeded = element.hasExplicitPrimaryConstructor() || element.secondaryConstructors.isNotEmpty()
val entriesToAdd = subclasses.mapIndexed { i, subclass -> val entriesToAdd = subclasses.mapIndexed { i, subclass ->
subclass as KtObjectDeclaration subclass as KtObjectDeclaration
val entryText = buildString { val entryText = buildString {
append(subclass.name) append(subclass.name)
if (constructorCallNeeded) { if (constructorCallNeeded) {
append((subclass.getSuperTypeListEntries().firstOrNull() as? KtSuperTypeCallEntry)?.valueArgumentList?.text ?: "()") append((subclass.superTypeListEntries.firstOrNull() as? KtSuperTypeCallEntry)?.valueArgumentList?.text ?: "()")
} }
} }
val entry = psiFactory.createEnumEntry(entryText) val entry = psiFactory.createEnumEntry(entryText)
@@ -33,7 +33,7 @@ import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils
class ConvertSecondaryConstructorToPrimaryInspection : IntentionBasedInspection<KtSecondaryConstructor>( class ConvertSecondaryConstructorToPrimaryInspection : IntentionBasedInspection<KtSecondaryConstructor>(
ConvertSecondaryConstructorToPrimaryIntention::class, ConvertSecondaryConstructorToPrimaryIntention::class,
{ constructor -> constructor.containingClass()?.getSecondaryConstructors()?.size == 1 } { constructor -> constructor.containingClass()?.secondaryConstructors?.size == 1 }
) { ) {
override fun inspectionTarget(element: KtSecondaryConstructor) = element.getConstructorKeyword() override fun inspectionTarget(element: KtSecondaryConstructor) = element.getConstructorKeyword()
} }
@@ -165,7 +165,7 @@ class ConvertSecondaryConstructorToPrimaryIntention : SelfTargetingRangeIntentio
val delegationCall = element.getDelegationCall() val delegationCall = element.getDelegationCall()
val argumentList = delegationCall.valueArgumentList val argumentList = delegationCall.valueArgumentList
if (!delegationCall.isImplicit && argumentList != null) { if (!delegationCall.isImplicit && argumentList != null) {
for (superTypeListEntry in klass.getSuperTypeListEntries()) { for (superTypeListEntry in klass.superTypeListEntries) {
val typeReference = superTypeListEntry.typeReference ?: continue val typeReference = superTypeListEntry.typeReference ?: continue
val type = context[BindingContext.TYPE, typeReference] val type = context[BindingContext.TYPE, typeReference]
if ((type?.constructor?.declarationDescriptor as? ClassDescriptor)?.kind == ClassKind.CLASS) { if ((type?.constructor?.declarationDescriptor as? ClassDescriptor)?.kind == ClassKind.CLASS) {

Some files were not shown because too many files have changed in this diff Show More