Eliminate a set of warnings, mostly nullability ones

This commit is contained in:
Mikhail Glukhikh
2017-08-15 11:05:56 +03:00
committed by Mikhail Glukhikh
parent 82fc221470
commit 3623f581b8
52 changed files with 49 additions and 74 deletions
@@ -278,8 +278,6 @@ fun CallTypeAndReceiver<*, *>.receiverTypesWithIndex(
is CallTypeAndReceiver.ANNOTATION,
is CallTypeAndReceiver.UNKNOWN ->
return null
else -> throw RuntimeException() //TODO: see KT-9394
}
val resolutionScope = contextElement.getResolutionScope(bindingContext, resolutionFacade)
@@ -73,7 +73,7 @@ fun ClassDescriptor.findCallableMemberBySignature(
if (it.containingDeclaration != this) return@firstOrNull false
val overridability = OverridingUtil.DEFAULT.isOverridableBy(it as CallableDescriptor, signature, null).result
overridability == OVERRIDABLE || (allowOverridabilityConflicts && overridability == CONFLICT)
} as? CallableMemberDescriptor
}
}
fun TypeConstructor.supertypesWithAny(): Collection<KotlinType> {
@@ -128,7 +128,7 @@ private fun JavaDescriptorResolver.resolveConstructor(constructor: JavaConstruct
}
private fun JavaDescriptorResolver.resolveField(field: JavaField): PropertyDescriptor? {
return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field) as? PropertyDescriptor
return getContainingScope(field)?.getContributedVariables(field.name, NoLookupLocation.FROM_IDE)?.findByJavaElement(field)
}
private fun JavaDescriptorResolver.getContainingScope(member: JavaMember): MemberScope? {
@@ -64,7 +64,7 @@ abstract class BaseKotlinCompilerSettings<T : Freezable> protected constructor()
override fun getState() = XmlSerializer.serialize(_settings, SKIP_DEFAULT_VALUES)
override fun loadState(state: Element) {
_settings = XmlSerializer.deserialize(state, _settings.javaClass) ?: createSettings()
_settings = XmlSerializer.deserialize(state, _settings.javaClass)
}
public override fun clone(): Any = super.clone()
@@ -139,7 +139,7 @@ class ExpressionsOfTypeProcessor(
if (runReadAction { searchScope is GlobalSearchScope && !FileTypeIndex.containsFileOfType(KotlinFileType.INSTANCE, searchScope) }) return
// for class from library always use plain search because we cannot search usages in compiled code (we could though)
if (classToSearch == null || !runReadAction { classToSearch.isValid && ProjectRootsUtil.isInProjectSource(classToSearch) }) {
if (!runReadAction { classToSearch.isValid && ProjectRootsUtil.isInProjectSource(classToSearch) }) {
possibleMatchesInScopeHandler(searchScope)
return
}
@@ -254,14 +254,14 @@ object KeywordCompletion {
is KtDeclarationWithInitializer -> {
val initializer = parent.initializer
if (prevParent == initializer) {
return buildFilterWithContext("val v = ", initializer!!, position)
return buildFilterWithContext("val v = ", initializer, position)
}
}
is KtParameter -> {
val default = parent.defaultValue
if (prevParent == default) {
return buildFilterWithContext("val v = ", default!!, position)
return buildFilterWithContext("val v = ", default, position)
}
}
@@ -568,7 +568,6 @@ class ExpectedInfos(
}
is PropertyGetterDescriptor -> {
if (descriptor !is PropertyGetterDescriptor) return null
val property = descriptor.correspondingProperty
ExpectedInfo.createForReturnValue(returnTypeToUse(property, hasExplicitReturnType), property)
}
@@ -40,7 +40,7 @@ val KOTLIN_PLUGIN_CLASSPATH_MARKER = "${KotlinWithGradleConfigurator.GROUP_ID}:$
abstract class KotlinGradleInspectionVisitor : BaseInspectionVisitor() {
override fun visitFile(file: GroovyFileBase) {
if (file == null || !FileUtilRt.extensionEquals(file.name, GradleConstants.EXTENSION)) return
if (!FileUtilRt.extensionEquals(file.name, GradleConstants.EXTENSION)) return
val fileIndex = ProjectRootManager.getInstance(file.project).fileIndex
@@ -30,7 +30,7 @@ object KotlinStdJSProjectDescriptor : KotlinLightProjectDescriptor() {
override fun getSdk(): Sdk? = null
override fun configureModule(module: Module, model: ModifiableRootModel) {
val configuration = JSLibraryStdDescription(module.project).createNewLibraryForTests() ?: error("Configuration should exist")
val configuration = JSLibraryStdDescription(module.project).createNewLibraryForTests()
val editor = NewLibraryEditor(configuration.libraryType, configuration.properties)
configuration.addRoots(editor)
@@ -69,7 +69,6 @@ fun Module.configureAs(kind: ModuleKind) {
this.configureAs(KotlinStdJSProjectDescriptor)
}
else -> throw IllegalArgumentException("Unknown kind=$kind")
}
}
@@ -62,7 +62,7 @@ class ConvertFunctionTypeReceiverToParameterIntention : SelfTargetingRangeIntent
class FunctionDefinitionInfo(element: KtFunction) : AbstractProcessableUsageInfo<KtFunction, ConversionData>(element) {
override fun process(data: ConversionData, elementsToShorten: MutableList<KtElement>) {
val function = element as? KtFunction ?: return
val function = element ?: return
val functionParameter = function.valueParameters.getOrNull(data.functionParameterIndex) ?: return
val functionType = functionParameter.typeReference?.typeElement as? KtFunctionType ?: return
val functionTypeParameterList = functionType.parameterList ?: return
@@ -196,7 +196,7 @@ class DeprecatedCallableAddReplaceWithIntention : SelfTargetingRangeIntention<Kt
val body = bodyExpression ?: return null
if (!hasBlockBody()) return body
val block = body as? KtBlockExpression ?: return null
val statement = block.statements.singleOrNull() as? KtExpression ?: return null
val statement = block.statements.singleOrNull() ?: return null
val returnsUnit = (analyze()[BindingContext.DECLARATION_TO_DESCRIPTOR, this] as? FunctionDescriptor)?.returnType?.isUnit() ?: return null
return when (statement) {
is KtReturnExpression -> statement.returnedExpression
@@ -150,7 +150,7 @@ class ChangeSuspendInHierarchyFix(
return DFS.dfs(
listOf(this),
{ (it as? FunctionDescriptor)?.getOverridables() ?: emptyList() },
{ it?.getOverridables() ?: emptyList() },
object : DFS.CollectingNodeHandler<FunctionDescriptor, FunctionDescriptor, ArrayList<FunctionDescriptor>>(ArrayList()) {
override fun afterChildren(current: FunctionDescriptor) {
if (current.getOverridables().isEmpty()) {
@@ -173,7 +173,7 @@ class ChangeSuspendInHierarchyFix(
containingClassDescriptor.defaultType,
currentClassDescriptor.defaultType
) ?: return@filter false
val signatureInCurrentClass = it.substitute(substitutor) as? FunctionDescriptor ?: return@filter false
val signatureInCurrentClass = it.substitute(substitutor) ?: return@filter false
OverridingUtil.DEFAULT.isOverridableBy(signatureInCurrentClass, currentDescriptor, null).result ==
OverridingUtil.OverrideCompatibilityInfo.Result.CONFLICT
}
@@ -586,7 +586,6 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
if (returnTypeRefs.isNotEmpty()) {
val returnType = typeCandidates[callableInfo.returnTypeInfo]!!.getTypeByRenderedType(
returnTypeRefs.map { it.text }
?: throw AssertionError("Expression for return type shouldn't be empty: declaration = ${declaration.text}")
)
if (returnType != null) {
// user selected a given type
@@ -603,7 +602,6 @@ class CallableBuilder(val config: CallableBuilderConfiguration) {
if (parameterTypeRef != null) {
val parameterType = parameterTypeExpressions[i].typeCandidates.getTypeByRenderedType(
listOf(parameterTypeRef.text)
?: throw AssertionError("Expression for parameter type shouldn't be empty: declaration = ${declaration.text}")
)
if (parameterType != null) {
replaceWithLongerName(listOf(parameterTypeRef), parameterType)
@@ -102,7 +102,6 @@ abstract class TypeInfo(val variance: Variance) {
val classDeclaration = receiverClassDescriptor?.let { DescriptorToSourceUtils.getSourceFromDescriptor(it) }
if (!config.isExtension && classDeclaration != null) classDeclaration else config.currentFile
}
else -> throw IllegalArgumentException("Unexpected placement: $placement")
}
return when (containingElement) {
is KtClassOrObject -> (containingElement.resolveToDescriptor() as? ClassDescriptorWithResolutionScopes)?.scopeForMemberDeclarationResolution
@@ -334,7 +334,7 @@ class KotlinFunctionCallUsage(
if (receiverValue is ExpressionReceiver && !receiverValue.expression.isValid) {
receiverValue = receiverValue.wrapInvalidated(element)
}
ArgumentInfo(param, index, resolvedArgument, receiverValue as? ReceiverValue)
ArgumentInfo(param, index, resolvedArgument, receiverValue)
}
val lastParameterIndex = newParameters.lastIndex
@@ -182,7 +182,7 @@ data class ExtractionData(
fun getPossibleTypes(expression: KtExpression, resolvedCall: ResolvedCall<*>?, context: BindingContext): Set<KotlinType> {
val dataFlowInfo = context.getDataFlowInfoAfter(expression)
(resolvedCall?.getImplicitReceiverValue() as? ImplicitReceiver)?.let {
resolvedCall?.getImplicitReceiverValue()?.let {
return dataFlowInfo.getCollectedTypes(DataFlowValueFactory.createDataFlowValueForStableReceiver(it))
}
@@ -282,7 +282,7 @@ open class KotlinIntroduceParameterHandler(
is KtExpression -> matchedElement
is KtStringTemplateEntryWithExpression -> matchedElement.expression
else -> null
} as? KtExpression
}
matchedExpr?.toRange()
}
}
@@ -211,7 +211,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler {
actualExpression = reference!!
diff = actualExpression.textRange.startOffset - emptyBody.textRange.startOffset
actualExpressionText = actualExpression.text
emptyBody = anchor!!.replace(emptyBody) as KtBlockExpression
emptyBody = anchor.replace(emptyBody) as KtBlockExpression
elem = findElementByOffsetAndText(diff, actualExpressionText, emptyBody)
if (elem != null) {
reference = elem as KtExpression
@@ -335,7 +335,7 @@ object KotlinIntroduceVariableHandler : RefactoringActionHandler {
is KtExpression -> candidate
is KtStringTemplateEntryWithExpression -> candidate.expression
else -> throw AssertionError("Unexpected candidate element: " + candidate.text)
} as? KtExpression
}
}
}
@@ -953,7 +953,7 @@ fun checkSuperMethodsWithPopup(
.setResizable(false)
.setRequestFocus(true)
.setItemChoosenCallback {
val value = list.selectedValue as? String ?: return@setItemChoosenCallback
val value = list.selectedValue ?: return@setItemChoosenCallback
val chosenElements = if (value == renameBase) deepestSuperMethods + declaration else listOf(declaration)
action(chosenElements)
}
@@ -100,8 +100,6 @@ fun extractClassMembers(
.mapTo(result) { KotlinMemberInfo(it as KtNamedDeclaration, isCompanionMember = isCompanion) }
}
if (aClass !is KtClassOrObject) return emptyList()
val result = ArrayList<KotlinMemberInfo>()
if (collectSuperTypeEntries) {
@@ -50,7 +50,7 @@ fun invokeMoveFilesOrDirectoriesRefactoring(
project.executeCommand(MoveHandler.REFACTORING_NAME) {
val selectedDir = (if (moveDialog != null) moveDialog.targetDirectory else initialTargetDirectory) ?: return@executeCommand
val updatePackageDirective = (moveDialog as? KotlinAwareMoveFilesOrDirectoriesDialog)?.updatePackageDirective
val updatePackageDirective = moveDialog?.updatePackageDirective
try {
val choice = if (elements.size > 1 || elements[0] is PsiDirectory) intArrayOf(-1) else null
@@ -76,7 +76,6 @@ fun markElements(
?: resolvedCall.extensionReceiver
?: resolvedCall.dispatchReceiver
?: return
if (receiver !is ReceiverValue) return
val implicitThis = receiver.type.constructor.declarationDescriptor as? ClassDescriptor ?: return
if (implicitThis.isCompanionObject
@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.psi.KtSimpleNameExpression
class RenameImportAliasByReferenceHandler : AbstractReferenceSubstitutionRenameHandler(VariableInplaceRenameHandler()) {
override fun getElementToRename(dataContext: DataContext): PsiElement? {
val refExpr = getReferenceExpression(dataContext) as? KtSimpleNameExpression ?: return null
val refExpr = getReferenceExpression(dataContext) ?: return null
return refExpr.mainReference.getImportAlias()
}
}
@@ -47,7 +47,7 @@ class KotlinOverridingMethodsWithGenericsSearcher : QueryExecutor<PsiMethod, Ove
// we do additional search for such methods.
if (!callDescriptor.valueParameters.any { it.type.constructor.declarationDescriptor is TypeParameterDescriptor }) return true
val parentClass = runReadAction { method.containingClass }!!
val parentClass = runReadAction { method.containingClass }
return ClassInheritorsSearch.search(parentClass, p.scope, true).forEach(Processor { inheritor: PsiClass ->
val found = runReadAction {
@@ -153,13 +153,10 @@ abstract class AbstractConfigureKotlinTest : PlatformTestCase() {
collector.showNotification()
}
private fun getPathToJar(runtimeState: FileState, jarFromDist: String, jarFromTemp: String): String {
when (runtimeState) {
KotlinWithLibraryConfigurator.FileState.EXISTS -> return jarFromDist
KotlinWithLibraryConfigurator.FileState.COPY -> return jarFromTemp
KotlinWithLibraryConfigurator.FileState.DO_NOT_COPY -> return jarFromDist
}
return jarFromDist
private fun getPathToJar(runtimeState: FileState, jarFromDist: String, jarFromTemp: String) = when (runtimeState) {
KotlinWithLibraryConfigurator.FileState.EXISTS -> jarFromDist
KotlinWithLibraryConfigurator.FileState.COPY -> jarFromTemp
KotlinWithLibraryConfigurator.FileState.DO_NOT_COPY -> jarFromDist
}
protected fun configure(module: Module, jarState: FileState, configurator: KotlinProjectConfigurator) {
@@ -102,7 +102,7 @@ class InplaceRenameTest : LightPlatformCodeInsightTestCase() {
val element = file.findElementForRename<KtNameReferenceExpression>(editor.caretModel.offset)!!
assertNotNull(element)
val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, element!!,
val dataContext = SimpleDataContext.getSimpleContext(CommonDataKeys.PSI_ELEMENT.name, element,
getCurrentEditorDataContext())
val handler = RenameKotlinImplicitLambdaParameter()
@@ -157,7 +157,7 @@ class KotlinChangeSignatureTest : KotlinLightCodeInsightFixtureTestCase() {
val message = when {
e is BaseRefactoringProcessor.ConflictsInTestsException -> StringUtil.join(e.messages.sorted(), "\n")
e is CommonRefactoringUtil.RefactoringErrorHintException -> e.message
e is RuntimeException && e.message!!.startsWith("Refactoring cannot be performed") -> e.message
e.message!!.startsWith("Refactoring cannot be performed") -> e.message
else -> throw e
}
val conflictsFile = File(testDataPath + getTestName(false) + "Messages.txt")