More cleanup: lift return / assignment out

This commit is contained in:
Mikhail Glukhikh
2017-07-07 13:57:36 +03:00
parent 9269de721e
commit dfe2c16bc7
116 changed files with 472 additions and 517 deletions
@@ -619,11 +619,11 @@ class MethodInliner(
} }
private fun wrapException(originalException: Throwable, node: MethodNode, errorSuffix: String): RuntimeException { private fun wrapException(originalException: Throwable, node: MethodNode, errorSuffix: String): RuntimeException {
if (originalException is InlineException) { return if (originalException is InlineException) {
return InlineException("$errorPrefix: $errorSuffix", originalException) InlineException("$errorPrefix: $errorSuffix", originalException)
} }
else { else {
return InlineException("$errorPrefix: $errorSuffix\nCause: ${node.nodeText}", originalException) InlineException("$errorPrefix: $errorSuffix\nCause: ${node.nodeText}", originalException)
} }
} }
@@ -679,11 +679,11 @@ class MethodInliner(
localReturns.add(LocalReturn(returnInsn, insertBeforeInsn, sourceValueFrame)) localReturns.add(LocalReturn(returnInsn, insertBeforeInsn, sourceValueFrame))
if (returnInsn.opcode != Opcodes.RETURN) { if (returnInsn.opcode != Opcodes.RETURN) {
if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) { returnVariableSize = if (returnInsn.opcode == Opcodes.LRETURN || returnInsn.opcode == Opcodes.DRETURN) {
returnVariableSize = 2 2
} }
else { else {
returnVariableSize = 1 1
} }
} }
} }
@@ -98,8 +98,8 @@ open class NestedSourceMapper(
override fun mapLineNumber(lineNumber: Int): Int { override fun mapLineNumber(lineNumber: Int): Int {
val mappedLineNumber = visitedLines.get(lineNumber) val mappedLineNumber = visitedLines.get(lineNumber)
if (mappedLineNumber > 0) { return if (mappedLineNumber > 0) {
return mappedLineNumber mappedLineNumber
} }
else { else {
val rangeForMapping = val rangeForMapping =
@@ -111,7 +111,7 @@ open class NestedSourceMapper(
visitedLines.put(lineNumber, newLineNumber) visitedLines.put(lineNumber, newLineNumber)
} }
lastVisitedRange = rangeForMapping lastVisitedRange = rangeForMapping
return newLineNumber newLineNumber
} }
} }
@@ -142,20 +142,20 @@ internal class FixStackAnalyzer(
} }
override fun pop(): BasicValue { override fun pop(): BasicValue {
if (extraStack.isNotEmpty()) { return if (extraStack.isNotEmpty()) {
return extraStack.pop() extraStack.pop()
} }
else { else {
return super.pop() super.pop()
} }
} }
override fun getStack(i: Int): BasicValue { override fun getStack(i: Int): BasicValue {
if (i < super.getMaxStackSize()) { return if (i < super.getMaxStackSize()) {
return super.getStack(i) super.getStack(i)
} }
else { else {
return extraStack[i - maxStackSize] extraStack[i - maxStackSize]
} }
} }
} }
@@ -68,11 +68,11 @@ 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) { return if (sourceElement is KotlinSourceElement) {
return modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.containingKtFile.virtualFile.path in it.getSourceFiles() } modules.singleOrNull() ?: modules.firstOrNull { sourceElement.psi.containingKtFile.virtualFile.path in it.getSourceFiles() }
} }
else { else {
return modules.firstOrNull { module -> modules.firstOrNull { module ->
isContainedByCompiledPartOfOurModule(descriptor, File(module.getOutputDirectory())) || isContainedByCompiledPartOfOurModule(descriptor, File(module.getOutputDirectory())) ||
module.getFriendPaths().any { isContainedByCompiledPartOfOurModule(descriptor, File(it)) } module.getFriendPaths().any { isContainedByCompiledPartOfOurModule(descriptor, File(it)) }
} }
@@ -113,14 +113,14 @@ class ReplCodeAnalyzer(environment: KotlinCoreEnvironment) {
val diagnostics = trace.bindingContext.diagnostics val diagnostics = trace.bindingContext.diagnostics
val hasErrors = diagnostics.any { it.severity == Severity.ERROR } val hasErrors = diagnostics.any { it.severity == Severity.ERROR }
if (hasErrors) { return if (hasErrors) {
replState.lineFailure(linePsi, codeLine) replState.lineFailure(linePsi, codeLine)
return ReplLineAnalysisResult.WithErrors(diagnostics) ReplLineAnalysisResult.WithErrors(diagnostics)
} }
else { else {
val scriptDescriptor = context.scripts[linePsi.script]!! val scriptDescriptor = context.scripts[linePsi.script]!!
replState.lineSuccess(linePsi, codeLine, scriptDescriptor) replState.lineSuccess(linePsi, codeLine, scriptDescriptor)
return ReplLineAnalysisResult.Successful(scriptDescriptor, diagnostics) ReplLineAnalysisResult.Successful(scriptDescriptor, diagnostics)
} }
} }
@@ -96,11 +96,11 @@ class ReplFromTerminal(
} }
val lineResult = eval(line) val lineResult = eval(line)
if (lineResult is ReplEvalResult.Incomplete) { return if (lineResult is ReplEvalResult.Incomplete) {
return WhatNextAfterOneLine.INCOMPLETE WhatNextAfterOneLine.INCOMPLETE
} }
else { else {
return WhatNextAfterOneLine.READ_LINE WhatNextAfterOneLine.READ_LINE
} }
} }
@@ -27,14 +27,14 @@ class JavaPropertyInitializerEvaluatorImpl : JavaPropertyInitializerEvaluator {
val evaluated = field.initializerValue ?: return null val evaluated = field.initializerValue ?: return null
val factory = ConstantValueFactory(descriptor.builtIns) val factory = ConstantValueFactory(descriptor.builtIns)
when (evaluated) { return when (evaluated) {
//Note: evaluated expression may be of class that does not match field type in some cases //Note: evaluated expression may be of class that does not match field type in some cases
// tested for Int, left other checks just in case // tested for Int, left other checks just in case
is Byte, is Short, is Int, is Long -> { is Byte, is Short, is Int, is Long -> {
return factory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type) factory.createIntegerConstantValue((evaluated as Number).toLong(), descriptor.type)
} }
else -> { else -> {
return factory.createConstantValue(evaluated) factory.createConstantValue(evaluated)
} }
} }
} }
@@ -151,15 +151,13 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon
val variableUseStatusData: Map<Instruction, Edges<UseControlFlowInfo>> val variableUseStatusData: Map<Instruction, Edges<UseControlFlowInfo>>
get() = pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) { get() = pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) {
instruction: Instruction, incomingEdgesData: Collection<UseControlFlowInfo> -> instruction: Instruction, incomingEdgesData: Collection<UseControlFlowInfo> ->
val enterResult: UseControlFlowInfo
if (incomingEdgesData.size == 1) { val enterResult: UseControlFlowInfo = if (incomingEdgesData.size == 1) {
enterResult = incomingEdgesData.single() incomingEdgesData.single()
} }
else { else {
enterResult = incomingEdgesData.fold(UseControlFlowInfo()) { result, edgeData -> incomingEdgesData.fold(UseControlFlowInfo()) { result, edgeData ->
edgeData.iterator().fold(result) { edgeData.iterator().fold(result) { subResult, (variableDescriptor, variableUseState) ->
subResult, (variableDescriptor, variableUseState) ->
subResult.put(variableDescriptor, variableUseState.merge(subResult.getOrNull(variableDescriptor))) subResult.put(variableDescriptor, variableUseState.merge(subResult.getOrNull(variableDescriptor)))
} }
} }
@@ -32,22 +32,22 @@ object EditCommaSeparatedListHelper {
fun <TItem: KtElement> addItemAfter(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem { fun <TItem: KtElement> addItemAfter(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem {
assert(anchor == null || anchor.parent == list) assert(anchor == null || anchor.parent == list)
if (allItems.isEmpty()) { if (allItems.isEmpty()) {
if (list.firstChild?.node?.elementType == prefix) { return if (list.firstChild?.node?.elementType == prefix) {
return list.addAfter(item, list.firstChild) as TItem list.addAfter(item, list.firstChild) as TItem
} }
else { else {
return list.add(item) as TItem list.add(item) as TItem
} }
} }
else { else {
var comma = KtPsiFactory(list).createComma() var comma = KtPsiFactory(list).createComma()
if (anchor != null) { return if (anchor != null) {
comma = list.addAfter(comma, anchor) comma = list.addAfter(comma, anchor)
return list.addAfter(item, comma) as TItem list.addAfter(item, comma) as TItem
} }
else { else {
comma = list.addBefore(comma, allItems.first()) comma = list.addBefore(comma, allItems.first())
return list.addBefore(item, comma) as TItem list.addBefore(item, comma) as TItem
} }
} }
} }
@@ -55,18 +55,18 @@ object EditCommaSeparatedListHelper {
@JvmOverloads @JvmOverloads
fun <TItem: KtElement> addItemBefore(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem { fun <TItem: KtElement> addItemBefore(list: KtElement, allItems: List<TItem>, item: TItem, anchor: TItem?, prefix: KtToken = KtTokens.LPAR): TItem {
val anchorAfter: TItem? val anchorAfter: TItem?
if (allItems.isEmpty()) { anchorAfter = if (allItems.isEmpty()) {
assert(anchor == null) assert(anchor == null)
anchorAfter = null null
} }
else { else {
if (anchor != null) { if (anchor != null) {
val index = allItems.indexOf(anchor) val index = allItems.indexOf(anchor)
assert(index >= 0) assert(index >= 0)
anchorAfter = if (index > 0) allItems[index - 1] else null if (index > 0) allItems[index - 1] else null
} }
else { else {
anchorAfter = allItems[allItems.size - 1] allItems[allItems.size - 1]
} }
} }
return addItemAfter(list, allItems, item, anchorAfter, prefix) return addItemAfter(list, allItems, item, anchorAfter, prefix)
@@ -43,15 +43,15 @@ class KtObjectDeclaration : KtClassOrObject {
} }
override fun setName(@NonNls name: String): PsiElement { override fun setName(@NonNls name: String): PsiElement {
if (nameIdentifier == null) { return if (nameIdentifier == null) {
val psiFactory = KtPsiFactory(project) val psiFactory = KtPsiFactory(project)
val result = addAfter(psiFactory.createIdentifier(name), getObjectKeyword()!!) val result = addAfter(psiFactory.createIdentifier(name), getObjectKeyword()!!)
addAfter(psiFactory.createWhiteSpace(), getObjectKeyword()!!) addAfter(psiFactory.createWhiteSpace(), getObjectKeyword()!!)
return result result
} }
else { else {
return super.setName(name) super.setName(name)
} }
} }
@@ -660,13 +660,13 @@ class KtPsiFactory @JvmOverloads constructor(private val project: Project, val m
assert(name != CONSTRUCTOR_NAME || target == Target.CONSTRUCTOR) assert(name != CONSTRUCTOR_NAME || target == Target.CONSTRUCTOR)
sb.append(name) sb.append(name)
when (target) { state = when (target) {
Target.FUNCTION, Target.CONSTRUCTOR -> { Target.FUNCTION, Target.CONSTRUCTOR -> {
sb.append("(") sb.append("(")
state = State.FIRST_PARAM State.FIRST_PARAM
} }
else -> else ->
state = State.TYPE_CONSTRAINTS State.TYPE_CONSTRAINTS
} }
return this return this
@@ -41,12 +41,12 @@ class KtTypeAlias : KtTypeParameterListOwnerStub<KotlinTypeAliasStub>, KtNamedDe
@IfNotParsed @IfNotParsed
fun getTypeReference(): KtTypeReference? { fun getTypeReference(): KtTypeReference? {
if (stub != null) { return if (stub != null) {
val typeReferences = getStubOrPsiChildrenAsList<KtTypeReference, KotlinPlaceHolderStub<KtTypeReference>>(KtStubElementTypes.TYPE_REFERENCE) val typeReferences = getStubOrPsiChildrenAsList<KtTypeReference, KotlinPlaceHolderStub<KtTypeReference>>(KtStubElementTypes.TYPE_REFERENCE)
return typeReferences[0] typeReferences[0]
} }
else { else {
return findChildByType(KtNodeTypes.TYPE_REFERENCE) findChildByType(KtNodeTypes.TYPE_REFERENCE)
} }
} }
@@ -34,8 +34,8 @@ fun getTypeReference(declaration: KtCallableDeclaration): KtTypeReference? {
fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, typeRef: KtTypeReference?): KtTypeReference? { fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?, typeRef: KtTypeReference?): KtTypeReference? {
val oldTypeRef = getTypeReference(declaration) val oldTypeRef = getTypeReference(declaration)
if (typeRef != null) { if (typeRef != null) {
if (oldTypeRef != null) { return if (oldTypeRef != null) {
return oldTypeRef.replace(typeRef) as KtTypeReference oldTypeRef.replace(typeRef) as KtTypeReference
} }
else { else {
val anchor = addAfter val anchor = addAfter
@@ -43,7 +43,7 @@ fun setTypeReference(declaration: KtCallableDeclaration, addAfter: PsiElement?,
?: (declaration as? KtParameter)?.destructuringDeclaration ?: (declaration as? KtParameter)?.destructuringDeclaration
val newTypeRef = declaration.addAfter(typeRef, anchor) as KtTypeReference val newTypeRef = declaration.addAfter(typeRef, anchor) as KtTypeReference
declaration.addAfter(KtPsiFactory(declaration.project).createColon(), anchor) declaration.addAfter(KtPsiFactory(declaration.project).createColon(), anchor)
return newTypeRef newTypeRef
} }
} }
else { else {
@@ -49,10 +49,7 @@ fun PsiElement.siblings(forward: Boolean = true, withItself: Boolean = true): Se
override fun hasNext(): Boolean = next != null override fun hasNext(): Boolean = next != null
override fun next(): PsiElement { override fun next(): PsiElement {
val result = next ?: throw NoSuchElementException() val result = next ?: throw NoSuchElementException()
if (forward) next = if (forward) result.nextSibling else result.prevSibling
next = result.nextSibling
else
next = result.prevSibling
return result return result
} }
} }
@@ -347,7 +347,7 @@ class FunctionDescriptorResolver(
} }
} }
else { else {
if (isFunctionLiteral(functionDescriptor) || isFunctionExpression(functionDescriptor)) { type = if (isFunctionLiteral(functionDescriptor) || isFunctionExpression(functionDescriptor)) {
val containsUninferredParameter = TypeUtils.contains(expectedType) { val containsUninferredParameter = TypeUtils.contains(expectedType) {
TypeUtils.isDontCarePlaceholder(it) || ErrorUtils.isUninferredParameter(it) TypeUtils.isDontCarePlaceholder(it) || ErrorUtils.isUninferredParameter(it)
} }
@@ -355,11 +355,11 @@ class FunctionDescriptorResolver(
trace.report(CANNOT_INFER_PARAMETER_TYPE.on(valueParameter)) trace.report(CANNOT_INFER_PARAMETER_TYPE.on(valueParameter))
} }
type = expectedType ?: TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE expectedType ?: TypeUtils.CANT_INFER_FUNCTION_PARAM_TYPE
} }
else { else {
trace.report(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION.on(valueParameter)) trace.report(VALUE_PARAMETER_WITH_NO_TYPE_ANNOTATION.on(valueParameter))
type = ErrorUtils.createErrorType("Type annotation was missing for parameter ${valueParameter.nameAsSafeName}") ErrorUtils.createErrorType("Type annotation was missing for parameter ${valueParameter.nameAsSafeName}")
} }
} }
@@ -44,11 +44,11 @@ data class ImportPath @JvmOverloads constructor(val fqName: FqName, val isAllUnd
companion object { companion object {
@JvmStatic fun fromString(pathStr: String): ImportPath { @JvmStatic fun fromString(pathStr: String): ImportPath {
if (pathStr.endsWith(".*")) { return if (pathStr.endsWith(".*")) {
return ImportPath(FqName(pathStr.substring(0, pathStr.length - 2)), isAllUnder = true) ImportPath(FqName(pathStr.substring(0, pathStr.length - 2)), isAllUnder = true)
} }
else { else {
return ImportPath(FqName(pathStr), isAllUnder = false) ImportPath(FqName(pathStr), isAllUnder = false)
} }
} }
@@ -199,11 +199,11 @@ object ModifierCheckerCore {
private fun deprecationRegister(vararg list: KtModifierKeywordToken) = compatibilityRegister(Compatibility.DEPRECATED, *list) private fun deprecationRegister(vararg list: KtModifierKeywordToken) = compatibilityRegister(Compatibility.DEPRECATED, *list)
private fun compatibility(first: KtModifierKeywordToken, second: KtModifierKeywordToken): Compatibility { private fun compatibility(first: KtModifierKeywordToken, second: KtModifierKeywordToken): Compatibility {
if (first == second) { return if (first == second) {
return Compatibility.REPEATED Compatibility.REPEATED
} }
else { else {
return mutualCompatibility[Pair(first, second)] ?: Compatibility.COMPATIBLE mutualCompatibility[Pair(first, second)] ?: Compatibility.COMPATIBLE
} }
} }
@@ -799,11 +799,11 @@ class OverrideResolver(
val substitutedSuperReturnType = typeSubstitutor.substitute(superDescriptor.type, Variance.OUT_VARIANCE)!! val substitutedSuperReturnType = typeSubstitutor.substitute(superDescriptor.type, Variance.OUT_VARIANCE)!!
if (superDescriptor.isVar) { return if (superDescriptor.isVar) {
return KotlinTypeChecker.DEFAULT.equalTypes(subDescriptor.type, substitutedSuperReturnType) KotlinTypeChecker.DEFAULT.equalTypes(subDescriptor.type, substitutedSuperReturnType)
} }
else { else {
return KotlinTypeChecker.DEFAULT.isSubtypeOf(subDescriptor.type, substitutedSuperReturnType) KotlinTypeChecker.DEFAULT.isSubtypeOf(subDescriptor.type, substitutedSuperReturnType)
} }
} }
@@ -211,12 +211,7 @@ internal class DelegatingDataFlowInfo private constructor(
while (current != null) { while (current != null) {
if (current is DelegatingDataFlowInfo) { if (current is DelegatingDataFlowInfo) {
types.addAll(current.typeInfo.get(value)) types.addAll(current.typeInfo.get(value))
if (value == current.valueWithGivenTypeInfo) { current = if (value == current.valueWithGivenTypeInfo) null else current.parent
current = null
}
else {
current = current.parent
}
} }
else { else {
types.addAll(current.getCollectedTypes(value)) types.addAll(current.getCollectedTypes(value))
@@ -262,11 +262,11 @@ class BindingContextSuppressCache(val context: BindingContext) : KotlinSuppressC
override fun getSuppressionAnnotations(annotated: KtAnnotated): List<AnnotationDescriptor> { override fun getSuppressionAnnotations(annotated: KtAnnotated): List<AnnotationDescriptor> {
val descriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated) val descriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated)
if (descriptor != null) { return if (descriptor != null) {
return descriptor.annotations.toList() descriptor.annotations.toList()
} }
else { else {
return annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) } annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) }
} }
} }
} }
@@ -119,11 +119,11 @@ internal class FunctionsTypingVisitor(facade: ExpressionTypingInternals) : Expre
components.identifierChecker.checkDeclaration(function, context.trace) components.identifierChecker.checkDeclaration(function, context.trace)
components.declarationsCheckerBuilder.withTrace(context.trace).checkFunction(function, functionDescriptor) components.declarationsCheckerBuilder.withTrace(context.trace).checkFunction(function, functionDescriptor)
if (isDeclaration) { return if (isDeclaration) {
return createTypeInfo(components.dataFlowAnalyzer.checkStatementType(function, context), context) createTypeInfo(components.dataFlowAnalyzer.checkStatementType(function, context), context)
} }
else { else {
return components.dataFlowAnalyzer.createCheckedTypeInfo(functionDescriptor.createFunctionType(), context, function) components.dataFlowAnalyzer.createCheckedTypeInfo(functionDescriptor.createFunctionType(), context, function)
} }
} }
@@ -344,11 +344,11 @@ class PatternMatchingTypingVisitor internal constructor(facade: ExpressionTyping
val typeReference = condition.typeReference val typeReference = condition.typeReference
if (typeReference != null) { if (typeReference != null) {
val result = checkTypeForIs(context, condition, condition.isNegated, subjectType, typeReference, subjectDataFlowValue) val result = checkTypeForIs(context, condition, condition.isNegated, subjectType, typeReference, subjectDataFlowValue)
if (condition.isNegated) { newDataFlowInfo = if (condition.isNegated) {
newDataFlowInfo = ConditionalDataFlowInfo(result.elseInfo, result.thenInfo) ConditionalDataFlowInfo(result.elseInfo, result.thenInfo)
} }
else { else {
newDataFlowInfo = result result
} }
val rhsType = context.trace[BindingContext.TYPE, typeReference] val rhsType = context.trace[BindingContext.TYPE, typeReference]
if (subjectExpression != null) { if (subjectExpression != null) {
@@ -49,11 +49,11 @@ fun resolveUnqualifiedSuperFromExpressionContext(
val calleeExpression = selectorExpression.calleeExpression val calleeExpression = selectorExpression.calleeExpression
if (calleeExpression is KtSimpleNameExpression) { if (calleeExpression is KtSimpleNameExpression) {
val calleeName = calleeExpression.getReferencedNameAsName() val calleeName = calleeExpression.getReferencedNameAsName()
if (isCallingMethodOfAny(selectorExpression, calleeName)) { return if (isCallingMethodOfAny(selectorExpression, calleeName)) {
return resolveSupertypesForMethodOfAny(supertypes, calleeName, anyType) resolveSupertypesForMethodOfAny(supertypes, calleeName, anyType)
} }
else { else {
return resolveSupertypesByCalleeName(supertypes, calleeName) resolveSupertypesByCalleeName(supertypes, calleeName)
} }
} }
} }
@@ -31,11 +31,11 @@ protected constructor(
fun get(): R { fun get(): R {
val cached = cached.get() ?: return update() val cached = cached.get() ?: return update()
val (app, extensions) = cached val (app, extensions) = cached
if (app == ApplicationManager.getApplication()) { return if (app == ApplicationManager.getApplication()) {
return extensions extensions
} }
else { else {
return update() update()
} }
} }
@@ -903,11 +903,11 @@ class ExpressionCodegen(
} }
if (descriptor is CallableMemberDescriptor && JvmCodegenUtil.getDirectMember(descriptor) is SyntheticJavaPropertyDescriptor) { if (descriptor is CallableMemberDescriptor && JvmCodegenUtil.getDirectMember(descriptor) is SyntheticJavaPropertyDescriptor) {
val propertyDescriptor = JvmCodegenUtil.getDirectMember(descriptor) as SyntheticJavaPropertyDescriptor val propertyDescriptor = JvmCodegenUtil.getDirectMember(descriptor) as SyntheticJavaPropertyDescriptor
if (descriptor is PropertyGetterDescriptor) { descriptor = if (descriptor is PropertyGetterDescriptor) {
descriptor = propertyDescriptor.getMethod propertyDescriptor.getMethod
} }
else { else {
descriptor = propertyDescriptor.setMethod!! propertyDescriptor.setMethod!!
} }
} }
return typeMapper.mapToCallableMethod(descriptor as FunctionDescriptor, isSuper) return typeMapper.mapToCallableMethod(descriptor as FunctionDescriptor, isSuper)
@@ -935,11 +935,11 @@ class ExpressionCodegen(
if (!isInline) return IrCallGenerator.DefaultCallGenerator if (!isInline) return IrCallGenerator.DefaultCallGenerator
val original = unwrapInitialSignatureDescriptor(DescriptorUtils.unwrapFakeOverride(descriptor.original as FunctionDescriptor)) val original = unwrapInitialSignatureDescriptor(DescriptorUtils.unwrapFakeOverride(descriptor.original as FunctionDescriptor))
if (isDefaultCompilation) { return if (isDefaultCompilation) {
return TODO() TODO()
} }
else { else {
return IrInlineCodegen(this, state, original, typeParameterMappings!!, IrSourceCompilerForInline(state, element)) IrInlineCodegen(this, state, original, typeParameterMappings!!, IrSourceCompilerForInline(state, element))
} }
} }
@@ -412,11 +412,11 @@ class EnumClassLowering(val context: JvmBackendContext) : ClassLoweringPass {
override fun visitGetValue(expression: IrGetValue): IrExpression { override fun visitGetValue(expression: IrGetValue): IrExpression {
val loweredParameter = loweredEnumConstructorParameters[expression.descriptor] val loweredParameter = loweredEnumConstructorParameters[expression.descriptor]
if (loweredParameter != null) { return if (loweredParameter != null) {
return IrGetValueImpl(expression.startOffset, expression.endOffset, loweredParameter, expression.origin) IrGetValueImpl(expression.startOffset, expression.endOffset, loweredParameter, expression.origin)
} }
else { else {
return expression expression
} }
} }
@@ -205,12 +205,12 @@ private fun tryToResolveInner(name: String,
private fun KtFile.tryToResolvePackageClass(name: String, private fun KtFile.tryToResolvePackageClass(name: String,
javac: JavacWrapper, javac: JavacWrapper,
nameParts: List<String> = emptyList()): JavaClass? { nameParts: List<String> = emptyList()): JavaClass? {
if (nameParts.size > 1) { return if (nameParts.size > 1) {
return find(FqName("${packageFqName.asString()}.${nameParts.first()}"), javac, nameParts) find(FqName("${packageFqName.asString()}.${nameParts.first()}"), javac, nameParts)
} }
else { else {
return javac.findClass(FqName("${packageFqName.asString()}.$name")) javac.findClass(FqName("${packageFqName.asString()}.$name"))
?: javac.getKotlinClassifier(FqName("${packageFqName.asString()}.$name")) ?: javac.getKotlinClassifier(FqName("${packageFqName.asString()}.$name"))
} }
} }
@@ -277,13 +277,12 @@ abstract class KtLightClassForSourceDeclaration(protected val classOrObject: KtC
override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean { override fun isInheritor(baseClass: PsiClass, checkDeep: Boolean): Boolean {
LightClassInheritanceHelper.getService(project).isInheritor(this, baseClass, checkDeep).ifSure { return it } LightClassInheritanceHelper.getService(project).isInheritor(this, baseClass, checkDeep).ifSure { return it }
val qualifiedName: String? val qualifiedName: String? = if (baseClass is KtLightClassForSourceDeclaration) {
if (baseClass is KtLightClassForSourceDeclaration) {
val baseDescriptor = baseClass.getDescriptor() val baseDescriptor = baseClass.getDescriptor()
qualifiedName = if (baseDescriptor != null) DescriptorUtils.getFqName(baseDescriptor).asString() else null if (baseDescriptor != null) DescriptorUtils.getFqName(baseDescriptor).asString() else null
} }
else { else {
qualifiedName = baseClass.qualifiedName baseClass.qualifiedName
} }
val thisDescriptor = getDescriptor() val thisDescriptor = getDescriptor()
@@ -112,13 +112,9 @@ sealed class KtLightFieldImpl<D : PsiField>(
KtLightFieldImpl<PsiField>(origin, computeDelegate, containingClass, dummyDelegate) KtLightFieldImpl<PsiField>(origin, computeDelegate, containingClass, dummyDelegate)
companion object Factory { companion object Factory {
fun create(origin: LightMemberOrigin?, delegate: PsiField, containingClass: KtLightClass): KtLightField { fun create(origin: LightMemberOrigin?, delegate: PsiField, containingClass: KtLightClass): KtLightField = when (delegate) {
when (delegate) { is PsiEnumConstant -> KtLightEnumConstant(origin, { delegate }, containingClass, null)
is PsiEnumConstant -> { else -> KtLightFieldForDeclaration(origin, { delegate }, containingClass, null)
return KtLightEnumConstant(origin, { delegate }, containingClass, null)
}
else -> return KtLightFieldForDeclaration(origin, { delegate }, containingClass, null)
}
} }
fun lazy( fun lazy(
@@ -167,22 +167,22 @@ fun <C : Candidate> createCallTowerProcessorForExplicitInvoke(
): ScopeTowerProcessor<C> { ): ScopeTowerProcessor<C> {
val invokeExtensionDescriptor = scopeTower.getExtensionInvokeCandidateDescriptor(expressionForInvoke) val invokeExtensionDescriptor = scopeTower.getExtensionInvokeCandidateDescriptor(expressionForInvoke)
if (explicitReceiver != null) { if (explicitReceiver != null) {
if (invokeExtensionDescriptor == null) { return if (invokeExtensionDescriptor == null) {
// case 1.(foo())(), where foo() isn't extension function // case 1.(foo())(), where foo() isn't extension function
return KnownResultProcessor(emptyList()) KnownResultProcessor(emptyList())
} }
else { else {
return InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = explicitReceiver) InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = explicitReceiver)
} }
} }
else { else {
val usualInvoke = ExplicitReceiverScopeTowerProcessor(scopeTower, functionContext, expressionForInvoke) { getFunctions(OperatorNameConventions.INVOKE, it) } // todo operator val usualInvoke = ExplicitReceiverScopeTowerProcessor(scopeTower, functionContext, expressionForInvoke) { getFunctions(OperatorNameConventions.INVOKE, it) } // todo operator
if (invokeExtensionDescriptor == null) { return if (invokeExtensionDescriptor == null) {
return usualInvoke usualInvoke
} }
else { else {
return CompositeScopeTowerProcessor( CompositeScopeTowerProcessor(
usualInvoke, usualInvoke,
InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = null) InvokeExtensionScopeTowerProcessor(functionContext, invokeExtensionDescriptor, explicitReceiver = null)
) )
@@ -98,11 +98,11 @@ object DescriptorEquivalenceForOverrides {
// This check is needed when we call areTypeParametersEquivalent() from areCallableMemberDescriptorsEquivalent: // This check is needed when we call areTypeParametersEquivalent() from areCallableMemberDescriptorsEquivalent:
// if the type parameter owners are, e.g., functions, we'll go into infinite recursion here // if the type parameter owners are, e.g., functions, we'll go into infinite recursion here
if (aOwner is CallableMemberDescriptor || bOwner is CallableMemberDescriptor) { return if (aOwner is CallableMemberDescriptor || bOwner is CallableMemberDescriptor) {
return equivalentCallables(aOwner, bOwner) equivalentCallables(aOwner, bOwner)
} }
else { else {
return areEquivalent(aOwner, bOwner) areEquivalent(aOwner, bOwner)
} }
} }
@@ -85,11 +85,11 @@ abstract class WrappedType : KotlinType() {
} }
override fun toString(): String { override fun toString(): String {
if (isComputed()) { return if (isComputed()) {
return delegate.toString() delegate.toString()
} }
else { else {
return "<Not computed yet>" "<Not computed yet>"
} }
} }
} }
@@ -287,12 +287,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
if (supertypes.size < 2) return supertypes if (supertypes.size < 2) return supertypes
val allPureSupertypes = supertypes.filter { it.arguments.all { !it.type.isFlexible() } } val allPureSupertypes = supertypes.filter { it.arguments.all { !it.type.isFlexible() } }
if (allPureSupertypes.isNotEmpty()) { return if (allPureSupertypes.isNotEmpty()) allPureSupertypes else supertypes
return allPureSupertypes
}
else {
return supertypes
}
} }
private fun effectiveVariance(declared: Variance, useSite: Variance): Variance? { private fun effectiveVariance(declared: Variance, useSite: Variance): Variance? {
@@ -47,16 +47,16 @@ fun findCorrespondingSupertype(
while (currentPathNode != null) { while (currentPathNode != null) {
val currentType = currentPathNode.type val currentType = currentPathNode.type
if (currentType.arguments.any { it.projectionKind != Variance.INVARIANT }) { substituted = if (currentType.arguments.any { it.projectionKind != Variance.INVARIANT }) {
substituted = TypeConstructorSubstitution.create(currentType) TypeConstructorSubstitution.create(currentType)
.wrapWithCapturingSubstitution().buildSubstitutor() .wrapWithCapturingSubstitution().buildSubstitutor()
.safeSubstitute(substituted, Variance.INVARIANT) .safeSubstitute(substituted, Variance.INVARIANT)
.approximate() .approximate()
} }
else { else {
substituted = TypeConstructorSubstitution.create(currentType) TypeConstructorSubstitution.create(currentType)
.buildSubstitutor() .buildSubstitutor()
.safeSubstitute(substituted, Variance.INVARIANT) .safeSubstitute(substituted, Variance.INVARIANT)
} }
isAnyMarkedNullable = isAnyMarkedNullable || currentType.isMarkedNullable isAnyMarkedNullable = isAnyMarkedNullable || currentType.isMarkedNullable
@@ -105,18 +105,14 @@ internal sealed class JvmPropertySignature {
val nameResolver: NameResolver, val nameResolver: NameResolver,
val typeTable: TypeTable val typeTable: TypeTable
) : JvmPropertySignature() { ) : JvmPropertySignature() {
private val string: String private val string: String = if (signature.hasGetter()) {
nameResolver.getString(signature.getter.name) + nameResolver.getString(signature.getter.desc)
init { }
if (signature.hasGetter()) { else {
string = nameResolver.getString(signature.getter.name) + nameResolver.getString(signature.getter.desc) val (name, desc) =
} JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable) ?:
else { throw KotlinReflectionInternalError("No field signature for property: $descriptor")
val (name, desc) = JvmAbi.getterName(name) + getManglingSuffix() + "()" + desc
JvmProtoBufUtil.getJvmFieldSignature(proto, nameResolver, typeTable) ?:
throw KotlinReflectionInternalError("No field signature for property: $descriptor")
string = JvmAbi.getterName(name) + getManglingSuffix() + "()" + desc
}
} }
private fun getManglingSuffix(): String { private fun getManglingSuffix(): String {
@@ -194,11 +190,11 @@ internal object RuntimeTypeMapper {
} }
is JavaClassConstructorDescriptor -> { is JavaClassConstructorDescriptor -> {
val element = (function.source as? JavaSourceElement)?.javaElement val element = (function.source as? JavaSourceElement)?.javaElement
when { return when {
element is ReflectJavaConstructor -> element is ReflectJavaConstructor ->
return JvmFunctionSignature.JavaConstructor(element.member) JvmFunctionSignature.JavaConstructor(element.member)
element is ReflectJavaClass && element.isAnnotationType -> element is ReflectJavaClass && element.isAnnotationType ->
return JvmFunctionSignature.FakeJavaAnnotationConstructor(element.element) JvmFunctionSignature.FakeJavaAnnotationConstructor(element.element)
else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java constructor $function ($element)") else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java constructor $function ($element)")
} }
} }
@@ -327,13 +327,13 @@ class JDIEval(
} }
val obj = instance.jdiObj.checkNull() val obj = instance.jdiObj.checkNull()
if (invokespecial) { return if (invokespecial) {
val method = findMethod(methodDesc) val method = findMethod(methodDesc)
return doInvokeMethod(obj, method, invokePolicy or ObjectReference.INVOKE_NONVIRTUAL) doInvokeMethod(obj, method, invokePolicy or ObjectReference.INVOKE_NONVIRTUAL)
} }
else { else {
val method = findMethod(methodDesc, obj.referenceType() ?: methodDesc.ownerType.asReferenceType()) val method = findMethod(methodDesc, obj.referenceType() ?: methodDesc.ownerType.asReferenceType())
return doInvokeMethod(obj, method, invokePolicy) doInvokeMethod(obj, method, invokePolicy)
} }
} }
@@ -79,10 +79,10 @@ private fun chooseMoreSpecific(type1: KotlinType, type2: KotlinType): KotlinType
else -> { // type1IsSubtype && type2IsSubtype else -> { // type1IsSubtype && type2IsSubtype
val flexible1 = type1.unwrap() as? FlexibleType val flexible1 = type1.unwrap() as? FlexibleType
val flexible2 = type2.unwrap() as? FlexibleType val flexible2 = type2.unwrap() as? FlexibleType
when { return when {
flexible1 != null && flexible2 == null -> return type2 flexible1 != null && flexible2 == null -> type2
flexible2 != null && flexible1 == null -> return type1 flexible2 != null && flexible1 == null -> type1
else -> return null //TODO? else -> null //TODO?
} }
} }
} }
@@ -42,11 +42,11 @@ fun <TCallable : CallableDescriptor> TCallable.substituteExtensionIfCallable(
containingDeclarationOrModule: DeclarationDescriptor containingDeclarationOrModule: DeclarationDescriptor
): Collection<TCallable> { ): Collection<TCallable> {
val sequence = receivers.asSequence().flatMap { substituteExtensionIfCallable(it, callType, context, dataFlowInfo, containingDeclarationOrModule).asSequence() } val sequence = receivers.asSequence().flatMap { substituteExtensionIfCallable(it, callType, context, dataFlowInfo, containingDeclarationOrModule).asSequence() }
if (typeParameters.isEmpty()) { // optimization for non-generic callables return if (typeParameters.isEmpty()) { // optimization for non-generic callables
return sequence.firstOrNull()?.let { listOf(it) } ?: listOf() sequence.firstOrNull()?.let { listOf(it) } ?: listOf()
} }
else { else {
return sequence.toList() sequence.toList()
} }
} }
@@ -91,11 +91,11 @@ fun <TCallable : CallableDescriptor> TCallable.substituteExtensionIfCallable(
} }
substitutor substitutor
} }
if (typeParameters.isEmpty()) { // optimization for non-generic callables return if (typeParameters.isEmpty()) { // optimization for non-generic callables
return if (substitutors.any()) listOf(this) else listOf() if (substitutors.any()) listOf(this) else listOf()
} }
else { else {
return substitutors substitutors
.mapNotNull { @Suppress("UNCHECKED_CAST") (substitute(it) as TCallable?) } .mapNotNull { @Suppress("UNCHECKED_CAST") (substitute(it) as TCallable?) }
.toList() .toList()
} }
@@ -186,13 +186,13 @@ class IDELightClassGenerationSupport(private val project: Project) : LightClassG
facadeFiles: List<KtFile>, facadeFiles: List<KtFile>,
moduleInfo: IdeaModuleInfo moduleInfo: IdeaModuleInfo
): List<PsiClass> { ): List<PsiClass> {
if (moduleInfo is ModuleSourceInfo) { return if (moduleInfo is ModuleSourceInfo) {
val lightClassForFacade = KtLightClassForFacade.createForFacade( val lightClassForFacade = KtLightClassForFacade.createForFacade(
psiManager, facadeFqName, moduleInfo.contentScope(), facadeFiles) psiManager, facadeFqName, moduleInfo.contentScope(), facadeFiles)
return withFakeLightClasses(lightClassForFacade, facadeFiles) withFakeLightClasses(lightClassForFacade, facadeFiles)
} }
else { else {
return facadeFiles.filterIsInstance<KtClsFile>().mapNotNull { createLightClassForDecompiledKotlinFile(it) } facadeFiles.filterIsInstance<KtClsFile>().mapNotNull { createLightClassForDecompiledKotlinFile(it) }
} }
} }
@@ -197,16 +197,15 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
val syntheticFileModule = files.map(KtFile::getModuleInfo).toSet().single() val syntheticFileModule = files.map(KtFile::getModuleInfo).toSet().single()
val sdk = syntheticFileModule.sdk val sdk = syntheticFileModule.sdk
val settings = PlatformAnalysisSettings(targetPlatform, sdk, syntheticFileModule.supportsAdditionalBuiltInsMembers()) val settings = PlatformAnalysisSettings(targetPlatform, sdk, syntheticFileModule.supportsAdditionalBuiltInsMembers())
val filesModificationTracker: ModificationTracker
// File copies are created during completion and receive correct modification events through POM. // File copies are created during completion and receive correct modification events through POM.
// Dummy files created e.g. by J2K do not receive events. // Dummy files created e.g. by J2K do not receive events.
if (files.all { it.originalFile != it }) { val filesModificationTracker = if (files.all { it.originalFile != it }) {
filesModificationTracker = ModificationTracker { ModificationTracker {
files.sumByLong { it.outOfBlockModificationCount } files.sumByLong { it.outOfBlockModificationCount }
} }
} }
else { else {
filesModificationTracker = ModificationTracker { ModificationTracker {
files.sumByLong { it.outOfBlockModificationCount + it.modificationStamp } files.sumByLong { it.outOfBlockModificationCount + it.modificationStamp }
} }
} }
@@ -322,11 +321,11 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
val annotatedDescriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated) val annotatedDescriptor = context.get(BindingContext.DECLARATION_TO_DESCRIPTOR, annotated)
if (annotatedDescriptor != null) { return if (annotatedDescriptor != null) {
return annotatedDescriptor.annotations.toList() annotatedDescriptor.annotations.toList()
} }
else { else {
return annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) } annotated.annotationEntries.mapNotNull { context.get(BindingContext.ANNOTATION, it) }
} }
} }
}, LibraryModificationTracker.getInstance(project), PsiModificationTracker.MODIFICATION_COUNT) }, LibraryModificationTracker.getInstance(project), PsiModificationTracker.MODIFICATION_COUNT)
@@ -357,13 +356,13 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
val file = files.first() val file = files.first()
val moduleInfo = file.getModuleInfo() val moduleInfo = file.getModuleInfo()
val notInSourceFiles = files.filterNotInProjectSource(moduleInfo) val notInSourceFiles = files.filterNotInProjectSource(moduleInfo)
if (notInSourceFiles.isNotEmpty()) { return if (notInSourceFiles.isNotEmpty()) {
val projectFacade = getFacadeForSyntheticFiles(notInSourceFiles) val projectFacade = getFacadeForSyntheticFiles(notInSourceFiles)
return ResolutionFacadeImpl(projectFacade, moduleInfo) ResolutionFacadeImpl(projectFacade, moduleInfo)
} }
else { else {
val platform = TargetPlatformDetector.getPlatform(file) val platform = TargetPlatformDetector.getPlatform(file)
return getResolutionFacadeByModuleInfo(moduleInfo, platform) getResolutionFacadeByModuleInfo(moduleInfo, platform)
} }
} }
@@ -61,14 +61,14 @@ internal class ResolutionFacadeImpl(
= projectFacade.getAnalysisResultsForElements(elements) = projectFacade.getAnalysisResultsForElements(elements)
override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor { override fun resolveToDescriptor(declaration: KtDeclaration, bodyResolveMode: BodyResolveMode): DeclarationDescriptor {
if (KtPsiUtil.isLocal(declaration)) { return if (KtPsiUtil.isLocal(declaration)) {
val bindingContext = analyze(declaration, bodyResolveMode) val bindingContext = analyze(declaration, bodyResolveMode)
return bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration] bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, declaration]
?: getFrontendService(moduleInfo, AbsentDescriptorHandler::class.java).diagnoseDescriptorNotFound(declaration) ?: getFrontendService(moduleInfo, AbsentDescriptorHandler::class.java).diagnoseDescriptorNotFound(declaration)
} }
else { else {
val resolveSession = projectFacade.resolverForModuleInfo(declaration.getModuleInfo()).componentProvider.get<ResolveSession>() val resolveSession = projectFacade.resolverForModuleInfo(declaration.getModuleInfo()).componentProvider.get<ResolveSession>()
return resolveSession.resolveToDescriptor(declaration) resolveSession.resolveToDescriptor(declaration)
} }
} }
@@ -118,11 +118,11 @@ private fun getModuleInfoByVirtualFile(project: Project, virtualFile: VirtualFil
val isBinary = virtualFile.isKotlinBinary() val isBinary = virtualFile.isKotlinBinary()
val scriptConfigurationManager = KotlinScriptConfigurationManager.getInstance(project) val scriptConfigurationManager = KotlinScriptConfigurationManager.getInstance(project)
if (isBinary && virtualFile in scriptConfigurationManager.getAllScriptsClasspathScope()) { if (isBinary && virtualFile in scriptConfigurationManager.getAllScriptsClasspathScope()) {
if (treatAsLibrarySource) { return if (treatAsLibrarySource) {
return ScriptDependenciesSourceModuleInfo(project) ScriptDependenciesSourceModuleInfo(project)
} }
else { else {
return ScriptDependenciesModuleInfo(project, null) ScriptDependenciesModuleInfo(project, null)
} }
} }
if (!isBinary && virtualFile in scriptConfigurationManager.getAllLibrarySourcesScope()) { if (!isBinary && virtualFile in scriptConfigurationManager.getAllLibrarySourcesScope()) {
@@ -247,11 +247,11 @@ private class KtLightMethodWrapper(
private fun substituteType(psiType: PsiType): PsiType { private fun substituteType(psiType: PsiType): PsiType {
val substituted = containingClass.substitutor.substitute(psiType) val substituted = containingClass.substitutor.substitute(psiType)
if (TypeUtils.isJavaLangObject(substituted) && substituteObjectWith != null) { return if (TypeUtils.isJavaLangObject(substituted) && substituteObjectWith != null) {
return substituteObjectWith substituteObjectWith
} }
else { else {
return substituted substituted
} }
} }
@@ -32,11 +32,11 @@ import java.util.HashSet
//NOTE: this is an approximation that may contain more module infos then the exact solution //NOTE: this is an approximation that may contain more module infos then the exact solution
fun ModuleSourceInfo.getDependentModules(): Set<ModuleSourceInfo> { fun ModuleSourceInfo.getDependentModules(): Set<ModuleSourceInfo> {
val dependents = getDependents(module) val dependents = getDependents(module)
if (isTests()) { return if (isTests()) {
return dependents.mapTo(HashSet<ModuleSourceInfo>(), Module::testSourceInfo) dependents.mapTo(HashSet<ModuleSourceInfo>(), Module::testSourceInfo)
} }
else { else {
return dependents.flatMapTo(HashSet<ModuleSourceInfo>()) { listOf(it.productionSourceInfo(), it.testSourceInfo()) } dependents.flatMapTo(HashSet<ModuleSourceInfo>()) { listOf(it.productionSourceInfo(), it.testSourceInfo()) }
} }
} }
@@ -31,15 +31,15 @@ class IdePackageOracleFactory(val project: Project) : PackageOracleFactory {
override fun createOracle(moduleInfo: ModuleInfo): PackageOracle { override fun createOracle(moduleInfo: ModuleInfo): PackageOracle {
if (moduleInfo !is IdeaModuleInfo) return PackageOracle.Optimistic if (moduleInfo !is IdeaModuleInfo) return PackageOracle.Optimistic
when { return when (moduleInfo.platform) {
moduleInfo.platform == JvmPlatform -> when (moduleInfo.moduleOrigin) { JvmPlatform -> when (moduleInfo.moduleOrigin) {
ModuleOrigin.LIBRARY -> return JavaPackagesOracle(moduleInfo, project) ModuleOrigin.LIBRARY -> JavaPackagesOracle(moduleInfo, project)
ModuleOrigin.MODULE -> return JvmSourceOracle(moduleInfo as ModuleSourceInfo, project) ModuleOrigin.MODULE -> JvmSourceOracle(moduleInfo as ModuleSourceInfo, project)
ModuleOrigin.OTHER -> return PackageOracle.Optimistic ModuleOrigin.OTHER -> PackageOracle.Optimistic
} }
else -> when (moduleInfo.moduleOrigin) { else -> when (moduleInfo.moduleOrigin) {
ModuleOrigin.MODULE -> return KotlinSourceFilesOracle(moduleInfo as ModuleSourceInfo) ModuleOrigin.MODULE -> KotlinSourceFilesOracle(moduleInfo as ModuleSourceInfo)
else -> return PackageOracle.Optimistic // binaries for non-jvm platform need some oracles based on their structure else -> PackageOracle.Optimistic // binaries for non-jvm platform need some oracles based on their structure
} }
} }
} }
@@ -196,12 +196,10 @@ object SourceNavigationHelper {
private fun getIndexForTopLevelPropertyOrFunction( private fun getIndexForTopLevelPropertyOrFunction(
decompiledDeclaration: KtNamedDeclaration decompiledDeclaration: KtNamedDeclaration
): StringStubIndexExtension<out KtNamedDeclaration> { ): StringStubIndexExtension<out KtNamedDeclaration> = when (decompiledDeclaration) {
when (decompiledDeclaration) { is KtNamedFunction -> KotlinTopLevelFunctionFqnNameIndex.getInstance()
is KtNamedFunction -> return KotlinTopLevelFunctionFqnNameIndex.getInstance() is KtProperty -> KotlinTopLevelPropertyFqnNameIndex.getInstance()
is KtProperty -> return KotlinTopLevelPropertyFqnNameIndex.getInstance() else -> throw IllegalArgumentException("Neither function nor declaration: " + decompiledDeclaration::class.java.name)
else -> throw IllegalArgumentException("Neither function nor declaration: " + decompiledDeclaration::class.java.name)
}
} }
private fun getInitialMemberCandidates( private fun getInitialMemberCandidates(
@@ -85,11 +85,11 @@ private fun findInScope(referencedDescriptor: DeclarationDescriptor, scope: Glob
} }
private fun isLocal(descriptor: DeclarationDescriptor): Boolean { private fun isLocal(descriptor: DeclarationDescriptor): Boolean {
if (descriptor is ParameterDescriptor) { return if (descriptor is ParameterDescriptor) {
return isLocal(descriptor.containingDeclaration) isLocal(descriptor.containingDeclaration)
} }
else { else {
return DescriptorUtils.isLocal(descriptor) DescriptorUtils.isLocal(descriptor)
} }
} }
@@ -317,11 +317,11 @@ private class AnnotationPresentationInfo(
var message = IdeErrorMessages.render(diagnostic) var message = IdeErrorMessages.render(diagnostic)
if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode) { if (KotlinInternalMode.enabled || ApplicationManager.getApplication().isUnitTestMode) {
val factoryName = diagnostic.factory.name val factoryName = diagnostic.factory.name
if (message.startsWith("<html>")) { message = if (message.startsWith("<html>")) {
message = "<html>[$factoryName] ${message.substring("<html>".length)}" "<html>[$factoryName] ${message.substring("<html>".length)}"
} }
else { else {
message = "[$factoryName] $message" "[$factoryName] $message"
} }
} }
if (!message.startsWith("<html>")) { if (!message.startsWith("<html>")) {
@@ -95,16 +95,11 @@ internal class TypeKindHighlightingVisitor(holder: AnnotationHolder, bindingCont
// Do nothing: 'dynamic' is highlighted as a keyword // Do nothing: 'dynamic' is highlighted as a keyword
} }
private fun textAttributesKeyForClass(descriptor: ClassDescriptor): TextAttributesKey { private fun textAttributesKeyForClass(descriptor: ClassDescriptor): TextAttributesKey = when (descriptor.kind) {
when (descriptor.kind) { ClassKind.INTERFACE -> TRAIT
ClassKind.INTERFACE -> return TRAIT ClassKind.ANNOTATION_CLASS -> ANNOTATION
ClassKind.ANNOTATION_CLASS -> return ANNOTATION ClassKind.OBJECT -> OBJECT
ClassKind.OBJECT -> return OBJECT ClassKind.ENUM_ENTRY -> ENUM_ENTRY
ClassKind.ENUM_ENTRY -> return ENUM_ENTRY else -> if (descriptor.modality === Modality.ABSTRACT) ABSTRACT_CLASS else CLASS
else -> return if (descriptor.modality === Modality.ABSTRACT)
ABSTRACT_CLASS
else
CLASS
}
} }
} }
@@ -96,13 +96,13 @@ abstract class AbstractKtReference<T : KtElement>(element: T) : PsiPolyVariantRe
} }
private fun resolveToPsiElements(ref: AbstractKtReference<KtElement>, targetDescriptor: DeclarationDescriptor): Collection<PsiElement> { private fun resolveToPsiElements(ref: AbstractKtReference<KtElement>, targetDescriptor: DeclarationDescriptor): Collection<PsiElement> {
if (targetDescriptor is PackageViewDescriptor) { return if (targetDescriptor is PackageViewDescriptor) {
val psiFacade = JavaPsiFacade.getInstance(ref.expression.project) val psiFacade = JavaPsiFacade.getInstance(ref.expression.project)
val fqName = targetDescriptor.fqName.asString() val fqName = targetDescriptor.fqName.asString()
return listOfNotNull(psiFacade.findPackage(fqName)) listOfNotNull(psiFacade.findPackage(fqName))
} }
else { else {
return DescriptorToSourceUtilsIde.getAllDeclarations(ref.expression.project, targetDescriptor, ref.expression.resolveScope) DescriptorToSourceUtilsIde.getAllDeclarations(ref.expression.project, targetDescriptor, ref.expression.resolveScope)
} }
} }
@@ -233,12 +233,12 @@ class KtSimpleNameReference(expression: KtSimpleNameExpression) : KtSimpleRefere
tokenType, element.parent is KtUnaryExpression, element.parent is KtBinaryExpression tokenType, element.parent is KtUnaryExpression, element.parent is KtBinaryExpression
) ?: return emptyList() ) ?: return emptyList()
val counterpart = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[tokenType] val counterpart = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[tokenType]
if (counterpart != null) { return if (counterpart != null) {
val counterpartName = OperatorConventions.getNameForOperationSymbol(counterpart, false, true)!! val counterpartName = OperatorConventions.getNameForOperationSymbol(counterpart, false, true)!!
return listOf(name, counterpartName) listOf(name, counterpartName)
} }
else { else {
return listOf(name) listOf(name)
} }
} }
} }
@@ -70,14 +70,14 @@ fun SearchScope.restrictToKotlinSources(): SearchScope {
fun SearchScope.excludeKotlinSources(): SearchScope = excludeFileTypes(KotlinFileType.INSTANCE) fun SearchScope.excludeKotlinSources(): SearchScope = excludeFileTypes(KotlinFileType.INSTANCE)
fun SearchScope.excludeFileTypes(vararg fileTypes: FileType): SearchScope { fun SearchScope.excludeFileTypes(vararg fileTypes: FileType): SearchScope {
if (this is GlobalSearchScope) { return if (this is GlobalSearchScope) {
val includedFileTypes = FileTypeRegistry.getInstance().registeredFileTypes.filter { it !in fileTypes }.toTypedArray() val includedFileTypes = FileTypeRegistry.getInstance().registeredFileTypes.filter { it !in fileTypes }.toTypedArray()
return GlobalSearchScope.getScopeRestrictedByFileTypes(this, *includedFileTypes) GlobalSearchScope.getScopeRestrictedByFileTypes(this, *includedFileTypes)
} }
else { else {
this as LocalSearchScope this as LocalSearchScope
val filteredElements = scope.filter { it.containingFile.fileType !in fileTypes } val filteredElements = scope.filter { it.containingFile.fileType !in fileTypes }
return if (filteredElements.isNotEmpty()) if (filteredElements.isNotEmpty())
LocalSearchScope(filteredElements.toTypedArray()) LocalSearchScope(filteredElements.toTypedArray())
else else
GlobalSearchScope.EMPTY_SCOPE GlobalSearchScope.EMPTY_SCOPE
@@ -433,21 +433,19 @@ class ExpressionsOfTypeProcessor(
/** /**
* Process reference to declaration whose type is our class (or our class used anywhere inside that type) * Process reference to declaration whose type is our class (or our class used anywhere inside that type)
*/ */
private fun processReferenceToCallableOfOurType(reference: PsiReference): Boolean { private fun processReferenceToCallableOfOurType(reference: PsiReference) = when (reference.element.language) {
when (reference.element.language) { KotlinLanguage.INSTANCE -> {
KotlinLanguage.INSTANCE -> { if (reference is KtDestructuringDeclarationReference) {
if (reference is KtDestructuringDeclarationReference) { // declaration usage in form of destructuring declaration entry
// declaration usage in form of destructuring declaration entry addCallableDeclarationOfOurType(reference.element)
addCallableDeclarationOfOurType(reference.element)
}
else {
(reference.element as? KtReferenceExpression)?.let { processSuspiciousExpression(it) }
}
return true
} }
else {
else -> return false // reference in unknown language - we don't know how to handle it (reference.element as? KtReferenceExpression)?.let { processSuspiciousExpression(it) }
}
true
} }
else -> false // reference in unknown language - we don't know how to handle it
} }
private fun addSamInterfaceToProcess(psiClass: PsiClass) { private fun addSamInterfaceToProcess(psiClass: PsiClass) {
@@ -39,11 +39,11 @@ class DestructuringDeclarationReferenceSearcher(
) : OperatorReferenceSearcher<KtDestructuringDeclaration>(targetDeclaration, searchScope, consumer, optimizer, options, wordsToSearch = listOf("(")) { ) : OperatorReferenceSearcher<KtDestructuringDeclaration>(targetDeclaration, searchScope, consumer, optimizer, options, wordsToSearch = listOf("(")) {
override fun resolveTargetToDescriptor(): FunctionDescriptor? { override fun resolveTargetToDescriptor(): FunctionDescriptor? {
if (targetDeclaration is KtParameter) { return if (targetDeclaration is KtParameter) {
return targetDeclaration.dataClassComponentFunction() targetDeclaration.dataClassComponentFunction()
} }
else { else {
return super.resolveTargetToDescriptor() super.resolveTargetToDescriptor()
} }
} }
@@ -81,11 +81,11 @@ abstract class OperatorReferenceSearcher<TReferenceElement : KtElement>(
protected fun processReferenceElement(element: TReferenceElement): Boolean { protected fun processReferenceElement(element: TReferenceElement): Boolean {
val reference = extractReference(element) ?: return true val reference = extractReference(element) ?: return true
testLog { "Resolved ${logPresentation(element)}" } testLog { "Resolved ${logPresentation(element)}" }
if (reference.isReferenceTo(targetDeclaration)) { return if (reference.isReferenceTo(targetDeclaration)) {
return consumer.process(reference) consumer.process(reference)
} }
else { else {
return true true
} }
} }
@@ -246,11 +246,11 @@ object KotlinOutputParserHelper {
try { try {
val severityConst: Any = severityObjectMap[severity] ?: return null val severityConst: Any = severityObjectMap[severity] ?: return null
if (isNewAndroidPlugin) { return if (isNewAndroidPlugin) {
return createNewMessage(severityConst, text.trim(), file, lineNumber, columnIndex, offset) createNewMessage(severityConst, text.trim(), file, lineNumber, columnIndex, offset)
} }
else { else {
return createOldMessage(severityConst, text.trim(), file, lineNumber, columnIndex) createOldMessage(severityConst, text.trim(), file, lineNumber, columnIndex)
} }
} }
catch(e: Throwable) { catch(e: Throwable) {
@@ -294,11 +294,11 @@ object KotlinOutputParserHelper {
lineNumber: Int?, lineNumber: Int?,
columnIndex: Int? columnIndex: Int?
): Any? { ): Any? {
if (file == null || lineNumber == null || columnIndex == null) { return if (file == null || lineNumber == null || columnIndex == null) {
return simpleMessageConstructor.newInstance(severityConst, text) simpleMessageConstructor.newInstance(severityConst, text)
} }
else { else {
return complexMessageConstructor.newInstance( complexMessageConstructor.newInstance(
severityConst, severityConst,
text, file, text, file,
lineNumber, columnIndex) lineNumber, columnIndex)
@@ -375,12 +375,12 @@ private fun KtClass.createSecondaryConstructor(factory: KtPsiFactory): KtConstru
val constructor = factory.createSecondaryConstructor(constructorText) val constructor = factory.createSecondaryConstructor(constructorText)
val lastProperty = declarations.findLast { it is KtProperty } val lastProperty = declarations.findLast { it is KtProperty }
if (lastProperty != null) { return if (lastProperty != null) {
return addDeclarationAfter(constructor, lastProperty).apply { addNewLineBeforeDeclaration() } addDeclarationAfter(constructor, lastProperty).apply { addNewLineBeforeDeclaration() }
} }
else { else {
val firstFunction = declarations.find { it is KtFunction } val firstFunction = declarations.find { it is KtFunction }
return addDeclarationBefore(constructor, firstFunction).apply { addNewLineBeforeDeclaration() } addDeclarationBefore(constructor, firstFunction).apply { addNewLineBeforeDeclaration() }
} }
} }
@@ -58,10 +58,10 @@ abstract class DeclarationLookupObjectImpl(
if (this === other) return true if (this === other) return true
if (other == null || this::class.java != other::class.java) return false if (other == null || this::class.java != other::class.java) return false
val lookupObject = other as DeclarationLookupObjectImpl val lookupObject = other as DeclarationLookupObjectImpl
if (descriptor != null) return if (descriptor != null)
return descriptorsEqualWithSubstitution(descriptor, lookupObject.descriptor) descriptorsEqualWithSubstitution(descriptor, lookupObject.descriptor)
else else
return lookupObject.descriptor == null && psiElement == lookupObject.psiElement lookupObject.descriptor == null && psiElement == lookupObject.psiElement
} }
override val isDeprecated: Boolean override val isDeprecated: Boolean
@@ -147,19 +147,19 @@ class KDocNameCompletionSession(
fun collectDescriptorsForLinkCompletion(declarationDescriptor: DeclarationDescriptor, kDocLink: KDocLink): Sequence<DeclarationDescriptor> { fun collectDescriptorsForLinkCompletion(declarationDescriptor: DeclarationDescriptor, kDocLink: KDocLink): Sequence<DeclarationDescriptor> {
val qualifiedLink = kDocLink.getLinkText().split('.').dropLast(1) val qualifiedLink = kDocLink.getLinkText().split('.').dropLast(1)
val nameFilter = descriptorNameFilter.toNameFilter() val nameFilter = descriptorNameFilter.toNameFilter()
if (qualifiedLink.isNotEmpty()) { return if (qualifiedLink.isNotEmpty()) {
val parentDescriptors = resolveKDocLink(bindingContext, resolutionFacade, declarationDescriptor, kDocLink.getTagIfSubject(), qualifiedLink) val parentDescriptors = resolveKDocLink(bindingContext, resolutionFacade, declarationDescriptor, kDocLink.getTagIfSubject(), qualifiedLink)
val childDescriptorsOfPartialLink = parentDescriptors.asSequence().flatMap { val childDescriptorsOfPartialLink = parentDescriptors.asSequence().flatMap {
val scope = getKDocLinkResolutionScope(resolutionFacade, it) val scope = getKDocLinkResolutionScope(resolutionFacade, it)
collectDescriptorsFromScope(scope, nameFilter, false) collectDescriptorsFromScope(scope, nameFilter, false)
} }
return (collectPackageViewDescriptors(qualifiedLink, nameFilter) + childDescriptorsOfPartialLink) (collectPackageViewDescriptors(qualifiedLink, nameFilter) + childDescriptorsOfPartialLink)
} }
else { else {
val scope = getKDocLinkResolutionScope(resolutionFacade, declarationDescriptor) val scope = getKDocLinkResolutionScope(resolutionFacade, declarationDescriptor)
return (collectDescriptorsFromScope(scope, nameFilter, true) (collectDescriptorsFromScope(scope, nameFilter, true)
+ collectPackageViewDescriptors(qualifiedLink, nameFilter)) + collectPackageViewDescriptors(qualifiedLink, nameFilter))
} }
} }
@@ -254,11 +254,11 @@ object KeywordCompletion {
val scope = parent.parent val scope = parent.parent
when (scope) { when (scope) {
is KtClassOrObject -> { is KtClassOrObject -> {
if (parent is KtPrimaryConstructor) { return if (parent is KtPrimaryConstructor) {
return buildFilterWithReducedContext("class X ", parent, position) buildFilterWithReducedContext("class X ", parent, position)
} }
else { else {
return buildFilterWithReducedContext("class X { ", parent, position) buildFilterWithReducedContext("class X { ", parent, position)
} }
} }
@@ -386,22 +386,22 @@ class KotlinCompletionContributor : CompletionContributor() {
val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null val nameRef = nameToken.parent as? KtNameReferenceExpression ?: return null
val bindingContext = nameRef.getResolutionFacade().analyze(nameRef, BodyResolveMode.PARTIAL) val bindingContext = nameRef.getResolutionFacade().analyze(nameRef, BodyResolveMode.PARTIAL)
val targets = nameRef.getReferenceTargets(bindingContext) val targets = nameRef.getReferenceTargets(bindingContext)
if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) { return if (targets.isNotEmpty() && targets.all { it is FunctionDescriptor || it is ClassDescriptor && it.kind == ClassKind.CLASS }) {
return CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$" CompletionUtilCore.DUMMY_IDENTIFIER_TRIMMED + ">".repeat(balance) + "$"
} }
else { else {
return null null
} }
} }
private fun unclosedTypeArgListNameAndBalance(tokenBefore: PsiElement): Pair<PsiElement, Int>? { private fun unclosedTypeArgListNameAndBalance(tokenBefore: PsiElement): Pair<PsiElement, Int>? {
val nameToken = findCallNameTokenIfInTypeArgs(tokenBefore) ?: return null val nameToken = findCallNameTokenIfInTypeArgs(tokenBefore) ?: return null
val pair = unclosedTypeArgListNameAndBalance(nameToken) val pair = unclosedTypeArgListNameAndBalance(nameToken)
if (pair == null) { return if (pair == null) {
return Pair(nameToken, 1) Pair(nameToken, 1)
} }
else { else {
return Pair(pair.first, pair.second + 1) Pair(pair.first, pair.second + 1)
} }
} }
@@ -154,11 +154,11 @@ class OverridesCompletion(
is KtValVarKeywordOwner -> { is KtValVarKeywordOwner -> {
if (descriptorToOverride !is PropertyDescriptor) return false if (descriptorToOverride !is PropertyDescriptor) return false
if (declaration.valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) { return if (declaration.valOrVarKeyword?.node?.elementType == KtTokens.VAL_KEYWORD) {
return !descriptorToOverride.isVar !descriptorToOverride.isVar
} }
else { else {
return true // var can override either var or val true // var can override either var or val
} }
} }
@@ -214,7 +214,7 @@ object PreferGetSetMethodsToPropertyWeigher : LookupElementWeigher("kotlin.prefe
val prefixMatcher = context.itemMatcher(element) val prefixMatcher = context.itemMatcher(element)
if (prefixMatcher.prefixMatches(property.name.asString())) return 0 if (prefixMatcher.prefixMatches(property.name.asString())) return 0
val matchedLookupStrings = element.allLookupStrings.filter { prefixMatcher.prefixMatches(it) } val matchedLookupStrings = element.allLookupStrings.filter { prefixMatcher.prefixMatches(it) }
if (matchedLookupStrings.all { it.startsWith("get") || it.startsWith("set") }) return 1 else return 0 return if (matchedLookupStrings.all { it.startsWith("get") || it.startsWith("set") }) 1 else 0
} }
} }
@@ -94,12 +94,12 @@ object KotlinClassifierInsertHandler : BaseDeclarationInsertHandler() {
private fun qualifiedNameToInsert(item: LookupElement): String { private fun qualifiedNameToInsert(item: LookupElement): String {
val lookupObject = item.`object` as DeclarationLookupObject val lookupObject = item.`object` as DeclarationLookupObject
if (lookupObject.descriptor != null) { return if (lookupObject.descriptor != null) {
return IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(lookupObject.descriptor as ClassifierDescriptor) IdeDescriptorRenderers.SOURCE_CODE.renderClassifierName(lookupObject.descriptor as ClassifierDescriptor)
} }
else { else {
val qualifiedName = (lookupObject.psiElement as PsiClass).qualifiedName!! val qualifiedName = (lookupObject.psiElement as PsiClass).qualifiedName!!
return if (FqNameUnsafe.isValid(qualifiedName)) FqNameUnsafe(qualifiedName).render() else qualifiedName if (FqNameUnsafe.isValid(qualifiedName)) FqNameUnsafe(qualifiedName).render() else qualifiedName
} }
} }
} }
@@ -176,11 +176,11 @@ class TypeInstantiationItems(
val typeArgsToUse = typeArgs.map { TypeProjectionImpl(Variance.INVARIANT, it.type) } val typeArgsToUse = typeArgs.map { TypeProjectionImpl(Variance.INVARIANT, it.type) }
val allTypeArgsKnown = fuzzyType.freeParameters.isEmpty() || typeArgs.none { it.type.areTypeParametersUsedInside(fuzzyType.freeParameters) } val allTypeArgsKnown = fuzzyType.freeParameters.isEmpty() || typeArgs.none { it.type.areTypeParametersUsedInside(fuzzyType.freeParameters) }
if (allTypeArgsKnown) { itemText += if (allTypeArgsKnown) {
itemText += IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.renderTypeArguments(typeArgsToUse) IdeDescriptorRenderers.SOURCE_CODE_SHORT_NAMES_IN_TYPES.renderTypeArguments(typeArgsToUse)
} }
else { else {
itemText += "<...>" "<...>"
} }
val constructorParenthesis = if (classifier.kind != ClassKind.INTERFACE) "()" else "" val constructorParenthesis = if (classifier.kind != ClassKind.INTERFACE) "()" else ""
@@ -315,11 +315,11 @@ fun DeclarationDescriptor.fuzzyTypesForSmartCompletion(
return emptyList() return emptyList()
} }
if (this is VariableDescriptor) { //TODO: generic properties! return if (this is VariableDescriptor) { //TODO: generic properties!
return smartCastCalculator.types(this).map { it.toFuzzyType(emptyList()) } smartCastCalculator.types(this).map { it.toFuzzyType(emptyList()) }
} }
else { else {
return listOf(returnType) listOf(returnType)
} }
} }
else if (this is ClassDescriptor && kind.isSingleton) { else if (this is ClassDescriptor && kind.isSingleton) {
@@ -500,9 +500,9 @@ class ExpectedInfos(
if (expressionWithType != block.statements.last()) return null if (expressionWithType != block.statements.last()) return null
val functionLiteral = block.parent as? KtFunctionLiteral val functionLiteral = block.parent as? KtFunctionLiteral
if (functionLiteral != null) { return if (functionLiteral != null) {
val literalExpression = functionLiteral.parent as KtLambdaExpression val literalExpression = functionLiteral.parent as KtLambdaExpression
return calculate(literalExpression) calculate(literalExpression)
.mapNotNull { it.fuzzyType } .mapNotNull { it.fuzzyType }
.filter { it.type.isFunctionType } .filter { it.type.isFunctionType }
.map { .map {
@@ -511,7 +511,7 @@ class ExpectedInfos(
} }
} }
else { else {
return calculate(block).map { ExpectedInfo(it.filter, it.expectedName, null) } calculate(block).map { ExpectedInfo(it.filter, it.expectedName, null) }
} }
} }
@@ -287,12 +287,12 @@ class ShortenReferences(val options: (KtElement) -> Options = { Options.DEFAULT
val tryImport = result.descriptors.isNotEmpty() val tryImport = result.descriptors.isNotEmpty()
&& result.descriptors.none { it in failedToImportDescriptors } && result.descriptors.none { it in failedToImportDescriptors }
&& result.descriptors.all { mayImport(it, file) } && result.descriptors.all { mayImport(it, file) }
if (tryImport) { toBeShortened = if (tryImport) {
descriptorsToImport.addAll(result.descriptors) descriptorsToImport.addAll(result.descriptors)
toBeShortened = true true
} }
else { else {
toBeShortened = false false
} }
} }
@@ -548,11 +548,11 @@ class ShortenReferences(val options: (KtElement) -> Options = { Options.DEFAULT
private fun targetsMatch(targets1: Collection<DeclarationDescriptor>, targets2: Collection<DeclarationDescriptor>): Boolean { private fun targetsMatch(targets1: Collection<DeclarationDescriptor>, targets2: Collection<DeclarationDescriptor>): Boolean {
if (targets1.size != targets2.size) return false if (targets1.size != targets2.size) return false
if (targets1.size == 1) { return if (targets1.size == 1) {
return targets1.single().asString() == targets2.single().asString() targets1.single().asString() == targets2.single().asString()
} }
else { else {
return targets1.map { it.asString() }.toSet() == targets2.map { it.asString() }.toSet() targets1.map { it.asString() }.toSet() == targets2.map { it.asString() }.toSet()
} }
} }
@@ -77,13 +77,13 @@ abstract class TypesWithOperatorDetector(
} }
fun findOperator(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? { fun findOperator(type: FuzzyType): Pair<FunctionDescriptor, TypeSubstitutor>? {
if (cache.containsKey(type)) { return if (cache.containsKey(type)) {
return cache[type] cache[type]
} }
else { else {
val result = findOperatorNoCache(type) val result = findOperatorNoCache(type)
cache[type] = result cache[type] = result
return result result
} }
} }
@@ -118,15 +118,17 @@ fun compareDescriptors(project: Project, currentDescriptor: DeclarationDescripto
fun Visibility.toKeywordToken(): KtModifierKeywordToken { fun Visibility.toKeywordToken(): KtModifierKeywordToken {
val normalized = normalize() val normalized = normalize()
when (normalized) { return when (normalized) {
Visibilities.PUBLIC -> return KtTokens.PUBLIC_KEYWORD Visibilities.PUBLIC -> KtTokens.PUBLIC_KEYWORD
Visibilities.PROTECTED -> return KtTokens.PROTECTED_KEYWORD Visibilities.PROTECTED -> KtTokens.PROTECTED_KEYWORD
Visibilities.INTERNAL -> return KtTokens.INTERNAL_KEYWORD Visibilities.INTERNAL -> KtTokens.INTERNAL_KEYWORD
else -> { else -> {
if (Visibilities.isPrivate(normalized)) { if (Visibilities.isPrivate(normalized)) {
return KtTokens.PRIVATE_KEYWORD KtTokens.PRIVATE_KEYWORD
}
else {
error("Unexpected visibility '$normalized'")
} }
error("Unexpected visibility '$normalized'")
} }
} }
} }
@@ -60,11 +60,11 @@ interface OverrideMemberChooserObject : ClassMember {
preferConstructorParameter: Boolean = false preferConstructorParameter: Boolean = false
): OverrideMemberChooserObject { ): OverrideMemberChooserObject {
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor)
if (declaration != null) { return if (declaration != null) {
return WithDeclaration(descriptor, declaration, immediateSuper, bodyType, preferConstructorParameter) WithDeclaration(descriptor, declaration, immediateSuper, bodyType, preferConstructorParameter)
} }
else { else {
return WithoutDeclaration(descriptor, immediateSuper, bodyType, preferConstructorParameter) WithoutDeclaration(descriptor, immediateSuper, bodyType, preferConstructorParameter)
} }
} }
@@ -84,14 +84,14 @@ open class DescriptorMemberChooserObject(
if (declaration != null && declaration.isValid) { if (declaration != null && declaration.isValid) {
val isClass = declaration is PsiClass || declaration is KtClass val isClass = declaration is PsiClass || declaration is KtClass
val flags = if (isClass) 0 else Iconable.ICON_FLAG_VISIBILITY val flags = if (isClass) 0 else Iconable.ICON_FLAG_VISIBILITY
if (declaration is KtDeclaration) { return if (declaration is KtDeclaration) {
// kotlin declaration // kotlin declaration
// visibility and abstraction better detect by a descriptor // visibility and abstraction better detect by a descriptor
return KotlinDescriptorIconProvider.getIcon(descriptor, declaration, flags) KotlinDescriptorIconProvider.getIcon(descriptor, declaration, flags)
} }
else { else {
// it is better to show java icons for java code // it is better to show java icons for java code
return declaration.getIcon(flags) declaration.getIcon(flags)
} }
} }
else { else {
@@ -146,11 +146,11 @@ class MavenPluginSourcesMoveToBuild : PsiElementBaseIntentionAction() {
} }
} }
if (couldMove == 1) { return if (couldMove == 1) {
block(pom, sourceDirsToMove.single(), execution, build) block(pom, sourceDirsToMove.single(), execution, build)
return true true
} else { } else {
return false false
} }
} }
@@ -107,10 +107,7 @@ class SearchNotPropertyCandidatesAction : AnAction() {
val t = this.text val t = this.text
val s = t.indexOf('{') val s = t.indexOf('{')
val e = t.lastIndexOf('}') val e = t.lastIndexOf('}')
if (s != e && s != -1) { return if (s != e && s != -1) t.substring(s, e).lines().size <= 3 else true
return t.substring(s, e).lines().size <= 3
}
else return true
} }
@@ -365,12 +365,12 @@ class KotlinBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() {
val condition = conditions.firstOrNull() ?: return "->" val condition = conditions.firstOrNull() ?: return "->"
val firstConditionText = condition.buildText(kind) val firstConditionText = condition.buildText(kind)
if (conditions.size == 1) { return if (conditions.size == 1) {
return firstConditionText + " ->" firstConditionText + " ->"
} }
else { else {
//TODO: show all conditions for tooltip //TODO: show all conditions for tooltip
return (if (firstConditionText.endsWith(ellipsis)) firstConditionText else firstConditionText + ",$ellipsis") + " ->" (if (firstConditionText.endsWith(ellipsis)) firstConditionText else firstConditionText + ",$ellipsis") + " ->"
} }
} }
} }
@@ -434,12 +434,12 @@ class KotlinBreadcrumbsInfoProvider : BreadcrumbsInfoProvider() {
override fun getParent(e: PsiElement): PsiElement? { override fun getParent(e: PsiElement): PsiElement? {
val node = e.node ?: return null val node = e.node ?: return null
when (node.elementType) { return when (node.elementType) {
KtNodeTypes.PROPERTY_ACCESSOR -> KtNodeTypes.PROPERTY_ACCESSOR ->
return e.parent.parent e.parent.parent
else -> else ->
return e.parent e.parent
} }
} }
@@ -188,13 +188,12 @@ class DebuggerClassNameProvider(
val classNamesOfContainingDeclaration = getOuterClassNamesForElement(element.relevantParentInReadAction) val classNamesOfContainingDeclaration = getOuterClassNamesForElement(element.relevantParentInReadAction)
val nonInlineClasses: ComputedClassNames val nonInlineClasses: ComputedClassNames = if (runReadAction { element.name == null || element.isLocal }) {
if (runReadAction { element.name == null || element.isLocal }) { classNamesOfContainingDeclaration + ComputedClassNames.Cached(
nonInlineClasses = classNamesOfContainingDeclaration + ComputedClassNames.Cached(
asmTypeForAnonymousClass(typeMapper.bindingContext, element).internalName.toJdiName()) asmTypeForAnonymousClass(typeMapper.bindingContext, element).internalName.toJdiName())
} }
else { else {
nonInlineClasses = classNamesOfContainingDeclaration classNamesOfContainingDeclaration
} }
if (!findInlineUseSites || !element.isInlineInReadAction) { if (!findInlineUseSites || !element.isInlineInReadAction) {
@@ -101,11 +101,11 @@ class InlineCallableUsagesSearcher(val myDebugProcess: DebugProcess, val scopes:
private fun getScopeForInlineDeclarationUsages(inlineDeclaration: KtDeclaration): GlobalSearchScope { private fun getScopeForInlineDeclarationUsages(inlineDeclaration: KtDeclaration): GlobalSearchScope {
val virtualFile = runReadAction { inlineDeclaration.containingFile.virtualFile } val virtualFile = runReadAction { inlineDeclaration.containingFile.virtualFile }
if (virtualFile != null && ProjectRootsUtil.isLibraryFile(myDebugProcess.project, virtualFile)) { return if (virtualFile != null && ProjectRootsUtil.isLibraryFile(myDebugProcess.project, virtualFile)) {
return GlobalSearchScope.union(scopes.toTypedArray()) GlobalSearchScope.union(scopes.toTypedArray())
} }
else { else {
return myDebugProcess.searchScope myDebugProcess.searchScope
} }
} }
} }
@@ -160,11 +160,11 @@ class KotlinFieldBreakpointType : JavaBreakpointType<KotlinPropertyBreakpointPro
override fun getDisplayText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String? { override fun getDisplayText(breakpoint: XLineBreakpoint<KotlinPropertyBreakpointProperties>): String? {
val kotlinBreakpoint = BreakpointManager.getJavaBreakpoint(breakpoint) as? BreakpointWithHighlighter val kotlinBreakpoint = BreakpointManager.getJavaBreakpoint(breakpoint) as? BreakpointWithHighlighter
if (kotlinBreakpoint != null) { return if (kotlinBreakpoint != null) {
return kotlinBreakpoint.description kotlinBreakpoint.description
} }
else { else {
return super.getDisplayText(breakpoint) super.getDisplayText(breakpoint)
} }
} }
@@ -44,11 +44,11 @@ class KotlinStepOverInlinedLinesHint(
val frameProxy = context.frameProxy val frameProxy = context.frameProxy
if (frameProxy != null) { if (frameProxy != null) {
if (isTheSameFrame(context)) { if (isTheSameFrame(context)) {
if (filter.locationMatches(context, frameProxy.location())) { return if (filter.locationMatches(context, frameProxy.location())) {
return STOP STOP
} }
else { else {
return StepRequest.STEP_OVER StepRequest.STEP_OVER
} }
} }
@@ -58,14 +58,14 @@ private fun deduceBlockSelectionWidth(startOffsets: IntArray, endOffsets: IntArr
val fragmentCount = startOffsets.size val fragmentCount = startOffsets.size
assert(fragmentCount > 0) assert(fragmentCount > 0)
var totalLength = fragmentCount - 1 // number of line breaks inserted between fragments var totalLength = fragmentCount - 1 // number of line breaks inserted between fragments
for (i in 0..fragmentCount - 1) { for (i in 0 until fragmentCount) {
totalLength += endOffsets[i] - startOffsets[i] totalLength += endOffsets[i] - startOffsets[i]
} }
if (totalLength < text.length && (text.length + 1) % fragmentCount == 0) { return if (totalLength < text.length && (text.length + 1) % fragmentCount == 0) {
return (text.length + 1) / fragmentCount - 1 (text.length + 1) / fragmentCount - 1
} }
else { else {
return -1 -1
} }
} }
@@ -83,11 +83,11 @@ class KotlinExceptionFilter(private val searchScope: GlobalSearchScope) : Filter
} }
if (filesByName.isNotEmpty()) { if (filesByName.isNotEmpty()) {
if (filesByName.size > 1) { return if (filesByName.size > 1) {
return HyperlinkInfoFactoryImpl.getInstance().createMultipleFilesHyperlinkInfo(filesByName.toList(), lineNumber, project) HyperlinkInfoFactoryImpl.getInstance().createMultipleFilesHyperlinkInfo(filesByName.toList(), lineNumber, project)
} }
else { else {
return OpenFileHyperlinkInfo(project, filesByName.first(), lineNumber) OpenFileHyperlinkInfo(project, filesByName.first(), lineNumber)
} }
} }
} }
@@ -82,11 +82,11 @@ class KotlinSuspendCallLineMarkerProvider : LineMarkerProvider {
if (!calleeDescriptor.isSuspend) continue if (!calleeDescriptor.isSuspend) continue
markedLineNumbers += lineNumber markedLineNumbers += lineNumber
if (element is KtForExpression) { result += if (element is KtForExpression) {
result += SuspendCallMarkerInfo(element.loopRange!!, "Suspending iteration") SuspendCallMarkerInfo(element.loopRange!!, "Suspending iteration")
} else { } else {
result += SuspendCallMarkerInfo(element, "Suspend function call") SuspendCallMarkerInfo(element, "Suspend function call")
} }
} }
} }
@@ -228,15 +228,14 @@ private fun prevWalker(element: PsiElement, scope: PsiElement): Iterator<PsiElem
if (current == null || current === scope) return null if (current == null || current === scope) return null
val prev = current.prevSibling val prev = current.prevSibling
if (prev != null) { e = if (prev != null) {
e = getDeepestLast(prev) getDeepestLast(prev)
return e
} }
else { else {
val parent = current.parent val parent = current.parent
e = if (parent === scope || parent is PsiFile) null else parent if (parent === scope || parent is PsiFile) null else parent
return e
} }
return e
} }
} }
} }
@@ -70,7 +70,7 @@ abstract class ImplementAbstractMemberIntentionBase :
val substitutor = getTypeSubstitutor(superClass.defaultType, subClass.defaultType) ?: TypeSubstitutor.EMPTY val substitutor = getTypeSubstitutor(superClass.defaultType, subClass.defaultType) ?: TypeSubstitutor.EMPTY
val signatureInSubClass = superMember.substitute(substitutor) as? CallableMemberDescriptor ?: return null val signatureInSubClass = superMember.substitute(substitutor) as? CallableMemberDescriptor ?: return null
val subMember = subClass.findCallableMemberBySignature(signatureInSubClass) val subMember = subClass.findCallableMemberBySignature(signatureInSubClass)
if (subMember?.kind?.isReal ?: false) return subMember else return null return if (subMember?.kind?.isReal == true) subMember else null
} }
protected abstract fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean protected abstract fun acceptSubClass(subClassDescriptor: ClassDescriptor, memberDescriptor: CallableMemberDescriptor): Boolean
@@ -54,10 +54,11 @@ class RemoveRedundantCallsOfConversionMethodsIntention : SelfTargetingRangeInten
val selectorExpression = element.selectorExpression ?: return null val selectorExpression = element.selectorExpression ?: return null
val selectorExpressionText = selectorExpression.text val selectorExpressionText = selectorExpression.text
val qualifiedName = targetClassMap[selectorExpressionText] ?: return null val qualifiedName = targetClassMap[selectorExpressionText] ?: return null
if(element.receiverExpression.isApplicableReceiverExpression(qualifiedName)) { return if(element.receiverExpression.isApplicableReceiverExpression(qualifiedName)) {
return selectorExpression.textRange selectorExpression.textRange
} else { }
return null else {
null
} }
} }
@@ -102,11 +102,9 @@ fun KtQualifiedExpression.toResolvedCall(bodyResolveMode: BodyResolveMode): Reso
return callExpression.getResolvedCall(callExpression.analyze(bodyResolveMode)) ?: return null return callExpression.getResolvedCall(callExpression.analyze(bodyResolveMode)) ?: return null
} }
fun KtExpression.isExitStatement(): Boolean { fun KtExpression.isExitStatement(): Boolean = when (this) {
when (this) { is KtContinueExpression, is KtBreakExpression, is KtThrowExpression, is KtReturnExpression -> true
is KtContinueExpression, is KtBreakExpression, is KtThrowExpression, is KtReturnExpression -> return true else -> false
else -> return false
}
} }
// returns false for call of super, static method or method from package // returns false for call of super, static method or method from package
@@ -41,11 +41,11 @@ class IfThenToSafeAccessIntention : SelfTargetingOffsetIndependentIntention<KtIf
val ifThenToSelectData = element.buildSelectTransformationData() ?: return false val ifThenToSelectData = element.buildSelectTransformationData() ?: return false
if (!ifThenToSelectData.receiverExpression.isStable(ifThenToSelectData.context)) return false if (!ifThenToSelectData.receiverExpression.isStable(ifThenToSelectData.context)) return false
if (ifThenToSelectData.baseClause !is KtDotQualifiedExpression) { if (ifThenToSelectData.baseClause !is KtDotQualifiedExpression) {
if (ifThenToSelectData.condition is KtIsExpression) { text = if (ifThenToSelectData.condition is KtIsExpression) {
text = "Replace 'if' expression with safe cast expression" "Replace 'if' expression with safe cast expression"
} }
else { else {
text = "Remove redundant 'if' expression" "Remove redundant 'if' expression"
} }
} }
@@ -175,12 +175,12 @@ class CommentSavingRangeHolder(range: PsiChildRange) {
val rangeParent = range.first!!.parent val rangeParent = range.first!!.parent
val elementToAdd = element.parentsWithSelf.takeWhile { it != rangeParent }.last() val elementToAdd = element.parentsWithSelf.takeWhile { it != rangeParent }.last()
when (elementToAdd) { range = when (elementToAdd) {
in range -> return in range -> return
in range.first!!.siblingsBefore() -> range = PsiChildRange(elementToAdd, range.last) in range.first!!.siblingsBefore() -> PsiChildRange(elementToAdd, range.last)
else -> range = PsiChildRange(range.first, elementToAdd) else -> PsiChildRange(range.first, elementToAdd)
} }
} }
@@ -196,11 +196,11 @@ class CommentSavingRangeHolder(range: PsiChildRange) {
.siblings(forward = true, withItself = false) .siblings(forward = true, withItself = false)
.takeWhile { it != range.last!!.nextSibling } .takeWhile { it != range.last!!.nextSibling }
.firstOrNull { it !is PsiWhiteSpace } .firstOrNull { it !is PsiWhiteSpace }
if (newFirst != null) { range = if (newFirst != null) {
range = PsiChildRange(newFirst, range.last) PsiChildRange(newFirst, range.last)
} }
else { else {
range = PsiChildRange.EMPTY PsiChildRange.EMPTY
} }
} }
@@ -209,11 +209,11 @@ class CommentSavingRangeHolder(range: PsiChildRange) {
.siblings(forward = false, withItself = false) .siblings(forward = false, withItself = false)
.takeWhile { it != range.first!!.prevSibling } .takeWhile { it != range.first!!.prevSibling }
.firstOrNull { it !is PsiWhiteSpace } .firstOrNull { it !is PsiWhiteSpace }
if (newLast != null) { range = if (newLast != null) {
range = PsiChildRange(range.first, newLast) PsiChildRange(range.first, newLast)
} }
else { else {
range = PsiChildRange.EMPTY PsiChildRange.EMPTY
} }
} }
} }
@@ -235,13 +235,13 @@ object FindTransformationMatcher : TransformationMatcher {
if (valueIfFound.isVariableReference(indexVariable) && valueIfNotFound.text == "-1") { if (valueIfFound.isVariableReference(indexVariable) && valueIfNotFound.text == "-1") {
val filterExpression = filterCondition!!.asExpression() val filterExpression = filterCondition!!.asExpression()
val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop) val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop)
if (containsArgument != null) { return if (containsArgument != null) {
val functionName = if (findFirst) "indexOf" else "lastIndexOf" val functionName = if (findFirst) "indexOf" else "lastIndexOf"
return SimpleGenerator(functionName, inputVariable, null, containsArgument) SimpleGenerator(functionName, inputVariable, null, containsArgument)
} }
else { else {
val functionName = if (findFirst) "indexOfFirst" else "indexOfLast" val functionName = if (findFirst) "indexOfFirst" else "indexOfLast"
return SimpleGenerator(functionName, inputVariable, filterExpression) SimpleGenerator(functionName, inputVariable, filterExpression)
} }
} }
@@ -337,15 +337,14 @@ object FindTransformationMatcher : TransformationMatcher {
val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop) val containsArgument = filterExpression.isFilterForContainsOperation(inputVariable, loop)
if (containsArgument != null) { if (containsArgument != null) {
val generator = SimpleGenerator("contains", inputVariable, null, containsArgument) val generator = SimpleGenerator("contains", inputVariable, null, containsArgument)
if (negated) { return if (negated) {
return object : FindOperationGenerator(generator) { object : FindOperationGenerator(generator) {
override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression { override fun generate(chainedCallGenerator: ChainedCallGenerator): KtExpression =
return generator.generate(chainedCallGenerator).negate() generator.generate(chainedCallGenerator).negate()
}
} }
} }
else { else {
return generator generator
} }
} }
@@ -36,11 +36,11 @@ abstract class SumTransformationBase(
override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression { override fun generateCode(chainedCallGenerator: ChainedCallGenerator): KtExpression {
val call = generateCall(chainedCallGenerator) val call = generateCall(chainedCallGenerator)
if (initialization.initializer.isZeroConstant()) { return if (initialization.initializer.isZeroConstant()) {
return call call
} }
else { else {
return KtPsiFactory(call).createExpressionByPattern("$0 + $1", initialization.initializer, call) KtPsiFactory(call).createExpressionByPattern("$0 + $1", initialization.initializer, call)
} }
} }
@@ -101,12 +101,12 @@ abstract class FilterTransformationBase : SequenceTransformation {
assert(transformations.isNotEmpty()) assert(transformations.isNotEmpty())
val findTransformationMatch = FindTransformationMatcher.matchWithFilterBefore(currentState, transformations.last()) val findTransformationMatch = FindTransformationMatcher.matchWithFilterBefore(currentState, transformations.last())
if (findTransformationMatch != null) { return if (findTransformationMatch != null) {
return TransformationMatch.Result(findTransformationMatch.resultTransformation, TransformationMatch.Result(findTransformationMatch.resultTransformation,
transformations.dropLast(1) + findTransformationMatch.sequenceTransformations) transformations.dropLast(1) + findTransformationMatch.sequenceTransformations)
} }
else { else {
return TransformationMatch.Sequence(transformations, currentState) TransformationMatch.Sequence(transformations, currentState)
} }
} }
@@ -376,15 +376,15 @@ fun KtExpression.countEmbeddedBreaksAndContinues(): Int {
private fun isEmbeddedBreakOrContinue(expression: KtExpressionWithLabel): Boolean { private fun isEmbeddedBreakOrContinue(expression: KtExpressionWithLabel): Boolean {
if (expression !is KtBreakExpression && expression !is KtContinueExpression) return false if (expression !is KtBreakExpression && expression !is KtContinueExpression) return false
val parent = expression.parent val parent = expression.parent
when (parent) { return when (parent) {
is KtBlockExpression -> return false is KtBlockExpression -> false
is KtContainerNode -> { is KtContainerNode -> {
val containerExpression = parent.parent as KtExpression val containerExpression = parent.parent as KtExpression
return containerExpression.isUsedAsExpression(containerExpression.analyze(BodyResolveMode.PARTIAL)) containerExpression.isUsedAsExpression(containerExpression.analyze(BodyResolveMode.PARTIAL))
} }
else -> return true else -> true
} }
} }
@@ -162,11 +162,11 @@ object KDocRenderer {
// Avoid wrapping the entire converted contents in a <p> tag if it's just a single paragraph // Avoid wrapping the entire converted contents in a <p> tag if it's just a single paragraph
val maybeSingleParagraph = markdownNode.children.singleOrNull { it.type != MarkdownTokenTypes.EOL } val maybeSingleParagraph = markdownNode.children.singleOrNull { it.type != MarkdownTokenTypes.EOL }
if (maybeSingleParagraph != null && !allowSingleParagraph) { return if (maybeSingleParagraph != null && !allowSingleParagraph) {
return maybeSingleParagraph.children.joinToString("") { it.toHtml() } maybeSingleParagraph.children.joinToString("") { it.toHtml() }
} }
else { else {
return markdownNode.toHtml() markdownNode.toHtml()
} }
} }
@@ -34,8 +34,8 @@ class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObjec
override fun extractPsiFromValue(): PsiElement? = value override fun extractPsiFromValue(): PsiElement? = value
override fun getChildrenImpl(): Collection<AbstractTreeNode<*>>? { override fun getChildrenImpl(): Collection<AbstractTreeNode<*>>? {
if (value != null && settings.isShowMembers) { return if (value != null && settings.isShowMembers) {
return value.getStructureDeclarations().map { declaration -> value.getStructureDeclarations().map { declaration ->
if (declaration is KtClassOrObject) if (declaration is KtClassOrObject)
KtClassOrObjectTreeNode(project, declaration, settings) KtClassOrObjectTreeNode(project, declaration, settings)
else else
@@ -43,7 +43,7 @@ class KtClassOrObjectTreeNode(project: Project?, ktClassOrObject: KtClassOrObjec
} }
} }
else { else {
return emptyList() emptyList()
} }
} }
@@ -68,10 +68,10 @@ class ReplaceInfixOrOperatorCallFix(
replacement = element.replace(newExpression) replacement = element.replace(newExpression)
} }
is KtBinaryExpression -> { is KtBinaryExpression -> {
if (element.operationToken == KtTokens.IDENTIFIER) { replacement = if (element.operationToken == KtTokens.IDENTIFIER) {
val newExpression = psiFactory.createExpressionByPattern( val newExpression = psiFactory.createExpressionByPattern(
"$0?.$1($2)$elvis", element.left ?: return, element.operationReference, element.right ?: return) "$0?.$1($2)$elvis", element.left ?: return, element.operationReference, element.right ?: return)
replacement = element.replace(newExpression) element.replace(newExpression)
} }
else { else {
val nameExpression = OperatorToFunctionIntention.convert(element).second val nameExpression = OperatorToFunctionIntention.convert(element).second
@@ -79,7 +79,7 @@ class ReplaceInfixOrOperatorCallFix(
val qualifiedExpression = callExpression.parent as KtDotQualifiedExpression val qualifiedExpression = callExpression.parent as KtDotQualifiedExpression
val safeExpression = psiFactory.createExpressionByPattern( val safeExpression = psiFactory.createExpressionByPattern(
"$0?.$1$elvis", qualifiedExpression.receiverExpression, callExpression) "$0?.$1$elvis", qualifiedExpression.receiverExpression, callExpression)
replacement = qualifiedExpression.replace(safeExpression) qualifiedExpression.replace(safeExpression)
} }
} }
} }
@@ -220,12 +220,12 @@ private fun KtNamedDeclaration.guessType(context: BindingContext): Array<KotlinT
return arrayOf() return arrayOf()
} }
val theType = TypeIntersector.intersectTypes(KotlinTypeChecker.DEFAULT, expectedTypes) val theType = TypeIntersector.intersectTypes(KotlinTypeChecker.DEFAULT, expectedTypes)
if (theType != null) { return if (theType != null) {
return arrayOf(theType) arrayOf(theType)
} }
else { else {
// intersection doesn't exist; let user make an imperfect choice // intersection doesn't exist; let user make an imperfect choice
return expectedTypes.toTypedArray() expectedTypes.toTypedArray()
} }
} }
@@ -238,19 +238,19 @@ internal fun KotlinType.substitute(substitution: KotlinTypeSubstitution, varianc
val nullable = isMarkedNullable val nullable = isMarkedNullable
val currentType = makeNotNullable() val currentType = makeNotNullable()
if (when (variance) { return if (when (variance) {
Variance.INVARIANT -> KotlinTypeChecker.DEFAULT.equalTypes(currentType, substitution.forType) Variance.INVARIANT -> KotlinTypeChecker.DEFAULT.equalTypes(currentType, substitution.forType)
Variance.IN_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(currentType, substitution.forType) Variance.IN_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(currentType, substitution.forType)
Variance.OUT_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(substitution.forType, currentType) Variance.OUT_VARIANCE -> KotlinTypeChecker.DEFAULT.isSubtypeOf(substitution.forType, currentType)
}) { }) {
return TypeUtils.makeNullableAsSpecified(substitution.byType, nullable) TypeUtils.makeNullableAsSpecified(substitution.byType, nullable)
} }
else { else {
val newArguments = arguments.zip(constructor.parameters).map { pair -> val newArguments = arguments.zip(constructor.parameters).map { pair ->
val (projection, typeParameter) = pair val (projection, typeParameter) = pair
TypeProjectionImpl(Variance.INVARIANT, projection.type.substitute(substitution, typeParameter.variance)) TypeProjectionImpl(Variance.INVARIANT, projection.type.substitute(substitution, typeParameter.variance))
} }
return KotlinTypeFactory.simpleType(annotations, constructor, newArguments, isMarkedNullable, memberScope) KotlinTypeFactory.simpleType(annotations, constructor, newArguments, isMarkedNullable, memberScope)
} }
} }
@@ -87,16 +87,15 @@ class KotlinChangeSignatureDialog(
override fun getRowPresentation(item: ParameterTableModelItemBase<KotlinParameterInfo>, selected: Boolean, focused: Boolean): JComponent? { override fun getRowPresentation(item: ParameterTableModelItemBase<KotlinParameterInfo>, selected: Boolean, focused: Boolean): JComponent? {
val panel = JPanel(BorderLayout()) val panel = JPanel(BorderLayout())
val valOrVar: String val valOrVar = if (myMethod.kind === Kind.PRIMARY_CONSTRUCTOR) {
if (myMethod.kind === Kind.PRIMARY_CONSTRUCTOR) { when (item.parameter.valOrVar) {
valOrVar = when (item.parameter.valOrVar) {
KotlinValVar.None -> " " KotlinValVar.None -> " "
KotlinValVar.Val -> "val " KotlinValVar.Val -> "val "
KotlinValVar.Var -> "var " KotlinValVar.Var -> "var "
} }
} }
else { else {
valOrVar = "" ""
} }
val parameterName = getPresentationName(item) val parameterName = getPresentationName(item)
@@ -197,11 +197,11 @@ class KotlinCallableDefinitionUsage<T : PsiElement>(
if (newParameterList == null) return if (newParameterList == null) return
if (parameterList != null) { if (parameterList != null) {
if (canReplaceEntireList) { newParameterList = if (canReplaceEntireList) {
newParameterList = parameterList.replace(newParameterList) as KtParameterList parameterList.replace(newParameterList) as KtParameterList
} }
else { else {
newParameterList = replaceListPsiAndKeepDelimiters(parameterList, newParameterList) { parameters } replaceListPsiAndKeepDelimiters(parameterList, newParameterList) { parameters }
} }
} }
else { else {
@@ -435,8 +435,7 @@ class KotlinFunctionCallUsage(
var newElement: KtElement = element var newElement: KtElement = element
if (newReceiverInfo != originalReceiverInfo) { if (newReceiverInfo != originalReceiverInfo) {
val replacingElement: PsiElement val replacingElement: PsiElement = if (newReceiverInfo != null) {
if (newReceiverInfo != null) {
val receiverArgument = getResolvedValueArgument(newReceiverInfo.oldIndex)?.arguments?.singleOrNull() val receiverArgument = getResolvedValueArgument(newReceiverInfo.oldIndex)?.arguments?.singleOrNull()
val extensionReceiverExpression = receiverArgument?.getArgumentExpression() val extensionReceiverExpression = receiverArgument?.getArgumentExpression()
val defaultValueForCall = newReceiverInfo.defaultValueForCall val defaultValueForCall = newReceiverInfo.defaultValueForCall
@@ -444,10 +443,10 @@ class KotlinFunctionCallUsage(
?: defaultValueForCall ?: defaultValueForCall
?: psiFactory.createExpression("_") ?: psiFactory.createExpression("_")
replacingElement = psiFactory.createExpressionByPattern("$0.$1", receiver, element) psiFactory.createExpressionByPattern("$0.$1", receiver, element)
} }
else { else {
replacingElement = psiFactory.createExpression(element.text) psiFactory.createExpression(element.text)
} }
newElement = fullCallElement.replace(replacingElement) as KtElement newElement = fullCallElement.replace(replacingElement) as KtElement
@@ -116,10 +116,10 @@ open class ExtractFunctionParameterTablePanel : AbstractParameterTablePanel<Para
override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean { override fun isCellEditable(rowIndex: Int, columnIndex: Int): Boolean {
val info = parameterInfos[rowIndex] val info = parameterInfos[rowIndex]
when (columnIndex) { return when (columnIndex) {
AbstractParameterTablePanel.PARAMETER_NAME_COLUMN -> return super.isCellEditable(rowIndex, columnIndex) && !info.isReceiver AbstractParameterTablePanel.PARAMETER_NAME_COLUMN -> super.isCellEditable(rowIndex, columnIndex) && !info.isReceiver
PARAMETER_TYPE_COLUMN -> return isEnabled && info.isEnabled && info.originalParameter.getParameterTypeCandidates(false).size > 1 PARAMETER_TYPE_COLUMN -> isEnabled && info.isEnabled && info.originalParameter.getParameterTypeCandidates(false).size > 1
else -> return super.isCellEditable(rowIndex, columnIndex) else -> super.isCellEditable(rowIndex, columnIndex)
} }
} }
} }

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