Fix minor compile warnings

This commit is contained in:
Dmitry Gridin
2019-04-17 17:48:26 +07:00
parent 79793a4bda
commit 37c856290f
226 changed files with 618 additions and 479 deletions
@@ -60,13 +60,11 @@ class SyntheticKotlinBlock(
}
val textRange = getTextRange()
if (treeNode != null) {
val psi = treeNode.psi
if (psi != null) {
val file = psi.containingFile
if (file != null) {
return file.text!!.subSequence(textRange.startOffset, textRange.endOffset).toString() + " " + textRange
}
val psi = treeNode.psi
if (psi != null) {
val file = psi.containingFile
if (file != null) {
return file.text!!.subSequence(textRange.startOffset, textRange.endOffset).toString() + " " + textRange
}
}
@@ -199,8 +199,8 @@ class KotlinPsiUnifier(
s and when {
arg1 == arg2 -> MATCHED
arg1 == null || arg2 == null -> UNMATCHED
else -> (arg1.arguments.asSequence().zip(arg2.arguments.asSequence())).fold(MATCHED) { s, p ->
s and matchArguments(p.first, p.second)
else -> (arg1.arguments.asSequence().zip(arg2.arguments.asSequence())).fold(MATCHED) { status, pair ->
status and matchArguments(pair.first, pair.second)
}
}
}
@@ -711,7 +711,7 @@ class KotlinPsiUnifier(
null
}
if (status == UNMATCHED) {
declarationPatternsToTargets.removeValue(desc1, desc2)
declarationPatternsToTargets.remove(desc1, desc2)
}
return status
@@ -110,7 +110,7 @@ sealed class LazyLightClassDataHolder(
return dummyDelegate!!.fields.map { dummyField ->
val fieldOrigin = KtLightFieldImpl.getOrigin(dummyField)
val fieldName = dummyField.name!!
val fieldName = dummyField.name
KtLightFieldImpl.lazy(dummyField, fieldOrigin, containingClass) {
clsDelegate.findFieldByName(fieldName, false).assertMatches(dummyField, containingClass)
}
@@ -60,7 +60,7 @@ data class LightMemberOriginForCompiledField(val psiField: PsiField, val file: K
override val originalElement: KtDeclaration? by lazyPub {
val desc = MapPsiToAsmDesc.typeDesc(psiField.type)
val signature = MemberSignature.fromFieldNameAndDesc(psiField.name!!, desc)
val signature = MemberSignature.fromFieldNameAndDesc(psiField.name, desc)
findDeclarationInCompiledFile(file, psiField, signature)
}
}
@@ -33,6 +33,7 @@ abstract class AbstractApplicabilityBasedInspection<TElement: KtElement>(
super.visitKtElement(element)
if (!elementType.isInstance(element) || element.textLength == 0) return
@Suppress("UNCHECKED_CAST")
visitTargetElement(element as TElement, holder, isOnTheFly)
}
}
@@ -175,7 +175,11 @@ abstract class IntentionBasedInspection<TElement : PsiElement> private construct
override fun isAvailable(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement): Boolean {
assert(startElement == endElement)
return intention.applicabilityRange(startElement as TElement) != null && additionalChecker(startElement, this@IntentionBasedInspection)
@Suppress("UNCHECKED_CAST")
return intention.applicabilityRange(startElement as TElement) != null && additionalChecker(
startElement,
this@IntentionBasedInspection
)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
@@ -190,6 +194,7 @@ abstract class IntentionBasedInspection<TElement : PsiElement> private construct
val editor = startElement.findExistingEditor()
editor?.caretModel?.moveToOffset(startElement.textOffset)
@Suppress("UNCHECKED_CAST")
intention.applyTo(startElement as TElement, editor)
}
}
@@ -22,6 +22,7 @@ import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
interface KotlinUniversalQuickFix : IntentionAction, LocalQuickFix {
@JvmDefault
override fun getName() = text
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
@@ -136,7 +136,7 @@ sealed class SyntheticPropertyAccessorReference(expression: KtNameReferenceExpre
val fullExpression = expression.getQualifiedExpressionForSelectorOrThis()
fullExpression.getAssignmentByLHS()?.let { assignment ->
val rhs = assignment.right ?: return expression
val operationToken = assignment.operationToken as? KtSingleValueToken
val operationToken = assignment.operationToken as? KtSingleValueToken ?: return expression
val counterpartOp = OperatorConventions.ASSIGNMENT_OPERATION_COUNTERPARTS[operationToken]
val setterArgument = if (counterpartOp != null) {
val getterCall = if (getter) fullExpression.createCall(psiFactory, newGetterName) else fullExpression
@@ -121,4 +121,4 @@ fun indexInternals(stub: KotlinCallableStubBase<*>, sink: IndexSink) {
}
private val KotlinStubWithFqName<*>.modifierList: KotlinModifierListStub?
get() = findChildStubByType(KtStubElementTypes.MODIFIER_LIST) as? KotlinModifierListStub
get() = findChildStubByType(KtStubElementTypes.MODIFIER_LIST)
@@ -27,7 +27,7 @@ class KotlinTypeAliasByExpansionShortNameIndex : StringStubIndexExtension<KtType
override fun getKey(): StubIndexKey<String, KtTypeAlias> = KEY
override fun get(key: String, project: Project, scope: GlobalSearchScope) =
StubIndex.getElements(KEY, key, project, scope, KtTypeAlias::class.java)!!
StubIndex.getElements(KEY, key, project, scope, KtTypeAlias::class.java)
companion object {
val KEY = KotlinIndexUtil.createIndexKey(KotlinTypeAliasByExpansionShortNameIndex::class.java)
@@ -40,7 +40,7 @@ fun <T> Project.executeWriteCommand(name: String, groupId: Any? = null, command:
}
fun <T> Project.executeCommand(name: String, groupId: Any? = null, command: () -> T): T {
var result: T = null as T
@Suppress("UNCHECKED_CAST") var result: T = null as T
CommandProcessor.getInstance().executeCommand(this, { result = command() }, name, groupId)
@Suppress("USELESS_CAST")
return result as T
@@ -26,7 +26,7 @@ fun <T> Project.runReadActionInSmartMode(action: () -> T): T {
}
fun <T> Project.runWithAlternativeResolveEnabled(action: () -> T): T {
var result: T = null as T
@Suppress("UNCHECKED_CAST") var result: T = null as T
DumbService.getInstance(this).withAlternativeResolveEnabled { result = action() }
@Suppress("USELESS_CAST")
return result as T
@@ -57,8 +57,8 @@ fun parse(lineText: String, reader: OutputLineReader, messages: MutableList<Mess
val column = if (matcher.groupCount() >= 2) matcher.group(2)?.toInt() ?: 1 else 1
if (line != null) {
val position = SourceFilePosition(file, SourcePosition(line, column, column))
return addMessage(Message(getMessageKind(severity), message.trim(), position), messages)
val filePosition = SourceFilePosition(file, SourcePosition(line, column, column))
return addMessage(Message(getMessageKind(severity), message.trim(), filePosition), messages)
}
}
@@ -33,7 +33,7 @@ class AndroidGradleModelFacade : KotlinGradleModelFacade {
}
override fun getDependencyModules(ideModule: DataNode<ModuleData>, gradleIdeaProject: IdeaProject): Collection<DataNode<ModuleData>> {
val ideProject = ideModule.parent as DataNode<ProjectData>
@Suppress("UNCHECKED_CAST") val ideProject = ideModule.parent as DataNode<ProjectData>
ExternalSystemApiUtil.find(ideModule, AndroidProjectKeys.JAVA_MODULE_MODEL)?.let { javaModuleModel ->
val moduleNames = javaModuleModel.data.javaModuleDependencies.map { it.moduleName }.toHashSet()
return findModulesByNames(moduleNames, gradleIdeaProject, ideProject)
@@ -43,6 +43,7 @@ class AndroidGradleModelFacade : KotlinGradleModelFacade {
val projects = androidModel.data.mainArtifact.dependencies.projects
val projectIds = libraries.mapNotNull { it.projectSafe } + projects
return projectIds.mapNotNullTo(LinkedHashSet()) { projectId ->
@Suppress("UNCHECKED_CAST")
ExternalSystemApiUtil.findFirstRecursively(ideProject) {
(it.data as? ModuleData)?.id == projectId
} as DataNode<ModuleData>?
@@ -46,7 +46,7 @@ object PackageDirectiveCompletion {
val prefixLength = parameters.offset - expression.textOffset
val prefix = expression.text!!
val prefixMatcher = PlainPrefixMatcher(prefix.substring(0, prefixLength))
val result = result.withPrefixMatcher(prefixMatcher)
val resultSet = result.withPrefixMatcher(prefixMatcher)
val resolutionFacade = expression.getResolutionFacade()
@@ -57,7 +57,7 @@ object PackageDirectiveCompletion {
for (variant in variants) {
val lookupElement = lookupElementFactory.createLookupElement(variant)
if (!lookupElement.lookupString.contains(DUMMY_IDENTIFIER)) {
result.addElement(lookupElement)
resultSet.addElement(lookupElement)
}
}
@@ -123,8 +123,8 @@ class VariableOrParameterNameWithTypeCompletion(
val parameterType = descriptor.type
if (parameterType.isVisible(visibilityFilter)) {
val lookupElement = MyLookupElement.create(name, ArbitraryType(parameterType), withType, lookupElementFactory)!!
val (count, name) = lookupElementToCount[lookupElement] ?: Pair(0, name)
lookupElementToCount[lookupElement] = Pair(count + 1, name)
val (count, s) = lookupElementToCount[lookupElement] ?: Pair(0, name)
lookupElementToCount[lookupElement] = Pair(count + 1, s)
}
}
}
@@ -84,22 +84,28 @@ object LambdaItems {
}
private fun createLookupElement(
functionType: KotlinType,
functionExpectedInfos: List<ExpectedInfo>,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
functionType: KotlinType,
functionExpectedInfos: List<ExpectedInfo>,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.lambdaPresentation(functionType, signaturePresentation)
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
val placeholderRange = TextRange(offset, offset + placeholder.length)
LambdaSignatureTemplates.insertTemplate(context, placeholderRange, functionType, explicitParameterTypes, signatureOnly = false)
})
.suppressAutoInsertion()
.assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA)
.addTailAndNameSimilarity(functionExpectedInfos.filter { it.fuzzyType?.type == functionType })
.withInsertHandler { context, _ ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
val placeholderRange = TextRange(offset, offset + placeholder.length)
LambdaSignatureTemplates.insertTemplate(
context,
placeholderRange,
functionType,
explicitParameterTypes,
signatureOnly = false
)
}
.suppressAutoInsertion()
.assignSmartCompletionPriority(SmartCompletionItemPriority.LAMBDA)
.addTailAndNameSimilarity(functionExpectedInfos.filter { it.fuzzyType?.type == functionType })
}
}
@@ -64,9 +64,9 @@ object LambdaSignatureItems {
}
private fun createLookupElement(
functionType: KotlinType,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
functionType: KotlinType,
signaturePresentation: LambdaSignatureTemplates.SignaturePresentation,
explicitParameterTypes: Boolean
): LookupElement {
val lookupString = LambdaSignatureTemplates.signaturePresentation(functionType, signaturePresentation)
val priority = if (explicitParameterTypes)
@@ -74,13 +74,19 @@ object LambdaSignatureItems {
else
SmartCompletionItemPriority.LAMBDA_SIGNATURE
return LookupElementBuilder.create(lookupString)
.withInsertHandler({ context, lookupElement ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
LambdaSignatureTemplates.insertTemplate(context, TextRange(offset, offset + placeholder.length), functionType, explicitParameterTypes, signatureOnly = true)
})
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
.withInsertHandler { context, _ ->
val offset = context.startOffset
val placeholder = "{}"
context.document.replaceString(offset, context.tailOffset, placeholder)
LambdaSignatureTemplates.insertTemplate(
context,
TextRange(offset, offset + placeholder.length),
functionType,
explicitParameterTypes,
signatureOnly = true
)
}
.suppressAutoInsertion()
.assignSmartCompletionPriority(priority)
}
}
@@ -169,8 +169,8 @@ class SmartCompletion(
val types = descriptor.fuzzyTypesForSmartCompletion(smartCastCalculator, callTypeAndReceiver, resolutionFacade, bindingContext)
val infoMatcher = { expectedInfo: ExpectedInfo -> types.matchExpectedInfo(expectedInfo) }
result.addLookupElements(descriptor, expectedInfos, infoMatcher, noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { descriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(descriptor, useReceiverTypes = true)
result.addLookupElements(descriptor, expectedInfos, infoMatcher, noNameSimilarityForReturnItself = callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) { declarationDescriptor ->
lookupElementFactory.createStandardLookupElementsForDescriptor(declarationDescriptor, useReceiverTypes = true)
}
if (callTypeAndReceiver is CallTypeAndReceiver.DEFAULT) {
@@ -273,8 +273,8 @@ class TypeInstantiationItems(
presentation.itemText = itemText
presentation.clearTail()
if (signatureText != null) {
presentation.appendTailText(signatureText!!, false)
signatureText?.let {
presentation.appendTailText(it, false)
}
presentation.appendTailText(" (" + DescriptorUtils.getFqName(classifier.containingDeclaration) + ")", true)
}
@@ -50,7 +50,7 @@ class KotlinNameSuggestionProvider : NameSuggestionProvider {
val names = SmartList<String>().apply {
val name = element.name
if (!name.isNullOrBlank()) {
this += KotlinNameSuggester.getCamelNames(name!!, validator, name.first().isLowerCase())
this += KotlinNameSuggester.getCamelNames(name, validator, name.first().isLowerCase())
}
val callableDescriptor = element.unsafeResolveToDescriptor(BodyResolveMode.PARTIAL) as CallableDescriptor
@@ -60,7 +60,7 @@ fun getFunctionBodyTextFromTemplate(
}
return try {
fileTemplate!!.getText(properties)
fileTemplate.getText(properties)
}
catch (e: ProcessCanceledException) {
throw e
@@ -111,7 +111,7 @@ class KotlinGradleProjectResolverExtension : AbstractProjectResolverExtension()
when (dependency) {
is ExternalProjectDependency -> {
if (dependency.configurationName == Dependency.DEFAULT_CONFIGURATION) {
val targetModuleNode = ExternalSystemApiUtil.findFirstRecursively(ideProject) {
@Suppress("UNCHECKED_CAST") val targetModuleNode = ExternalSystemApiUtil.findFirstRecursively(ideProject) {
(it.data as? ModuleData)?.id == dependency.projectPath
} as DataNode<ModuleData>? ?: return@mapNotNullTo null
ExternalSystemApiUtil.findAll(targetModuleNode, GradleSourceSetData.KEY)
@@ -278,6 +278,7 @@ class KotlinGradleProjectResolverExtension : AbstractProjectResolverExtension()
val fullModuleId = compositePrefix + moduleId
@Suppress("UNCHECKED_CAST")
return ideProject.children.find { (it.data as? ModuleData)?.id == fullModuleId } as DataNode<ModuleData>?
}
}
@@ -34,7 +34,7 @@ class KotlinTargetDataService : AbstractProjectDataService<KotlinTargetData, Voi
it.outputPath = archiveFile.parent
for (moduleId in targetData.moduleIds) {
val compilationModuleDataNode = nodeToImport.parent?.findChildModuleById(moduleId) ?: continue
val compilationData = compilationModuleDataNode.data ?: continue
val compilationData = compilationModuleDataNode.data
val kotlinSourceSet = compilationModuleDataNode.kotlinSourceSet ?: continue
if (kotlinSourceSet.isTestModule) continue
val moduleToPackage = modelsProvider.findIdeModule(compilationData) ?: continue
@@ -38,7 +38,7 @@ class DefaultGradleModelFacade : KotlinGradleModelFacade {
}
override fun getDependencyModules(ideModule: DataNode<ModuleData>, gradleIdeaProject: IdeaProject): Collection<DataNode<ModuleData>> {
val ideProject = ideModule.parent as DataNode<ProjectData>
@Suppress("UNCHECKED_CAST") val ideProject = ideModule.parent as DataNode<ProjectData>
val dependencyModuleNames =
ExternalSystemApiUtil.getChildren(ideModule, ProjectKeys.MODULE_DEPENDENCY).map { it.data.target.externalName }.toHashSet()
return findModulesByNames(dependencyModuleNames, gradleIdeaProject, ideProject)
@@ -42,6 +42,7 @@ class GradleUpdateConfigurationQuickFixTest : GradleImportingTestCase() {
override fun tearDownFixtures() {
codeInsightTestFixture.tearDown()
@Suppress("UNCHECKED_CAST")
(this::codeInsightTestFixture as KMutableProperty0<CodeInsightTestFixture?>).set(null)
myTestFixture = null
}
@@ -259,7 +259,7 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro
}
collector.addMessage(library.name!! + " library was created")
return library!!
return library
}
private fun isProjectLibraryPresent(project: Project): Boolean {
@@ -397,14 +397,14 @@ abstract class KotlinWithLibraryConfigurator protected constructor() : KotlinPro
val project = module.project
val collector = createConfigureKotlinNotificationCollector(project)
for (library in findAllUsedLibraries(project).keySet()) {
val runtimeJar = LibraryJarDescriptor.RUNTIME_JAR.findExistingJar(library) ?: continue
for (lib in findAllUsedLibraries(project).keySet()) {
val runtimeJar = LibraryJarDescriptor.RUNTIME_JAR.findExistingJar(lib) ?: continue
val model = library.modifiableModel
val model = lib.modifiableModel
val libFilesDir = VfsUtilCore.virtualToIoFile(runtimeJar).parent
for (libraryJarDescriptor in libraryJarDescriptors) {
if (libraryJarDescriptor.findExistingJar(library) != null) continue
if (libraryJarDescriptor.findExistingJar(lib) != null) continue
val libFile = libraryJarDescriptor.getPathInPlugin()
if (!libFile.exists()) continue
@@ -39,11 +39,11 @@ class ConfigureKotlinNotification(
}
}
) {
override fun equals(o: Any?): Boolean {
if (this === o) return true
if (o !is ConfigureKotlinNotification) return false
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is ConfigureKotlinNotification) return false
if (content != o.content) return false
if (content != other.content) return false
return true
}
@@ -122,8 +122,6 @@ abstract class FileRankingCalculator(private val checkClassFqName: Boolean = tru
if (function !is KtConstructor<*> && method.name() != descriptor.name.asString())
return LOW
val typeMapper = makeTypeMapper(bindingContext)
return collect(
method.isConstructor && function is KtConstructor<*>,
method.isAbstract && descriptor.modality == Modality.ABSTRACT,
@@ -361,6 +361,11 @@ class KotlinFieldBreakpoint(
}
}
// BUNCH: 182
override fun getInvalidIcon(isMuted: Boolean): Icon {
return AllIcons.Debugger.Db_invalid_breakpoint
}
override fun getVerifiedIcon(isMuted: Boolean): Icon {
return when {
isMuted -> AllIcons.Debugger.Db_muted_field_breakpoint
@@ -294,6 +294,7 @@ class CodeFragmentParameterAnalyzer(
is ValueDescriptor -> {
parameters.getOrPut(target) {
val type = target.type
@Suppress("DEPRECATION")
val kind = if (target is LocalVariableDescriptor && target.isDelegated) Kind.DELEGATED else Kind.ORDINARY
Smart(Dumb(kind, target.name.asString()), type, target)
}
@@ -16,8 +16,6 @@ fun IntermediateStreamCall.withArgs(args: List<CallArgument>) =
fun TerminatorStreamCall.withArgs(args: List<CallArgument>) =
TerminatorStreamCallImpl(name, args, typeBefore, resultType, textRange)
fun StreamCall.typeBefore() =
if (StreamCall@ this is TypeBeforeAware) StreamCall@ this.typeBefore else KotlinSequenceTypes.ANY
fun StreamCall.typeBefore() = if (this is TypeBeforeAware) this.typeBefore else KotlinSequenceTypes.ANY
fun StreamCall.typeAfter() =
if (StreamCall@ this is TypeAfterAware) StreamCall@ this.typeAfter else KotlinSequenceTypes.ANY
fun StreamCall.typeAfter() = if (this is TypeAfterAware) this.typeAfter else KotlinSequenceTypes.ANY
@@ -72,7 +72,7 @@ class KotlinDistinctByHandler(callNumber: Int, private val call: IntermediateStr
declare(keys2TimesBefore.defaultDeclaration())
declare(transitions.defaultDeclaration())
integerIteration(keys.size(), block@ this) {
integerIteration(keys.size(), this) {
val key = declare(variable(KotlinSequenceTypes.NULLABLE_ANY, "key"), keys.get(loopVariable), false)
val lst = list(dsl.types.INT, "lst")
declare(lst, keys2TimesBefore.computeIfAbsent(key, lambda("k") {
@@ -85,7 +85,7 @@ class KotlinDistinctByHandler(callNumber: Int, private val call: IntermediateStr
val afterTime = loopVariable
val valueAfter = declare(variable(call.typeAfter, "valueAfter"), time2ValueAfter.get(loopVariable), false)
val key = declare(variable(KotlinSequenceTypes.NULLABLE_ANY, "key"), nullExpression, true)
integerIteration(beforeTimes.size(), forEachLoop@ this) {
integerIteration(beforeTimes.size(), this) {
ifBranch((valueAfter same beforeValues.get(loopVariable)) and !transitions.contains(beforeTimes.get(loopVariable))) {
key assign keys.get(loopVariable)
statement { breakIteration() }
@@ -28,7 +28,7 @@ val HISTORY_LABEL_KEY = Key.create<String>("history label")
class MakeBackupCompileTask : CompileTask {
override fun execute(context: CompileContext?): Boolean {
val project = context!!.project!!
val project = context!!.project
val localHistory = LocalHistory.getInstance()!!
val label = HISTORY_LABEL_PREFIX + Integer.toHexString(random.nextInt())
@@ -178,7 +178,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService {
val platform = KotlinPlatform.byId(platformId) ?: return null
val disambiguationClassifier = getDisambiguationClassifier(gradleTarget) as? String
val getPreset = targetClass.getMethodOrNull("getPreset")
var targetPresetName: String? = null
var targetPresetName: String?
try {
val targetPreset = getPreset?.invoke(gradleTarget)
val getPresetName = targetPreset?.javaClass?.getMethodOrNull("getName")
@@ -315,7 +315,7 @@ class KotlinMPPGradleModelBuilder : ModelBuilderService {
val getOutputFile = compileKotlinTaskClass.getMethodOrNull("getOutputFile")
val classesDirs = getClassesDirs(gradleOutput) as? FileCollection ?: return null
val resourcesDir = getResourcesDir(gradleOutput) as? File ?: return null
val destinationDir =
@Suppress("UNCHECKED_CAST") val destinationDir =
getDestinationDir?.invoke(compileKotlinTask) as? File
//TODO: Hack for KotlinNativeCompile
?: (getOutputFile?.invoke(compileKotlinTask) as? Property<File>)?.orNull?.parentFile
@@ -27,7 +27,7 @@ class KotlinCreateFromTemplateHandler : DefaultCreateFromTemplateHandler() {
override fun prepareProperties(props: MutableMap<String, Any>) {
val packageName = props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] as? String
if (!packageName.isNullOrEmpty()) {
props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] = packageName!!
props[FileTemplate.ATTRIBUTE_PACKAGE_NAME] = packageName
.split('.')
.joinToString(".", transform = String::quoteIfNeeded)
}
@@ -39,7 +39,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
class SearchNotPropertyCandidatesAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e?.project!!
val project = e.project!!
val psiFile = e.getData(CommonDataKeys.PSI_FILE) as? KtFile ?: return
val desc = psiFile.findModuleDescriptor()
@@ -116,15 +116,15 @@ class SearchNotPropertyCandidatesAction : AnAction() {
var i = 0
resultDescriptors.forEach { desc ->
progress("Step 2: ${i++} of ${resultDescriptors.size}", "$desc")
val source = DescriptorToSourceUtilsIde.getAllDeclarations(project, desc)
resultDescriptors.forEach { descriptor ->
progress("Step 2: ${i++} of ${resultDescriptors.size}", "$descriptor")
val source = DescriptorToSourceUtilsIde.getAllDeclarations(project, descriptor)
.filterIsInstance<PsiMethod>()
.firstOrNull() ?: return@forEach
val abstract = source.modifierList.hasModifierProperty(PsiModifier.ABSTRACT)
if (!abstract) {
if (!source.isTrivial()) {
descriptorToPsiBinding[desc] = source
descriptorToPsiBinding[descriptor] = source
}
}
}
@@ -150,8 +150,8 @@ class KotlinCopyPasteReferenceProcessor : CopyPastePostProcessor<KotlinReference
) {
if (PsiTreeUtil.getNonStrictParentOfType(element, *IGNORE_REFERENCES_INSIDE) != null) return
element.forEachDescendantOfType<KtElement>(canGoInside = { it::class.java as Class<*> !in IGNORE_REFERENCES_INSIDE }) { element ->
val reference = element.mainReference ?: return@forEachDescendantOfType
element.forEachDescendantOfType<KtElement>(canGoInside = { it::class.java as Class<*> !in IGNORE_REFERENCES_INSIDE }) { ktElement ->
val reference = ktElement.mainReference ?: return@forEachDescendantOfType
val descriptors = resolveReference(reference, bindingContext)
//check whether this reference is unambiguous
@@ -168,9 +168,9 @@ class KotlinCopyPasteReferenceProcessor : CopyPastePostProcessor<KotlinReference
val fqName = descriptor.importableFqName!!
val kind = KotlinReferenceData.Kind.fromDescriptor(descriptor) ?: continue
val isQualifiable = KotlinReferenceData.isQualifiable(element, descriptor)
val relativeStart = element.range.start - startOffset
val relativeEnd = element.range.end - startOffset
val isQualifiable = KotlinReferenceData.isQualifiable(ktElement, descriptor)
val relativeStart = ktElement.range.start - startOffset
val relativeEnd = ktElement.range.end - startOffset
add(KotlinReferenceData(relativeStart, relativeEnd, fqName.asString(), isQualifiable, kind))
}
}
@@ -28,7 +28,7 @@ class KotlinStringTemplateBackspaceHandler : BackspaceHandlerDelegate() {
override fun beforeCharDeleted(c: Char, file: PsiFile, editor: Editor) {
if (c != '{' || file !is KtFile || !CodeInsightSettings.getInstance().AUTOINSERT_PAIR_BRACKET) return
val offset = editor?.caretModel?.offset ?: return
val offset = editor.caretModel.offset
val highlighter = (editor as EditorEx).highlighter
val iterator = highlighter.createIterator(offset)
@@ -336,4 +336,5 @@ class KotlinFacetEditorGeneralTab(
}
}
@Suppress("UNCHECKED_CAST")
val <T> ComboBox<T>.selectedItemTyped: T? get() = selectedItem as T?
@@ -41,7 +41,7 @@ import java.util.*
object SuperDeclarationMarkerTooltip : Function<PsiElement, String> {
override fun `fun`(element: PsiElement): String? {
val ktDeclaration = element.getParentOfType<KtDeclaration>(false) ?: return null
val (elementDescriptor, overriddenDescriptors) = resolveDeclarationWithParents(ktDeclaration!!)
val (elementDescriptor, overriddenDescriptors) = resolveDeclarationWithParents(ktDeclaration)
if (overriddenDescriptors.isEmpty()) return ""
val isAbstract = elementDescriptor!!.modality == Modality.ABSTRACT
@@ -44,7 +44,7 @@ class ConvertEnumToSealedClassIntention : SelfTargetingRangeIntention<KtClass>(K
for (klass in element.withExpectedActuals()) {
klass as? KtClass ?: continue
val classDescriptor = klass.resolveToDescriptorIfAny() as? ClassDescriptor ?: continue
val classDescriptor = klass.resolveToDescriptorIfAny() ?: continue
val isExpect = classDescriptor.isExpect
val isActual = classDescriptor.isActual
@@ -196,7 +196,7 @@ class ConvertFunctionTypeParameterToReceiverIntention : SelfTargetingRangeIntent
}
usageLoop@ for (ref in callable.searchReferencesOrMethodReferences()) {
val refElement = ref.element ?: continue
val refElement = ref.element
when (ref) {
is KtSimpleReference<*> -> processExternalUsage(conflicts, refElement, usages)
is KtReference -> continue@usageLoop
@@ -46,6 +46,7 @@ import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isTypeParameter
import org.jetbrains.kotlin.types.typeUtil.isUnit
@Suppress("DEPRECATION")
class ConvertLambdaToReferenceInspection : IntentionBasedInspection<KtLambdaExpression>(ConvertLambdaToReferenceIntention::class)
open class ConvertLambdaToReferenceIntention(text: String) :
@@ -37,6 +37,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.expressions.DoubleColonLHS
@Suppress("DEPRECATION")
class ConvertReferenceToLambdaInspection : IntentionBasedInspection<KtCallableReferenceExpression>(ConvertReferenceToLambdaIntention::class)
class ConvertReferenceToLambdaIntention : SelfTargetingOffsetIndependentIntention<KtCallableReferenceExpression>(
@@ -32,6 +32,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.types.typeUtil.supertypes
@Suppress("DEPRECATION")
class ConvertTryFinallyToUseCallInspection : IntentionBasedInspection<KtTryExpression>(ConvertTryFinallyToUseCallIntention::class) {
override fun inspectionTarget(element: KtTryExpression) = element.tryKeyword ?: element.tryBlock
}
@@ -32,6 +32,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.typeUtil.builtIns
import org.jetbrains.kotlin.types.typeUtil.isPrimitiveNumberType
@Suppress("DEPRECATION")
class ConvertTwoComparisonsToRangeCheckInspection : IntentionBasedInspection<KtBinaryExpression>(
ConvertTwoComparisonsToRangeCheckIntention::class
)
@@ -45,6 +45,7 @@ import org.jetbrains.kotlin.types.typeUtil.isSubtypeOf
import org.jetbrains.kotlin.types.typeUtil.makeNotNullable
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
@Suppress("DEPRECATION")
class FoldInitializerAndIfToElvisInspection : IntentionBasedInspection<KtIfExpression>(FoldInitializerAndIfToElvisIntention::class)
class FoldInitializerAndIfToElvisIntention :
@@ -86,11 +86,11 @@ class IterateExpressionIntention : SelfTargetingIntention<KtExpression>(KtExpres
var forExpression = psiFactory.createExpressionByPattern("for($0 in $1) {\nx\n}", paramPattern, element) as KtForExpression
forExpression = element.replaced(forExpression)
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(forExpression)?.let { forExpression ->
val bodyPlaceholder = (forExpression.body as KtBlockExpression).statements.single()
val parameters = forExpression.destructuringDeclaration?.entries ?: listOf(forExpression.loopParameter!!)
CodeInsightUtilCore.forcePsiPostprocessAndRestoreElement(forExpression)?.let { expression ->
val bodyPlaceholder = (expression.body as KtBlockExpression).statements.single()
val parameters = expression.destructuringDeclaration?.entries ?: listOf(expression.loopParameter!!)
val templateBuilder = TemplateBuilderImpl(forExpression)
val templateBuilder = TemplateBuilderImpl(expression)
for ((parameter, parameterNames) in (parameters zip names)) {
templateBuilder.replaceElement(parameter, ChooseStringExpression(parameterNames))
}
@@ -36,6 +36,7 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
@Suppress("DEPRECATION")
class JoinDeclarationAndAssignmentInspection : IntentionBasedInspection<KtProperty>(
JoinDeclarationAndAssignmentIntention::class,
"Can be joined with assignment"
@@ -48,6 +48,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitClassReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
@Suppress("DEPRECATION")
class ObjectLiteralToLambdaInspection : IntentionBasedInspection<KtObjectLiteralExpression>(ObjectLiteralToLambdaIntention::class) {
override fun problemHighlightType(element: KtObjectLiteralExpression): ProblemHighlightType {
val (_, baseType, singleFunction) = extractData(element) ?: return super.problemHighlightType(element)
@@ -22,6 +22,7 @@ import org.jetbrains.kotlin.idea.core.dropBraces
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.psi.KtBlockStringTemplateEntry
@Suppress("DEPRECATION")
class RemoveCurlyBracesFromTemplateInspection :
IntentionBasedInspection<KtBlockStringTemplateEntry>(RemoveCurlyBracesFromTemplateIntention::class)
@@ -20,7 +20,6 @@ import com.intellij.codeInspection.CleanupLocalInspectionTool
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.editor.fixers.range
import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
@@ -28,10 +27,11 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.getNextSiblingIgnoringWhitespaceAndComments
import org.jetbrains.kotlin.psi.psiUtil.getStrictParentOfType
@Suppress("DEPRECATION")
class RemoveEmptyClassBodyInspection :
IntentionBasedInspection<KtClassBody>(RemoveEmptyClassBodyIntention::class), CleanupLocalInspectionTool {
IntentionBasedInspection<KtClassBody>(RemoveEmptyClassBodyIntention::class), CleanupLocalInspectionTool {
override fun problemHighlightType(element: KtClassBody): ProblemHighlightType =
ProblemHighlightType.LIKE_UNUSED_SYMBOL
ProblemHighlightType.LIKE_UNUSED_SYMBOL
}
class RemoveEmptyClassBodyIntention : SelfTargetingOffsetIndependentIntention<KtClassBody>(KtClassBody::class.java, "Redundant empty class body") {
@@ -28,6 +28,7 @@ import org.jetbrains.kotlin.psi.KtQualifiedExpression
import org.jetbrains.kotlin.psi.KtValueArgumentList
import org.jetbrains.kotlin.psi.psiUtil.getPrevSiblingIgnoringWhitespaceAndComments
@Suppress("DEPRECATION")
class RemoveEmptyParenthesesFromLambdaCallInspection : IntentionBasedInspection<KtValueArgumentList>(
RemoveEmptyParenthesesFromLambdaCallIntention::class
), CleanupLocalInspectionTool {
@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.idea.util.isExpectDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
import org.jetbrains.kotlin.psi.psiUtil.containingClass
@Suppress("DEPRECATION")
class RemoveEmptyPrimaryConstructorInspection : IntentionBasedInspection<KtPrimaryConstructor>(
RemoveEmptyPrimaryConstructorIntention::class
), CleanupLocalInspectionTool {
@@ -23,6 +23,7 @@ import org.jetbrains.kotlin.idea.inspections.IntentionBasedInspection
import org.jetbrains.kotlin.psi.KtBlockExpression
import org.jetbrains.kotlin.psi.KtSecondaryConstructor
@Suppress("DEPRECATION")
class RemoveEmptySecondaryConstructorBodyInspection : IntentionBasedInspection<KtBlockExpression>(
RemoveEmptySecondaryConstructorBodyIntention::class
), CleanupLocalInspectionTool {
@@ -34,11 +34,12 @@ import org.jetbrains.kotlin.resolve.calls.callUtil.getResolvedCall
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.types.ErrorUtils
@Suppress("DEPRECATION")
class RemoveExplicitSuperQualifierInspection : IntentionBasedInspection<KtSuperExpression>(
RemoveExplicitSuperQualifierIntention::class
RemoveExplicitSuperQualifierIntention::class
), CleanupLocalInspectionTool {
override fun problemHighlightType(element: KtSuperExpression): ProblemHighlightType =
ProblemHighlightType.LIKE_UNUSED_SYMBOL
ProblemHighlightType.LIKE_UNUSED_SYMBOL
}
class RemoveExplicitSuperQualifierIntention : SelfTargetingRangeIntention<KtSuperExpression>(KtSuperExpression::class.java, "Remove explicit supertype qualification") {
@@ -42,9 +42,10 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@Suppress("DEPRECATION")
class RemoveExplicitTypeArgumentsInspection : IntentionBasedInspection<KtTypeArgumentList>(RemoveExplicitTypeArgumentsIntention::class) {
override fun problemHighlightType(element: KtTypeArgumentList): ProblemHighlightType =
ProblemHighlightType.LIKE_UNUSED_SYMBOL
ProblemHighlightType.LIKE_UNUSED_SYMBOL
}
class RemoveExplicitTypeArgumentsIntention : SelfTargetingOffsetIndependentIntention<KtTypeArgumentList>(KtTypeArgumentList::class.java, "Remove explicit type arguments") {
@@ -29,9 +29,10 @@ import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameUnsafe
@Suppress("DEPRECATION")
class RemoveForLoopIndicesInspection : IntentionBasedInspection<KtForExpression>(
RemoveForLoopIndicesIntention::class,
"Index is not used in the loop body"
RemoveForLoopIndicesIntention::class,
"Index is not used in the loop body"
) {
override fun problemHighlightType(element: KtForExpression): ProblemHighlightType = ProblemHighlightType.LIKE_UNUSED_SYMBOL
}
@@ -30,6 +30,7 @@ import org.jetbrains.kotlin.types.KotlinType
import org.jetbrains.kotlin.types.expressions.OperatorConventions
import org.jetbrains.kotlin.types.isFlexible
@Suppress("DEPRECATION")
class RemoveRedundantCallsOfConversionMethodsInspection : IntentionBasedInspection<KtQualifiedExpression>(
RemoveRedundantCallsOfConversionMethodsIntention::class
) {
@@ -21,7 +21,9 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
class ReplaceSizeCheckWithIsNotEmptyInspection : IntentionBasedInspection<KtBinaryExpression>(ReplaceSizeCheckWithIsNotEmptyIntention::class)
@Suppress("DEPRECATION")
class ReplaceSizeCheckWithIsNotEmptyInspection :
IntentionBasedInspection<KtBinaryExpression>(ReplaceSizeCheckWithIsNotEmptyIntention::class)
class ReplaceSizeCheckWithIsNotEmptyIntention : ReplaceSizeCheckIntention("Replace size check with 'isNotEmpty'") {
@@ -21,7 +21,9 @@ import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.KtBinaryExpression
import org.jetbrains.kotlin.psi.KtExpression
class ReplaceSizeZeroCheckWithIsEmptyInspection : IntentionBasedInspection<KtBinaryExpression>(ReplaceSizeZeroCheckWithIsEmptyIntention::class)
@Suppress("DEPRECATION")
class ReplaceSizeZeroCheckWithIsEmptyInspection :
IntentionBasedInspection<KtBinaryExpression>(ReplaceSizeZeroCheckWithIsEmptyIntention::class)
class ReplaceSizeZeroCheckWithIsEmptyIntention : ReplaceSizeCheckIntention("Replace size zero check with 'isEmpty'") {
@@ -34,6 +34,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode.PARTIAL
import org.jetbrains.kotlin.types.isFlexible
@Suppress("DEPRECATION")
class SimplifyBooleanWithConstantsInspection : IntentionBasedInspection<KtBinaryExpression>(SimplifyBooleanWithConstantsIntention::class)
class SimplifyBooleanWithConstantsIntention :
@@ -58,6 +58,7 @@ import org.jetbrains.kotlin.types.TypeUtils
import org.jetbrains.kotlin.types.typeUtil.isUnit
import javax.swing.JComponent
@Suppress("DEPRECATION")
class UsePropertyAccessSyntaxInspection : IntentionBasedInspection<KtCallExpression>(UsePropertyAccessSyntaxIntention::class),
CleanupLocalInspectionTool {
@@ -25,6 +25,7 @@ import org.jetbrains.kotlin.psi.KtForExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.createExpressionByPattern
@Suppress("DEPRECATION")
class UseWithIndexInspection : IntentionBasedInspection<KtForExpression>(UseWithIndexIntention::class)
class UseWithIndexIntention : SelfTargetingRangeIntention<KtForExpression>(
@@ -105,10 +105,13 @@ object IntroduceIndexMatcher : TransformationMatcher {
}
private fun isAccessedAfter(variableDescriptor: VariableDescriptor, instruction: Instruction, loop: KtForExpression): Boolean {
return !traverseFollowingInstructions(instruction) { instruction ->
return !traverseFollowingInstructions(instruction) {
when {
!loop.isAncestor(instruction.blockScope.block, strict = true) -> TraverseInstructionResult.SKIP // we are outside the loop or going to the next iteration
instruction.isReadOfVariable(variableDescriptor) -> TraverseInstructionResult.HALT
!loop.isAncestor(
it.blockScope.block,
strict = true
) -> TraverseInstructionResult.SKIP // we are outside the loop or going to the next iteration
it.isReadOfVariable(variableDescriptor) -> TraverseInstructionResult.HALT
else -> TraverseInstructionResult.CONTINUE
}
}
@@ -175,7 +175,6 @@ object InitializePropertyQuickFixFactory : KotlinIntentionActionsFactory() {
val descriptor = descriptorsToProcess.next()
val constructorPointer = descriptor.source.getPsi()?.createSmartPointer()
val config = configureChangeSignature(propertyDescriptor)
val changeSignature = { }
object : CompositeRefactoringRunner(project, "refactoring.changeSignature") {
override fun runRefactoring() {
@@ -44,7 +44,7 @@ class RenameModToRemFix(element: KtNamedFunction, val newName: Name) : KotlinQui
if (diagnostic.factory != Errors.DEPRECATED_BINARY_MOD && diagnostic.factory != Errors.FORBIDDEN_BINARY_MOD) return null
val operatorMod = diagnostic.psiElement.getNonStrictParentOfType<KtNamedFunction>() ?: return null
val newName = REM_TO_MOD_OPERATION_NAMES.inverse()[operatorMod.nameAsName] ?: return null
val newName = operatorMod.nameAsName?.let { REM_TO_MOD_OPERATION_NAMES.inverse()[it] } ?: return null
return RenameModToRemFix(operatorMod, newName)
}
}
@@ -272,7 +272,7 @@ class MigrateExternalExtensionFix(declaration: KtNamedDeclaration)
}
}
if ((e as? KtNamedDeclaration)?.modifierList?.annotationEntries?.any { it.isJsNativeAnnotation() } == true) {
return MigrateExternalExtensionFix(e as KtNamedDeclaration)
return MigrateExternalExtensionFix(e)
}
}
}
@@ -234,7 +234,7 @@ class KotlinChangeSignatureUsageProcessor : ChangeSignatureUsageProcessor {
val functionPsi = functionUsageInfo.element ?: return
for (reference in findReferences(functionPsi)) {
val element = reference.element ?: continue
val element = reference.element
when {
reference is KtInvokeFunctionReference || reference is KtArrayAccessReference -> {
@@ -111,9 +111,9 @@ fun suggestReceiverNames(project: Project, descriptor: CallableDescriptor): List
val callable = DescriptorToSourceUtilsIde.getAnyDeclaration(project, descriptor) as? KtCallableDeclaration ?: return emptyList()
val bodyScope = (callable as? KtFunction)?.bodyExpression?.let { it.getResolutionScope(it.analyze(), it.getResolutionFacade()) }
val paramNames = descriptor.valueParameters.map { it.name.asString() }
val validator = bodyScope?.let { bodyScope ->
val validator = bodyScope?.let { scope ->
CollectingNameValidator(paramNames) {
bodyScope.findVariable(Name.identifier(it), NoLookupLocation.FROM_IDE) == null
scope.findVariable(Name.identifier(it), NoLookupLocation.FROM_IDE) == null
}
} ?: CollectingNameValidator(paramNames)
val receiverType = descriptor.extensionReceiverParameter?.type ?: return emptyList()
@@ -119,7 +119,7 @@ class KotlinInlineValHandler(private val withPrompt: Boolean) : InlineActionHand
val referenceExpressions = mutableListOf<KtExpression>()
val conflictUsages = MultiMap.create<PsiElement, String>()
for (ref in references) {
val refElement = ref.element ?: continue
val refElement = ref.element
if (refElement !is KtElement) {
conflictUsages.putValue(refElement, "Non-Kotlin usage: ${refElement.text}")
continue
@@ -57,17 +57,17 @@ class KotlinExtractInterfaceDialog(
}
extractableMemberInfos.forEach { it.isToAbstract = true }
return object : MemberInfoModelBase(
originalClass,
extractableMemberInfos,
getInterfaceContainmentVerifier { selectedMembers }
originalClass,
extractableMemberInfos,
getInterfaceContainmentVerifier { selectedMembers }
) {
override fun isMemberEnabled(memberInfo: KotlinMemberInfo): Boolean {
if (!super.isMemberEnabled(memberInfo)) return false
override fun isMemberEnabled(member: KotlinMemberInfo): Boolean {
if (!super.isMemberEnabled(member)) return false
val member = memberInfo.member
return !(member.hasModifier(KtTokens.INLINE_KEYWORD) ||
member.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
member.hasModifier(KtTokens.LATEINIT_KEYWORD))
val declaration = member.member
return !(declaration.hasModifier(KtTokens.INLINE_KEYWORD) ||
declaration.hasModifier(KtTokens.EXTERNAL_KEYWORD) ||
declaration.hasModifier(KtTokens.LATEINIT_KEYWORD))
}
override fun isAbstractEnabled(memberInfo: KotlinMemberInfo): Boolean {
@@ -278,7 +278,7 @@ open class KotlinIntroduceParameterHandler(
?: Collections.emptyList()
val occurrencesToReplace = if (expression is KtProperty) {
ReferencesSearch.search(expression).mapNotNullTo(SmartList(expression.toRange())) { it.element?.toRange() }
ReferencesSearch.search(expression).mapNotNullTo(SmartList(expression.toRange())) { it.element.toRange() }
}
else {
expression.toRange()
@@ -530,8 +530,8 @@ fun createJavaMethod(template: PsiMethod, targetClass: PsiClass): PsiMethod {
method.modifierList.setModifierProperty(PsiModifier.FINAL, false)
}
copyTypeParameters(template, method) { method, typeParameterList ->
method.addAfter(typeParameterList, method.modifierList)
copyTypeParameters(template, method) { psiMethod, typeParameterList ->
psiMethod.addAfter(typeParameterList, psiMethod.modifierList)
}
val targetParamList = method.parameterList
@@ -597,8 +597,8 @@ fun createJavaClass(klass: KtClass, targetClass: PsiClass?, forcePlainClass: Boo
javaClass.modifierList!!.setModifierProperty(PsiModifier.ABSTRACT, false)
}
copyTypeParameters(template, javaClass) { klass, typeParameterList ->
klass.addAfter(typeParameterList, klass.nameIdentifier)
copyTypeParameters(template, javaClass) { clazz, typeParameterList ->
clazz.addAfter(typeParameterList, clazz.nameIdentifier)
}
// Turning interface to class
@@ -73,7 +73,6 @@ class ChangePackageIntention: SelfTargetingOffsetIndependentIntention<KtPackageD
builder.buildInlineTemplate(),
object: TemplateEditingAdapter() {
override fun beforeTemplateFinished(state: TemplateState, template: Template?) {
if (state == null) return
enteredName = state.getVariableValue(PACKAGE_NAME_VAR)!!.text
affectedRange = state.getSegmentRange(0)
}
@@ -202,7 +202,7 @@ class MoveKotlinDeclarationsHandler : MoveHandlerDelegate() {
element: PsiElement, project: Project, dataContext: DataContext?, reference: PsiReference?, editor: Editor?
): Boolean {
val elementsToMove = element.unwrapped?.let { arrayOf(it) } ?: PsiElement.EMPTY_ARRAY
val targetContainer = dataContext?.let { dataContext -> LangDataKeys.TARGET_PSI_ELEMENT.getData(dataContext) }
val targetContainer = dataContext?.let { context -> LangDataKeys.TARGET_PSI_ELEMENT.getData(context) }
return canMove(elementsToMove, targetContainer, true) && doMoveWithCheck(project, elementsToMove, targetContainer, null, editor)
}
@@ -508,7 +508,7 @@ class MoveConflictChecker(
for (memberToCheck in membersToCheck) {
for (reference in ReferencesSearch.search(memberToCheck)) {
val element = reference.element ?: continue
val element = reference.element
val usageModule = ModuleUtilCore.findModuleForPsiElement(element) ?: continue
if (usageModule != targetModule && targetModule !in usageModule.implementedModules && !isToBeMoved(element)) {
val container = element.getUsageContext()
@@ -68,7 +68,7 @@ class JavaToKotlinPreconversionPullUpHelper(
private fun collectFieldReferencesToEncapsulate(member: PsiField) {
val helper = EncapsulateFieldHelper.getHelper(member.language) ?: return
val fieldName = member.name!!
val fieldName = member.name
val getterName = JvmAbi.getterName(fieldName)
val setterName = JvmAbi.setterName(fieldName)
val getter = helper.generateMethodPrototype(member, getterName, true)
@@ -103,8 +103,8 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() {
}
override fun getElementToSearchInStringsAndComments(element: PsiElement): PsiElement? {
val unwrapped = element?.unwrapped ?: return null
if ((unwrapped is KtDeclaration) && KtPsiUtil.isLocal(unwrapped as KtDeclaration)) return null
val unwrapped = element.unwrapped ?: return null
if ((unwrapped is KtDeclaration) && KtPsiUtil.isLocal(unwrapped)) return null
return element
}
@@ -185,7 +185,7 @@ abstract class RenameKotlinPsiProcessor : RenamePsiElementProcessor() {
}
}
else {
ref.element?.getStrictParentOfType<KtImportDirective>()?.let { importDirective ->
ref.element.getStrictParentOfType<KtImportDirective>()?.let { importDirective ->
val fqName = importDirective.importedFqName!!
val newFqName = fqName.parent().child(Name.identifier(newName))
val importList = importDirective.parent as KtImportList
@@ -30,7 +30,7 @@ fun JpsModuleSourceRoot.getMigratedSourceRootTypeWithProperties(): Pair<JpsModul
val currentRootType = rootType
@Suppress("UNCHECKED_CAST")
val newSourceRootType: JpsModuleSourceRootType<JpsElement> = when (currentRootType) {
JavaSourceRootType.SOURCE -> SourceKotlinRootType
JavaSourceRootType.SOURCE -> SourceKotlinRootType as JpsModuleSourceRootType<JpsElement>
JavaSourceRootType.TEST_SOURCE -> TestSourceKotlinRootType
JavaResourceRootType.RESOURCE -> ResourceKotlinRootType
JavaResourceRootType.TEST_RESOURCE -> TestResourceKotlinRootType
@@ -43,7 +43,7 @@ import java.util.*
class KotlinDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSearch.SearchParameters> {
override fun execute(queryParameters: DefinitionsScopedSearch.SearchParameters, consumer: Processor<in PsiElement>): Boolean {
val consumer = skipDelegatedMethodsConsumer(consumer)
val processor = skipDelegatedMethodsConsumer(consumer)
val element = queryParameters.element
val scope = queryParameters.scope
@@ -51,35 +51,35 @@ class KotlinDefinitionsSearcher : QueryExecutor<PsiElement, DefinitionsScopedSea
is KtClass -> {
val isExpectEnum = runReadAction { element.isEnum() && element.isExpectDeclaration() }
if (isExpectEnum) {
processActualDeclarations(element, consumer)
processActualDeclarations(element, processor)
} else {
processClassImplementations(element, consumer) && processActualDeclarations(element, consumer)
processClassImplementations(element, processor) && processActualDeclarations(element, processor)
}
}
is KtObjectDeclaration -> {
processActualDeclarations(element, consumer)
processActualDeclarations(element, processor)
}
is KtLightClass -> {
val useScope = runReadAction { element.useScope }
if (useScope is LocalSearchScope)
processLightClassLocalImplementations(element, useScope, consumer)
processLightClassLocalImplementations(element, useScope, processor)
else
true
}
is KtNamedFunction, is KtSecondaryConstructor -> {
processFunctionImplementations(element as KtFunction, scope, consumer) && processActualDeclarations(element, consumer)
processFunctionImplementations(element as KtFunction, scope, processor) && processActualDeclarations(element, processor)
}
is KtProperty -> {
processPropertyImplementations(element, scope, consumer) && processActualDeclarations(element, consumer)
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
}
is KtParameter -> {
if (isFieldParameter(element)) {
processPropertyImplementations(element, scope, consumer) && processActualDeclarations(element, consumer)
processPropertyImplementations(element, scope, processor) && processActualDeclarations(element, processor)
} else {
true
}
@@ -163,7 +163,7 @@ class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration
val generatedFile = generatedClass.containingFile as? PsiJavaFile ?: return@runWhenSmart
if (generatedClass.language == JavaLanguage.INSTANCE) {
project.executeCommand("Convert class '${generatedClass.name}' to Kotlin", this) {
project.executeCommand<Unit>("Convert class '${generatedClass.name}' to Kotlin", this) {
runWriteAction {
generatedClass.methods.forEach { it.throwsList.referenceElements.forEach { referenceElement -> referenceElement.delete() } }
}
@@ -181,6 +181,7 @@ class KotlinCreateTestIntention : SelfTargetingRangeIntention<KtNamedDeclaration
.forEach { it.j2k()?.let { declaration -> existingClass.addDeclaration(declaration) } }
generatedClass.delete()
}
NavigationUtil.activateFileWithPsiElement(existingClass)
} else {
with(PsiDocumentManager.getInstance(project)) {
@@ -432,7 +432,7 @@ class IdeaModuleInfoTest : ModuleTestCase() {
get() = LibraryInfo(project!!, this)
private fun module(name: String, hasProductionRoot: Boolean = true, hasTestRoot: Boolean = true): Module {
return createModuleFromTestData(createTempDirectory()!!.absolutePath, name, StdModuleTypes.JAVA, false)!!.apply {
return createModuleFromTestData(createTempDirectory().absolutePath, name, StdModuleTypes.JAVA, false).apply {
if (hasProductionRoot)
PsiTestUtil.addSourceContentToRoots(this, dir(), false)
if (hasTestRoot)
@@ -196,12 +196,12 @@ open class MultiModuleHighlightingTest : AbstractMultiModuleHighlightingTest() {
fun testSamWithReceiverExtension() {
val module1 = module("m1").setupKotlinFacet {
settings.compilerArguments!!.pluginOptions =
arrayOf("plugin:${PLUGIN_ID}:${ANNOTATION_OPTION.name}=anno.A")
arrayOf("plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}=anno.A")
}
val module2 = module("m2").setupKotlinFacet {
settings.compilerArguments!!.pluginOptions =
arrayOf("plugin:${PLUGIN_ID}:${ANNOTATION_OPTION.name}=anno.B")
arrayOf("plugin:$PLUGIN_ID:${ANNOTATION_OPTION.optionName}=anno.B")
}
@@ -94,7 +94,7 @@ abstract class AbstractAsyncStackTraceTest : KotlinDebuggerTestBase() {
@Suppress("UNCHECKED_CAST")
val variablesField = item.javaClass.declaredFields.first { !Modifier.isStatic(it.modifiers) && it.type == List::class.java }
val variables = variablesField.getSafe(item) as? List<JavaValue>
@Suppress("UNCHECKED_CAST") val variables = variablesField.getSafe(item) as? List<JavaValue>
if (variables != null) {
for (variable in variables) {
val descriptor = variable.descriptor
@@ -14,8 +14,8 @@ val DEX_BEFORE_PATCH_EXTENSION = "before_dex"
fun String.needDexPatch() = split('.').any { it.endsWith("Dex") }
fun patchDexTests(dir: File) {
dir.listFiles({ file -> file.isDirectory && file.name.needDexPatch() }).forEach { dir ->
dir.listFiles { testOutputFile -> testOutputFile.extension == "class" }.forEach(::applyDexLikePatch)
dir.listFiles { file -> file.isDirectory && file.name.needDexPatch() }.forEach {
it.listFiles { testOutputFile -> testOutputFile.extension == "class" }.forEach(::applyDexLikePatch)
}
}
@@ -10,8 +10,8 @@ import com.intellij.psi.PsiElement
import com.intellij.testFramework.LightProjectDescriptor
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.idea.caches.lightClasses.KtLightClassForDecompiledDeclaration
import org.jetbrains.kotlin.idea.test.SdkAndMockLibraryProjectDescriptor
import org.jetbrains.kotlin.idea.test.PluginTestCaseBase
import org.jetbrains.kotlin.idea.test.SdkAndMockLibraryProjectDescriptor
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.test.JUnit3WithIdeaConfigurationRunner
@@ -36,10 +36,12 @@ class NavigateFromLibrarySourcesTest: AbstractNavigateFromLibrarySourcesTest() {
fun testLightClassForLibrarySource() {
val navigationElement = navigationElementForReferenceInLibrarySource("usage.kt", "Foo")
assertTrue(navigationElement is KtClassOrObject, "Foo should navigate to JetClassOrObject")
val lightClass = (navigationElement as KtClassOrObject).toLightClass()
assertTrue(lightClass is KtLightClassForDecompiledDeclaration,
"Light classes for decompiled declaration should be provided for library source")
assertEquals("Foo", lightClass!!.name)
val lightClass = navigationElement.toLightClass()
assertTrue(
lightClass is KtLightClassForDecompiledDeclaration,
"Light classes for decompiled declaration should be provided for library source"
)
assertEquals("Foo", lightClass.name)
}
private fun checkNavigationFromLibrarySource(referenceText: String, targetFqName: String) {
@@ -128,7 +128,7 @@ class NavigationToSingleJarInMultipleLibrariesTest : AbstractNavigationWithMulti
abstract class AbstractNavigationWithMultipleLibrariesTest : ModuleTestCase() {
abstract val testDataPath: String
protected fun module(name: String, srcPath: String) = createModuleFromTestData(srcPath, name, StdModuleTypes.JAVA, true)!!
protected fun module(name: String, srcPath: String) = createModuleFromTestData(srcPath, name, StdModuleTypes.JAVA, true)
protected fun checkReferencesInModule(module: Module, libraryName: String, expectedFileName: String) {
checkAnnotatedCode(findSourceFile(module), File(testDataPath + expectedFileName)) {
@@ -66,7 +66,7 @@ class BuiltInDecompilerConsistencyTest : KotlinLightCodeInsightFixtureTestCase()
val fileContent = FileContentImpl.createByFile(classFile)
if (IDEKotlinBinaryClassCache.getKotlinBinaryClassHeaderData(fileContent.file) == null) continue
val fileStub = classFileDecompiler.stubBuilder.buildFileStub(fileContent) ?: continue
val classStub = fileStub.findChildStubByType(KtClassElementType.getStubType(false)) as? KotlinClassStub ?: continue
val classStub = fileStub.findChildStubByType(KtClassElementType.getStubType(false)) ?: continue
val classFqName = classStub.getFqName()!!
val builtInClassStub = builtInFileStub.childrenStubs.firstOrNull {
it is KotlinClassStub && it.getFqName() == classFqName
@@ -28,6 +28,7 @@ abstract class AbstractKotlinTypeAliasByExpansionShortNameIndexTest : KotlinLigh
}
override fun tearDown() {
@Suppress("UNCHECKED_CAST")
(this::scope as KMutableProperty0<GlobalSearchScope?>).set(null)
super.tearDown()
}
@@ -149,12 +149,13 @@ private class JvmDeclared(val textToContain: String, vararg jvmClasses: KClass<o
}
fun <T> assertMatches(elements: Collection<T>, vararg conditions: (T) -> Boolean) {
val matchResult = matchElementsToConditions(elements, conditions.toList())
when (matchResult) {
when (val matchResult = matchElementsToConditions(elements, conditions.toList())) {
is MatchResult.UnmatchedCondition ->
throw AssertionError("no one matches the ${matchResult.condition}, elements = ${elements.joinToString { it.toString() }}")
is MatchResult.UnmatchedElements ->
throw AssertionError("elements ${matchResult.elements.joinToString { it.toString() }} wasn't matched by any condition")
is MatchResult.Matched -> {
}
}
}
@@ -61,5 +61,5 @@ class GotoWithMultipleLibrariesTest : AbstractMultiModuleTest() {
}
}
private fun module(name: String, srcPath: String) = createModuleFromTestData(srcPath, name, StdModuleTypes.JAVA, true)!!
private fun module(name: String, srcPath: String) = createModuleFromTestData(srcPath, name, StdModuleTypes.JAVA, true)
}
@@ -45,7 +45,7 @@ abstract class AbstractParameterInfoTest : LightCodeInsightFixtureTestCase() {
val prefix = FileUtil.getNameWithoutExtension(PathUtil.getFileName(fileName))
val mainFile = File(FileUtil.toSystemDependentName(fileName))
mainFile.parentFile
.listFiles { dir, name -> name.startsWith("$prefix.") && name != mainFile.name }
.listFiles { _, name -> name.startsWith("$prefix.") && name != mainFile.name }
.forEach { myFixture.configureByFile(FileUtil.toSystemIndependentName(it.path)) }
myFixture.configureByFile(fileName)
@@ -13,7 +13,7 @@ import org.junit.runner.RunWith
@RunWith(JUnit3WithIdeaConfigurationRunner::class)
class KotlinAddRequiredModuleTest : KotlinLightJava9ModulesCodeInsightFixtureTestCase() {
private val messageM2 = QuickFixBundle.message("module.info.add.requires.name", "M_TWO")!!
private val messageM2 = QuickFixBundle.message("module.info.add.requires.name", "M_TWO")
override fun setUp() {
super.setUp()
@@ -72,7 +72,7 @@ class KotlinAddRequiredModuleTest : KotlinLightJava9ModulesCodeInsightFixtureTes
MAIN)
myFixture.configureFromExistingVirtualFile(editedFile)
findActionAndExecute(QuickFixBundle.message("module.info.add.requires.name", "java.logging")!!)
findActionAndExecute(QuickFixBundle.message("module.info.add.requires.name", "java.logging"))
assertNoErrors()
checkModuleInfo(
@@ -30,8 +30,8 @@ interface QuickFixTest {
val inspectionFile = findInspectionFile(File(beforeFileName).parentFile)
if (inspectionFile != null) {
val className = FileUtil.loadFile(inspectionFile).trim { it <= ' ' }
val inspectionClass = Class.forName(className) as Class<InspectionProfileEntry>
return InspectionTestUtil.instantiateTools(listOf<Class<out InspectionProfileEntry>>(inspectionClass))
@Suppress("UNCHECKED_CAST") val inspectionClass = Class.forName(className) as Class<InspectionProfileEntry>
return InspectionTestUtil.instantiateTools(listOf(inspectionClass))
}
return emptyList()
@@ -48,7 +48,7 @@ abstract class AbstractMultiModuleTest : DaemonAnalyzerTestCase() {
fun module(name: String, jdk: TestJdkKind = TestJdkKind.MOCK_JDK, hasTestRoot: Boolean = false): Module {
val srcDir = testDataPath + "${getTestName(true)}/$name"
val moduleWithSrcRootSet = createModuleFromTestData(srcDir, name, StdModuleTypes.JAVA, true)!!
val moduleWithSrcRootSet = createModuleFromTestData(srcDir, name, StdModuleTypes.JAVA, true)
if (hasTestRoot) {
addRoot(
moduleWithSrcRootSet,
@@ -68,7 +68,7 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() {
fun clazz(text: String, expectedText: String? = null) {
val (file, tree) = createFileAndStubTree(text)
val clazz = tree.findChildStubByType(KtStubElementTypes.CLASS)!!
val psiFromStub = KtClass(clazz as KotlinClassStub)
val psiFromStub = KtClass(clazz)
val classByPsi = file.findChildByClass(KtClass::class.java)
val toCheckAgainst = "STUB: " + (expectedText ?: classByPsi!!.text)
Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText())
@@ -80,7 +80,7 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() {
fun obj(text: String, expectedText: String? = null) {
val (file, tree) = createFileAndStubTree(text)
val obj = tree.findChildStubByType(KtStubElementTypes.OBJECT_DECLARATION)!!
val psiFromStub = KtObjectDeclaration(obj as KotlinObjectStub)
val psiFromStub = KtObjectDeclaration(obj)
val objectByPsi = file.findChildByClass(KtObjectDeclaration::class.java)
val toCheckAgainst = "STUB: " + (expectedText ?: objectByPsi!!.text)
Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText())
@@ -89,7 +89,7 @@ class DebugTextByStubTest : LightCodeInsightFixtureTestCase() {
fun property(text: String, expectedText: String? = null) {
val (file, tree) = createFileAndStubTree(text)
val property = tree.findChildStubByType(KtStubElementTypes.PROPERTY)!!
val psiFromStub = KtProperty(property as KotlinPropertyStub)
val psiFromStub = KtProperty(property)
val propertyByPsi = file.findChildByClass(KtProperty::class.java)
val toCheckAgainst = "STUB: " + (expectedText ?: propertyByPsi!!.text)
Assert.assertEquals(toCheckAgainst, psiFromStub.getDebugText())