Code cleanup: unnecessary local variable applied

This commit is contained in:
Mikhail Glukhikh
2017-07-20 16:10:35 +03:00
parent 202fb19cf6
commit 951e8cd91a
57 changed files with 118 additions and 203 deletions
@@ -448,12 +448,11 @@ fun createSpacingBuilder(settings: CodeStyleSettings, builderUtil: KotlinSpacing
.customRule { _, _, right ->
val rightNode = right.node!!
val rightType = rightNode.elementType
val numSpaces = spacesInSimpleFunction
if (rightType == VALUE_PARAMETER_LIST) {
createSpacing(numSpaces, keepLineBreaks = false)
createSpacing(spacesInSimpleFunction, keepLineBreaks = false)
}
else {
createSpacing(numSpaces)
createSpacing(spacesInSimpleFunction)
}
}
@@ -120,8 +120,7 @@ fun collectAllModuleInfosFromIdeaModel(project: Project): List<IdeaModuleInfo> {
val sdksInfos = (sdksFromModulesDependencies + getAllProjectSdks()).filterNotNull().toSet().map { SdkInfo(project, it) }
val collectAllModuleInfos = modulesSourcesInfos + librariesInfos + sdksInfos
return collectAllModuleInfos
return modulesSourcesInfos + librariesInfos + sdksInfos
}
private fun createBuiltIns(settings: PlatformAnalysisSettings, sdkContext: GlobalContextImpl): KotlinBuiltIns = when {
@@ -85,9 +85,8 @@ class ScriptExternalHighlightingPass(
private fun Int.coerceLineIn(document: Document) = coerceIn(0, document.lineCount - 1)
private fun Document.offsetBy(line: Int, col: Int): Int {
val offset = (getLineStartOffset(line) + col).
return (getLineStartOffset(line) + col).
coerceIn(getLineStartOffset(line), getLineEndOffset(line))
return offset
}
private fun ScriptReport.Severity.convertSeverity(): HighlightSeverity? {
@@ -177,19 +177,18 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName:
}
private fun analyzeSingleImport(result: Result, importedFqName: FqName?, isAllUnder: Boolean, aliasName: String?): Result {
val qName = importedFqName
if (!isAllUnder) {
if (qName?.asString() == targetClassFqName &&
if (importedFqName?.asString() == targetClassFqName &&
(aliasName == null || aliasName == targetShortName)) {
return result.changeTo(Result.Found)
}
else if (qName?.shortName()?.asString() == targetShortName &&
qName.parent().asString() in conflictingPackages &&
else if (importedFqName?.shortName()?.asString() == targetShortName &&
importedFqName.parent().asString() in conflictingPackages &&
aliasName == null) {
return result.changeTo(Result.FoundOther)
}
else if (qName?.shortName()?.asString() == targetShortName &&
qName.parent().asString() in packagesWithTypeAliases &&
else if (importedFqName?.shortName()?.asString() == targetShortName &&
importedFqName.parent().asString() in packagesWithTypeAliases &&
aliasName == null) {
return Result.Ambiguity
}
@@ -199,9 +198,9 @@ class PsiBasedClassResolver @TestOnly constructor(private val targetClassFqName:
}
else {
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
importedFqName?.asString() == targetPackage -> return result.changeTo(Result.Found)
importedFqName?.asString() in conflictingPackages -> return result.changeTo(Result.FoundOther)
importedFqName?.asString() in packagesWithTypeAliases -> return Result.Ambiguity
}
}
return result
@@ -37,14 +37,12 @@ class CommentSaver(originalElements: PsiChildRange, private val saveLineBreaks:
companion object {
fun create(element: PsiElement): TreeElement? {
val tokenType = element.tokenType
val treeElement = when {
return when {
element is PsiWhiteSpace -> if (element.textContains('\n')) LineBreakTreeElement() else null
element is PsiComment -> CommentTreeElement.create(element)
tokenType != null -> TokenTreeElement(tokenType)
else -> if (element.textLength > 0) StandardTreeElement() else null // don't save empty elements
}
// treeElement?.debugText = element.getText()
return treeElement
}
}
@@ -52,7 +52,7 @@ internal fun KtClass.findComponentDeclarationInManifest(manifest: Manifest): And
val application = manifest.application ?: return null
val type = (resolveToDescriptor(BodyResolveMode.PARTIAL) as? ClassDescriptor)?.defaultType ?: return null
val component = when {
return when {
type.isSubclassOf(AndroidUtils.ACTIVITY_BASE_CLASS_NAME) ->
application.activities?.find { it.activityClass.value?.qualifiedName == fqName?.asString() }?.activityClass
type.isSubclassOf(AndroidUtils.SERVICE_CLASS_NAME) ->
@@ -63,8 +63,6 @@ internal fun KtClass.findComponentDeclarationInManifest(manifest: Manifest): And
application.providers?.find { it.providerClass.value?.qualifiedName == fqName?.asString() }?.providerClass
else -> null
}
return component
}
internal fun PsiElement.getAndroidFacetForFile(): AndroidFacet? {
@@ -194,8 +194,7 @@ class NewKotlinActivityAction: AnAction(KotlinIcons.ACTIVITY) {
val project = e.project
if (project == null || project.isDisposed) return null
val module = LangDataKeys.MODULE.getData(e.dataContext)
val facet = if (module != null) AndroidFacet.getInstance(module) else null
return facet
return if (module != null) AndroidFacet.getInstance(module) else null
}
private fun isVisible(facet: AndroidFacet): Boolean {
@@ -90,7 +90,7 @@ object LambdaItems {
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.lambdaPresentation(functionType, signaturePresentation)
val lookupElement = LookupElementBuilder.create(lookupString)
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
@@ -101,6 +101,5 @@ object LambdaItems {
.suppressAutoInsertion()
.assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA)
.addTailAndNameSimilarity(functionExpectedInfos.filter { it.fuzzyType?.type == functionType })
return lookupElement
}
}
@@ -73,7 +73,7 @@ object LambdaSignatureItems {
SmartCompletionItemPriority.LAMBDA_SIGNATURE_EXPLICIT_PARAMETER_TYPES
else
SmartCompletionItemPriority.LAMBDA_SIGNATURE
val lookupElement = LookupElementBuilder.create(lookupString)
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
@@ -82,6 +82,5 @@ object LambdaSignatureItems {
})
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
return lookupElement
}
}
@@ -37,8 +37,7 @@ class KotlinScriptDependenciesClassFinder(project: Project,
object : ConcurrentFactoryMap<VirtualFile, PackageDirectoryCache>() {
override fun create(file: VirtualFile): PackageDirectoryCache? {
val scriptClasspath = scriptDependenciesManager.getScriptClasspath(file)
val v = createCache(scriptClasspath)
return v
return createCache(scriptClasspath)
}
}
}
@@ -42,8 +42,7 @@ class CommandExecutor(private val runner: KotlinConsoleRunner) {
private fun getTrimmedCommandText(): String {
val consoleView = runner.consoleView
val document = consoleView.editorDocument
val inputText = document.text.trim()
return inputText
return document.text.trim()
}
private fun sendCommandToProcess(command: String) {
@@ -151,13 +151,13 @@ class ReplOutputProcessor(
logError(this::class.java, internalErrorText)
}
private fun getAttributesForSeverity(start: Int, end: Int, severity: Severity): TextAttributes {
val attributes = when (severity) {
Severity.ERROR -> getAttributesForSeverity(HighlightInfoType.ERROR, HighlightSeverity.ERROR, CodeInsightColors.ERRORS_ATTRIBUTES, start, end)
Severity.WARNING -> getAttributesForSeverity(HighlightInfoType.WARNING, HighlightSeverity.WARNING, CodeInsightColors.WARNINGS_ATTRIBUTES, start, end)
Severity.INFO -> getAttributesForSeverity(HighlightInfoType.WEAK_WARNING, HighlightSeverity.WEAK_WARNING, CodeInsightColors.WEAK_WARNING_ATTRIBUTES, start, end)
}
return attributes
private fun getAttributesForSeverity(start: Int, end: Int, severity: Severity): TextAttributes = when (severity) {
Severity.ERROR ->
getAttributesForSeverity(HighlightInfoType.ERROR, HighlightSeverity.ERROR, CodeInsightColors.ERRORS_ATTRIBUTES, start, end)
Severity.WARNING ->
getAttributesForSeverity(HighlightInfoType.WARNING, HighlightSeverity.WARNING, CodeInsightColors.WARNINGS_ATTRIBUTES, start, end)
Severity.INFO ->
getAttributesForSeverity(HighlightInfoType.WEAK_WARNING, HighlightSeverity.WEAK_WARNING, CodeInsightColors.WEAK_WARNING_ATTRIBUTES, start, end)
}
private fun getAttributesForSeverity(
@@ -113,12 +113,11 @@ class KotlinGenerateToStringAction : KotlinGenerateMemberActionBase<KotlinGenera
protected fun renderVariableValue(variableDescriptor: VariableDescriptor, ref: String): String {
val type = variableDescriptor.type
val rhs = when {
return when {
KotlinBuiltIns.isArray(type) || KotlinBuiltIns.isPrimitiveArray(type) -> "\${java.util.Arrays.toString($ref)}"
KotlinBuiltIns.isString(type) -> "'$$ref'"
else -> "$$ref"
}
return rhs
}
abstract fun generate(info: Info): String
@@ -137,8 +137,7 @@ class KotlinSetupEnvironmentNotificationProvider(
}
}
}
val configuratorsPopup = JBPopupFactory.getInstance().createListPopup(step)
return configuratorsPopup
return JBPopupFactory.getInstance().createListPopup(step)
}
}
}
@@ -262,7 +262,7 @@ class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransf
}
}
val copiedJavaCode = when (context) {
return when (context) {
JavaContext.TOP_LEVEL -> createCopiedJavaCode(prefix, "$", text)
JavaContext.CLASS_BODY -> createCopiedJavaCode(prefix, "$classDef {\n$\n}", text)
@@ -271,8 +271,6 @@ class ConvertTextJavaCopyPasteProcessor : CopyPastePostProcessor<TextBlockTransf
JavaContext.EXPRESSION -> createCopiedJavaCode(prefix, "$classDef {\nObject field = $\n}", text)
}
return copiedJavaCode
}
private fun createCopiedJavaCode(prefix: String, templateWithoutPrefix: String, text: String): CopiedJavaCode {
@@ -269,9 +269,8 @@ internal fun getLocationsOfInlinedLine(type: ReferenceType, position: SourcePosi
}
val lines = inlinedLinesNumbers(line + 1, position.file.name, FqName(type.name()), type.sourceName(), project, sourceSearchScope)
val inlineLocations = lines.flatMap { type.locationsOfLine(it) }
return inlineLocations
return lines.flatMap { type.locationsOfLine(it) }
}
fun isInCrossinlineArgument(ktElement: KtElement): Boolean {
@@ -313,13 +312,11 @@ private fun inlinedLinesNumbers(
val mappingsToInlinedFile = smap.fileMappings.filter { it.name == inlineFileName }
val mappingIntervals = mappingsToInlinedFile.flatMap { it.lineMappings }
val mappedLines = mappingIntervals.asSequence().
return mappingIntervals.asSequence().
filter { rangeMapping -> rangeMapping.hasMappingForSource(inlineLineNumber) }.
map { rangeMapping -> rangeMapping.mapSourceToDest(inlineLineNumber) }.
filter { line -> line != -1 }.
toList()
return mappedLines
}
@Volatile var emulateDexDebugInTests: Boolean = false
@@ -186,8 +186,7 @@ private fun getInlineFunctionsIfAny(file: KtFile, offset: Int): List<KtNamedFunc
val descriptor = containingFunction.resolveToDescriptor()
if (!InlineUtil.isInline(descriptor)) return emptyList()
val inlineFunctionsCalls = DebuggerUtils.analyzeElementWithInline(containingFunction, false).filterIsInstance<KtNamedFunction>()
return inlineFunctionsCalls
return DebuggerUtils.analyzeElementWithInline(containingFunction, false).filterIsInstance<KtNamedFunction>()
}
private fun getInlineArgumentsIfAny(inlineFunctionCalls: List<KtCallExpression>): List<KtFunction> {
@@ -191,10 +191,8 @@ abstract class CustomLibraryDescriptorWithDeferredConfig
}
private val configurator: KotlinWithLibraryConfigurator
get() {
val configurator = getConfiguratorByName(configuratorName) as KotlinWithLibraryConfigurator? ?: error("Configurator with name $configuratorName should exists")
return configurator
}
get() = getConfiguratorByName(configuratorName) as KotlinWithLibraryConfigurator?
?: error("Configurator with name ${configuratorName} should exists")
// Implements an API added in IDEA 16
override fun createNewLibraryWithDefaultSettings(contextDirectory: VirtualFile?): NewLibraryConfiguration? {
@@ -166,7 +166,7 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection(), Clean
}
private fun createFixes(property: KtProperty, conflictingExtension: SyntheticJavaPropertyDescriptor, isOnTheFly: Boolean): Array<IntentionWrapper> {
val fixes = if (isSameAsSynthetic(property, conflictingExtension)) {
return if (isSameAsSynthetic(property, conflictingExtension)) {
val fix1 = IntentionWrapper(DeleteRedundantExtensionAction(property), property.containingFile)
// don't add the second fix when on the fly to allow code cleanup
val fix2 = if (isOnTheFly)
@@ -178,7 +178,6 @@ class ConflictingExtensionPropertyInspection : AbstractKotlinInspection(), Clean
else {
emptyArray()
}
return fixes
}
private class DeleteRedundantExtensionAction(property: KtProperty) : KotlinQuickFixAction<KtProperty>(property) {
@@ -17,7 +17,6 @@
package org.jetbrains.kotlin.idea.intentions
import com.intellij.codeInsight.CodeInsightUtil
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInsight.daemon.impl.quickfix.CreateClassKind
import com.intellij.codeInsight.intention.impl.CreateClassDialog
import com.intellij.openapi.application.ApplicationManager
@@ -47,17 +46,16 @@ private const val IMPL_SUFFIX = "Impl"
class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>(KtClass::class.java, "Create Kotlin subclass") {
override fun applicabilityRange(element: KtClass): TextRange? {
val baseClass = element
if (baseClass.name == null || baseClass.getParentOfType<KtFunction>(true) != null) {
if (element.name == null || element.getParentOfType<KtFunction>(true) != null) {
// Local / anonymous classes are not supported
return null
}
if (!baseClass.isInterface() && !baseClass.isSealed() && !baseClass.isAbstract() && !baseClass.hasModifier(KtTokens.OPEN_KEYWORD)) {
if (!element.isInterface() && !element.isSealed() && !element.isAbstract() && !element.hasModifier(KtTokens.OPEN_KEYWORD)) {
return null
}
val primaryConstructor = baseClass.primaryConstructor
if (!baseClass.isInterface() && primaryConstructor != null) {
val constructors = baseClass.secondaryConstructors + primaryConstructor
val primaryConstructor = element.primaryConstructor
if (!element.isInterface() && primaryConstructor != null) {
val constructors = element.secondaryConstructors + primaryConstructor
if (constructors.none() {
!it.isPrivate() &&
it.getValueParameters().all { it.hasDefaultValue() }
@@ -67,8 +65,8 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>(KtCla
return null
}
}
text = getImplementTitle(baseClass)
return TextRange(baseClass.startOffset, baseClass.getBody()?.lBrace?.startOffset ?: baseClass.endOffset)
text = getImplementTitle(element)
return TextRange(element.startOffset, element.getBody()?.lBrace?.startOffset ?: element.endOffset)
}
private fun getImplementTitle(baseClass: KtClass) =
@@ -85,12 +83,11 @@ class CreateKotlinSubClassIntention : SelfTargetingRangeIntention<KtClass>(KtCla
if (editor == null) throw IllegalArgumentException("This intention requires an editor")
val name = element.name ?: throw IllegalStateException("This intention should not be applied to anonymous classes")
val baseClass = element
if (baseClass.isSealed()) {
createSealedSubclass(baseClass, name, editor)
if (element.isSealed()) {
createSealedSubclass(element, name, editor)
}
else {
createExternalSubclass(baseClass, name, editor)
createExternalSubclass(element, name, editor)
}
}
@@ -96,8 +96,7 @@ class AddNameToArgumentFix(argument: KtValueArgument) : KotlinQuickFixAction<KtV
private fun createArgumentWithName(name: Name): KtValueArgument {
val argumentExpression = element!!.getArgumentExpression()!!
val newArgument = KtPsiFactory(element!!).createArgument(argumentExpression, name, element!!.getSpreadElement() != null)
return newArgument
return KtPsiFactory(element!!).createArgument(argumentExpression, name, element!!.getSpreadElement() != null)
}
private fun chooseNameAndAdd(project: Project, editor: Editor, names: List<Name>) {
@@ -68,7 +68,8 @@ abstract class KotlinIntentionActionFactoryWithDelegate<E : KtElement, D : Any>
// Cache data so that it can be shared between quick fixes bound to the same element & diagnostic
// Cache null values
val cachedData: Ref<D> = Ref.create(extractFixData(originalElement, diagnostic))
val actions: List<QuickFixWithDelegateFactory> = try {
return try {
createFixes(originalElementPointer, diagnostic) factory@ {
val element = originalElementPointer.element ?: return@factory null
val diagnosticElement = diagnosticElementPointer.element ?: return@factory null
@@ -86,7 +87,5 @@ abstract class KotlinIntentionActionFactoryWithDelegate<E : KtElement, D : Any>
finally {
cachedData.set(null) // Do not keep cache after all actions are initialized
}
return actions
}
}
@@ -159,8 +159,7 @@ fun KtExpression.guessTypes(
}
parent is KtTypeConstraint -> {
// expression is on the left side of a type assertion
val constraint = parent
arrayOf(context[BindingContext.TYPE, constraint.boundTypeReference]!!)
arrayOf(context[BindingContext.TYPE, parent.boundTypeReference]!!)
}
this is KtDestructuringDeclarationEntry -> {
// expression is on the lhs of a multi-declaration
@@ -188,15 +187,14 @@ fun KtExpression.guessTypes(
}
parent is KtProperty && parent.isLocal -> {
// the expression is the RHS of a variable assignment with a specified type
val variable = parent
val typeRef = variable.typeReference
val typeRef = parent.typeReference
if (typeRef != null) {
// and has a specified type
arrayOf(context[BindingContext.TYPE, typeRef]!!)
}
else {
// otherwise guess, based on LHS
variable.guessType(context)
parent.guessType(context)
}
}
parent is KtPropertyDelegate -> {
@@ -32,14 +32,12 @@ abstract class CreateClassFromUsageFactory<E : KtElement> : KotlinIntentionActio
): List<QuickFixWithDelegateFactory> {
val possibleClassKinds = getPossibleClassKinds(originalElementPointer.element ?: return emptyList(), diagnostic)
val classFixes = possibleClassKinds.map { classKind ->
return possibleClassKinds.map { classKind ->
QuickFixWithDelegateFactory(classKind.actionPriority) {
val currentElement = originalElementPointer.element ?: return@QuickFixWithDelegateFactory null
val data = quickFixDataFactory() ?: return@QuickFixWithDelegateFactory null
CreateClassFromUsageFix.create(currentElement, data.copy(kind = classKind))
}
}
return classFixes
}
}
@@ -513,8 +513,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor {
val parameterNames = HashSet<String>()
val function = info.method
val element = function
val bindingContext = (element as KtElement).analyze(BodyResolveMode.FULL)
val bindingContext = (function as KtElement).analyze(BodyResolveMode.FULL)
val oldDescriptor = ktChangeInfo.originalBaseFunctionDescriptor
val containingDeclaration = oldDescriptor.containingDeclaration
@@ -557,7 +556,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor {
val parameterName = parameter.name
if (!parameterNames.add(parameterName)) {
result.putValue(element, "Duplicating parameter '$parameterName'")
result.putValue(function, "Duplicating parameter '$parameterName'")
}
if (parametersScope != null) {
@@ -91,7 +91,7 @@ class MoveKotlinFileHandler : MoveFileHandler() {
}
}
val declarationMoveProcessor = MoveKotlinDeclarationsProcessor(
return MoveKotlinDeclarationsProcessor(
MoveDeclarationsDescriptor(
project = project,
elementsToMove = psiFile.declarations.filterIsInstance<KtNamedDeclaration>(),
@@ -102,7 +102,6 @@ class MoveKotlinFileHandler : MoveFileHandler() {
),
Mover.Idle
)
return declarationMoveProcessor
}
override fun canProcessElement(element: PsiFile?): Boolean {
@@ -70,11 +70,10 @@ fun addMemberToTarget(targetMember: KtNamedDeclaration, targetClass: KtClassOrOb
}
val anchor = targetClass.declarations.filterIsInstance(targetMember::class.java).lastOrNull()
val movedMember = when {
return when {
anchor == null && targetMember is KtProperty -> targetClass.addDeclarationBefore(targetMember, null)
else -> targetClass.addDeclarationAfter(targetMember, anchor)
}
return movedMember
}
private fun KtParameter.needToBeAbstract(targetClass: KtClassOrObject): Boolean {
@@ -335,12 +335,11 @@ fun getStdlibArtifactId(sdk: Sdk?, version: String): String {
}
val sdkVersion = sdk?.let { JavaSdk.getInstance().getVersion(it) }
val artifactId = when (sdkVersion) {
return when (sdkVersion) {
JavaSdkVersion.JDK_1_8, JavaSdkVersion.JDK_1_9 -> MAVEN_STDLIB_ID_JRE8
JavaSdkVersion.JDK_1_7 -> MAVEN_STDLIB_ID_JRE7
else -> MAVEN_STDLIB_ID
}
return artifactId
}
fun getDefaultJvmTarget(sdk: Sdk?, version: String): JvmTarget? {