Cleanup: apply "cascade if..." inspection (+ some others)

This commit is contained in:
Mikhail Glukhikh
2017-06-28 15:19:20 +03:00
committed by Mikhail Glukhikh
parent 9c06739594
commit 1d2017b0fc
80 changed files with 1079 additions and 1190 deletions
@@ -292,14 +292,10 @@ fun calcTypeForIEEE754ArithmeticIfNeeded(expression: KtExpression?, bindingConte
val dataFlow = DataFlowValueFactory.createDataFlowValue(expression!!, ktType, bindingContext, descriptor)
val stableTypes = bindingContext.getDataFlowInfoBefore(expression).getStableTypes(dataFlow)
return stableTypes.firstNotNullResult {
if (KotlinBuiltIns.isDoubleOrNullableDouble(it)) {
TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it))
}
else if (KotlinBuiltIns.isFloatOrNullableFloat(it)) {
TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it))
}
else {
null
when {
KotlinBuiltIns.isDoubleOrNullableDouble(it) -> TypeAndNullability(Type.DOUBLE_TYPE, TypeUtils.isNullableType(it))
KotlinBuiltIns.isFloatOrNullableFloat(it) -> TypeAndNullability(Type.FLOAT_TYPE, TypeUtils.isNullableType(it))
else -> null
}
}
}
@@ -83,18 +83,16 @@ private fun ExpressionCodegen.createOptimizedForLoopGeneratorOrNull(
private fun getLoopRangeResolvedCall(forExpression: KtForExpression, bindingContext: BindingContext): ResolvedCall<out CallableDescriptor>? {
val loopRange = KtPsiUtil.deparenthesize(forExpression.loopRange)
if (loopRange is KtQualifiedExpression) {
val qualifiedExpression = loopRange as KtQualifiedExpression?
val selector = qualifiedExpression!!.selectorExpression
if (selector is KtCallExpression || selector is KtSimpleNameExpression) {
return selector.getResolvedCall(bindingContext)
when (loopRange) {
is KtQualifiedExpression -> {
val qualifiedExpression = loopRange as KtQualifiedExpression?
val selector = qualifiedExpression!!.selectorExpression
if (selector is KtCallExpression || selector is KtSimpleNameExpression) {
return selector.getResolvedCall(bindingContext)
}
}
}
else if (loopRange is KtSimpleNameExpression || loopRange is KtCallExpression) {
return loopRange.getResolvedCall(bindingContext)
}
else if (loopRange is KtBinaryExpression) {
return loopRange.operationReference.getResolvedCall(bindingContext)
is KtSimpleNameExpression, is KtCallExpression -> return loopRange.getResolvedCall(bindingContext)
is KtBinaryExpression -> return loopRange.operationReference.getResolvedCall(bindingContext)
}
return null
@@ -610,14 +610,10 @@ class PsiInlineCodegen(
override fun putClosureParametersOnStack(next: LambdaInfo, functionReferenceReceiver: StackValue?) {
activeLambda = next
if (next is ExpressionLambda) {
codegen.pushClosureOnStack(next.classDescriptor, true, this, functionReferenceReceiver)
}
else if (next is DefaultLambda) {
rememberCapturedForDefaultLambda(next)
}
else {
throw RuntimeException("Unknown lambda: $next")
when (next) {
is ExpressionLambda -> codegen.pushClosureOnStack(next.classDescriptor, true, this, functionReferenceReceiver)
is DefaultLambda -> rememberCapturedForDefaultLambda(next)
else -> throw RuntimeException("Unknown lambda: $next")
}
activeLambda = null
}
@@ -408,23 +408,27 @@ class PsiSourceCompilerForInline(private val codegen: ExpressionCodegen, overrid
sourceFile
)
if (descriptor is ScriptDescriptor) {
val earlierScripts = state.replSpecific.earlierScriptsForReplInterpreter
return parent.intoScript(
descriptor,
earlierScripts ?: emptyList(),
descriptor as ClassDescriptor, state.typeMapper
)
}
else if (descriptor is ClassDescriptor) {
val kind = if (DescriptorUtils.isInterface(descriptor)) OwnerKind.DEFAULT_IMPLS else OwnerKind.IMPLEMENTATION
return parent.intoClass(descriptor, kind, state)
}
else if (descriptor is FunctionDescriptor) {
return parent.intoFunction(descriptor)
return when (descriptor) {
is ScriptDescriptor -> {
val earlierScripts = state.replSpecific.earlierScriptsForReplInterpreter
parent.intoScript(
descriptor,
earlierScripts ?: emptyList(),
descriptor as ClassDescriptor, state.typeMapper
)
}
is ClassDescriptor -> {
val kind = if (DescriptorUtils.isInterface(descriptor)) OwnerKind.DEFAULT_IMPLS else OwnerKind.IMPLEMENTATION
parent.intoClass(descriptor, kind, state)
}
is FunctionDescriptor -> {
parent.intoFunction(descriptor)
}
else -> {
throw IllegalStateException("Couldn't build context for " + descriptor)
}
}
throw IllegalStateException("Couldn't build context for " + descriptor)
}
}
}
@@ -171,33 +171,35 @@ private fun getInlineName(
typeMapper: KotlinTypeMapper,
fileClassesProvider: JvmFileClassesProvider
): String {
if (currentDescriptor is PackageFragmentDescriptor) {
val file = DescriptorToSourceUtils.getContainingFile(codegenContext.contextDescriptor)
when (currentDescriptor) {
is PackageFragmentDescriptor -> {
val file = DescriptorToSourceUtils.getContainingFile(codegenContext.contextDescriptor)
val implementationOwnerType: Type? =
if (file == null) {
CodegenContextUtil.getImplementationOwnerClassType(codegenContext)
}
else fileClassesProvider.getFileClassType(file)
val implementationOwnerType: Type? =
if (file == null) {
CodegenContextUtil.getImplementationOwnerClassType(codegenContext)
}
else fileClassesProvider.getFileClassType(file)
if (implementationOwnerType == null) {
val contextDescriptor = codegenContext.contextDescriptor
throw RuntimeException(
"Couldn't find declaration for " +
contextDescriptor.containingDeclaration!!.name + "." + contextDescriptor.name +
"; context: " + codegenContext
)
if (implementationOwnerType == null) {
val contextDescriptor = codegenContext.contextDescriptor
throw RuntimeException(
"Couldn't find declaration for " +
contextDescriptor.containingDeclaration!!.name + "." + contextDescriptor.name +
"; context: " + codegenContext
)
}
return implementationOwnerType.internalName
}
return implementationOwnerType.internalName
}
else if (currentDescriptor is ClassifierDescriptor) {
return typeMapper.mapType(currentDescriptor).internalName
}
else if (currentDescriptor is FunctionDescriptor) {
val descriptor = typeMapper.bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, currentDescriptor)
if (descriptor != null) {
return typeMapper.mapType(descriptor).internalName
is ClassifierDescriptor -> {
return typeMapper.mapType(currentDescriptor).internalName
}
is FunctionDescriptor -> {
val descriptor = typeMapper.bindingContext.get(CodegenBinding.CLASS_FOR_CALLABLE, currentDescriptor)
if (descriptor != null) {
return typeMapper.mapType(descriptor).internalName
}
}
}
@@ -43,21 +43,23 @@ object JavaClassProperty : IntrinsicPropertyGetter() {
fun generateImpl(v: InstructionAdapter, receiver: StackValue): Type {
val type = receiver.type
if (type == Type.VOID_TYPE) {
receiver.put(Type.VOID_TYPE, v)
StackValue.unit().put(UNIT_TYPE, v)
v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false)
}
else if (isPrimitive(type)) {
if (!StackValue.couldSkipReceiverOnStaticCall(receiver)) {
receiver.put(type, v)
AsmUtil.pop(v, type)
when {
type == Type.VOID_TYPE -> {
receiver.put(Type.VOID_TYPE, v)
StackValue.unit().put(UNIT_TYPE, v)
v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false)
}
isPrimitive(type) -> {
if (!StackValue.couldSkipReceiverOnStaticCall(receiver)) {
receiver.put(type, v)
AsmUtil.pop(v, type)
}
v.getstatic(boxType(type).internalName, "TYPE", "Ljava/lang/Class;")
}
else -> {
receiver.put(type, v)
v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false)
}
v.getstatic(boxType(type).internalName, "TYPE", "Ljava/lang/Class;")
}
else {
receiver.put(type, v)
v.invokevirtual("java/lang/Object", "getClass", "()Ljava/lang/Class;", false)
}
return getType(Class::class.java)
@@ -1123,15 +1123,10 @@ class ControlFlowInformationProvider private constructor(
kind
}
else {
if (check(kind, existingKind, IN_TRY, TAIL_CALL)) {
IN_TRY
}
else if (check(kind, existingKind, IN_TRY, NON_TAIL)) {
IN_TRY
}
else {
// TAIL_CALL, NON_TAIL
NON_TAIL
when {
check(kind, existingKind, IN_TRY, TAIL_CALL) -> IN_TRY
check(kind, existingKind, IN_TRY, NON_TAIL) -> IN_TRY
else -> NON_TAIL // TAIL_CALL, NON_TAIL
}
}
}
@@ -107,15 +107,17 @@ class UnreachableCodeImpl(
currentTextRange, element ->
val elementRange = element.textRange!!
if (currentTextRange == null) {
elementRange
}
else if (currentTextRange.endOffset == elementRange.startOffset) {
currentTextRange.union(elementRange)
}
else {
result.add(currentTextRange)
elementRange
when {
currentTextRange == null -> {
elementRange
}
currentTextRange.endOffset == elementRange.startOffset -> {
currentTextRange.union(elementRange)
}
else -> {
result.add(currentTextRange)
elementRange
}
}
}
if (lastRange != null) {
@@ -47,4 +47,8 @@ class SyntheticFieldDescriptor private constructor(
}
val DeclarationDescriptor.referencedProperty: PropertyDescriptor?
get() = if (this is SyntheticFieldDescriptor) this.propertyDescriptor else if (this is PropertyDescriptor) this else null
get() = when (this) {
is SyntheticFieldDescriptor -> this.propertyDescriptor
is PropertyDescriptor -> this
else -> null
}
@@ -458,7 +458,11 @@ object Renderers {
private fun renderTypeBounds(typeBounds: TypeBounds, short: Boolean): String {
val renderBound = { bound: Bound ->
val arrow = if (bound.kind == LOWER_BOUND) ">: " else if (bound.kind == UPPER_BOUND) "<: " else ":= "
val arrow = when (bound.kind) {
LOWER_BOUND -> ">: "
UPPER_BOUND -> "<: "
else -> ":= "
}
val renderer = if (short) DescriptorRenderer.SHORT_NAMES_IN_TYPES else DescriptorRenderer.FQ_NAMES_IN_TYPES
val renderedBound = arrow + renderer.renderType(bound.constrainingType) + if (!bound.isProper) "*" else ""
if (short) renderedBound else renderedBound + '(' + bound.position + ')'
@@ -202,32 +202,28 @@ class AnnotationChecker(private val additionalCheckers: Iterable<AdditionalAnnot
(descriptor as? ClassDescriptor)?.let { TargetList(KotlinTarget.classActualTargets(it)) } ?: TargetLists.T_CLASSIFIER
is KtDestructuringDeclarationEntry -> TargetLists.T_LOCAL_VARIABLE
is KtProperty -> {
if (annotated.isLocal)
TargetLists.T_LOCAL_VARIABLE
else if (annotated.isMember)
TargetLists.T_MEMBER_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate())
else
TargetLists.T_TOP_LEVEL_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate())
when {
annotated.isLocal -> TargetLists.T_LOCAL_VARIABLE
annotated.isMember -> TargetLists.T_MEMBER_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate())
else -> TargetLists.T_TOP_LEVEL_PROPERTY(descriptor.hasBackingField(trace), annotated.hasDelegate())
}
}
is KtParameter -> {
val destructuringDeclaration = annotated.destructuringDeclaration
if (destructuringDeclaration != null)
TargetLists.T_DESTRUCTURING_DECLARATION
else if (annotated.hasValOrVar())
TargetLists.T_VALUE_PARAMETER_WITH_VAL
else
TargetLists.T_VALUE_PARAMETER_WITHOUT_VAL
when {
destructuringDeclaration != null -> TargetLists.T_DESTRUCTURING_DECLARATION
annotated.hasValOrVar() -> TargetLists.T_VALUE_PARAMETER_WITH_VAL
else -> TargetLists.T_VALUE_PARAMETER_WITHOUT_VAL
}
}
is KtConstructor<*> -> TargetLists.T_CONSTRUCTOR
is KtFunction -> {
if (ExpressionTypingUtils.isFunctionExpression(descriptor))
TargetLists.T_FUNCTION_EXPRESSION
else if (annotated.isLocal)
TargetLists.T_LOCAL_FUNCTION
else if (annotated.parent is KtClassOrObject || annotated.parent is KtClassBody)
TargetLists.T_MEMBER_FUNCTION
else
TargetLists.T_TOP_LEVEL_FUNCTION
when {
ExpressionTypingUtils.isFunctionExpression(descriptor) -> TargetLists.T_FUNCTION_EXPRESSION
annotated.isLocal -> TargetLists.T_LOCAL_FUNCTION
annotated.parent is KtClassOrObject || annotated.parent is KtClassBody -> TargetLists.T_MEMBER_FUNCTION
else -> TargetLists.T_TOP_LEVEL_FUNCTION
}
}
is KtTypeAlias -> TargetLists.T_TYPEALIAS
is KtPropertyAccessor -> if (annotated.isGetter) TargetLists.T_PROPERTY_GETTER else TargetLists.T_PROPERTY_SETTER
@@ -266,18 +262,20 @@ class AnnotationChecker(private val additionalCheckers: Iterable<AdditionalAnnot
}
fun T_MEMBER_PROPERTY(backingField: Boolean, delegate: Boolean) =
targetList(if (backingField) MEMBER_PROPERTY_WITH_BACKING_FIELD
else if (delegate) MEMBER_PROPERTY_WITH_DELEGATE
else MEMBER_PROPERTY_WITHOUT_FIELD_OR_DELEGATE,
MEMBER_PROPERTY, PROPERTY) {
targetList(when {
backingField -> MEMBER_PROPERTY_WITH_BACKING_FIELD
delegate -> MEMBER_PROPERTY_WITH_DELEGATE
else -> MEMBER_PROPERTY_WITHOUT_FIELD_OR_DELEGATE
}, MEMBER_PROPERTY, PROPERTY) {
propertyTargets(backingField, delegate)
}
fun T_TOP_LEVEL_PROPERTY(backingField: Boolean, delegate: Boolean) =
targetList(if (backingField) TOP_LEVEL_PROPERTY_WITH_BACKING_FIELD
else if (delegate) TOP_LEVEL_PROPERTY_WITH_DELEGATE
else TOP_LEVEL_PROPERTY_WITHOUT_FIELD_OR_DELEGATE,
TOP_LEVEL_PROPERTY, PROPERTY) {
targetList(when {
backingField -> TOP_LEVEL_PROPERTY_WITH_BACKING_FIELD
delegate -> TOP_LEVEL_PROPERTY_WITH_DELEGATE
else -> TOP_LEVEL_PROPERTY_WITHOUT_FIELD_OR_DELEGATE
}, TOP_LEVEL_PROPERTY, PROPERTY) {
propertyTargets(backingField, delegate)
}
@@ -418,19 +418,19 @@ class DeclarationsChecker(
FiniteBoundRestrictionChecker.check(aClass, classDescriptor, trace)
NonExpansiveInheritanceRestrictionChecker.check(aClass, classDescriptor, trace)
if (aClass.isInterface()) {
checkConstructorInInterface(aClass)
checkMethodsOfAnyInInterface(classDescriptor)
if (aClass.isLocal && classDescriptor.containingDeclaration !is ClassDescriptor) {
trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor))
when {
aClass.isInterface() -> {
checkConstructorInInterface(aClass)
checkMethodsOfAnyInInterface(classDescriptor)
if (aClass.isLocal && classDescriptor.containingDeclaration !is ClassDescriptor) {
trace.report(LOCAL_INTERFACE_NOT_ALLOWED.on(aClass, classDescriptor))
}
}
}
else if (classDescriptor.kind == ClassKind.ANNOTATION_CLASS) {
checkAnnotationClassWithBody(aClass)
checkValOnAnnotationParameter(aClass)
}
else if (aClass is KtEnumEntry) {
checkEnumEntry(aClass, classDescriptor)
classDescriptor.kind == ClassKind.ANNOTATION_CLASS -> {
checkAnnotationClassWithBody(aClass)
checkValOnAnnotationParameter(aClass)
}
aClass is KtEnumEntry -> checkEnumEntry(aClass, classDescriptor)
}
}
@@ -692,17 +692,11 @@ class DeclarationsChecker(
val delegate = property.delegate
val isHeader = propertyDescriptor.isHeader
if (initializer != null) {
if (inInterface) {
trace.report(PROPERTY_INITIALIZER_IN_INTERFACE.on(initializer))
}
else if (isHeader) {
trace.report(HEADER_PROPERTY_INITIALIZER.on(initializer))
}
else if (!backingFieldRequired) {
trace.report(PROPERTY_INITIALIZER_NO_BACKING_FIELD.on(initializer))
}
else if (property.receiverTypeReference != null) {
trace.report(EXTENSION_PROPERTY_WITH_BACKING_FIELD.on(initializer))
when {
inInterface -> trace.report(PROPERTY_INITIALIZER_IN_INTERFACE.on(initializer))
isHeader -> trace.report(HEADER_PROPERTY_INITIALIZER.on(initializer))
!backingFieldRequired -> trace.report(PROPERTY_INITIALIZER_NO_BACKING_FIELD.on(initializer))
property.receiverTypeReference != null -> trace.report(EXTENSION_PROPERTY_WITH_BACKING_FIELD.on(initializer))
}
}
else if (delegate != null) {
@@ -69,12 +69,11 @@ open class DelegatingBindingTrace(
private val bindingContext = MyBindingContext()
init {
this.mutableDiagnostics = if (filter.ignoreDiagnostics)
null
else if (withParentDiagnostics)
MutableDiagnosticsWithSuppression(bindingContext, parentContext.diagnostics)
else
MutableDiagnosticsWithSuppression(bindingContext)
this.mutableDiagnostics = when {
filter.ignoreDiagnostics -> null
withParentDiagnostics -> MutableDiagnosticsWithSuppression(bindingContext, parentContext.diagnostics)
else -> MutableDiagnosticsWithSuppression(bindingContext)
}
}
constructor(parentContext: BindingContext,
@@ -122,14 +122,13 @@ class FunctionDescriptorResolver(
assert(function.typeReference == null) {
"Return type must be initialized early for function: " + function.text + ", at: " + DiagnosticUtils.atLocation(function) }
val returnType = if (function.hasBlockBody()) {
builtIns.unitType
}
else if (function.hasBody()) {
descriptorResolver.inferReturnTypeFromExpressionBody(trace, scope, dataFlowInfo, function, functionDescriptor)
}
else {
ErrorUtils.createErrorType("No type, no body")
val returnType = when {
function.hasBlockBody() ->
builtIns.unitType
function.hasBody() ->
descriptorResolver.inferReturnTypeFromExpressionBody(trace, scope, dataFlowInfo, function, functionDescriptor)
else ->
ErrorUtils.createErrorType("No type, no body")
}
functionDescriptor.setReturnType(returnType)
}
@@ -340,14 +340,10 @@ object ModifierCheckerCore {
checkCompatibility(trace, first, second, list.owner, incorrectNodes)
}
if (second !in incorrectNodes) {
if (!checkTarget(trace, second, actualTargets)) {
incorrectNodes += second
}
else if (!checkParent(trace, second, parentDescriptor)) {
incorrectNodes += second
}
else if (!checkLanguageLevelSupport(trace, second, languageVersionSettings, actualTargets)) {
incorrectNodes += second
when {
!checkTarget(trace, second, actualTargets) -> incorrectNodes += second
!checkParent(trace, second, parentDescriptor) -> incorrectNodes += second
!checkLanguageLevelSupport(trace, second, languageVersionSettings, actualTargets) -> incorrectNodes += second
}
}
}
@@ -568,15 +568,17 @@ class QualifiedExpressionResolver {
) {
if (descriptors.size > 1) {
val visibleDescriptors = descriptors.filter { isVisible(it, shouldBeVisibleFrom, position) }
if (visibleDescriptors.isEmpty()) {
val descriptor = descriptors.first() as DeclarationDescriptorWithVisibility
trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor))
}
else if (visibleDescriptors.size > 1) {
trace.record(BindingContext.AMBIGUOUS_REFERENCE_TARGET, referenceExpression, visibleDescriptors)
}
else {
storeResult(trace, referenceExpression, visibleDescriptors.single(), null, position, isQualifier)
when {
visibleDescriptors.isEmpty() -> {
val descriptor = descriptors.first() as DeclarationDescriptorWithVisibility
trace.report(Errors.INVISIBLE_REFERENCE.on(referenceExpression, descriptor, descriptor.visibility, descriptor))
}
visibleDescriptors.size > 1 -> {
trace.record(BindingContext.AMBIGUOUS_REFERENCE_TARGET, referenceExpression, visibleDescriptors)
}
else -> {
storeResult(trace, referenceExpression, visibleDescriptors.single(), null, position, isQualifier)
}
}
}
else {
@@ -155,21 +155,23 @@ internal class InlineChecker(private val descriptor: FunctionDescriptor) : CallC
val varDescriptor: CallableDescriptor?
val receiverExpression: KtExpression?
if (receiver is ExpressionReceiver) {
receiverExpression = receiver.expression
varDescriptor = getCalleeDescriptor(context, receiverExpression, true)
}
else if (receiver is ExtensionReceiver) {
val extension = receiver.declarationDescriptor
when (receiver) {
is ExpressionReceiver -> {
receiverExpression = receiver.expression
varDescriptor = getCalleeDescriptor(context, receiverExpression, true)
}
is ExtensionReceiver -> {
val extension = receiver.declarationDescriptor
varDescriptor = extension.extensionReceiverParameter
assert(varDescriptor != null) { "Extension should have receiverParameterDescriptor: " + extension }
varDescriptor = extension.extensionReceiverParameter
assert(varDescriptor != null) { "Extension should have receiverParameterDescriptor: " + extension }
receiverExpression = expression
}
else {
varDescriptor = null
receiverExpression = null
receiverExpression = expression
}
else -> {
varDescriptor = null
receiverExpression = null
}
}
if (inlinableParameters.contains(varDescriptor)) {
@@ -50,18 +50,18 @@ fun ResolvedCall<*>.hasThisOrNoDispatchReceiver(
if (resultingDescriptor.dispatchReceiverParameter == null || dispatchReceiverValue == null) return true
var dispatchReceiverDescriptor: DeclarationDescriptor? = null
if (dispatchReceiverValue is ImplicitReceiver) {
// foo() -- implicit receiver
dispatchReceiverDescriptor = dispatchReceiverValue.declarationDescriptor
}
else if (dispatchReceiverValue is ClassValueReceiver) {
dispatchReceiverDescriptor = dispatchReceiverValue.classQualifier.descriptor
}
else if (dispatchReceiverValue is ExpressionReceiver) {
val expression = KtPsiUtil.deparenthesize(dispatchReceiverValue.expression)
if (expression is KtThisExpression) {
// this.foo() -- explicit receiver
dispatchReceiverDescriptor = context.get(BindingContext.REFERENCE_TARGET, expression.instanceReference)
when (dispatchReceiverValue) {
is ImplicitReceiver -> // foo() -- implicit receiver
dispatchReceiverDescriptor = dispatchReceiverValue.declarationDescriptor
is ClassValueReceiver -> {
dispatchReceiverDescriptor = dispatchReceiverValue.classQualifier.descriptor
}
is ExpressionReceiver -> {
val expression = KtPsiUtil.deparenthesize(dispatchReceiverValue.expression)
if (expression is KtThisExpression) {
// this.foo() -- explicit receiver
dispatchReceiverDescriptor = context.get(BindingContext.REFERENCE_TARGET, expression.instanceReference)
}
}
}
@@ -283,9 +283,11 @@ internal class DelegatingDataFlowInfo private constructor(
private fun Set<KotlinType>.containsNothing() = any { KotlinBuiltIns.isNothing(it) }
private fun Set<KotlinType>.intersect(other: Set<KotlinType>) =
if (other.containsNothing()) this
else if (this.containsNothing()) other
else Sets.intersection(this, other)
when {
other.containsNothing() -> this
this.containsNothing() -> other
else -> Sets.intersection(this, other)
}
override fun or(other: DataFlowInfo): DataFlowInfo {
if (other === DataFlowInfo.EMPTY) return DataFlowInfo.EMPTY
@@ -145,14 +145,10 @@ abstract class KotlinSuppressCache {
var suppressor: Suppressor? = suppressors[annotated]
if (suppressor == null) {
val strings = getSuppressingStrings(annotated)
if (strings.isEmpty()) {
suppressor = EmptySuppressor(annotated)
}
else if (strings.size == 1) {
suppressor = SingularSuppressor(annotated, strings.iterator().next())
}
else {
suppressor = MultiSuppressor(annotated, strings)
suppressor = when {
strings.isEmpty() -> EmptySuppressor(annotated)
strings.size == 1 -> SingularSuppressor(annotated, strings.iterator().next())
else -> MultiSuppressor(annotated, strings)
}
suppressors.put(annotated, suppressor)
}
@@ -169,46 +169,48 @@ protected constructor(
val declarations = declarationProvider.getDeclarations(kindFilter, nameFilter)
val result = LinkedHashSet<DeclarationDescriptor>(declarations.size)
for (declaration in declarations) {
if (declaration is KtClassOrObject) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(classDescriptors(name))
when (declaration) {
is KtClassOrObject -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(classDescriptors(name))
}
}
}
else if (declaration is KtFunction) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedFunctions(name, location))
is KtFunction -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedFunctions(name, location))
}
}
}
else if (declaration is KtProperty) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedVariables(name, location))
is KtProperty -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedVariables(name, location))
}
}
}
else if (declaration is KtParameter) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedVariables(name, location))
is KtParameter -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedVariables(name, location))
}
}
}
else if (declaration is KtTypeAlias) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedTypeAliasDescriptors(name, location))
is KtTypeAlias -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(getContributedTypeAliasDescriptors(name, location))
}
}
}
else if (declaration is KtScript) {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(classDescriptors(name))
is KtScript -> {
val name = declaration.nameAsSafeName
if (nameFilter(name)) {
result.addAll(classDescriptors(name))
}
}
is KtDestructuringDeclaration -> {
// MultiDeclarations are not supported on global level
}
else -> throw IllegalArgumentException("Unsupported declaration kind: " + declaration)
}
else if (declaration is KtDestructuringDeclaration) {
// MultiDeclarations are not supported on global level
}
else throw IllegalArgumentException("Unsupported declaration kind: " + declaration)
}
return result.toList()
}
@@ -137,44 +137,45 @@ object LabelResolver {
val declarationsByLabel = context.scope.getDeclarationsByLabel(labelName)
val size = declarationsByLabel.size
if (size == 1) {
val declarationDescriptor = declarationsByLabel.single()
val thisReceiver = when (declarationDescriptor) {
is ClassDescriptor -> declarationDescriptor.thisAsReceiverParameter
is FunctionDescriptor -> declarationDescriptor.extensionReceiverParameter
is PropertyDescriptor -> declarationDescriptor.extensionReceiverParameter
else -> throw UnsupportedOperationException("Unsupported descriptor: " + declarationDescriptor) // TODO
}
val element = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor) ?: error("No PSI element for descriptor: " + declarationDescriptor)
context.trace.record(LABEL_TARGET, targetLabel, element)
context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor)
if (declarationDescriptor is ClassDescriptor) {
if (!DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, targetLabel, declarationDescriptor)) {
return LabeledReceiverResolutionResult.labelResolutionFailed()
when (size) {
1 -> {
val declarationDescriptor = declarationsByLabel.single()
val thisReceiver = when (declarationDescriptor) {
is ClassDescriptor -> declarationDescriptor.thisAsReceiverParameter
is FunctionDescriptor -> declarationDescriptor.extensionReceiverParameter
is PropertyDescriptor -> declarationDescriptor.extensionReceiverParameter
else -> throw UnsupportedOperationException("Unsupported descriptor: " + declarationDescriptor) // TODO
}
}
return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver)
}
else if (size == 0) {
val element = resolveNamedLabel(labelName, targetLabel, context.trace)
val declarationDescriptor = context.trace.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element]
if (declarationDescriptor is FunctionDescriptor) {
val thisReceiver = declarationDescriptor.extensionReceiverParameter
if (thisReceiver != null) {
context.trace.record(LABEL_TARGET, targetLabel, element)
context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor)
val element = DescriptorToSourceUtils.descriptorToDeclaration(declarationDescriptor)
?: error("No PSI element for descriptor: " + declarationDescriptor)
context.trace.record(LABEL_TARGET, targetLabel, element)
context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor)
if (declarationDescriptor is ClassDescriptor) {
if (!DescriptorResolver.checkHasOuterClassInstance(context.scope, context.trace, targetLabel, declarationDescriptor)) {
return LabeledReceiverResolutionResult.labelResolutionFailed()
}
}
return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver)
}
else {
context.trace.report(UNRESOLVED_REFERENCE.on(targetLabel, targetLabel))
0 -> {
val element = resolveNamedLabel(labelName, targetLabel, context.trace)
val declarationDescriptor = context.trace.bindingContext[BindingContext.DECLARATION_TO_DESCRIPTOR, element]
if (declarationDescriptor is FunctionDescriptor) {
val thisReceiver = declarationDescriptor.extensionReceiverParameter
if (thisReceiver != null) {
context.trace.record(LABEL_TARGET, targetLabel, element)
context.trace.record(REFERENCE_TARGET, referenceExpression, declarationDescriptor)
}
return LabeledReceiverResolutionResult.labelResolutionSuccess(thisReceiver)
}
else {
context.trace.report(UNRESOLVED_REFERENCE.on(targetLabel, targetLabel))
}
}
}
else {
BindingContextUtils.reportAmbiguousLabel(context.trace, targetLabel, declarationsByLabel)
else -> BindingContextUtils.reportAmbiguousLabel(context.trace, targetLabel, declarationsByLabel)
}
return LabeledReceiverResolutionResult.labelResolutionFailed()
}
@@ -38,9 +38,11 @@ object SenselessComparisonChecker {
getNullability: (DataFlowValue) -> Nullability
) {
val expr =
if (KtPsiUtil.isNullConstant(left)) right
else if (KtPsiUtil.isNullConstant(right)) left
else return
when {
KtPsiUtil.isNullConstant(left) -> right
KtPsiUtil.isNullConstant(right) -> left
else -> return
}
val type = getType(expr)
if (type == null || type.isError) return
@@ -52,10 +54,12 @@ object SenselessComparisonChecker {
val nullability = getNullability(value)
val expressionIsAlways =
if (nullability == Nullability.NULL) equality
else if (nullability == Nullability.NOT_NULL) !equality
else if (nullability == Nullability.IMPOSSIBLE) false
else return
when (nullability) {
Nullability.NULL -> equality
Nullability.NOT_NULL -> !equality
Nullability.IMPOSSIBLE -> false
else -> return
}
context.trace.report(Errors.SENSELESS_COMPARISON.on(expression, expression, expressionIsAlways))
}
@@ -632,22 +632,20 @@ class ExpressionCodegen(
val stackElement = data.peek()
if (stackElement is TryInfo) {
//noinspection ConstantConditions
genFinallyBlockOrGoto(stackElement, null, afterBreakContinueLabel, data)
}
else if (stackElement is LoopInfo) {
val loop = expression.loop
//noinspection ConstantConditions
if (loop == stackElement.loop) {
val label = if (expression is IrBreak) stackElement.breakLabel else stackElement.continueLabel
mv.fixStackAndJump(label)
mv.mark(afterBreakContinueLabel)
return
when (stackElement) {
is TryInfo -> //noinspection ConstantConditions
genFinallyBlockOrGoto(stackElement, null, afterBreakContinueLabel, data)
is LoopInfo -> {
val loop = expression.loop
//noinspection ConstantConditions
if (loop == stackElement.loop) {
val label = if (expression is IrBreak) stackElement.breakLabel else stackElement.continueLabel
mv.fixStackAndJump(label)
mv.mark(afterBreakContinueLabel)
return
}
}
}
else {
throw UnsupportedOperationException("Wrong BlockStackElement in processing stack")
else -> throw UnsupportedOperationException("Wrong BlockStackElement in processing stack")
}
data.pop()
@@ -829,14 +827,12 @@ class ExpressionCodegen(
private fun doFinallyOnReturn(afterReturnLabel: Label, data: BlockInfo) {
if (!data.isEmpty()) {
val stackElement = data.peek()
if (stackElement is TryInfo) {
genFinallyBlockOrGoto(stackElement, null, afterReturnLabel, data)
}
else if (stackElement is LoopInfo) {
when (stackElement) {
is TryInfo -> genFinallyBlockOrGoto(stackElement, null, afterReturnLabel, data)
is LoopInfo -> {
}
else {
throw UnsupportedOperationException("Wrong BlockStackElement in processing stack")
}
else -> throw UnsupportedOperationException("Wrong BlockStackElement in processing stack")
}
data.pop()
@@ -163,16 +163,18 @@ class StatementGenerator(
}
else {
val label = expression.getTargetLabel()
if (label != null) {
val labelTarget = getOrFail(BindingContext.LABEL_TARGET, label)
val labelTargetDescriptor = getOrFail(BindingContext.DECLARATION_TO_DESCRIPTOR, labelTarget)
labelTargetDescriptor as CallableDescriptor
}
else if (ExpressionTypingUtils.isFunctionLiteral(scopeOwner)) {
BindingContextUtils.getContainingFunctionSkipFunctionLiterals(scopeOwner, true).first
}
else {
scopeOwnerAsCallable()
when {
label != null -> {
val labelTarget = getOrFail(BindingContext.LABEL_TARGET, label)
val labelTargetDescriptor = getOrFail(BindingContext.DECLARATION_TO_DESCRIPTOR, labelTarget)
labelTargetDescriptor as CallableDescriptor
}
ExpressionTypingUtils.isFunctionLiteral(scopeOwner) -> {
BindingContextUtils.getContainingFunctionSkipFunctionLiterals(scopeOwner, true).first
}
else -> {
scopeOwnerAsCallable()
}
}
}
@@ -168,25 +168,27 @@ private fun <C : Candidate> createSimpleProcessor(
classValueReceiver: Boolean,
collectCandidates: CandidatesCollector
) : ScopeTowerProcessor<C> {
if (explicitReceiver is ReceiverValueWithSmartCastInfo) {
return ExplicitReceiverScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates)
}
else if (explicitReceiver is QualifierReceiver) {
val qualifierProcessor = QualifierScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates)
if (!classValueReceiver) return qualifierProcessor
// todo enum entry, object.
val classValue = explicitReceiver.classValueReceiverWithSmartCastInfo ?: return qualifierProcessor
return CompositeScopeTowerProcessor(
qualifierProcessor,
ExplicitReceiverScopeTowerProcessor(scopeTower, context, classValue, collectCandidates)
)
}
else {
assert(explicitReceiver == null) {
"Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!::class.java.simpleName})"
return when (explicitReceiver) {
is ReceiverValueWithSmartCastInfo -> {
ExplicitReceiverScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates)
}
is QualifierReceiver -> {
val qualifierProcessor = QualifierScopeTowerProcessor(scopeTower, context, explicitReceiver, collectCandidates)
if (!classValueReceiver) return qualifierProcessor
// todo enum entry, object.
val classValue = explicitReceiver.classValueReceiverWithSmartCastInfo ?: return qualifierProcessor
CompositeScopeTowerProcessor(
qualifierProcessor,
ExplicitReceiverScopeTowerProcessor(scopeTower, context, classValue, collectCandidates)
)
}
else -> {
assert(explicitReceiver == null) {
"Illegal explicit receiver: $explicitReceiver(${explicitReceiver!!::class.java.simpleName})"
}
NoExplicitReceiverScopeTowerProcessor(context, collectCandidates)
}
return NoExplicitReceiverScopeTowerProcessor(context, collectCandidates)
}
}
@@ -252,19 +252,21 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
anySupertype(baseType, { false }) {
val current = captureFromArguments(it, CaptureStatus.FOR_SUBTYPING)
if (areEqualTypeConstructors(current.constructor, constructor)) {
if (result == null) {
result = SmartList()
}
result!!.add(current)
when {
areEqualTypeConstructors(current.constructor, constructor) -> {
if (result == null) {
result = SmartList()
}
result!!.add(current)
SupertypesPolicy.None
}
else if (current.arguments.isEmpty()) {
SupertypesPolicy.LowerIfFlexible
}
else {
SupertypesPolicy.LowerIfFlexibleWithCustomSubstitutor(TypeConstructorSubstitution.create(current).buildSubstitutor())
SupertypesPolicy.None
}
current.arguments.isEmpty() -> {
SupertypesPolicy.LowerIfFlexible
}
else -> {
SupertypesPolicy.LowerIfFlexibleWithCustomSubstitutor(TypeConstructorSubstitution.create(current).buildSubstitutor())
}
}
}
@@ -208,29 +208,33 @@ internal object RuntimeTypeMapper {
fun mapPropertySignature(possiblyOverriddenProperty: PropertyDescriptor): JvmPropertySignature {
val property = DescriptorUtils.unwrapFakeOverride(possiblyOverriddenProperty).original
if (property is DeserializedPropertyDescriptor) {
val proto = property.proto
if (!proto.hasExtension(JvmProtoBuf.propertySignature)) {
// If this property has no JVM signature, it must be from built-ins
throw KotlinReflectionInternalError("Reflection on built-in Kotlin types is not yet fully supported. " +
"No metadata found for $property")
}
return JvmPropertySignature.KotlinProperty(
property, proto, proto.getExtension(JvmProtoBuf.propertySignature), property.nameResolver, property.typeTable
)
}
else if (property is JavaPropertyDescriptor) {
val element = (property.source as? JavaSourceElement)?.javaElement
when (element) {
is ReflectJavaField -> return JvmPropertySignature.JavaField(element.member)
is ReflectJavaMethod -> return JvmPropertySignature.JavaMethodProperty(
element.member,
((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member
return when (property) {
is DeserializedPropertyDescriptor -> {
val proto = property.proto
if (!proto.hasExtension(JvmProtoBuf.propertySignature)) {
// If this property has no JVM signature, it must be from built-ins
throw KotlinReflectionInternalError("Reflection on built-in Kotlin types is not yet fully supported. " +
"No metadata found for $property")
}
JvmPropertySignature.KotlinProperty(
property, proto, proto.getExtension(JvmProtoBuf.propertySignature), property.nameResolver, property.typeTable
)
else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java field $property (source = $element)")
}
is JavaPropertyDescriptor -> {
val element = (property.source as? JavaSourceElement)?.javaElement
when (element) {
is ReflectJavaField -> JvmPropertySignature.JavaField(element.member)
is ReflectJavaMethod -> JvmPropertySignature.JavaMethodProperty(
element.member,
((property.setter?.source as? JavaSourceElement)?.javaElement as? ReflectJavaMethod)?.member
)
else -> throw KotlinReflectionInternalError("Incorrect resolution sequence for Java field $property (source = $element)")
}
}
else -> {
throw KotlinReflectionInternalError("Unknown origin of $property (${property.javaClass})")
}
}
else throw KotlinReflectionInternalError("Unknown origin of $property (${property.javaClass})")
}
private fun mapIntrinsicFunctionSignature(function: FunctionDescriptor): JvmFunctionSignature? {
@@ -181,13 +181,10 @@ class SingleInstructionInterpreter(private val eval: Eval) : Interpreter<Value>(
CHECKCAST -> {
val targetType = Type.getObjectType((insn as TypeInsnNode).desc)
if (value == NULL_VALUE) {
NULL_VALUE
} else if (eval.isInstanceOf(value, targetType)) {
ObjectValue(value.obj(), targetType)
}
else {
throwEvalException(ClassCastException("${value.asmType.className} cannot be cast to ${targetType.className}"))
when {
value == NULL_VALUE -> NULL_VALUE
eval.isInstanceOf(value, targetType) -> ObjectValue(value.obj(), targetType)
else -> throwEvalException(ClassCastException("${value.asmType.className} cannot be cast to ${targetType.className}"))
}
}
@@ -212,14 +212,13 @@ class OptimizedImportsBuilder(
val explicitImportPath = ImportPath(fqName, false)
val starImportPath = ImportPath(fqName.parent(), true)
val importPaths = file.importDirectives.map { it.importPath }
if (explicitImportPath in importPaths) {
importRules.add(ImportRule.Add(explicitImportPath))
}
else if (starImportPath in importPaths) {
importRules.add(ImportRule.Add(starImportPath))
}
else { // there is no import for this descriptor in the original import list, so do not allow to import it by star-import
importRules.add(ImportRule.DoNotAdd(starImportPath))
when {
explicitImportPath in importPaths ->
importRules.add(ImportRule.Add(explicitImportPath))
starImportPath in importPaths ->
importRules.add(ImportRule.Add(starImportPath))
else -> // there is no import for this descriptor in the original import list, so do not allow to import it by star-import
importRules.add(ImportRule.DoNotAdd(starImportPath))
}
}
@@ -277,14 +276,10 @@ class OptimizedImportsBuilder(
val iterator1 = tower1.iterator()
val iterator2 = tower2.iterator()
while (true) {
if (!iterator1.hasNext()) {
return !iterator2.hasNext()
}
else if (!iterator2.hasNext()) {
return false
}
else {
if (!areTargetsEqual(iterator1.next(), iterator2.next())) return false
when {
!iterator1.hasNext() -> return !iterator2.hasNext()
!iterator2.hasNext() -> return false
else -> if (!areTargetsEqual(iterator1.next(), iterator2.next())) return false
}
}
}
@@ -271,18 +271,18 @@ class PartialBodyResolveFilter(
val left = condition.left ?: return emptyResult
val right = condition.right ?: return emptyResult
fun smartCastInEq(): Pair<Set<SmartCastName>, Set<SmartCastName>> {
if (left.isNullLiteral()) {
return Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet())
fun smartCastInEq(): Pair<Set<SmartCastName>, Set<SmartCastName>> = when {
left.isNullLiteral() -> {
Pair(setOf(), right.smartCastExpressionName().singletonOrEmptySet())
}
else if (right.isNullLiteral()) {
return Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet())
right.isNullLiteral() -> {
Pair(setOf(), left.smartCastExpressionName().singletonOrEmptySet())
}
else {
else -> {
val leftName = left.smartCastExpressionName()
val rightName = right.smartCastExpressionName()
val names = listOfNotNull(leftName, rightName).toSet()
return Pair(names, setOf())
Pair(names, setOf())
}
}
@@ -217,26 +217,26 @@ object IDELightClassContexts {
}
for (declaration in file.declarations) {
if (declaration is KtFunction) {
val name = declaration.nameAsSafeName
val functions = packageDescriptor.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE)
for (descriptor in functions) {
ForceResolveUtil.forceResolveAllContents(descriptor)
when (declaration) {
is KtFunction -> {
val name = declaration.nameAsSafeName
val functions = packageDescriptor.memberScope.getContributedFunctions(name, NoLookupLocation.FROM_IDE)
for (descriptor in functions) {
ForceResolveUtil.forceResolveAllContents(descriptor)
}
}
}
else if (declaration is KtProperty) {
val name = declaration.nameAsSafeName
val properties = packageDescriptor.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE)
for (descriptor in properties) {
ForceResolveUtil.forceResolveAllContents(descriptor)
is KtProperty -> {
val name = declaration.nameAsSafeName
val properties = packageDescriptor.memberScope.getContributedVariables(name, NoLookupLocation.FROM_IDE)
for (descriptor in properties) {
ForceResolveUtil.forceResolveAllContents(descriptor)
}
}
}
else if (declaration is KtClassOrObject || declaration is KtTypeAlias || declaration is KtDestructuringDeclaration) {
// Do nothing: we are not interested in classes or type aliases,
// and all destructuring declarations are erroneous at top level
}
else {
LOG.error("Unsupported declaration kind: " + declaration + " in file " + file.name + "\n" + file.text)
is KtClassOrObject, is KtTypeAlias, is KtDestructuringDeclaration -> {
// Do nothing: we are not interested in classes or type aliases,
// and all destructuring declarations are erroneous at top level
}
else -> LOG.error("Unsupported declaration kind: " + declaration + " in file " + file.name + "\n" + file.text)
}
}
@@ -101,11 +101,18 @@ object UsageTypeUtils {
CLASS_CAST_TO
with(refExpr.getNonStrictParentOfType<KtDotQualifiedExpression>()) {
if (this == null) false
else if (receiverExpression == refExpr) true
else
selectorExpression == refExpr
&& getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { receiverExpression } != null
when {
this == null -> {
false
}
receiverExpression == refExpr -> {
true
}
else -> {
selectorExpression == refExpr
&& getParentOfTypeAndBranch<KtDotQualifiedExpression>(strict = true) { receiverExpression } != null
}
}
} ->
CLASS_OBJECT_ACCESS
@@ -49,12 +49,11 @@ object CommonLibraryDetectionUtil {
var platform: TargetPlatform? = null
VfsUtilCore.processFilesRecursively(root) { file ->
if (file.fileType == JavaClassFileType.INSTANCE)
platform = JvmPlatform
else if (isKotlinMetadataFile(file))
platform = TargetPlatform.Default
else if (KotlinJavaScriptLibraryDetectionUtil.isJsFileWithMetadata(file))
platform = JsPlatform
when {
file.fileType == JavaClassFileType.INSTANCE -> platform = JvmPlatform
isKotlinMetadataFile(file) -> platform = TargetPlatform.Default
KotlinJavaScriptLibraryDetectionUtil.isJsFileWithMetadata(file) -> platform = JsPlatform
}
platform == null
}
@@ -129,16 +129,12 @@ class KotlinSuppressIntentionAction private constructor(
val args = entry.valueArgumentList
val psiFactory = KtPsiFactory(entry)
val newArgList = psiFactory.createCallArguments("($id)")
if (args == null) {
// new argument list
entry.addAfter(newArgList, entry.lastChild)
}
else if (args.arguments.isEmpty()) {
// replace '()' with a new argument list
args.replace(newArgList)
}
else {
args.addArgument(newArgList.arguments[0])
when {
args == null -> // new argument list
entry.addAfter(newArgList, entry.lastChild)
args.arguments.isEmpty() -> // replace '()' with a new argument list
args.replace(newArgList)
else -> args.addArgument(newArgList.arguments[0])
}
}
@@ -151,14 +151,10 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName:
val file = ref.containingKtFile
var result: Result = Result.NothingFound
val filePackage = file.packageFqName.asString()
if (filePackage == targetPackage) {
result = result.changeTo(Result.Found)
}
else if (filePackage in conflictingPackages) {
result = result.changeTo(Result.FoundOther)
}
else if (filePackage in packagesWithTypeAliases) {
return UNSURE
when (filePackage) {
targetPackage -> result = result.changeTo(Result.Found)
in conflictingPackages -> result = result.changeTo(Result.FoundOther)
in packagesWithTypeAliases -> return UNSURE
}
for (importPath in file.getDefaultImports()) {
@@ -202,14 +198,10 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName:
}
}
else {
if (qName?.asString() == targetPackage) {
return result.changeTo(Result.Found)
}
else if (qName?.asString() in conflictingPackages) {
return result.changeTo(Result.FoundOther)
}
else if (qName?.asString() in packagesWithTypeAliases) {
return Result.Ambiguity
when {
qName?.asString() == targetPackage -> return result.changeTo(Result.Found)
qName?.asString() in conflictingPackages -> return result.changeTo(Result.FoundOther)
qName?.asString() in packagesWithTypeAliases -> return Result.Ambiguity
}
}
return result
@@ -276,12 +276,11 @@ class BasicLookupElementFactory(
appendTailText(" for $receiverPresentation")
val container = descriptor.containingDeclaration
val containerPresentation = if (container is ClassDescriptor)
DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
else if (container is PackageFragmentDescriptor)
container.fqName.toString()
else
null
val containerPresentation = when (container) {
is ClassDescriptor -> DescriptorUtils.getFqNameFromTopLevelClass(container).toString()
is PackageFragmentDescriptor -> container.fqName.toString()
else -> null
}
if (containerPresentation != null) {
appendTailText(" in $containerPresentation")
}
@@ -96,32 +96,29 @@ class CompletionBindingContextProvider(project: Project) {
val psiElementsBeforeAndAfter = modificationScope?.let { collectPsiElementsBeforeAndAfter(modificationScope, inStatement) }
val prevCompletionData = prevCompletionDataCache.value.data
if (prevCompletionData == null) {
log("No up-to-date data from previous completion\n")
}
else if (block != prevCompletionData.block) {
log("Not in the same block\n")
}
else if (prevStatement != prevCompletionData.prevStatement) {
log("Previous statement is not the same\n")
}
else if (psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter) {
log("PSI-tree has changed inside current scope\n")
}
else if (inStatement.isTooComplex()) {
log("Current statement is too complex to use optimization\n")
}
else {
log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n")
LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"")
when {
prevCompletionData == null ->
log("No up-to-date data from previous completion\n")
block != prevCompletionData.block ->
log("Not in the same block\n")
prevStatement != prevCompletionData.prevStatement ->
log("Previous statement is not the same\n")
psiElementsBeforeAndAfter != prevCompletionData.psiElementsBeforeAndAfter ->
log("PSI-tree has changed inside current scope\n")
inStatement.isTooComplex() ->
log("Current statement is too complex to use optimization\n")
else -> {
log("Statement position is the same - analyzing only one statement:\n${inStatement.text.prependIndent(" ")}\n")
LOG.debug("Reusing data from completion of \"${prevCompletionData.debugText}\"")
//TODO: expected type?
val statementContext = inStatement.analyzeInContext(scope = prevCompletionData.statementResolutionScope,
contextExpression = block,
dataFlowInfo = prevCompletionData.statementDataFlowInfo,
isStatement = true)
// we do not update prevCompletionDataCache because the same data should work
return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext))
//TODO: expected type?
val statementContext = inStatement.analyzeInContext(scope = prevCompletionData.statementResolutionScope,
contextExpression = block,
dataFlowInfo = prevCompletionData.statementDataFlowInfo,
isStatement = true)
// we do not update prevCompletionDataCache because the same data should work
return CompositeBindingContext.create(listOf(statementContext, prevCompletionData.bindingContext))
}
}
val bindingContext = resolutionFacade.analyze(position.parentsWithSelf.firstIsInstance<KtElement>(), BodyResolveMode.PARTIAL_FOR_COMPLETION)
@@ -381,20 +381,17 @@ class LookupElementFactory(
return CallableWeight(bestWeight, receiverIndexToUse)
}
private fun CallableDescriptor.callableWeightForReceiverType(receiverType: KotlinType, receiverParameterType: KotlinType): CallableWeightEnum? {
if (TypeUtils.equalTypes(receiverType, receiverParameterType)) {
return when {
isExtensionForTypeParameter() -> CallableWeightEnum.typeParameterExtension
isExtension -> CallableWeightEnum.thisTypeExtension
else -> CallableWeightEnum.thisClassMember
}
}
else if (receiverType.isSubtypeOf(receiverParameterType)) {
return if (isExtension) CallableWeightEnum.baseTypeExtension else CallableWeightEnum.baseClassMember
}
else {
return null
private fun CallableDescriptor.callableWeightForReceiverType(
receiverType: KotlinType,
receiverParameterType: KotlinType
): CallableWeightEnum? = when {
TypeUtils.equalTypes(receiverType, receiverParameterType) -> when {
isExtensionForTypeParameter() -> CallableWeightEnum.typeParameterExtension
isExtension -> CallableWeightEnum.thisTypeExtension
else -> CallableWeightEnum.thisClassMember
}
receiverType.isSubtypeOf(receiverParameterType) -> if (isExtension) CallableWeightEnum.baseTypeExtension else CallableWeightEnum.baseClassMember
else -> null
}
private fun CallableDescriptor.isExtensionForTypeParameter(): Boolean {
@@ -343,12 +343,11 @@ class ExpectedInfos(
}
val tail = if (argumentName == null) {
if (parameter == parameters.last())
rparenthTail
else if (parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter))
Tail.COMMA
else
null
when {
parameter == parameters.last() -> rparenthTail
parameters.dropWhile { it != parameter }.drop(1).any(::needCommaForParameter) -> Tail.COMMA
else -> null
}
}
else {
namedArgumentTail(argumentToParameter, argumentName, descriptor)
@@ -404,12 +403,11 @@ class ExpectedInfos(
private fun namedArgumentTail(argumentToParameter: Map<ValueArgument, ValueParameterDescriptor>, argumentName: Name, descriptor: FunctionDescriptor): Tail? {
val usedParameterNames = (argumentToParameter.values.map { it.name } + listOf(argumentName)).toSet()
val notUsedParameters = descriptor.valueParameters.filter { it.name !in usedParameterNames }
return if (notUsedParameters.isEmpty())
Tail.RPARENTH // named arguments no supported for []
else if (notUsedParameters.all { it.hasDefaultValue() })
null
else
Tail.COMMA
return when {
notUsedParameters.isEmpty() -> Tail.RPARENTH // named arguments no supported for []
notUsedParameters.all { it.hasDefaultValue() } -> null
else -> Tail.COMMA
}
}
private fun calculateForEqAndAssignment(expressionWithType: KtExpression): Collection<ExpectedInfo>? {
@@ -35,15 +35,14 @@ class ImportableFqNameClassifier(private val file: KtFile) {
for (import in file.importDirectives) {
val importPath = import.importPath ?: continue
val fqName = importPath.fqName
if (importPath.isAllUnder) {
allUnderImports.add(fqName)
}
else if (!importPath.hasAlias()) {
preciseImports.add(fqName)
preciseImportPackages.add(fqName.parent())
} else {
excludedImports.add(fqName)
// TODO: support aliased imports in completion
when {
importPath.isAllUnder -> allUnderImports.add(fqName)
!importPath.hasAlias() -> {
preciseImports.add(fqName)
preciseImportPackages.add(fqName.parent())
}
else -> excludedImports.add(fqName)
// TODO: support aliased imports in completion
}
}
}
@@ -174,79 +174,45 @@ object KotlinNameSuggester {
val typeChecker = KotlinTypeChecker.DEFAULT
if (ErrorUtils.containsErrorType(type)) return
if (typeChecker.equalTypes(builtIns.booleanType, type)) {
addName("b", validator)
}
else if (typeChecker.equalTypes(builtIns.intType, type)) {
addName("i", validator)
}
else if (typeChecker.equalTypes(builtIns.byteType, type)) {
addName("byte", validator)
}
else if (typeChecker.equalTypes(builtIns.longType, type)) {
addName("l", validator)
}
else if (typeChecker.equalTypes(builtIns.floatType, type)) {
addName("fl", validator)
}
else if (typeChecker.equalTypes(builtIns.doubleType, type)) {
addName("d", validator)
}
else if (typeChecker.equalTypes(builtIns.shortType, type)) {
addName("sh", validator)
}
else if (typeChecker.equalTypes(builtIns.charType, type)) {
addName("c", validator)
}
else if (typeChecker.equalTypes(builtIns.stringType, type)) {
addName("s", validator)
}
else if (KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type)) {
val elementType = builtIns.getArrayElementType(type)
if (typeChecker.equalTypes(builtIns.booleanType, elementType)) {
addName("booleans", validator)
}
else if (typeChecker.equalTypes(builtIns.intType, elementType)) {
addName("ints", validator)
}
else if (typeChecker.equalTypes(builtIns.byteType, elementType)) {
addName("bytes", validator)
}
else if (typeChecker.equalTypes(builtIns.longType, elementType)) {
addName("longs", validator)
}
else if (typeChecker.equalTypes(builtIns.floatType, elementType)) {
addName("floats", validator)
}
else if (typeChecker.equalTypes(builtIns.doubleType, elementType)) {
addName("doubles", validator)
}
else if (typeChecker.equalTypes(builtIns.shortType, elementType)) {
addName("shorts", validator)
}
else if (typeChecker.equalTypes(builtIns.charType, elementType)) {
addName("chars", validator)
}
else if (typeChecker.equalTypes(builtIns.stringType, elementType)) {
addName("strings", validator)
}
else {
val classDescriptor = TypeUtils.getClassDescriptor(elementType)
if (classDescriptor != null) {
val className = classDescriptor.name
addName("arrayOf" + StringUtil.capitalize(className.asString()) + "s", validator)
when {
typeChecker.equalTypes(builtIns.booleanType, type) -> addName("b", validator)
typeChecker.equalTypes(builtIns.intType, type) -> addName("i", validator)
typeChecker.equalTypes(builtIns.byteType, type) -> addName("byte", validator)
typeChecker.equalTypes(builtIns.longType, type) -> addName("l", validator)
typeChecker.equalTypes(builtIns.floatType, type) -> addName("fl", validator)
typeChecker.equalTypes(builtIns.doubleType, type) -> addName("d", validator)
typeChecker.equalTypes(builtIns.shortType, type) -> addName("sh", validator)
typeChecker.equalTypes(builtIns.charType, type) -> addName("c", validator)
typeChecker.equalTypes(builtIns.stringType, type) -> addName("s", validator)
KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> {
val elementType = builtIns.getArrayElementType(type)
when {
typeChecker.equalTypes(builtIns.booleanType, elementType) -> addName("booleans", validator)
typeChecker.equalTypes(builtIns.intType, elementType) -> addName("ints", validator)
typeChecker.equalTypes(builtIns.byteType, elementType) -> addName("bytes", validator)
typeChecker.equalTypes(builtIns.longType, elementType) -> addName("longs", validator)
typeChecker.equalTypes(builtIns.floatType, elementType) -> addName("floats", validator)
typeChecker.equalTypes(builtIns.doubleType, elementType) -> addName("doubles", validator)
typeChecker.equalTypes(builtIns.shortType, elementType) -> addName("shorts", validator)
typeChecker.equalTypes(builtIns.charType, elementType) -> addName("chars", validator)
typeChecker.equalTypes(builtIns.stringType, elementType) -> addName("strings", validator)
else -> {
val classDescriptor = TypeUtils.getClassDescriptor(elementType)
if (classDescriptor != null) {
val className = classDescriptor.name
addName("arrayOf" + StringUtil.capitalize(className.asString()) + "s", validator)
}
}
}
}
}
else if (type.isFunctionType) {
addName("function", validator)
}
else {
val descriptor = type.constructor.declarationDescriptor
if (descriptor != null) {
val className = descriptor.name
if (!className.isSpecial) {
addCamelNames(className.asString(), validator)
type.isFunctionType -> addName("function", validator)
else -> {
val descriptor = type.constructor.declarationDescriptor
if (descriptor != null) {
val className = descriptor.name
if (!className.isSpecial) {
addCamelNames(className.asString(), validator)
}
}
}
}
@@ -204,25 +204,24 @@ fun KtModifierListOwner.setVisibility(visibilityModifier: KtModifierKeywordToken
}
fun KtDeclaration.implicitVisibility(): KtModifierKeywordToken? =
if (this is KtConstructor<*>) {
val klass = getContainingClassOrObject()
if (klass is KtClass && (klass.isEnum() || klass.isSealed())) KtTokens.PRIVATE_KEYWORD
else KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
else if (hasModifier(KtTokens.OVERRIDE_KEYWORD)) {
(resolveToDescriptor(BodyResolveMode.PARTIAL) as? CallableMemberDescriptor)
?.overriddenDescriptors
?.let { OverridingUtil.findMaxVisibility(it) }
?.toKeywordToken()
}
else {
KtTokens.DEFAULT_VISIBILITY_KEYWORD
when {
this is KtConstructor<*> -> {
val klass = getContainingClassOrObject()
if (klass is KtClass && (klass.isEnum() || klass.isSealed())) KtTokens.PRIVATE_KEYWORD
else KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
hasModifier(KtTokens.OVERRIDE_KEYWORD) -> {
(resolveToDescriptor(BodyResolveMode.PARTIAL) as? CallableMemberDescriptor)
?.overriddenDescriptors
?.let { OverridingUtil.findMaxVisibility(it) }
?.toKeywordToken()
}
else -> {
KtTokens.DEFAULT_VISIBILITY_KEYWORD
}
}
fun KtModifierListOwner.canBePrivate(): Boolean {
if (modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) ?: false) return false
return true
}
fun KtModifierListOwner.canBePrivate() = modifierList?.hasModifier(KtTokens.ABSTRACT_KEYWORD) != true
fun KtModifierListOwner.canBeProtected(): Boolean {
val parent = this.parent
@@ -75,12 +75,12 @@ class MavenPluginSourcesMoveToExecutionIntention : PsiElementBaseIntentionAction
val domElement = DomManager.getDomManager(project).getDomElement(tag) as? GenericDomValue<*> ?: return
val dir = domElement.rawText ?: return
val relevantExecutions = if (domElement.getParentOfType(MavenDomBuild::class.java, false)?.sourceDirectory === domElement) {
pomFile.findKotlinExecutions(PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.Js)
} else if (domElement.getParentOfType(MavenDomBuild::class.java, false)?.testSourceDirectory === domElement) {
pomFile.findKotlinExecutions(PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.TestJs)
} else {
emptyList()
val relevantExecutions = when {
domElement.getParentOfType(MavenDomBuild::class.java, false)?.sourceDirectory === domElement ->
pomFile.findKotlinExecutions(PomFile.KotlinGoals.Compile, PomFile.KotlinGoals.Js)
domElement.getParentOfType(MavenDomBuild::class.java, false)?.testSourceDirectory === domElement ->
pomFile.findKotlinExecutions(PomFile.KotlinGoals.TestCompile, PomFile.KotlinGoals.TestJs)
else -> emptyList()
}
if (relevantExecutions.isNotEmpty()) {
@@ -263,19 +263,11 @@ abstract class KotlinWithLibraryConfigurator internal constructor() : KotlinProj
targetFile: File,
jarType: OrderRootType,
useBundled: Boolean
): FileState {
if (targetFile.exists()) {
return FileState.EXISTS
}
else if (getPathFromLibrary(project, jarType) != null) {
return FileState.COPY
}
else if (useBundled) {
return FileState.DO_NOT_COPY
}
else {
return FileState.COPY
}
): FileState = when {
targetFile.exists() -> FileState.EXISTS
getPathFromLibrary(project, jarType) != null -> FileState.COPY
useBundled -> FileState.DO_NOT_COPY
else -> FileState.COPY
}
private fun getPathToCopyFileTo(
@@ -120,26 +120,27 @@ class DebuggerClassNameProvider(
}
is KtClassOrObject -> {
val enclosingElementForLocal = runReadAction { KtPsiUtil.getEnclosingElementForLocalDeclaration(element) }
if (enclosingElementForLocal != null) { // A local class
getOuterClassNamesForElement(enclosingElementForLocal)
}
else if (runReadAction { element.isObjectLiteral() }) {
getOuterClassNamesForElement(element.relevantParentInReadAction)
}
else { // Guaranteed to be non-local class or object
element.readAction {
if (it is KtClass && runReadAction { it.isInterface() }) {
val name = getNameForNonLocalClass(it)
when {
enclosingElementForLocal != null ->
// A local class
getOuterClassNamesForElement(enclosingElementForLocal)
runReadAction { element.isObjectLiteral() } ->
getOuterClassNamesForElement(element.relevantParentInReadAction)
else ->
// Guaranteed to be non-local class or object
element.readAction {
if (it is KtClass && runReadAction { it.isInterface() }) {
val name = getNameForNonLocalClass(it)
if (name != null)
Cached(listOf(name, name + JvmAbi.DEFAULT_IMPLS_SUFFIX))
else
ComputedClassNames.EMPTY
if (name != null)
Cached(listOf(name, name + JvmAbi.DEFAULT_IMPLS_SUFFIX))
else
ComputedClassNames.EMPTY
}
else {
getNameForNonLocalClass(it)?.let { ComputedClassNames.Cached(it) } ?: ComputedClassNames.EMPTY
}
}
else {
getNameForNonLocalClass(it)?.let { ComputedClassNames.Cached(it) } ?: ComputedClassNames.EMPTY
}
}
}
}
is KtProperty -> {
@@ -300,14 +300,13 @@ class KotlinEvaluator(val codeFragment: KtCodeFragment, val sourcePosition: Sour
val jdiValue = when (this) {
is ValueReturned -> result
is ExceptionThrown -> {
if (this.kind == ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE) {
exception(InvocationException(this.exception.value as ObjectReference))
}
else if (this.kind == ExceptionThrown.ExceptionKind.BROKEN_CODE) {
throw exception.value as Throwable
}
else {
exception(exception.toString())
when {
this.kind == ExceptionThrown.ExceptionKind.FROM_EVALUATED_CODE ->
exception(InvocationException(this.exception.value as ObjectReference))
this.kind == ExceptionThrown.ExceptionKind.BROKEN_CODE ->
throw exception.value as Throwable
else ->
exception(exception.toString())
}
}
is AbnormalTermination -> exception(message)
@@ -187,33 +187,33 @@ private class TemplateTokenSequence(private val inputString: String) : Sequence<
val wrapped = '"' + input.substring(from) + '"'
val lexer = KotlinLexer().apply { start(wrapped) }.apply { advance() }
if (lexer.tokenType == KtTokens.SHORT_TEMPLATE_ENTRY_START) {
lexer.advance()
return if (lexer.tokenType == KtTokens.IDENTIFIER) {
from + lexer.tokenEnd - 1
}
else {
-1
}
}
else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) {
var depth = 0
while (lexer.tokenType != null) {
if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) {
depth++
}
else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) {
depth--
if (depth == 0) {
return from + lexer.currentPosition.offset
}
}
when (lexer.tokenType) {
KtTokens.SHORT_TEMPLATE_ENTRY_START -> {
lexer.advance()
return if (lexer.tokenType == KtTokens.IDENTIFIER) {
from + lexer.tokenEnd - 1
}
else {
-1
}
}
return -1
}
else {
return -1
KtTokens.LONG_TEMPLATE_ENTRY_START -> {
var depth = 0
while (lexer.tokenType != null) {
if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_START) {
depth++
}
else if (lexer.tokenType == KtTokens.LONG_TEMPLATE_ENTRY_END) {
depth--
if (depth == 0) {
return from + lexer.currentPosition.offset
}
}
lexer.advance()
}
return -1
}
else -> return -1
}
}
@@ -40,32 +40,34 @@ class KotlinRainbowVisitor : RainbowVisitor() {
override fun clone() = KotlinRainbowVisitor()
override fun visit(element: PsiElement) {
if (element.isRainbowDeclaration()) {
val rainbowElement = (element as KtNamedDeclaration).nameIdentifier ?: return
addRainbowHighlight(element, rainbowElement)
}
else if (element is KtSimpleNameExpression) {
val qualifiedExpression = PsiTreeUtil.getParentOfType(element, KtQualifiedExpression::class.java, true,
KtLambdaExpression::class.java, KtValueArgumentList::class.java)
if (qualifiedExpression?.selectorExpression?.isAncestor(element) == true) return
when {
element.isRainbowDeclaration() -> {
val rainbowElement = (element as KtNamedDeclaration).nameIdentifier ?: return
addRainbowHighlight(element, rainbowElement)
}
element is KtSimpleNameExpression -> {
val qualifiedExpression = PsiTreeUtil.getParentOfType(element, KtQualifiedExpression::class.java, true,
KtLambdaExpression::class.java, KtValueArgumentList::class.java)
if (qualifiedExpression?.selectorExpression?.isAncestor(element) == true) return
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
val targets = element.getReferenceTargets(bindingContext)
val targetVariable = targets.firstIsInstanceOrNull<VariableDescriptor>()
if (targetVariable != null) {
val targetElement = DescriptorToSourceUtils.getSourceFromDescriptor(targetVariable)
if (targetElement.isRainbowDeclaration()) {
addRainbowHighlight(targetElement!!, element)
}
else if (targetElement == null && element.getReferencedName() == "it") {
addRainbowHighlight(element, element)
val bindingContext = element.analyze(BodyResolveMode.PARTIAL_WITH_DIAGNOSTICS)
val targets = element.getReferenceTargets(bindingContext)
val targetVariable = targets.firstIsInstanceOrNull<VariableDescriptor>()
if (targetVariable != null) {
val targetElement = DescriptorToSourceUtils.getSourceFromDescriptor(targetVariable)
if (targetElement.isRainbowDeclaration()) {
addRainbowHighlight(targetElement!!, element)
}
else if (targetElement == null && element.getReferencedName() == "it") {
addRainbowHighlight(element, element)
}
}
}
}
else if (element is KDocName) {
val target = element.reference?.resolve() ?: return
if (target.isRainbowDeclaration()) {
addRainbowHighlight(target, element, KDOC_LINK)
element is KDocName -> {
val target = element.reference?.resolve() ?: return
if (target.isRainbowDeclaration()) {
addRainbowHighlight(target, element, KDOC_LINK)
}
}
}
}
@@ -95,14 +95,10 @@ class KotlinUnusedImportInspection : AbstractKotlinInspection() {
val importPath = directive.importPath ?: continue
if (importPath.alias != null) continue // highlighting of unused alias imports not supported yet
val isUsed = if (!importPaths.add(importPath)) {
false
}
else if (importPath.isAllUnder) {
importPath.fqName in parentFqNames
}
else {
importPath.fqName in fqNames
val isUsed = when {
!importPaths.add(importPath) -> false
importPath.isAllUnder -> importPath.fqName in parentFqNames
else -> importPath.fqName in fqNames
}
if (!isUsed) {
@@ -72,7 +72,11 @@ class NullableBooleanElvisInspection : AbstractKotlinInspection(), CleanupLocalI
val constPart = element.right as? KtConstantExpression ?: return
val exprPart = element.left ?: return
val constValue = if (KtPsiUtil.isTrueConstant(constPart)) true else if (KtPsiUtil.isFalseConstant(constPart)) false else return
val constValue = when {
KtPsiUtil.isTrueConstant(constPart) -> true
KtPsiUtil.isFalseConstant(constPart) -> false
else -> return
}
val equalityCheckExpression = element.replaced(KtPsiFactory(constPart).buildExpression {
appendExpression(exprPart)
appendFixedText(if (constValue) " != false" else " == true")
@@ -47,7 +47,11 @@ class NullableBooleanEqualityCheckToElvisIntention : SelfTargetingIntention<KtBi
val constPart = element.left as? KtConstantExpression ?:
element.right as? KtConstantExpression ?: return
val exprPart = (if (element.right == constPart) element.left else element.right) ?: return
val constValue = if (KtPsiUtil.isTrueConstant(constPart)) true else if (KtPsiUtil.isFalseConstant(constPart)) false else return
val constValue = when {
KtPsiUtil.isTrueConstant(constPart) -> true
KtPsiUtil.isFalseConstant(constPart) -> false
else -> return
}
val factory = KtPsiFactory(constPart)
val elvis = factory.createExpressionByPattern("$0 ?: ${!constValue}", exprPart)
@@ -168,14 +168,11 @@ data class IfThenToSelectData(
if (condition is KtIsExpression) newReceiver!! else baseClause
}
else {
if (condition is KtIsExpression) {
(baseClause as KtDotQualifiedExpression).replaceFirstReceiver(
when {
condition is KtIsExpression -> (baseClause as KtDotQualifiedExpression).replaceFirstReceiver(
factory, newReceiver!!, safeAccess = true)
}
else if (hasImplicitReceiver()) {
factory.createExpressionByPattern("this?.$0", baseClause).insertSafeCalls(factory)
} else {
baseClause.insertSafeCalls(factory)
hasImplicitReceiver() -> factory.createExpressionByPattern("this?.$0", baseClause).insertSafeCalls(factory)
else -> baseClause.insertSafeCalls(factory)
}
}
}
@@ -116,14 +116,10 @@ class MaxOrMinTransformation(
val functionName = if (isMax) "max" else "min"
val arguments = assignment.right.extractStaticFunctionCallArguments("java.lang.Math." + functionName) ?: return null
if (arguments.size != 2) return null
val value = if (arguments[0].isVariableReference(variableInitialization.variable)) {
arguments[1] ?: return null
}
else if (arguments[1].isVariableReference(variableInitialization.variable)) {
arguments[0] ?: return null
}
else {
return null
val value = when {
arguments[0].isVariableReference(variableInitialization.variable) -> arguments[1] ?: return null
arguments[1].isVariableReference(variableInitialization.variable) -> arguments[0] ?: return null
else -> return null
}
val mapTransformation = if (value.isVariableReference(state.inputVariable))
@@ -148,14 +144,10 @@ class MaxOrMinTransformation(
if (comparison !in setOf(KtTokens.GT, KtTokens.LT, KtTokens.GTEQ, KtTokens.LTEQ)) return null
val left = condition.left as? KtNameReferenceExpression ?: return null
val right = condition.right as? KtNameReferenceExpression ?: return null
val otherHand = if (left.isVariableReference(inputVariable)) {
right
}
else if (right.isVariableReference(inputVariable)) {
left
}
else {
return null
val otherHand = when {
left.isVariableReference(inputVariable) -> right
right.isVariableReference(inputVariable) -> left
else -> return null
}
val variableInitialization = otherHand.findVariableInitializationBeforeLoop(loop, checkNoOtherUsagesInLoop = false)
@@ -163,14 +155,10 @@ class MaxOrMinTransformation(
if (!assignmentTarget.isVariableReference(variableInitialization.variable)) return null
val valueToBeVariable = if (valueAssignedIfTrue.isVariableReference(inputVariable)) {
valueAssignedIfFalse
}
else if (valueAssignedIfFalse.isVariableReference(inputVariable)) {
valueAssignedIfTrue
}
else {
return null
val valueToBeVariable = when {
valueAssignedIfTrue.isVariableReference(inputVariable) -> valueAssignedIfFalse
valueAssignedIfFalse.isVariableReference(inputVariable) -> valueAssignedIfTrue
else -> return null
}
if (valueToBeVariable != null && !valueToBeVariable.isVariableReference(variableInitialization.variable)) return null
@@ -54,14 +54,10 @@ open class KotlinDefaultNamedDeclarationPresentation(private val declaration: Kt
qualifiedContainer
}
val receiverTypeRef = (declaration as? KtCallableDeclaration)?.receiverTypeReference
if (receiverTypeRef != null) {
return "(for " + receiverTypeRef.text + " in " + containerText + ")"
}
else if (parent is KtFile) {
return "(" + containerText + ")"
}
else {
return "(in " + containerText + ")"
return when {
receiverTypeRef != null -> "(for " + receiverTypeRef.text + " in " + containerText + ")"
parent is KtFile -> "($containerText)"
else -> "(in $containerText)"
}
}
@@ -63,15 +63,13 @@ abstract class ChangeFunctionSignatureFix(
val argumentName = argument.getArgumentName()
val expression = argument.getArgumentExpression()
return if (argumentName != null) {
KotlinNameSuggester.suggestNameByName(argumentName.asName.asString(), validator)
}
else if (expression != null) {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first()
}
else {
KotlinNameSuggester.suggestNameByName("param", validator)
return when {
argumentName != null -> KotlinNameSuggester.suggestNameByName(argumentName.asName.asString(), validator)
expression != null -> {
val bindingContext = expression.analyze(BodyResolveMode.PARTIAL)
KotlinNameSuggester.suggestNamesByExpressionAndType(expression, null, bindingContext, validator, "param").first()
}
else -> KotlinNameSuggester.suggestNameByName("param", validator)
}
}
@@ -100,16 +100,20 @@ class ReplaceInfixOrOperatorCallFix(
val parent = expression.parent
return when (parent) {
is KtBinaryExpression -> {
if (parent.left == null || parent.right == null) null
else if (parent.operationToken == KtTokens.EQ) null
else if (parent.operationToken in OperatorConventions.COMPARISON_OPERATIONS) null
else ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType())
when {
parent.left == null || parent.right == null -> null
parent.operationToken == KtTokens.EQ -> null
parent.operationToken in OperatorConventions.COMPARISON_OPERATIONS -> null
else -> ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType())
}
}
is KtCallExpression -> {
if (parent.calleeExpression == null) null
else if (parent.parent is KtQualifiedExpression) null
else if (parent.getResolvedCall(parent.analyze())?.getImplicitReceiverValue() != null) null
else ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType())
when {
parent.calleeExpression == null -> null
parent.parent is KtQualifiedExpression -> null
parent.getResolvedCall(parent.analyze())?.getImplicitReceiverValue() != null -> null
else -> ReplaceInfixOrOperatorCallFix(parent, parent.shouldHaveNotNullType())
}
}
else -> null
}
@@ -41,14 +41,10 @@ class SpecifyTypeExplicitlyFix : PsiElementBaseIntentionAction() {
override fun isAvailable(project: Project, editor: Editor, element: PsiElement): Boolean {
val declaration = declarationByElement(element)
if (declaration is KtProperty) {
text = "Specify type explicitly"
}
else if (declaration is KtNamedFunction) {
text = "Specify return type explicitly"
}
else {
return false
text = when (declaration) {
is KtProperty -> "Specify type explicitly"
is KtNamedFunction -> "Specify return type explicitly"
else -> return false
}
return !SpecifyTypeExplicitlyIntention.getTypeForDeclaration(declaration).isError
@@ -96,19 +96,23 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration)
val nativeAnnotations = ArrayList<KtAnnotationEntry>()
declaration.modifierList?.annotationEntries?.forEach {
if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER)) {
isGetter = true
nativeAnnotations.add(it)
} else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER)) {
isSetter = true
nativeAnnotations.add(it)
} else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE)) {
isInvoke = true
nativeAnnotations.add(it)
} else if (it.isJsAnnotation(PredefinedAnnotation.NATIVE)) {
nativeAnnotations.add(it)
nativeAnnotation = it
when {
it.isJsAnnotation(PredefinedAnnotation.NATIVE_GETTER) -> {
isGetter = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE_SETTER) -> {
isSetter = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE_INVOKE) -> {
isInvoke = true
nativeAnnotations.add(it)
}
it.isJsAnnotation(PredefinedAnnotation.NATIVE) -> {
nativeAnnotations.add(it)
nativeAnnotation = it
}
}
}
return JsNativeAnnotations(nativeAnnotations, nativeAnnotation, isGetter, isSetter, isInvoke)
@@ -122,30 +126,35 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration)
val ktPsiFactory = KtPsiFactory(declaration)
val body = ktPsiFactory.buildExpression {
appendName(Name.identifier("asDynamic"))
if (annotations.isGetter) {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]")
}
} else if (annotations.isSetter) {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]", skipLast = true)
declaration.valueParameters.last().nameAsName?.let {
appendFixedText(" = ")
appendName(it)
when {
annotations.isGetter -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]")
}
}
} else if (annotations.isInvoke) {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
annotations.isSetter -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "[", "]", skipLast = true)
declaration.valueParameters.last().nameAsName?.let {
appendFixedText(" = ")
appendName(it)
}
}
}
} else {
appendFixedText("().")
appendName(name)
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
annotations.isInvoke -> {
appendFixedText("()")
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
}
}
else -> {
appendFixedText("().")
appendName(name)
if (declaration is KtNamedFunction) {
appendParameters(declaration, "(", ")")
}
}
}
}
@@ -122,33 +122,19 @@ class KotlinChangeSignatureData(
}
}
override fun getParameters(): List<KotlinParameterInfo> {
return parameters
override fun getParameters(): List<KotlinParameterInfo> = parameters
override fun getName() = when (baseDescriptor) {
is ConstructorDescriptor -> baseDescriptor.containingDeclaration.name.asString()
is AnonymousFunctionDescriptor -> ""
else -> baseDescriptor.name.asString()
}
override fun getName(): String {
if (baseDescriptor is ConstructorDescriptor) {
return baseDescriptor.containingDeclaration.name.asString()
}
else if (baseDescriptor is AnonymousFunctionDescriptor) {
return ""
}
else {
return baseDescriptor.name.asString()
}
}
override fun getParametersCount(): Int = baseDescriptor.valueParameters.size
override fun getParametersCount(): Int {
return baseDescriptor.valueParameters.size
}
override fun getVisibility(): Visibility = baseDescriptor.visibility
override fun getVisibility(): Visibility {
return baseDescriptor.visibility
}
override fun getMethod(): PsiElement {
return baseDeclaration
}
override fun getMethod(): PsiElement = baseDeclaration
override fun canChangeVisibility(): Boolean {
if (DescriptorUtils.isLocal(baseDescriptor)) return false
@@ -156,15 +142,10 @@ class KotlinChangeSignatureData(
return !(baseDescriptor is AnonymousFunctionDescriptor || parent is ClassDescriptor && parent.kind == ClassKind.INTERFACE)
}
override fun canChangeParameters(): Boolean {
return true
}
override fun canChangeParameters() = true
override fun canChangeName(): Boolean {
return !(baseDescriptor is ConstructorDescriptor || baseDescriptor is AnonymousFunctionDescriptor)
}
override fun canChangeName() = !(baseDescriptor is ConstructorDescriptor || baseDescriptor is AnonymousFunctionDescriptor)
override fun canChangeReturnType(): MethodDescriptor.ReadWriteOption {
return if (baseDescriptor is ConstructorDescriptor) MethodDescriptor.ReadWriteOption.None else MethodDescriptor.ReadWriteOption.ReadWrite
}
override fun canChangeReturnType(): MethodDescriptor.ReadWriteOption =
if (baseDescriptor is ConstructorDescriptor) MethodDescriptor.ReadWriteOption.None else MethodDescriptor.ReadWriteOption.ReadWrite
}
@@ -248,16 +248,18 @@ class KotlinChangeSignatureDialog(
return JBTableRow { column ->
val columnInfo = parametersTableModel.columnInfos[column]
if (KotlinPrimaryConstructorParameterTableModel.isValVarColumn(columnInfo))
(components[column] as @Suppress("NO_TYPE_ARGUMENTS_ON_RHS") JComboBox).selectedItem
else if (KotlinCallableParameterTableModel.isTypeColumn(columnInfo))
item.typeCodeFragment
else if (KotlinCallableParameterTableModel.isNameColumn(columnInfo))
(components[column] as EditorTextField).text
else if (KotlinCallableParameterTableModel.isDefaultValueColumn(columnInfo))
item.defaultValueCodeFragment
else
null
when {
KotlinPrimaryConstructorParameterTableModel.isValVarColumn(columnInfo) ->
(components[column] as @Suppress("NO_TYPE_ARGUMENTS_ON_RHS") JComboBox).selectedItem
KotlinCallableParameterTableModel.isTypeColumn(columnInfo) ->
item.typeCodeFragment
KotlinCallableParameterTableModel.isNameColumn(columnInfo) ->
(components[column] as EditorTextField).text
KotlinCallableParameterTableModel.isDefaultValueColumn(columnInfo) ->
item.defaultValueCodeFragment
else ->
null
}
}
}
@@ -291,9 +293,11 @@ class KotlinChangeSignatureDialog(
override fun getPreferredFocusedComponent(): JComponent {
val me = mouseEvent
val index = if (me != null)
getEditorIndex(me.point.getX().toInt())
else if (myMethod.kind === Kind.PRIMARY_CONSTRUCTOR) 1 else 0
val index = when {
me != null -> getEditorIndex(me.point.getX().toInt())
myMethod.kind === Kind.PRIMARY_CONSTRUCTOR -> 1
else -> 0
}
val component = components[index]
return if (component is EditorTextField) component.focusTarget else component
}
@@ -353,16 +353,12 @@ private fun makeCall(
)
is Jump -> {
if (outputValue.elementToInsertAfterCall == null) {
Collections.singletonList(psiFactory.createExpression(callText))
}
else if (outputValue.conditional) {
Collections.singletonList(
when {
outputValue.elementToInsertAfterCall == null -> Collections.singletonList(psiFactory.createExpression(callText))
outputValue.conditional -> Collections.singletonList(
psiFactory.createExpression("if ($callText) ${outputValue.elementToInsertAfterCall.text}")
)
}
else {
listOf(
else -> listOf(
psiFactory.createExpression(callText),
newLine,
psiFactory.createExpression(outputValue.elementToInsertAfterCall.text!!)
@@ -134,14 +134,13 @@ fun IntroduceTypeAliasDescriptor.validate(): IntroduceTypeAliasDescriptorWithCon
val conflicts = MultiMap<PsiElement, String>()
val originalType = originalData.originalTypeElement
if (name.isEmpty()) {
conflicts.putValue(originalType, "No name provided for type alias")
}
else if (!KotlinNameSuggester.isIdentifier(name)) {
conflicts.putValue(originalType, "Type alias name must be a valid identifier: $name")
}
else if (originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null) {
conflicts.putValue(originalType, "Type $name already exists in the target scope")
when {
name.isEmpty() ->
conflicts.putValue(originalType, "No name provided for type alias")
!KotlinNameSuggester.isIdentifier(name) ->
conflicts.putValue(originalType, "Type alias name must be a valid identifier: $name")
originalData.getTargetScope().findClassifier(Name.identifier(name), NoLookupLocation.FROM_IDE) != null ->
conflicts.putValue(originalType, "Type $name already exists in the target scope")
}
if (typeParameters.distinctBy { it.name }.size != typeParameters.size) {
@@ -97,12 +97,14 @@ class KotlinRunConfigurationProducer : RunConfigurationProducer<JetRunConfigurat
null -> null
is KtFile -> container.javaFileFacadeFqName.asString()
is KtClassOrObject -> {
if (!container.isValid)
if (!container.isValid) {
null
}
else if (container is KtObjectDeclaration && container.isCompanion()) {
val containerClass = container.getParentOfType<KtClass>(true)
containerClass?.toLightClass()?.let { ClassUtil.getJVMClassName(it) }
} else {
}
else {
container.toLightClass()?.let { ClassUtil.getJVMClassName(it) }
}
}
@@ -115,17 +115,19 @@ fun notifyOutdatedKotlinRuntime(project: Project, outdatedLibraries: Collection<
Notifications.Bus.notify(Notification(OUTDATED_RUNTIME_GROUP_DISPLAY_ID, "Outdated Kotlin Runtime", message,
NotificationType.WARNING, NotificationListener { notification, event ->
if (event.eventType == HyperlinkEvent.EventType.ACTIVATED) {
if ("update" == event.description) {
val outdatedLibraries = findOutdatedKotlinLibraries(project).map { it.library }
ApplicationManager.getApplication().invokeLater {
updateLibraries(project, outdatedLibraries)
when {
"update" == event.description -> {
val outdatedLibraries = findOutdatedKotlinLibraries(project).map { it.library }
ApplicationManager.getApplication().invokeLater {
updateLibraries(project, outdatedLibraries)
}
}
"ignore" == event.description -> {
PropertiesComponent.getInstance(project).setValue(SUPPRESSED_PROPERTY_NAME, pluginVersion)
}
else -> {
throw AssertionError()
}
}
else if ("ignore" == event.description) {
PropertiesComponent.getInstance(project).setValue(SUPPRESSED_PROPERTY_NAME, pluginVersion)
}
else {
throw AssertionError()
}
notification.expire()
}
@@ -345,44 +345,44 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
if (target is KtLightMethod) {
val origin = target.kotlinOrigin
val isTopLevel = origin?.getStrictParentOfType<KtClassOrObject>() == null
if (origin is KtProperty || origin is KtPropertyAccessor || origin is KtParameter) {
val property = if (origin is KtPropertyAccessor)
origin.parent as KtProperty
else
origin as KtNamedDeclaration
val parameterCount = target.parameterList.parameters.size
if (parameterCount == arguments.size) {
val propertyName = Identifier.withNoPrototype(property.name!!, isNullable)
val isExtension = property.isExtensionDeclaration()
val propertyAccess = if (isTopLevel) {
if (isExtension)
QualifiedExpression(codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true), propertyName, null).assignNoPrototype()
else
when (origin) {
is KtProperty, is KtPropertyAccessor, is KtParameter -> {
val property = if (origin is KtPropertyAccessor)
origin.parent as KtProperty
else
origin as KtNamedDeclaration
val parameterCount = target.parameterList.parameters.size
if (parameterCount == arguments.size) {
val propertyName = Identifier.withNoPrototype(property.name!!, isNullable)
val isExtension = property.isExtensionDeclaration()
val propertyAccess = if (isTopLevel) {
if (isExtension)
QualifiedExpression(codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true), propertyName, null).assignNoPrototype()
else
propertyName
}
else if (qualifier != null) {
QualifiedExpression(codeConverter.convertExpression(qualifier), propertyName, dot).assignNoPrototype()
}
else {
propertyName
}
else if (qualifier != null) {
QualifiedExpression(codeConverter.convertExpression(qualifier), propertyName, dot).assignNoPrototype()
}
else {
propertyName
}
when(if (isExtension) parameterCount - 1 else parameterCount) {
0 /* getter */ -> {
result = propertyAccess
return
}
1 /* setter */ -> {
val argument = codeConverter.convertExpression(arguments[if (isExtension) 1 else 0])
result = AssignmentExpression(propertyAccess, argument, Operator.EQ)
return
when(if (isExtension) parameterCount - 1 else parameterCount) {
0 /* getter */ -> {
result = propertyAccess
return
}
1 /* setter */ -> {
val argument = codeConverter.convertExpression(arguments[if (isExtension) 1 else 0])
result = AssignmentExpression(propertyAccess, argument, Operator.EQ)
return
}
}
}
}
}
else if (origin is KtFunction) {
if (isTopLevel) {
is KtFunction -> if (isTopLevel) {
result = if (origin.isExtensionDeclaration()) {
val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true)
MethodCallExpression.build(qualifier,
@@ -401,27 +401,27 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
}
return
}
}
else if (origin == null){
val resolvedQualifier = (methodExpr.qualifier as? PsiReferenceExpression)?.resolve()
if (isFacadeClassFromLibrary(resolvedQualifier)) {
result = if (target.isKotlinExtensionFunction()) {
val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true)
MethodCallExpression.build(qualifier,
methodExpr.referenceName!!,
convertArguments(expression, isExtension = true),
typeArguments,
isNullable,
dot)
null -> {
val resolvedQualifier = (methodExpr.qualifier as? PsiReferenceExpression)?.resolve()
if (isFacadeClassFromLibrary(resolvedQualifier)) {
result = if (target.isKotlinExtensionFunction()) {
val qualifier = codeConverter.convertExpression(arguments.firstOrNull(), shouldParenthesize = true)
MethodCallExpression.build(qualifier,
methodExpr.referenceName!!,
convertArguments(expression, isExtension = true),
typeArguments,
isNullable,
dot)
}
else {
MethodCallExpression.build(null,
methodExpr.referenceName!!,
convertArguments(expression),
typeArguments,
isNullable)
}
return
}
else {
MethodCallExpression.build(null,
methodExpr.referenceName!!,
convertArguments(expression),
typeArguments,
isNullable)
}
return
}
}
}
@@ -826,39 +826,40 @@ class DefaultExpressionConverter : JavaElementVisitor(), ExpressionConverter {
val specialMethod = method?.let { SpecialMethod.match(it, callParams.size, converter.services) }
val statement: Statement
if (expression.isConstructor) {
val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first })
statement = MethodCallExpression.buildNonNull(null, convertMethodReferenceQualifier(qualifier), argumentList)
}
else if (specialMethod != null) {
val factory = PsiElementFactory.SERVICE.getInstance(converter.project)
val fakeReceiver = receiver?.let {
val psiExpression = qualifier as? PsiExpression ?: factory.createExpressionFromText("fakeReceiver", null)
psiExpression.convertedExpression = it.first
psiExpression
when {
expression.isConstructor -> {
val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first })
statement = MethodCallExpression.buildNonNull(null, convertMethodReferenceQualifier(qualifier), argumentList)
}
val fakeParams = callParams.mapIndexed {
i, param ->
with(factory.createExpressionFromText("fake$i", null)) {
this.convertedExpression = param.first
this
specialMethod != null -> {
val factory = PsiElementFactory.SERVICE.getInstance(converter.project)
val fakeReceiver = receiver?.let {
val psiExpression = qualifier as? PsiExpression ?: factory.createExpressionFromText("fakeReceiver", null)
psiExpression.convertedExpression = it.first
psiExpression
}
}
val patchedConverter = codeConverter.withSpecialExpressionConverter(object : SpecialExpressionConverter {
override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? {
val convertedExpression = expression.convertedExpression
expression.convertedExpression = null
return convertedExpression
val fakeParams = callParams.mapIndexed { i, param ->
with(factory.createExpressionFromText("fake$i", null)) {
this.convertedExpression = param.first
this
}
}
})
val patchedConverter = codeConverter.withSpecialExpressionConverter(object : SpecialExpressionConverter {
override fun convertExpression(expression: PsiExpression, codeConverter: CodeConverter): Expression? {
val convertedExpression = expression.convertedExpression
expression.convertedExpression = null
return convertedExpression
}
})
val callData = SpecialMethod.ConvertCallData(fakeReceiver, fakeParams, emptyList(), null, null, null, patchedConverter)
statement = specialMethod.convertCall(callData)!!
}
else {
val referenceName = expression.referenceName!!
val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first })
statement = MethodCallExpression.buildNonNull(receiver?.first, referenceName, argumentList)
val callData = SpecialMethod.ConvertCallData(fakeReceiver, fakeParams, emptyList(), null, null, null, patchedConverter)
statement = specialMethod.convertCall(callData)!!
}
else -> {
val referenceName = expression.referenceName!!
val argumentList = ArgumentList.withNoPrototype(callParams.map { it.first })
statement = MethodCallExpression.buildNonNull(receiver?.first, referenceName, argumentList)
}
}
statement.assignNoPrototype()
@@ -104,13 +104,14 @@ class ForConverter(
statement.isInSingleLine()).assignNoPrototype()
if (initializationConverted.isEmpty) return whileStatement
val kind = if (statement.parents.filter { it !is PsiLabeledStatement }.first() !is PsiCodeBlock) {
WhileWithInitializationPseudoStatement.Kind.WITH_BLOCK
val kind = when {
statement.parents.filter { it !is PsiLabeledStatement }.first() !is PsiCodeBlock ->
WhileWithInitializationPseudoStatement.Kind.WITH_BLOCK
hasNameConflict() ->
WhileWithInitializationPseudoStatement.Kind.WITH_RUN_BLOCK
else ->
WhileWithInitializationPseudoStatement.Kind.SIMPLE
}
else if (hasNameConflict())
WhileWithInitializationPseudoStatement.Kind.WITH_RUN_BLOCK
else
WhileWithInitializationPseudoStatement.Kind.SIMPLE
return WhileWithInitializationPseudoStatement(initializationConverted, whileStatement, kind)
}
@@ -266,12 +266,14 @@ class TypeConverter(val converter: Converter) {
override fun fromAnnotations(owner: PsiModifierListOwner): Nullability {
val manager = NullableNotNullManager.getInstance(owner.project)
return if (manager.isNotNull(owner, false/* we do not check bases because they are checked by callers of this method*/))
Nullability.NotNull
else if (manager.isNullable(owner, false))
Nullability.Nullable
else
Nullability.Default
return when {
manager.isNotNull(owner, false/* we do not check bases because they are checked by callers of this method*/) ->
Nullability.NotNull
manager.isNullable(owner, false) ->
Nullability.Nullable
else ->
Nullability.Default
}
}
override fun forVariableTypeBeforeUsageSearch(variable: PsiVariable): Nullability {
@@ -40,17 +40,11 @@ class TypeVisitor(
override fun visitPrimitiveType(primitiveType: PsiPrimitiveType): Type {
val name = primitiveType.canonicalText
return if (name == "void") {
UnitType()
}
else if (PRIMITIVE_TYPES_NAMES.contains(name)) {
PrimitiveType(Identifier.withNoPrototype(StringUtil.capitalize(name)))
}
else if (name == "null") {
NullType()
}
else {
PrimitiveType(Identifier.withNoPrototype(name))
return when {
name == "void" -> UnitType()
PRIMITIVE_TYPES_NAMES.contains(name) -> PrimitiveType(Identifier.withNoPrototype(StringUtil.capitalize(name)))
name == "null" -> NullType()
else -> PrimitiveType(Identifier.withNoPrototype(name))
}
}
+4 -8
View File
@@ -27,20 +27,16 @@ fun quoteKeywords(packageName: String): String = packageName.split('.').joinToSt
fun getDefaultInitializer(property: Property): Expression? {
val t = property.type
val result = if (t.isNullable) {
LiteralExpression("null")
}
else if (t is PrimitiveType) {
when (t.name.name) {
val result = when {
t.isNullable -> LiteralExpression("null")
t is PrimitiveType -> when (t.name.name) {
"Boolean" -> LiteralExpression("false")
"Char" -> LiteralExpression("' '")
"Double" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.DOUBLE.toString())
"Float" -> MethodCallExpression.buildNonNull(LiteralExpression("0").assignNoPrototype(), OperatorConventions.FLOAT.toString())
else -> LiteralExpression("0")
}
}
else {
null
else -> null
}
return result?.assignNoPrototype()
}
@@ -279,11 +279,10 @@ class ClassLiteralExpression(val type: Type): Expression() {
fun createArrayInitializerExpression(arrayType: ArrayType, initializers: List<Expression>, needExplicitType: Boolean = true) : MethodCallExpression {
val elementType = arrayType.elementType
val createArrayFunction = if (elementType is PrimitiveType)
(elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize()
else if (needExplicitType)
"arrayOf<" + arrayType.elementType.canonicalCode() + ">"
else
"arrayOf"
val createArrayFunction = when {
elementType is PrimitiveType -> (elementType.toNotNullType().canonicalCode() + "ArrayOf").decapitalize()
needExplicitType -> "arrayOf<" + arrayType.elementType.canonicalCode() + ">"
else -> "arrayOf"
}
return MethodCallExpression.buildNonNull(null, createArrayFunction, ArgumentList.withNoPrototype(initializers))
}
@@ -387,14 +387,10 @@ private class PropertyDetector(
modifiers.add(Modifier.OVERRIDE)
}
if (getMethod != null) {
modifiers.addIfNotNull(getterModifiers.accessModifier())
}
else if (setMethod != null) {
modifiers.addIfNotNull(getterModifiers.accessModifier())
}
else {
modifiers.addIfNotNull(fieldModifiers.accessModifier())
when {
getMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier())
setMethod != null -> modifiers.addIfNotNull(getterModifiers.accessModifier())
else -> modifiers.addIfNotNull(fieldModifiers.accessModifier())
}
val prototypes = listOfNotNull<PsiElement>(field, getMethod, setMethod)
@@ -432,16 +428,20 @@ private class PropertyDetector(
val superMethod = converter.services.superMethodsSearcher.findDeepestSuperMethods(getOrSetMethod).firstOrNull() ?: return null
val containingClass = superMethod.containingClass!!
if (converter.inConversionScope(containingClass)) {
val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod]
return if (propertyInfo != null) SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT)) else SuperInfo.Function
}
else if (superMethod is KtLightMethod) {
val origin = superMethod.kotlinOrigin
return if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD)) else SuperInfo.Function
}
else {
return SuperInfo.Function
return when {
converter.inConversionScope(containingClass) -> {
val propertyInfo = converter.propertyDetectionCache[containingClass][superMethod]
if (propertyInfo != null) SuperInfo.Property(propertyInfo.isVar, propertyInfo.name, propertyInfo.modifiers.contains(Modifier.ABSTRACT))
else SuperInfo.Function
}
superMethod is KtLightMethod -> {
val origin = superMethod.kotlinOrigin
if (origin is KtProperty) SuperInfo.Property(origin.isVar, origin.name ?: "", origin.hasModifier(KtTokens.ABSTRACT_KEYWORD))
else SuperInfo.Function
}
else -> {
SuperInfo.Function
}
}
}
@@ -37,12 +37,11 @@ class FieldToPropertyProcessing(
if (field.name != propertyName || replaceReadWithFieldReference || replaceWriteWithFieldReference) MyConvertedCodeProcessor() else null
override var javaCodeProcessors =
if (field.hasModifierProperty(PsiModifier.PRIVATE))
emptyList()
else if (field.name != propertyName)
listOf(ElementRenamedCodeProcessor(propertyName), UseAccessorsJavaCodeProcessor())
else
listOf(UseAccessorsJavaCodeProcessor())
when {
field.hasModifierProperty(PsiModifier.PRIVATE) -> emptyList()
field.name != propertyName -> listOf(ElementRenamedCodeProcessor(propertyName), UseAccessorsJavaCodeProcessor())
else -> listOf(UseAccessorsJavaCodeProcessor())
}
override val kotlinCodeProcessors =
if (field.name != propertyName)
@@ -56,54 +56,50 @@ class Analyzer(private val context: Context) : JsVisitor() {
override fun visitExpressionStatement(x: JsExpressionStatement) {
val expression = x.expression
if (expression is JsBinaryOperation) {
if (expression.operator == JsBinaryOperator.ASG) {
when (expression) {
is JsBinaryOperation -> if (expression.operator == JsBinaryOperator.ASG) {
processAssignment(x, expression.arg1, expression.arg2)?.let {
// Mark this statement with FQN extracted from assignment.
// Later, we eliminate such statements if corresponding FQN is reachable
nodeMap[x] = it
}
}
}
else if (expression is JsFunction) {
expression.name?.let { context.nodes[it]?.original }?.let {
is JsFunction -> expression.name?.let { context.nodes[it]?.original }?.let {
nodeMap[x] = it
it.functions += expression
}
}
else if (expression is JsInvocation) {
val function = expression.qualifier
is JsInvocation -> {
val function = expression.qualifier
// (function(params) { ... })(arguments), assume that params = arguments and walk its body
if (function is JsFunction) {
enterFunction(function, expression.arguments)
return
}
// f(arguments), where f is a parameter of outer function and it always receives function() { } as an argument.
if (function is JsNameRef && function.qualifier == null) {
val postponedFunction = function.name?.let { postponedFunctions[it] }
if (postponedFunction != null) {
enterFunction(postponedFunction, expression.arguments)
invocationsToSkip += expression
// (function(params) { ... })(arguments), assume that params = arguments and walk its body
if (function is JsFunction) {
enterFunction(function, expression.arguments)
return
}
}
// Object.defineProperty()
if (context.isObjectDefineProperty(function)) {
handleObjectDefineProperty(x, expression.arguments.getOrNull(0), expression.arguments.getOrNull(1),
expression.arguments.getOrNull(2))
}
// f(arguments), where f is a parameter of outer function and it always receives function() { } as an argument.
if (function is JsNameRef && function.qualifier == null) {
val postponedFunction = function.name?.let { postponedFunctions[it] }
if (postponedFunction != null) {
enterFunction(postponedFunction, expression.arguments)
invocationsToSkip += expression
return
}
}
// Kotlin.defineModule()
else if (context.isDefineModule(function)) {
// (just remove it)
astNodesToEliminate += x
}
// Object.defineProperty()
when {
context.isObjectDefineProperty(function) ->
handleObjectDefineProperty(x, expression.arguments.getOrNull(0), expression.arguments.getOrNull(1),
expression.arguments.getOrNull(2))
else if (context.isAmdDefine(function)) {
handleAmdDefine(expression, expression.arguments)
// Kotlin.defineModule()
context.isDefineModule(function) ->
// (just remove it)
astNodesToEliminate += x
context.isAmdDefine(function) ->
handleAmdDefine(expression, expression.arguments)
}
}
}
}
@@ -201,77 +197,75 @@ class Analyzer(private val context: Context) : JsVisitor() {
}
else if (leftNode != null) {
// lhs = foo()
if (rhs is JsInvocation) {
val function = rhs.qualifier
when {
rhs is JsInvocation -> {
val function = rhs.qualifier
// lhs = function(params) { ... }(arguments)
// see corresponding case in visitExpressionStatement
if (function is JsFunction) {
enterFunction(function, rhs.arguments)
astNodesToSkip += lhs
return null
}
// lhs = foo(arguments), where foo is a parameter of outer function that always take function literal
// see corresponding case in visitExpressionStatement
if (function is JsNameRef && function.qualifier == null) {
function.name?.let { postponedFunctions[it] }?.let {
enterFunction(it, rhs.arguments)
// lhs = function(params) { ... }(arguments)
// see corresponding case in visitExpressionStatement
if (function is JsFunction) {
enterFunction(function, rhs.arguments)
astNodesToSkip += lhs
return null
}
}
// lhs = Object.create(constructor)
if (context.isObjectFunction(function, "create")) {
// Do not alias lhs and constructor, make unidirectional dependency lhs -> constructor instead.
// Motivation: reachability of a base class does not imply reachability of its derived class
handleObjectCreate(leftNode, rhs.arguments.getOrNull(0))
return leftNode
}
// lhs = Kotlin.defineInlineFunction('fqn', function() { ... })
if (context.isDefineInlineFunction(function) && rhs.arguments.size == 2) {
leftNode.functions += rhs.arguments[1] as JsFunction
val defineInlineFunctionNode = context.extractNode(function)
if (defineInlineFunctionNode != null) {
leftNode.dependencies += defineInlineFunctionNode
}
return leftNode
}
}
else if (rhs is JsBinaryOperation) {
// Detect lhs = parent.child || (parent.child = {}), which is used to declare packages.
// Assume lhs = parent.child
if (rhs.operator == JsBinaryOperator.OR) {
val secondNode = context.extractNode(rhs.arg1)
val reassignment = rhs.arg2
if (reassignment is JsBinaryOperation && reassignment.operator == JsBinaryOperator.ASG) {
val reassignNode = context.extractNode(reassignment.arg1)
val reassignValue = reassignment.arg2
if (reassignNode == secondNode && reassignNode != null && reassignValue is JsObjectLiteral &&
reassignValue.propertyInitializers.isEmpty()
) {
return processAssignment(node, lhs, rhs.arg1)
// lhs = foo(arguments), where foo is a parameter of outer function that always take function literal
// see corresponding case in visitExpressionStatement
if (function is JsNameRef && function.qualifier == null) {
function.name?.let { postponedFunctions[it] }?.let {
enterFunction(it, rhs.arguments)
astNodesToSkip += lhs
return null
}
}
// lhs = Object.create(constructor)
if (context.isObjectFunction(function, "create")) {
// Do not alias lhs and constructor, make unidirectional dependency lhs -> constructor instead.
// Motivation: reachability of a base class does not imply reachability of its derived class
handleObjectCreate(leftNode, rhs.arguments.getOrNull(0))
return leftNode
}
// lhs = Kotlin.defineInlineFunction('fqn', function() { ... })
if (context.isDefineInlineFunction(function) && rhs.arguments.size == 2) {
leftNode.functions += rhs.arguments[1] as JsFunction
val defineInlineFunctionNode = context.extractNode(function)
if (defineInlineFunctionNode != null) {
leftNode.dependencies += defineInlineFunctionNode
}
return leftNode
}
}
}
else if (rhs is JsFunction) {
// lhs = function() { ... }
// During reachability tracking phase: eliminate it if lhs is unreachable, traverse function otherwise
leftNode.functions += rhs
return leftNode
}
else if (leftNode.qualifier?.memberName == Namer.METADATA) {
// lhs.$metadata$ = expression
// During reachability tracking phase: eliminate it if lhs is unreachable, traverse expression
// It's commonly used to supply class's metadata
leftNode.expressions += rhs
return leftNode
}
else if (rhs is JsObjectLiteral && rhs.propertyInitializers.isEmpty()) {
return leftNode
rhs is JsBinaryOperation -> // Detect lhs = parent.child || (parent.child = {}), which is used to declare packages.
// Assume lhs = parent.child
if (rhs.operator == JsBinaryOperator.OR) {
val secondNode = context.extractNode(rhs.arg1)
val reassignment = rhs.arg2
if (reassignment is JsBinaryOperation && reassignment.operator == JsBinaryOperator.ASG) {
val reassignNode = context.extractNode(reassignment.arg1)
val reassignValue = reassignment.arg2
if (reassignNode == secondNode && reassignNode != null && reassignValue is JsObjectLiteral &&
reassignValue.propertyInitializers.isEmpty()
) {
return processAssignment(node, lhs, rhs.arg1)
}
}
}
rhs is JsFunction -> {
// lhs = function() { ... }
// During reachability tracking phase: eliminate it if lhs is unreachable, traverse function otherwise
leftNode.functions += rhs
return leftNode
}
leftNode.qualifier?.memberName == Namer.METADATA -> {
// lhs.$metadata$ = expression
// During reachability tracking phase: eliminate it if lhs is unreachable, traverse expression
// It's commonly used to supply class's metadata
leftNode.expressions += rhs
return leftNode
}
rhs is JsObjectLiteral && rhs.propertyInitializers.isEmpty() -> return leftNode
}
val nodeInitializedByEmptyObject = extractVariableInitializedByEmptyObject(rhs)
@@ -222,15 +222,13 @@ object JsExternalChecker : SimpleDeclarationChecker {
private fun KtDeclarationWithBody.hasValidExternalBody(bindingContext: BindingContext): Boolean {
if (!hasBody()) return true
val body = bodyExpression!!
return if (!hasBlockBody()) {
body.isDefinedExternallyExpression(bindingContext)
}
else if (body is KtBlockExpression) {
val statement = body.statements.singleOrNull() ?: return false
statement.isDefinedExternallyExpression(bindingContext)
}
else {
false
return when {
!hasBlockBody() -> body.isDefinedExternallyExpression(bindingContext)
body is KtBlockExpression -> {
val statement = body.statements.singleOrNull() ?: return false
statement.isDefinedExternallyExpression(bindingContext)
}
else -> false
}
}
@@ -66,15 +66,17 @@ class RedundantStatementElimination(private val root: JsFunction) {
private fun replace(expression: JsExpression): List<JsExpression> {
return when (expression) {
is JsNameRef -> {
if (expression.name in localVars) {
listOf()
}
else if (expression.sideEffects != SideEffectKind.AFFECTS_STATE) {
val qualifier = expression.qualifier
if (qualifier != null) replace(qualifier) else listOf()
}
else {
listOf(expression)
when {
expression.name in localVars -> {
listOf()
}
expression.sideEffects != SideEffectKind.AFFECTS_STATE -> {
val qualifier = expression.qualifier
if (qualifier != null) replace(qualifier) else listOf()
}
else -> {
listOf(expression)
}
}
}
@@ -190,35 +190,27 @@ object Constants {
private fun formatChar(c: Char) = '\'' + quote(c) + '\''
private fun formatString(s: String) = '"' + quote(s) + '"'
private fun formatFloat(f: Float): String {
if (java.lang.Float.isNaN(f))
return "0.0f/0.0f"
else if (java.lang.Float.isInfinite(f))
return if (f < 0) "-1.0f/0.0f" else "1.0f/0.0f"
else
return "${f}f"
private fun formatFloat(f: Float): String = when {
java.lang.Float.isNaN(f) -> "0.0f/0.0f"
java.lang.Float.isInfinite(f) -> if (f < 0) "-1.0f/0.0f" else "1.0f/0.0f"
else -> "${f}f"
}
private fun formatDouble(d: Double): String {
if (java.lang.Double.isNaN(d))
return "0.0/0.0"
else if (java.lang.Double.isInfinite(d))
return if (d < 0) "-1.0/0.0" else "1.0/0.0"
else
return d.toString()
private fun formatDouble(d: Double): String = when {
java.lang.Double.isNaN(d) -> "0.0/0.0"
java.lang.Double.isInfinite(d) -> if (d < 0) "-1.0/0.0" else "1.0/0.0"
else -> d.toString()
}
fun quote(ch: Char): String {
return when (ch) {
'\b' -> "\\b"
'\n' -> "\\n"
'\r' -> "\\r"
'\t' -> "\\t"
'\'' -> "\\'"
'\"' -> "\\\""
'\\' -> "\\\\"
else -> if (isPrintableAscii(ch)) ch.toString() else String.format("\\u%04x", ch.toInt())
}
fun quote(ch: Char): String = when (ch) {
'\b' -> "\\b"
'\n' -> "\\n"
'\r' -> "\\r"
'\t' -> "\\t"
'\'' -> "\\'"
'\"' -> "\\\""
'\\' -> "\\\\"
else -> if (isPrintableAscii(ch)) ch.toString() else String.format("\\u%04x", ch.toInt())
}
fun quote(s: String): String {
@@ -95,12 +95,10 @@ class KotlinTypes(
if (extendsBound != null && extendsBound !is JePsiType) illegalArg("extendsBound should have PsiType")
if (superBound != null && superBound !is JePsiType) illegalArg("superBound should have PsiType")
return JeWildcardType(if (extendsBound != null) {
PsiWildcardType.createExtends(psiManager(), (extendsBound as JePsiType).psiType)
} else if (superBound != null) {
PsiWildcardType.createSuper(psiManager(), (superBound as JePsiType).psiType)
} else {
PsiWildcardType.createUnbounded(psiManager())
return JeWildcardType(when {
extendsBound != null -> PsiWildcardType.createExtends(psiManager(), (extendsBound as JePsiType).psiType)
superBound != null -> PsiWildcardType.createSuper(psiManager(), (superBound as JePsiType).psiType)
else -> PsiWildcardType.createUnbounded(psiManager())
}, isRaw = false)
}
@@ -80,16 +80,13 @@ class SuppressLintIntentionAction(val id: String, val element: PsiElement) : Int
val args = entry.valueArgumentList
val psiFactory = KtPsiFactory(entry)
val newArgList = psiFactory.createCallArguments("($argument)")
if (args == null) {
// new argument list
entry.addAfter(newArgList, entry.lastChild)
}
else if (args.arguments.isEmpty()) {
// replace '()' with a new argument list
args.replace(newArgList)
}
else if (args.arguments.none { it.textMatches(argument) }) {
args.addArgument(newArgList.arguments[0])
when {
args == null -> // new argument list
entry.addAfter(newArgList, entry.lastChild)
args.arguments.isEmpty() -> // replace '()' with a new argument list
args.replace(newArgList)
args.arguments.none { it.textMatches(argument) } ->
args.addArgument(newArgList.arguments[0])
}
return true
@@ -286,15 +286,16 @@ internal object KotlinConverter {
is KtVariableDeclaration -> expr<UDeclarationsExpression>(build(::convertVariablesDeclaration))
is KtStringTemplateExpression -> {
if (expression.entries.isEmpty()) {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, parent, "") }
}
else if (expression.entries.size == 1)
convertEntry(expression.entries[0], parentCallback, requiredType)
else {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
expr<UExpression> { KotlinStringTemplateUPolyadicExpression(expression, parent) }
when {
expression.entries.isEmpty() -> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
expr<ULiteralExpression> { KotlinStringULiteralExpression(expression, parent, "") }
}
expression.entries.size == 1 -> convertEntry(expression.entries[0], parentCallback, requiredType)
else -> {
val parent = if (parentCallback == null) null else (parentCallback() ?: return null)
expr<UExpression> { KotlinStringTemplateUPolyadicExpression(expression, parent) }
}
}
}
is KtDestructuringDeclaration -> expr<UDeclarationsExpression> {