Minor: Code cleanup

This commit is contained in:
Alexey Sedunov
2015-05-20 13:06:24 +03:00
parent cc351e55b0
commit 6a1ae8b911
11 changed files with 81 additions and 76 deletions
@@ -68,7 +68,6 @@ import org.jetbrains.kotlin.utils.addToStdlib.singletonOrEmptyList
import java.util.* import java.util.*
import kotlin.properties.Delegates import kotlin.properties.Delegates
private val TYPE_PARAMETER_LIST_VARIABLE_NAME = "typeParameterList"
private val TEMPLATE_FROM_USAGE_FUNCTION_BODY = "New Kotlin Function Body.kt" private val TEMPLATE_FROM_USAGE_FUNCTION_BODY = "New Kotlin Function Body.kt"
private val TEMPLATE_FROM_USAGE_SECONDARY_CONSTRUCTOR_BODY = "New Kotlin Secondary Constructor Body.kt" private val TEMPLATE_FROM_USAGE_SECONDARY_CONSTRUCTOR_BODY = "New Kotlin Secondary Constructor Body.kt"
private val ATTRIBUTE_FUNCTION_NAME = "FUNCTION_NAME" private val ATTRIBUTE_FUNCTION_NAME = "FUNCTION_NAME"
@@ -93,11 +92,11 @@ class TypeCandidate(val theType: JetType, scope: JetScope? = null) {
init { init {
val typeParametersInType = theType.getTypeParameters() val typeParametersInType = theType.getTypeParameters()
if (scope == null) { if (scope == null) {
typeParameters = typeParametersInType.copyToArray() typeParameters = typeParametersInType.toTypedArray()
renderedType = theType.renderShort(Collections.emptyMap()); renderedType = theType.renderShort(Collections.emptyMap());
} }
else { else {
typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).copyToArray(); typeParameters = getTypeParameterNamesNotInScope(typeParametersInType, scope).toTypedArray();
} }
} }
@@ -122,7 +121,7 @@ class CallableBuilderConfiguration(
val enableSubstitutions: Boolean = true val enableSubstitutions: Boolean = true
) )
trait CallablePlacement { interface CallablePlacement {
class WithReceiver(val receiverTypeCandidate: TypeCandidate): CallablePlacement class WithReceiver(val receiverTypeCandidate: TypeCandidate): CallablePlacement
class NoReceiver(val containingElement: PsiElement): CallablePlacement class NoReceiver(val containingElement: PsiElement): CallablePlacement
} }
@@ -159,7 +158,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val types = typeInfo.getPossibleTypes(this).reverse() val types = typeInfo.getPossibleTypes(this).reverse()
// We have to use semantic equality here // We have to use semantic equality here
[data] class EqWrapper(val _type: JetType) { @data class EqWrapper(val _type: JetType) {
override fun equals(other: Any?) = this === other override fun equals(other: Any?) = this === other
|| other is EqWrapper && JetTypeChecker.DEFAULT.equalTypes(_type, other._type) || other is EqWrapper && JetTypeChecker.DEFAULT.equalTypes(_type, other._type)
override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals() override fun hashCode() = 0 // no good way to compute hashCode() that would agree with our equals()
@@ -176,7 +175,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
newTypes.removeAll(toRemove) newTypes.removeAll(toRemove)
} }
if (newTypes.empty) { if (newTypes.isEmpty()) {
newTypes.add(EqWrapper(KotlinBuiltIns.getInstance().getAnyType())) newTypes.add(EqWrapper(KotlinBuiltIns.getInstance().getAnyType()))
} }
@@ -223,8 +222,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
// gather relevant information // gather relevant information
val placement = placement val placement = placement
when { when (placement) {
placement is CallablePlacement.NoReceiver -> { is CallablePlacement.NoReceiver -> {
containingElement = placement.containingElement containingElement = placement.containingElement
receiverClassDescriptor = with (placement.containingElement) { receiverClassDescriptor = with (placement.containingElement) {
when (this) { when (this) {
@@ -234,7 +233,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
} }
} }
} }
placement is CallablePlacement.WithReceiver -> { is CallablePlacement.WithReceiver -> {
receiverClassDescriptor = receiverClassDescriptor =
placement.receiverTypeCandidate.theType.getConstructor().getDeclarationDescriptor() as? ClassDescriptor placement.receiverTypeCandidate.theType.getConstructor().getDeclarationDescriptor() as? ClassDescriptor
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) } val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
@@ -253,7 +252,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
if (containingElement is JetElement) { if (containingElement is JetElement) {
jetFileToEdit = containingElement.getContainingJetFile() jetFileToEdit = containingElement.getContainingJetFile()
if (jetFileToEdit != config.currentFile) { if (jetFileToEdit != config.currentFile) {
containingFileEditor = FileEditorManager.getInstance(project).getSelectedTextEditor() containingFileEditor = FileEditorManager.getInstance(project).getSelectedTextEditor()!!
} }
else { else {
containingFileEditor = config.currentEditor!! containingFileEditor = config.currentEditor!!
@@ -294,8 +293,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
typeCandidates.first().theType typeCandidates.first().theType
} }
.subtract(substitutionMap.keySet()) .subtract(substitutionMap.keySet())
fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size) fakeFunction = createFakeFunctionDescriptor(scope, typeArgumentsForFakeFunction.size())
collectSubstitutionsForCallableTypeParameters(fakeFunction!!, typeArgumentsForFakeFunction, substitutionMap) collectSubstitutionsForCallableTypeParameters(fakeFunction, typeArgumentsForFakeFunction, substitutionMap)
mandatoryTypeParametersAsCandidates = receiverTypeCandidate.singletonOrEmptyList() + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it], scope) } mandatoryTypeParametersAsCandidates = receiverTypeCandidate.singletonOrEmptyList() + typeArgumentsForFakeFunction.map { TypeCandidate(substitutionMap[it], scope) }
} }
else { else {
@@ -372,7 +371,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val classTypeParameters = receiverType?.getArguments() ?: Collections.emptyList() val classTypeParameters = receiverType?.getArguments() ?: Collections.emptyList()
val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.getArguments() val ownerTypeArguments = (placement as? CallablePlacement.WithReceiver)?.receiverTypeCandidate?.theType?.getArguments()
?: Collections.emptyList() ?: Collections.emptyList()
assert(ownerTypeArguments.size == classTypeParameters.size) assert(ownerTypeArguments.size() == classTypeParameters.size())
ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.getType()] = it.second.getType() } ownerTypeArguments.zip(classTypeParameters).forEach { result[it.first.getType()] = it.second.getType() }
} }
@@ -396,7 +395,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val validator = CollectingValidator { scope.getClassifier(Name.identifier(it)) == null } val validator = CollectingValidator { scope.getClassifier(Name.identifier(it)) == null }
val parameterNames = JetNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator) val parameterNames = JetNameSuggester.suggestNamesForTypeParameters(typeParameterCount, validator)
val typeParameters = typeParameterCount.indices.map { val typeParameters = (0..typeParameterCount - 1).map {
TypeParameterDescriptorImpl.createWithDefaultBound( TypeParameterDescriptorImpl.createWithDefaultBound(
fakeFunction, fakeFunction,
Annotations.EMPTY, Annotations.EMPTY,
@@ -598,24 +597,26 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
return if (declaration is JetNamedFunction) { return if (declaration is JetNamedFunction) {
val anchor = PsiTreeUtil.skipSiblingsBackward( val anchor = PsiTreeUtil.skipSiblingsBackward(
classBody!!.getRBrace() ?: classBody!!.getLastChild()!!, classBody.getRBrace() ?: classBody.getLastChild()!!,
javaClass<PsiWhiteSpace>() javaClass<PsiWhiteSpace>()
) )
classBody.addAfter(declaration, anchor) as JetNamedDeclaration classBody.addAfter(declaration, anchor) as JetNamedDeclaration
} }
else classBody.addAfter(declaration, classBody!!.getLBrace()!!) as JetNamedDeclaration else classBody.addAfter(declaration, classBody.getLBrace()!!) as JetNamedDeclaration
} }
private fun getTypeParameterRenames(scope: JetScope): Map<TypeParameterDescriptor, String> { private fun getTypeParameterRenames(scope: JetScope): Map<TypeParameterDescriptor, String> {
val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>() val allTypeParametersNotInScope = LinkedHashSet<TypeParameterDescriptor>()
mandatoryTypeParametersAsCandidates.stream() mandatoryTypeParametersAsCandidates.asSequence()
.plus(callableInfo.parameterInfos.stream().flatMap { typeCandidates[it.typeInfo]!!.stream() }) .plus(callableInfo.parameterInfos.asSequence().flatMap { typeCandidates[it.typeInfo]!!.asSequence() })
.flatMap { it.typeParameters.stream() } .flatMap { it.typeParameters.asSequence() }
.toCollection(allTypeParametersNotInScope) .toCollection(allTypeParametersNotInScope)
if (!skipReturnType) { if (!skipReturnType) {
computeTypeCandidates(callableInfo.returnTypeInfo).stream().flatMapTo(allTypeParametersNotInScope) { it.typeParameters.stream() } computeTypeCandidates(callableInfo.returnTypeInfo).asSequence().flatMapTo(allTypeParametersNotInScope) {
it.typeParameters.asSequence()
}
} }
val validator = CollectingValidator { scope.getClassifier(Name.identifier(it)) == null } val validator = CollectingValidator { scope.getClassifier(Name.identifier(it)) == null }
@@ -653,8 +654,8 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val valueParameters = declaration.getValueParameters() val valueParameters = declaration.getValueParameters()
val parameterIndicesToShorten = ArrayList<Int>() val parameterIndicesToShorten = ArrayList<Int>()
assert(valueParameters.size == parameterTypeExpressions.size) assert(valueParameters.size() == parameterTypeExpressions.size())
for ((i, parameter) in valueParameters.stream().withIndices()) { for ((i, parameter) in valueParameters.asSequence().withIndex()) {
val parameterTypeRef = parameter.getTypeReference() val parameterTypeRef = parameter.getTypeReference()
if (parameterTypeRef != null) { if (parameterTypeRef != null) {
val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType( val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType(
@@ -669,7 +670,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
} }
val expandedValueParameters = declaration.getValueParameters() val expandedValueParameters = declaration.getValueParameters()
parameterIndicesToShorten.stream() parameterIndicesToShorten.asSequence()
.map { expandedValueParameters[it].getTypeReference() } .map { expandedValueParameters[it].getTypeReference() }
.filterNotNullTo(typeRefsToShorten) .filterNotNullTo(typeRefsToShorten)
@@ -684,7 +685,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
is JetNamedFunction -> TEMPLATE_FROM_USAGE_FUNCTION_BODY is JetNamedFunction -> TEMPLATE_FROM_USAGE_FUNCTION_BODY
else -> throw AssertionError("Unexpected declaration: " + func.getElementTextWithContext()) else -> throw AssertionError("Unexpected declaration: " + func.getElementTextWithContext())
} }
val fileTemplate = FileTemplateManager.getInstance()!!.getCodeTemplate(templateName) val fileTemplate = FileTemplateManager.getInstance(func.getProject())!!.getCodeTemplate(templateName)
val properties = Properties() val properties = Properties()
properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, if (skipReturnType) "Unit" else func.getTypeReference()!!.getText()) properties.setProperty(FileTemplate.ATTRIBUTE_RETURN_TYPE, if (skipReturnType) "Unit" else func.getTypeReference()!!.getText())
receiverClassDescriptor?.let { receiverClassDescriptor?.let {
@@ -744,7 +745,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
} }
if (elementToReplace == null) return null if (elementToReplace == null) return null
if (candidates.size == 1) { if (candidates.size() == 1) {
builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).getText()) builder.replaceElement(elementToReplace, (expression.calculateResult(null) as TextResult).getText())
return null return null
} }
@@ -774,11 +775,11 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>() val mandatoryTypeParameters = ArrayList<RenderedTypeParameter>()
//receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) } //receiverTypeCandidate?.let { mandatoryTypeParameters.addAll(it.renderedTypeParameters!!) }
mandatoryTypeParametersAsCandidates.stream().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.stream() } mandatoryTypeParametersAsCandidates.asSequence().flatMapTo(mandatoryTypeParameters) { it.renderedTypeParameters!!.asSequence() }
callableInfo.parameterInfos.stream().flatMap { typeCandidates[it.typeInfo]!!.stream() }.forEach { callableInfo.parameterInfos.asSequence()
typeParameterMap[it.renderedType!!] = it.renderedTypeParameters!! .flatMap { typeCandidates[it.typeInfo]!!.asSequence() }
} .forEach { typeParameterMap[it.renderedType!!] = it.renderedTypeParameters!! }
if (declaration.getReturnTypeReference() != null) { if (declaration.getReturnTypeReference() != null) {
typeCandidates[callableInfo.returnTypeInfo]!!.forEach { typeCandidates[callableInfo.returnTypeInfo]!!.forEach {
@@ -796,7 +797,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
} }
private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<JetParameter>): List<TypeExpression> { private fun setupParameterTypeTemplates(builder: TemplateBuilder, parameterList: List<JetParameter>): List<TypeExpression> {
assert(parameterList.size == callableInfo.parameterInfos.size) assert(parameterList.size() == callableInfo.parameterInfos.size())
val typeParameters = ArrayList<TypeExpression>() val typeParameters = ArrayList<TypeExpression>()
for ((parameter, jetParameter) in callableInfo.parameterInfos.zip(parameterList)) { for ((parameter, jetParameter) in callableInfo.parameterInfos.zip(parameterList)) {
@@ -808,7 +809,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val possibleNamesFromExpression = parameter.typeInfo.possibleNamesFromExpression val possibleNamesFromExpression = parameter.typeInfo.possibleNamesFromExpression
val preferredName = parameter.preferredName val preferredName = parameter.preferredName
val possibleNames = if (preferredName != null) { val possibleNames = if (preferredName != null) {
array(preferredName, *possibleNamesFromExpression) arrayOf(preferredName, *possibleNamesFromExpression)
} }
else { else {
possibleNamesFromExpression possibleNamesFromExpression
@@ -876,7 +877,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val newJavaMember = convertToJava(targetClass) ?: return false val newJavaMember = convertToJava(targetClass) ?: return false
val modifierList = newJavaMember.getModifierList() val modifierList = newJavaMember.getModifierList()!!
if (newJavaMember is PsiMethod || newJavaMember is PsiClass) { if (newJavaMember is PsiMethod || newJavaMember is PsiClass) {
modifierList.setModifierProperty(PsiModifier.FINAL, false) modifierList.setModifierProperty(PsiModifier.FINAL, false)
} }
@@ -938,7 +939,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
when (declaration) { when (declaration) {
is JetNamedFunction, is JetSecondaryConstructor -> { is JetNamedFunction, is JetSecondaryConstructor -> {
((declaration as JetFunction).getBodyExpression() as? JetBlockExpression)?.let { ((declaration as JetFunction).getBodyExpression() as? JetBlockExpression)?.let {
positionBetween(it.getLBrace(), it.getRBrace()) positionBetween(it.getLBrace()!!, it.getRBrace()!!)
} }
} }
is JetClassOrObject -> { is JetClassOrObject -> {
@@ -996,7 +997,7 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
val variables = templateImpl.getVariables()!! val variables = templateImpl.getVariables()!!
if (variables.isNotEmpty()) { if (variables.isNotEmpty()) {
val typeParametersVar = if (expression != null) variables.remove(0) else null val typeParametersVar = if (expression != null) variables.remove(0) else null
for (i in 0..(callableInfo.parameterInfos.size - 1)) { for (i in 0..(callableInfo.parameterInfos.size() - 1)) {
Collections.swap(variables, i * 2, i * 2 + 1) Collections.swap(variables, i * 2, i * 2 + 1)
} }
typeParametersVar?.let { variables.add(it) } typeParametersVar?.let { variables.add(it) }
@@ -54,7 +54,7 @@ private class ParameterNameExpression(
override fun calculateLookupItems(context: ExpressionContext?): Array<LookupElement>? { override fun calculateLookupItems(context: ExpressionContext?): Array<LookupElement>? {
context!! context!!
val names = LinkedHashSet<String>(this.names.toList()) val names = LinkedHashSet(this.names.toList())
// find the parameter list // find the parameter list
val project = context.getProject()!! val project = context.getProject()!!
@@ -63,15 +63,15 @@ private class ParameterNameExpression(
val editor = context.getEditor()!! val editor = context.getEditor()!!
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as JetFile val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as JetFile
val elementAt = file.findElementAt(offset) val elementAt = file.findElementAt(offset)
val declaration = PsiTreeUtil.getParentOfType(elementAt, javaClass<JetFunction>(), javaClass<JetClass>()) ?: return array<LookupElement>() val declaration = PsiTreeUtil.getParentOfType(elementAt, javaClass<JetFunction>(), javaClass<JetClass>()) ?: return arrayOf()
val parameterList = when (declaration) { val parameterList = when (declaration) {
is JetFunction -> declaration.getValueParameterList() is JetFunction -> declaration.getValueParameterList()!!
is JetClass -> declaration.getPrimaryConstructorParameterList() is JetClass -> declaration.getPrimaryConstructorParameterList()!!
else -> throw AssertionError("Unexpected declaration: ${declaration.getText()}") else -> throw AssertionError("Unexpected declaration: ${declaration.getText()}")
} }
// add names based on selected type // add names based on selected type
val parameter = elementAt.getStrictParentOfType<JetParameter>() val parameter = elementAt?.getStrictParentOfType<JetParameter>()
if (parameter != null) { if (parameter != null) {
val parameterTypeRef = parameter.getTypeReference() val parameterTypeRef = parameter.getTypeReference()
if (parameterTypeRef != null) { if (parameterTypeRef != null) {
@@ -83,7 +83,7 @@ private class ParameterNameExpression(
} }
// remember other parameter names for later use // remember other parameter names for later use
val parameterNames = parameterList.getParameters().stream().map { jetParameter -> val parameterNames = parameterList.getParameters().asSequence().map { jetParameter ->
if (jetParameter == parameter) null else jetParameter.getName() if (jetParameter == parameter) null else jetParameter.getName()
}.filterNotNullTo(HashSet<String>()) }.filterNotNullTo(HashSet<String>())
@@ -94,7 +94,7 @@ private class ParameterNameExpression(
// ensure there are no conflicts // ensure there are no conflicts
val validator = CollectingValidator(parameterNames) val validator = CollectingValidator(parameterNames)
return names.map { LookupElementBuilder.create(validator.validateName(it)) }.copyToArray() return names.map { LookupElementBuilder.create(validator.validateName(it)) }.toTypedArray()
} }
} }
@@ -104,7 +104,7 @@ private class ParameterNameExpression(
private abstract class TypeExpression(public val typeCandidates: List<TypeCandidate>) : Expression() { private abstract class TypeExpression(public val typeCandidates: List<TypeCandidate>) : Expression() {
class ForTypeReference(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) { class ForTypeReference(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) {
override val cachedLookupElements: Array<LookupElement> = override val cachedLookupElements: Array<LookupElement> =
typeCandidates.map { LookupElementBuilder.create(it, it.renderedType!!) }.copyToArray() typeCandidates.map { LookupElementBuilder.create(it, it.renderedType!!) }.toTypedArray()
} }
class ForDelegationSpecifier(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) { class ForDelegationSpecifier(typeCandidates: List<TypeCandidate>) : TypeExpression(typeCandidates) {
@@ -113,14 +113,14 @@ private abstract class TypeExpression(public val typeCandidates: List<TypeCandid
val descriptor = it.theType.getConstructor().getDeclarationDescriptor() as ClassDescriptor val descriptor = it.theType.getConstructor().getDeclarationDescriptor() as ClassDescriptor
val text = it.renderedType!! + if (descriptor.getKind() == ClassKind.INTERFACE) "" else "()" val text = it.renderedType!! + if (descriptor.getKind() == ClassKind.INTERFACE) "" else "()"
LookupElementBuilder.create(it, text) LookupElementBuilder.create(it, text)
}.copyToArray() }.toTypedArray()
} }
protected abstract val cachedLookupElements: Array<LookupElement> protected abstract val cachedLookupElements: Array<LookupElement>
override fun calculateResult(context: ExpressionContext?): Result { override fun calculateResult(context: ExpressionContext?): Result {
val lookupItems = calculateLookupItems(context) val lookupItems = calculateLookupItems(context)
return TextResult(if (lookupItems.size == 0) "" else lookupItems[0].getLookupString()) return TextResult(if (lookupItems.size() == 0) "" else lookupItems[0].getLookupString())
} }
override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context) override fun calculateQuickResult(context: ExpressionContext?) = calculateResult(context)
@@ -148,7 +148,7 @@ private class TypeParameterListExpression(private val mandatoryTypeParameters: L
val editor = context.getEditor()!! val editor = context.getEditor()!!
val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as JetFile val file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()) as JetFile
val elementAt = file.findElementAt(offset) val elementAt = file.findElementAt(offset)
val declaration = elementAt.getStrictParentOfType<JetNamedDeclaration>() ?: return TextResult("") val declaration = elementAt?.getStrictParentOfType<JetNamedDeclaration>() ?: return TextResult("")
val renderedTypeParameters = LinkedHashSet<RenderedTypeParameter>() val renderedTypeParameters = LinkedHashSet<RenderedTypeParameter>()
renderedTypeParameters.addAll(mandatoryTypeParameters) renderedTypeParameters.addAll(mandatoryTypeParameters)
@@ -174,18 +174,18 @@ private class TypeParameterListExpression(private val mandatoryTypeParameters: L
currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter } currentTypeParameters = sortedRenderedTypeParameters.map { it.typeParameter }
return TextResult( return TextResult(
if (sortedRenderedTypeParameters.empty) "" else sortedRenderedTypeParameters.map { it.text }.joinToString(", ", prefix, ">") if (sortedRenderedTypeParameters.isEmpty()) "" else sortedRenderedTypeParameters.map { it.text }.joinToString(", ", prefix, ">")
) )
} }
override fun calculateQuickResult(context: ExpressionContext?): Result = calculateResult(context) override fun calculateQuickResult(context: ExpressionContext?): Result = calculateResult(context)
// do not offer the user any choices // do not offer the user any choices
override fun calculateLookupItems(context: ExpressionContext?) = array<LookupElement>() override fun calculateLookupItems(context: ExpressionContext?) = arrayOf<LookupElement>()
} }
private object ValVarExpression: Expression() { private object ValVarExpression: Expression() {
private val cachedLookupElements = listOf("val", "var").map { LookupElementBuilder.create(it) }.copyToArray<LookupElement>() private val cachedLookupElements = listOf("val", "var").map { LookupElementBuilder.create(it) }.toTypedArray<LookupElement>()
override fun calculateResult(context: ExpressionContext?): Result? = TextResult("val") override fun calculateResult(context: ExpressionContext?): Result? = TextResult("val")
@@ -96,14 +96,14 @@ fun JetExpression.guessTypes(
if (coerceUnusedToUnit if (coerceUnusedToUnit
&& this !is JetDeclaration && this !is JetDeclaration
&& isUsedAsStatement(context) && isUsedAsStatement(context)
&& getNonStrictParentOfType<JetAnnotationEntry>() == null) return array(module.builtIns.getUnitType()) && getNonStrictParentOfType<JetAnnotationEntry>() == null) return arrayOf(module.builtIns.getUnitType())
// if we know the actual type of the expression // if we know the actual type of the expression
val theType1 = context.getType(this) val theType1 = context.getType(this)
if (theType1 != null) { if (theType1 != null) {
val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo val dataFlowInfo = context[BindingContext.EXPRESSION_TYPE_INFO, this]?.dataFlowInfo
val possibleTypes = dataFlowInfo?.getPossibleTypes(DataFlowValueFactory.createDataFlowValue(this, theType1, context, module)) val possibleTypes = dataFlowInfo?.getPossibleTypes(DataFlowValueFactory.createDataFlowValue(this, theType1, context, module))
return if (possibleTypes != null && possibleTypes.isNotEmpty()) possibleTypes.copyToArray() else array(theType1) return if (possibleTypes != null && possibleTypes.isNotEmpty()) possibleTypes.toTypedArray() else arrayOf(theType1)
} }
// expression has an expected type // expression has an expected type
@@ -115,19 +115,19 @@ fun JetExpression.guessTypes(
this is JetTypeConstraint -> { this is JetTypeConstraint -> {
// expression itself is a type assertion // expression itself is a type assertion
val constraint = this val constraint = this
array(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!) arrayOf(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!)
} }
parent is JetTypeConstraint -> { parent is JetTypeConstraint -> {
// expression is on the left side of a type assertion // expression is on the left side of a type assertion
val constraint = parent val constraint = parent
array(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!) arrayOf(context[BindingContext.TYPE, constraint.getBoundTypeReference()]!!)
} }
this is JetMultiDeclarationEntry -> { this is JetMultiDeclarationEntry -> {
// expression is on the lhs of a multi-declaration // expression is on the lhs of a multi-declaration
val typeRef = getTypeReference() val typeRef = getTypeReference()
if (typeRef != null) { if (typeRef != null) {
// and has a specified type // and has a specified type
array(context[BindingContext.TYPE, typeRef]!!) arrayOf(context[BindingContext.TYPE, typeRef]!!)
} }
else { else {
// otherwise guess // otherwise guess
@@ -139,7 +139,7 @@ fun JetExpression.guessTypes(
val typeRef = getTypeReference() val typeRef = getTypeReference()
if (typeRef != null) { if (typeRef != null) {
// and has a specified type // and has a specified type
array(context[BindingContext.TYPE, typeRef]!!) arrayOf(context[BindingContext.TYPE, typeRef]!!)
} }
else { else {
// otherwise guess // otherwise guess
@@ -152,7 +152,7 @@ fun JetExpression.guessTypes(
val typeRef = variable.getTypeReference() val typeRef = variable.getTypeReference()
if (typeRef != null) { if (typeRef != null) {
// and has a specified type // and has a specified type
array(context[BindingContext.TYPE, typeRef]!!) arrayOf(context[BindingContext.TYPE, typeRef]!!)
} }
else { else {
// otherwise guess, based on LHS // otherwise guess, based on LHS
@@ -163,14 +163,14 @@ fun JetExpression.guessTypes(
val property = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.getParent() as JetProperty] as PropertyDescriptor val property = context[BindingContext.DECLARATION_TO_DESCRIPTOR, parent.getParent() as JetProperty] as PropertyDescriptor
val delegateClassName = if (property.isVar()) "ReadWriteProperty" else "ReadOnlyProperty" val delegateClassName = if (property.isVar()) "ReadWriteProperty" else "ReadOnlyProperty"
val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName")) val delegateClass = module.resolveTopLevelClass(FqName("kotlin.properties.$delegateClassName"))
?: return array(module.builtIns.getAnyType()) ?: return arrayOf(module.builtIns.getAnyType())
val receiverType = (property.getExtensionReceiverParameter() ?: property.getDispatchReceiverParameter())?.getType() val receiverType = (property.getExtensionReceiverParameter() ?: property.getDispatchReceiverParameter())?.getType()
?: module.builtIns.getNullableNothingType() ?: module.builtIns.getNullableNothingType()
val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(property.getType())) val typeArguments = listOf(TypeProjectionImpl(receiverType), TypeProjectionImpl(property.getType()))
array(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments)) arrayOf(TypeUtils.substituteProjectionsForParameters(delegateClass, typeArguments))
} }
parent is JetStringTemplateEntryWithExpression && parent.getExpression() == this -> { parent is JetStringTemplateEntryWithExpression && parent.getExpression() == this -> {
array(module.builtIns.getStringType()) arrayOf(module.builtIns.getStringType())
} }
else -> { else -> {
pseudocode?.getElementValue(this)?.let { pseudocode?.getElementValue(this)?.let {
@@ -181,7 +181,7 @@ fun JetExpression.guessTypes(
} }
private fun JetNamedDeclaration.guessType(context: BindingContext): Array<JetType> { private fun JetNamedDeclaration.guessType(context: BindingContext): Array<JetType> {
val expectedTypes = SearchUtils.findAllReferences(this, getUseScope())!!.sequence().map { ref -> val expectedTypes = SearchUtils.findAllReferences(this, getUseScope())!!.asSequence().map { ref ->
if (ref is JetSimpleNameReference) { if (ref is JetSimpleNameReference) {
context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression] context[BindingContext.EXPECTED_EXPRESSION_TYPE, ref.expression]
} }
@@ -191,15 +191,15 @@ private fun JetNamedDeclaration.guessType(context: BindingContext): Array<JetTyp
}.filterNotNullTo(HashSet<JetType>()) }.filterNotNullTo(HashSet<JetType>())
if (expectedTypes.isEmpty() || expectedTypes.any { expectedType -> ErrorUtils.containsErrorType(expectedType) }) { if (expectedTypes.isEmpty() || expectedTypes.any { expectedType -> ErrorUtils.containsErrorType(expectedType) }) {
return array<JetType>() return arrayOf()
} }
val theType = TypeUtils.intersect(JetTypeChecker.DEFAULT, expectedTypes) val theType = TypeUtils.intersect(JetTypeChecker.DEFAULT, expectedTypes)
if (theType != null) { if (theType != null) {
return array<JetType>(theType) return arrayOf(theType)
} }
else { else {
// intersection doesn't exist; let user make an imperfect choice // intersection doesn't exist; let user make an imperfect choice
return expectedTypes.copyToArray() return expectedTypes.toTypedArray()
} }
} }
@@ -53,7 +53,7 @@ public class CreateCallableFromUsageFix(
} }
private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate): PsiElement? { private fun getDeclarationIfApplicable(project: Project, candidate: TypeCandidate): PsiElement? {
val descriptor = candidate.theType.getConstructor().getDeclarationDescriptor() val descriptor = candidate.theType.getConstructor().getDeclarationDescriptor() ?: return null
val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return null val declaration = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) ?: return null
if (declaration !is JetClassOrObject && declaration !is PsiClass) return null if (declaration !is JetClassOrObject && declaration !is PsiClass) return null
return if (isExtension || declaration.canRefactor()) declaration else null return if (isExtension || declaration.canRefactor()) declaration else null
@@ -42,14 +42,14 @@ object CreateComponentFunctionActionFactory : JetIntentionActionsFactory() {
TypeInfo(diagnosticWithParameters.getB(), Variance.IN_VARIANCE) TypeInfo(diagnosticWithParameters.getB(), Variance.IN_VARIANCE)
} }
else { else {
val rhs = multiDeclaration!!.getInitializer() ?: return null val rhs = multiDeclaration.getInitializer() ?: return null
TypeInfo(rhs, Variance.IN_VARIANCE) TypeInfo(rhs, Variance.IN_VARIANCE)
} }
val entries = multiDeclaration!!.getEntries() val entries = multiDeclaration.getEntries()
val entry = entries[componentNumber] val entry = entries[componentNumber]
val returnType = TypeInfo(entry, Variance.OUT_VARIANCE) val returnType = TypeInfo(entry, Variance.OUT_VARIANCE)
return CreateCallableFromUsageFixes(multiDeclaration!!, FunctionInfo(name.getIdentifier(), ownerType, returnType)) return CreateCallableFromUsageFixes(multiDeclaration, FunctionInfo(name.getIdentifier(), ownerType, returnType))
} }
} }
@@ -38,7 +38,6 @@ object CreatePropertyDelegateAccessorsActionFactory : JetIntentionActionsFactory
override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction>? { override fun doCreateActions(diagnostic: Diagnostic): List<IntentionAction>? {
val expression = diagnostic.getPsiElement() as? JetExpression ?: return null val expression = diagnostic.getPsiElement() as? JetExpression ?: return null
val context = expression.analyze() val context = expression.analyze()
[suppress("UNCHECKED_CAST")]
fun isApplicableForAccessor(accessor: PropertyAccessorDescriptor?): Boolean = fun isApplicableForAccessor(accessor: PropertyAccessorDescriptor?): Boolean =
accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null accessor != null && context[BindingContext.DELEGATED_PROPERTY_RESOLVED_CALL, accessor] == null
@@ -65,7 +65,7 @@ public object CreateClassFromCallWithConstructorCalleeActionFactory : JetSingleI
val anyType = KotlinBuiltIns.getInstance().getNullableAnyType() val anyType = KotlinBuiltIns.getInstance().getNullableAnyType()
val valueArguments = callElement.getValueArguments() val valueArguments = callElement.getValueArguments()
val defaultParamName = if (valueArguments.size == 1) "value" else null val defaultParamName = if (valueArguments.size() == 1) "value" else null
val parameterInfos = valueArguments.map { val parameterInfos = valueArguments.map {
ParameterInfo( ParameterInfo(
it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE), it.getArgumentExpression()?.let { TypeInfo(it, Variance.IN_VARIANCE) } ?: TypeInfo(anyType, Variance.IN_VARIANCE),
@@ -75,7 +75,9 @@ public object CreateClassFromCallWithConstructorCalleeActionFactory : JetSingleI
val typeArgumentInfos = when { val typeArgumentInfos = when {
isAnnotation -> Collections.emptyList<TypeInfo>() isAnnotation -> Collections.emptyList<TypeInfo>()
else -> callElement.getTypeArguments().map { TypeInfo(it.getTypeReference(), Variance.INVARIANT) } else -> callElement.getTypeArguments()
.map { it.getTypeReference()?.let { TypeInfo(it, Variance.INVARIANT) } }
.filterNotNull()
} }
val classInfo = ClassInfo( val classInfo = ClassInfo(
@@ -61,7 +61,7 @@ public object CreateClassFromConstructorCallActionFactory: JetSingleIntentionAct
val inner = isInnerClassExpected(call) val inner = isInnerClassExpected(call)
val valueArguments = callExpr.getValueArguments() val valueArguments = callExpr.getValueArguments()
val defaultParamName = if (inAnnotationEntry && valueArguments.size == 1) "value" else null val defaultParamName = if (inAnnotationEntry && valueArguments.size() == 1) "value" else null
val anyType = KotlinBuiltIns.getInstance().getNullableAnyType() val anyType = KotlinBuiltIns.getInstance().getNullableAnyType()
val parameterInfos = valueArguments.map { val parameterInfos = valueArguments.map {
ParameterInfo( ParameterInfo(
@@ -83,7 +83,7 @@ public object CreateClassFromReferenceExpressionActionFactory : JetIntentionActi
val createPackageAction = refExpr.getCreatePackageFixIfApplicable(targetParent) val createPackageAction = refExpr.getCreatePackageFixIfApplicable(targetParent)
if (createPackageAction != null) return Collections.singletonList(createPackageAction) if (createPackageAction != null) return Collections.singletonList(createPackageAction)
return (if (name.checkClassName()) ClassKind.values() else array()) return (if (name.checkClassName()) ClassKind.values() else arrayOf())
.filter { .filter {
when (it) { when (it) {
ClassKind.ANNOTATION_CLASS -> inImport ClassKind.ANNOTATION_CLASS -> inImport
@@ -21,7 +21,10 @@ import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.editor.Editor import com.intellij.openapi.editor.Editor
import com.intellij.openapi.module.ModuleUtilCore import com.intellij.openapi.module.ModuleUtilCore
import com.intellij.openapi.project.Project import com.intellij.openapi.project.Project
import com.intellij.psi.* import com.intellij.psi.PsiClass
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiPackage
import org.jetbrains.kotlin.idea.JetBundle import org.jetbrains.kotlin.idea.JetBundle
import org.jetbrains.kotlin.idea.JetFileType import org.jetbrains.kotlin.idea.JetFileType
import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils import org.jetbrains.kotlin.idea.codeInsight.CodeInsightUtils
@@ -66,7 +69,7 @@ public class CreateClassFromUsageFix(
override fun getText(): String = override fun getText(): String =
JetBundle.message("create.0.from.usage", "${classInfo.kind.description} '${classInfo.name}'") JetBundle.message("create.0.from.usage", "${classInfo.kind.description} '${classInfo.name}'")
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean { override fun isAvailable(project: Project, editor: Editor?, file: PsiFile): Boolean {
if (!super.isAvailable(project, editor, file)) return false if (!super.isAvailable(project, editor, file)) return false
with(classInfo) { with(classInfo) {
if (targetParent is PsiClass) { if (targetParent is PsiClass) {
@@ -87,8 +90,8 @@ public class CreateClassFromUsageFix(
directories.firstOrNull { ModuleUtilCore.findModuleForPsiElement(it) == currentModule } directories.firstOrNull { ModuleUtilCore.findModuleForPsiElement(it) == currentModule }
?: directories.firstOrNull() ?: directories.firstOrNull()
val targetDirectory = if (directories.size > 1 && !ApplicationManager.getApplication().isUnitTestMode()) { val targetDirectory = if (directories.size() > 1 && !ApplicationManager.getApplication().isUnitTestMode()) {
DirectoryChooserUtil.chooseDirectory(directories.copyToArray(), preferredDirectory, project, HashMap<PsiDirectory, String>()) DirectoryChooserUtil.chooseDirectory(directories.toTypedArray(), preferredDirectory, project, HashMap())
} }
else { else {
preferredDirectory preferredDirectory
@@ -95,7 +95,7 @@ private fun JetExpression.getInheritableTypeInfo(
if (types.size() != 1) return TypeInfo.Empty to { classKind -> true } if (types.size() != 1) return TypeInfo.Empty to { classKind -> true }
val type = types.first() val type = types.first()
val descriptor = type.getConstructor().getDeclarationDescriptor() val descriptor = type.getConstructor().getDeclarationDescriptor() ?: return TypeInfo.Empty to { classKind -> false }
val canHaveSubtypes = TypeUtils.canHaveSubtypes(JetTypeChecker.DEFAULT, type) val canHaveSubtypes = TypeUtils.canHaveSubtypes(JetTypeChecker.DEFAULT, type)
val isEnum = DescriptorUtils.isEnumClass(descriptor) val isEnum = DescriptorUtils.isEnumClass(descriptor)