From c2b532b167c0ac4f0a9244dbd1726dbd42cfdbc9 Mon Sep 17 00:00:00 2001 From: Dmitry Savvinov Date: Tue, 16 Jan 2018 18:24:10 +0300 Subject: [PATCH] Reformat the rest of 'frontend'-module according to new codestyle --- .../kotlin/analyzer/AnalyzerFacade.kt | 134 ++-- .../analyzer/common/CommonAnalyzerFacade.kt | 88 +-- .../kotlin/cfg/ControlFlowBuilder.kt | 1 + .../cfg/ControlFlowInformationProvider.kt | 4 +- .../kotlin/cfg/ControlFlowProcessor.kt | 30 +- .../cfg/PseudocodeVariableDataCollector.kt | 36 +- .../kotlin/cfg/PseudocodeVariablesData.kt | 173 ++--- .../jetbrains/kotlin/cfg/UnreachableCode.kt | 20 +- .../org/jetbrains/kotlin/cfg/WhenChecker.kt | 135 ++-- .../ControlFlowInstructionsGenerator.kt | 126 +-- .../kotlin/cfg/pseudocode/TypePredicate.kt | 32 +- .../jumps/AbstractJumpInstruction.kt | 6 +- .../jumps/NondeterministicJumpInstruction.kt | 12 +- .../kotlin/cfg/pseudocode/pseudocodeUtils.kt | 43 +- .../parsing/ContractParsingServices.kt | 18 +- .../contracts/parsing/PsiConditionParser.kt | 12 +- .../contracts/parsing/PsiEffectParser.kt | 3 +- .../diagnostics/PositioningStrategies.kt | 246 +++--- .../rendering/DiagnosticRendererUtil.kt | 7 +- .../kotlin/diagnostics/rendering/Renderers.kt | 324 +++++--- .../rendering/adaptiveClassifierNamePolicy.kt | 15 +- .../jetbrains/kotlin/frontend/di/injection.kt | 90 +-- .../kotlin/idea/MainFunctionDetector.kt | 17 +- .../kotlin/kdoc/parser/KDocLinkParser.kt | 18 +- .../kotlin/kdoc/psi/impl/KDocSection.kt | 9 +- .../jetbrains/kotlin/kdoc/psi/impl/KDocTag.kt | 9 +- .../kotlin/parsing/KotlinParserDefinition.kt | 4 +- .../KotlinWhitespaceAndCommentsBinders.kt | 23 +- .../psi/KotlinStringLiteralTextEscaper.kt | 2 +- ...tEnumEntrySuperclassReferenceExpression.kt | 4 +- .../jetbrains/kotlin/psi/KtExpressionImpl.kt | 3 +- .../kotlin/psi/KtPrimaryConstructor.kt | 6 +- .../org/jetbrains/kotlin/psi/KtPsiFactory.kt | 56 +- .../org/jetbrains/kotlin/psi/KtTypeAlias.kt | 12 +- .../kotlin/psi/KtTypeCodeFragment.kt | 8 +- .../jetbrains/kotlin/psi/addRemoveModifier.kt | 82 +- .../jetbrains/kotlin/psi/codeFragmentUtil.kt | 3 +- .../jetbrains/kotlin/psi/createByPattern.kt | 74 +- .../jetbrains/kotlin/psi/psiUtil/ktPsiUtil.kt | 83 +- .../jetbrains/kotlin/psi/psiUtil/psiUtils.kt | 61 +- .../kotlin/psi/stubs/StubInterfaces.kt | 2 +- .../KtAnnotationUseSiteTargetElementType.kt | 5 +- ...uperClassReferenceExpressionElementType.kt | 9 +- .../elements/KtImportAliasElementType.kt | 2 +- .../impl/KotlinAnnotationEntryStubImpl.kt | 6 +- .../impl/KotlinAnnotationUseSiteStubImpl.kt | 4 +- .../psi/stubs/impl/KotlinFunctionStubImpl.kt | 17 +- .../psi/stubs/impl/KotlinParameterStubImpl.kt | 12 +- .../psi/stubs/impl/KotlinStubBaseImpl.kt | 13 +- .../psi/stubs/impl/KotlinUserTypeStubImpl.kt | 2 +- .../jetbrains/kotlin/psi/stubs/impl/Utils.kt | 2 +- .../SyntheticClassOrObjectDescriptor.kt | 46 +- .../kotlin/resolve/AllUnderImportScope.kt | 23 +- .../kotlin/resolve/CompositeBindingContext.kt | 4 +- .../resolve/DataClassDescriptorResolver.kt | 104 ++- .../kotlin/resolve/DeclarationResolver.kt | 17 +- .../kotlin/resolve/DeclarationsChecker.kt | 211 ++--- .../kotlin/resolve/DelegationResolver.kt | 141 ++-- .../kotlin/resolve/DescriptorToSourceUtils.kt | 18 +- .../resolve/ExposedVisibilityChecker.kt | 98 ++- .../kotlin/resolve/LazyTopDownAnalyzer.kt | 92 ++- .../kotlin/resolve/ModifiersChecker.kt | 271 ++++--- ...nExpansiveInheritanceRestrictionChecker.kt | 20 +- .../kotlin/resolve/OverrideResolver.kt | 244 +++--- .../jetbrains/kotlin/resolve/TypeBinding.kt | 64 +- .../kotlin/resolve/VariableAsPropertyInfo.kt | 10 +- .../VariableTypeAndInitializerResolver.kt | 2 +- .../kotlin/resolve/calls/CallCompleter.kt | 145 ++-- .../resolve/calls/CallExpressionResolver.kt | 225 +++--- .../kotlin/resolve/calls/CallResolverUtil.kt | 66 +- .../kotlin/resolve/calls/CandidateResolver.kt | 276 +++---- .../DiagnosticReporterByTrackingStrategy.kt | 60 +- .../resolve/calls/GenericCandidateResolver.kt | 200 ++--- .../CallReturnsArrayOfNothingChecker.kt | 2 +- .../CallableReferenceCompatibilityChecker.kt | 11 +- .../checkers/CapturingInClosureChecker.kt | 4 +- .../calls/checkers/DeprecatedCallChecker.kt | 9 +- .../checkers/DslScopeViolationCallChecker.kt | 20 +- .../calls/checkers/OperatorCallChecker.kt | 21 +- .../calls/checkers/RttiExpressionChecker.kt | 8 +- .../calls/checkers/coroutineCallChecker.kt | 37 +- .../inference/ConstraintSystemBuilderImpl.kt | 151 ++-- .../calls/inference/ConstraintSystemImpl.kt | 47 +- .../calls/inference/CoroutineInferenceUtil.kt | 78 +- .../resolve/calls/inference/TypeVariable.kt | 18 +- .../inference/constraintIncorporation.kt | 11 +- .../resolve/calls/model/ArgumentMapping.kt | 7 +- .../model/VariableAsFunctionResolvedCall.kt | 4 +- .../resolve/calls/smartcasts/DataFlowValue.kt | 8 +- .../calls/smartcasts/DataFlowValueFactory.kt | 2 +- .../smartcasts/DelegatingDataFlowInfo.kt | 144 ++-- .../resolve/calls/tasks/dynamicCalls.kt | 83 +- .../tower/KotlinResolutionCallbacksImpl.kt | 79 +- .../calls/tower/NewResolutionOldInference.kt | 279 ++++--- .../resolve/calls/tower/PSICallResolver.kt | 355 +++++---- .../calls/tower/ResolvedAtomCompleter.kt | 103 ++- .../kotlin/resolve/calls/util/callUtil.kt | 36 +- .../ApiVersionClassifierUsageChecker.kt | 10 +- .../resolve/checkers/ConstModifierChecker.kt | 18 +- .../resolve/checkers/DelegationChecker.kt | 34 +- .../DeprecatedClassifierUsageChecker.kt | 10 +- .../ExpectedActualDeclarationChecker.kt | 264 ++++--- .../KClassWithIncorrectTypeArgumentChecker.kt | 14 +- .../evaluate/ConstantExpressionEvaluator.kt | 371 +++++---- .../evaluate/OperationsMapGenerated.kt | 728 +++++++++--------- .../kotlin/resolve/deprecationUtil.kt | 66 +- .../resolve/inline/InlineAnalyzerExtension.kt | 69 +- .../resolve/lazy/DefaultImportProvider.kt | 39 +- .../resolve/lazy/LazyDeclarationResolver.kt | 67 +- .../CliDeclarationProviderFactoryService.kt | 10 +- ...ombinedPackageMemberDeclarationProvider.kt | 6 +- .../DeclarationProviderFactoryService.kt | 25 +- .../PsiBasedClassMemberDeclarationProvider.kt | 6 +- .../descriptors/AbstractLazyMemberScope.kt | 76 +- .../lazy/descriptors/LazyAnnotations.kt | 50 +- .../lazy/descriptors/LazyClassMemberScope.kt | 167 ++-- .../descriptors/LazyPackageMemberScope.kt | 22 +- .../descriptors/LazyScriptClassMemberScope.kt | 31 +- .../scopes/LocalRedeclarationChecker.kt | 37 +- .../kotlin/resolve/source/PsiSourceElement.kt | 2 +- .../script/KotlinScriptDefinitionProvider.kt | 6 +- .../script/ScriptDependenciesProvider.kt | 6 +- .../kotlin/types/CastDiagnosticsUtil.kt | 8 +- .../kotlin/types/WrappedTypeFactory.kt | 4 +- .../DoubleColonExpressionResolver.kt | 319 ++++---- .../types/expressions/KotlinTypeInfo.kt | 18 +- .../expressions/LocalClassifierAnalyzer.kt | 198 ++--- .../PatternMatchingTypingVisitor.kt | 250 +++--- .../PreliminaryDeclarationVisitor.kt | 16 +- .../kotlin/util/MappedExtensionProvider.kt | 10 +- .../kotlin/util/PerformanceCounter.kt | 30 +- .../jetbrains/kotlin/util/exceptionUtil.kt | 43 +- 132 files changed, 4906 insertions(+), 4081 deletions(-) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt index 7ff185ea308..84172a5f852 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/AnalyzerFacade.kt @@ -48,8 +48,8 @@ import java.util.* import kotlin.coroutines.experimental.buildSequence class ResolverForModule( - val packageFragmentProvider: PackageFragmentProvider, - val componentProvider: ComponentProvider + val packageFragmentProvider: PackageFragmentProvider, + val componentProvider: ComponentProvider ) abstract class ResolverForProject { @@ -70,34 +70,36 @@ class EmptyResolverForProject : ResolverForProject() { get() = "Empty resolver" override fun tryGetResolverForModule(moduleInfo: M): ResolverForModule? = null - override fun resolverForModuleDescriptor(descriptor: ModuleDescriptor): ResolverForModule = throw IllegalStateException("$descriptor is not contained in this resolver") + override fun resolverForModuleDescriptor(descriptor: ModuleDescriptor): ResolverForModule = + throw IllegalStateException("$descriptor is not contained in this resolver") + override fun descriptorForModule(moduleInfo: M) = diagnoseUnknownModuleInfo(listOf(moduleInfo)) override val allModules: Collection = listOf() - override fun diagnoseUnknownModuleInfo(infos: List) = throw IllegalStateException("Should not be called for $infos") + override fun diagnoseUnknownModuleInfo(infos: List) = throw IllegalStateException("Should not be called for $infos") } class ResolverForProjectImpl( - private val debugName: String, - private val projectContext: ProjectContext, - modules: Collection, - private val analyzerFacade: (M) -> AnalyzerFacade, - private val modulesContent: (M) -> ModuleContent, - private val platformParameters: PlatformAnalysisParameters, - private val targetEnvironment: TargetEnvironment = CompilerEnvironment, - private val builtIns: KotlinBuiltIns = DefaultBuiltIns.Instance, - private val delegateResolver: ResolverForProject = EmptyResolverForProject(), - private val packagePartProviderFactory: (M, ModuleContent) -> PackagePartProvider = { _, _ -> PackagePartProvider.Empty }, - private val firstDependency: M? = null, - private val modulePlatforms: (M) -> MultiTargetPlatform?, - private val packageOracleFactory: PackageOracleFactory = PackageOracleFactory.OptimisticFactory, - private val languageSettingsProvider: LanguageSettingsProvider = LanguageSettingsProvider.Default, - private val invalidateOnOOCB: Boolean = true + private val debugName: String, + private val projectContext: ProjectContext, + modules: Collection, + private val analyzerFacade: (M) -> AnalyzerFacade, + private val modulesContent: (M) -> ModuleContent, + private val platformParameters: PlatformAnalysisParameters, + private val targetEnvironment: TargetEnvironment = CompilerEnvironment, + private val builtIns: KotlinBuiltIns = DefaultBuiltIns.Instance, + private val delegateResolver: ResolverForProject = EmptyResolverForProject(), + private val packagePartProviderFactory: (M, ModuleContent) -> PackagePartProvider = { _, _ -> PackagePartProvider.Empty }, + private val firstDependency: M? = null, + private val modulePlatforms: (M) -> MultiTargetPlatform?, + private val packageOracleFactory: PackageOracleFactory = PackageOracleFactory.OptimisticFactory, + private val languageSettingsProvider: LanguageSettingsProvider = LanguageSettingsProvider.Default, + private val invalidateOnOOCB: Boolean = true ) : ResolverForProject() { private class ModuleData( - val moduleDescriptor: ModuleDescriptorImpl, - val modificationTracker: ModificationTracker?, - val modificationCount: Long? + val moduleDescriptor: ModuleDescriptorImpl, + val modificationTracker: ModificationTracker?, + val modificationCount: Long? ) { fun isOutOfDate(): Boolean { val currentModCount = modificationTracker?.modificationCount @@ -117,16 +119,22 @@ class ResolverForProjectImpl( } private fun setupModuleDescriptor(module: M, moduleDescriptor: ModuleDescriptorImpl) { - moduleDescriptor.setDependencies(LazyModuleDependencies( + moduleDescriptor.setDependencies( + LazyModuleDependencies( projectContext.storageManager, module, firstDependency, - this)) + this + ) + ) val content = modulesContent(module) moduleDescriptor.initialize( - DelegatingPackageFragmentProvider(this, moduleDescriptor, content, - packageOracleFactory.createOracle(module))) + DelegatingPackageFragmentProvider( + this, moduleDescriptor, content, + packageOracleFactory.createOracle(module) + ) + ) } private val resolverByModuleDescriptor = mutableMapOf() @@ -153,16 +161,17 @@ class ResolverForProjectImpl( ResolverForModuleComputationTracker.getInstance(projectContext.project)?.onResolverComputed(module) analyzerFacade(module).createResolverForModule( - module, descriptor as ModuleDescriptorImpl, projectContext.withModule(descriptor), modulesContent(module), - platformParameters, targetEnvironment, this@ResolverForProjectImpl, - languageSettingsProvider, - packagePartProviderFactory(module, modulesContent(module))) + module, descriptor as ModuleDescriptorImpl, projectContext.withModule(descriptor), modulesContent(module), + platformParameters, targetEnvironment, this@ResolverForProjectImpl, + languageSettingsProvider, + packagePartProviderFactory(module, modulesContent(module)) + ) } } } internal fun isResolverForModuleDescriptorComputed(descriptor: ModuleDescriptor) = - descriptor in resolverByModuleDescriptor + descriptor in resolverByModuleDescriptor override fun descriptorForModule(moduleInfo: M): ModuleDescriptorImpl { if (!isCorrectModuleInfo(moduleInfo)) { @@ -172,7 +181,7 @@ class ResolverForProjectImpl( } override fun diagnoseUnknownModuleInfo(infos: List) = - throw AssertionError("$name does not know how to resolve $infos") + throw AssertionError("$name does not know how to resolve $infos") private fun doGetDescriptorForModule(module: M): ModuleDescriptorImpl { if (module in modules) { @@ -204,19 +213,21 @@ class ResolverForProjectImpl( } private fun createModuleDescriptor(module: M): ModuleData { - val moduleDescriptor = ModuleDescriptorImpl(module.name, - projectContext.storageManager, builtIns, modulePlatforms(module), module.capabilities) + val moduleDescriptor = ModuleDescriptorImpl( + module.name, + projectContext.storageManager, builtIns, modulePlatforms(module), module.capabilities + ) moduleInfoByDescriptor[moduleDescriptor] = module setupModuleDescriptor(module, moduleDescriptor) - val modificationTracker = (module as? TrackableModuleInfo)?.createModificationTracker() ?: - (PsiModificationTracker.SERVICE.getInstance(projectContext.project).outOfCodeBlockModificationTracker.takeIf { invalidateOnOOCB }) + val modificationTracker = (module as? TrackableModuleInfo)?.createModificationTracker() + ?: (PsiModificationTracker.SERVICE.getInstance(projectContext.project).outOfCodeBlockModificationTracker.takeIf { invalidateOnOOCB }) return ModuleData(moduleDescriptor, modificationTracker, modificationTracker?.modificationCount) } } data class ModuleContent( - val syntheticFiles: Collection, - val moduleContentScope: GlobalSearchScope + val syntheticFiles: Collection, + val moduleContentScope: GlobalSearchScope ) interface PlatformAnalysisParameters @@ -238,10 +249,10 @@ interface ModuleInfo { // but if they are present, they should come after JVM built-ins in the dependencies list, because JVM built-ins contain // additional members dependent on the JDK fun dependencyOnBuiltIns(): ModuleInfo.DependencyOnBuiltIns = - if (platform == TargetPlatform.Common) - ModuleInfo.DependencyOnBuiltIns.AFTER_SDK - else - ModuleInfo.DependencyOnBuiltIns.LAST + if (platform == TargetPlatform.Common) + ModuleInfo.DependencyOnBuiltIns.AFTER_SDK + else + ModuleInfo.DependencyOnBuiltIns.LAST //TODO: (module refactoring) provide dependency on builtins after runtime in IDEA enum class DependencyOnBuiltIns { NONE, AFTER_SDK, LAST } @@ -257,25 +268,25 @@ interface TrackableModuleInfo : ModuleInfo { abstract class AnalyzerFacade { abstract fun createResolverForModule( - moduleInfo: M, - moduleDescriptor: ModuleDescriptorImpl, - moduleContext: ModuleContext, - moduleContent: ModuleContent, - platformParameters: PlatformAnalysisParameters, - targetEnvironment: TargetEnvironment, - resolverForProject: ResolverForProject, - languageSettingsProvider: LanguageSettingsProvider, - packagePartProvider: PackagePartProvider + moduleInfo: M, + moduleDescriptor: ModuleDescriptorImpl, + moduleContext: ModuleContext, + moduleContent: ModuleContent, + platformParameters: PlatformAnalysisParameters, + targetEnvironment: TargetEnvironment, + resolverForProject: ResolverForProject, + languageSettingsProvider: LanguageSettingsProvider, + packagePartProvider: PackagePartProvider ): ResolverForModule abstract val targetPlatform: TargetPlatform } -class LazyModuleDependencies( - storageManager: StorageManager, - private val module: M, - firstDependency: M? = null, - private val resolverForProject: ResolverForProjectImpl +class LazyModuleDependencies( + storageManager: StorageManager, + private val module: M, + firstDependency: M? = null, + private val resolverForProject: ResolverForProjectImpl ) : ModuleDependencies { private val dependencies = storageManager.createLazyValue { val moduleDescriptor = resolverForProject.descriptorForModule(module) @@ -307,10 +318,10 @@ class LazyModuleDependencies( private class DelegatingPackageFragmentProvider( - private val resolverForProject: ResolverForProjectImpl, - private val module: ModuleDescriptor, - moduleContent: ModuleContent, - private val packageOracle: PackageOracle + private val resolverForProject: ResolverForProjectImpl, + private val module: ModuleDescriptor, + moduleContent: ModuleContent, + private val packageOracle: PackageOracle ) : PackageFragmentProvider { private val syntheticFilePackages = moduleContent.syntheticFiles.map { it.packageFqName }.toSet() @@ -366,6 +377,7 @@ interface ResolverForModuleComputationTracker { fun onResolverComputed(moduleInfo: ModuleInfo) companion object { - fun getInstance(project: Project): ResolverForModuleComputationTracker? = ServiceManager.getService(project, ResolverForModuleComputationTracker::class.java) ?: null + fun getInstance(project: Project): ResolverForModuleComputationTracker? = + ServiceManager.getService(project, ResolverForModuleComputationTracker::class.java) ?: null } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/common/CommonAnalyzerFacade.kt b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/common/CommonAnalyzerFacade.kt index 03d087945c5..57c58e4179b 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/analyzer/common/CommonAnalyzerFacade.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/analyzer/common/CommonAnalyzerFacade.kt @@ -51,42 +51,42 @@ import org.jetbrains.kotlin.serialization.deserialization.MetadataPackageFragmen */ object CommonAnalyzerFacade : AnalyzerFacade() { private class SourceModuleInfo( - override val name: Name, - override val capabilities: Map, Any?>, - private val dependOnOldBuiltIns: Boolean + override val name: Name, + override val capabilities: Map, Any?>, + private val dependOnOldBuiltIns: Boolean ) : ModuleInfo { override fun dependencies() = listOf(this) override fun dependencyOnBuiltIns(): ModuleInfo.DependencyOnBuiltIns = - if (dependOnOldBuiltIns) ModuleInfo.DependencyOnBuiltIns.LAST else ModuleInfo.DependencyOnBuiltIns.NONE + if (dependOnOldBuiltIns) ModuleInfo.DependencyOnBuiltIns.LAST else ModuleInfo.DependencyOnBuiltIns.NONE } fun analyzeFiles( - files: Collection, moduleName: Name, dependOnBuiltIns: Boolean, languageVersionSettings: LanguageVersionSettings, - capabilities: Map, Any?> = mapOf(MultiTargetPlatform.CAPABILITY to MultiTargetPlatform.Common), - packagePartProviderFactory: (ModuleInfo, ModuleContent) -> PackagePartProvider + files: Collection, moduleName: Name, dependOnBuiltIns: Boolean, languageVersionSettings: LanguageVersionSettings, + capabilities: Map, Any?> = mapOf(MultiTargetPlatform.CAPABILITY to MultiTargetPlatform.Common), + packagePartProviderFactory: (ModuleInfo, ModuleContent) -> PackagePartProvider ): AnalysisResult { val moduleInfo = SourceModuleInfo(moduleName, capabilities, dependOnBuiltIns) val project = files.firstOrNull()?.project ?: throw AssertionError("No files to analyze") val multiplatformLanguageSettings = object : LanguageVersionSettings by languageVersionSettings { override fun getFeatureSupport(feature: LanguageFeature): LanguageFeature.State = - if (feature == LanguageFeature.MultiPlatformProjects) LanguageFeature.State.ENABLED - else languageVersionSettings.getFeatureSupport(feature) + if (feature == LanguageFeature.MultiPlatformProjects) LanguageFeature.State.ENABLED + else languageVersionSettings.getFeatureSupport(feature) } @Suppress("NAME_SHADOWING") - val resolver = ResolverForProjectImpl ( - "sources for metadata serializer", - ProjectContext(project), listOf(moduleInfo), { CommonAnalyzerFacade }, - { ModuleContent(files, GlobalSearchScope.allScope(project)) }, - object : PlatformAnalysisParameters {}, - languageSettingsProvider = object : LanguageSettingsProvider { - override fun getLanguageVersionSettings(moduleInfo: ModuleInfo, project: Project) = multiplatformLanguageSettings - override fun getTargetPlatform(moduleInfo: ModuleInfo) = TargetPlatformVersion.NoVersion - }, - packagePartProviderFactory = packagePartProviderFactory, - modulePlatforms = { MultiTargetPlatform.Common } + val resolver = ResolverForProjectImpl( + "sources for metadata serializer", + ProjectContext(project), listOf(moduleInfo), { CommonAnalyzerFacade }, + { ModuleContent(files, GlobalSearchScope.allScope(project)) }, + object : PlatformAnalysisParameters {}, + languageSettingsProvider = object : LanguageSettingsProvider { + override fun getLanguageVersionSettings(moduleInfo: ModuleInfo, project: Project) = multiplatformLanguageSettings + override fun getTargetPlatform(moduleInfo: ModuleInfo) = TargetPlatformVersion.NoVersion + }, + packagePartProviderFactory = packagePartProviderFactory, + modulePlatforms = { MultiTargetPlatform.Common } ) val moduleDescriptor = resolver.descriptorForModule(moduleInfo) @@ -98,46 +98,46 @@ object CommonAnalyzerFacade : AnalyzerFacade() { } override fun createResolverForModule( - moduleInfo: M, - moduleDescriptor: ModuleDescriptorImpl, - moduleContext: ModuleContext, - moduleContent: ModuleContent, - platformParameters: PlatformAnalysisParameters, - targetEnvironment: TargetEnvironment, - resolverForProject: ResolverForProject, - languageSettingsProvider: LanguageSettingsProvider, - packagePartProvider: PackagePartProvider + moduleInfo: M, + moduleDescriptor: ModuleDescriptorImpl, + moduleContext: ModuleContext, + moduleContent: ModuleContent, + platformParameters: PlatformAnalysisParameters, + targetEnvironment: TargetEnvironment, + resolverForProject: ResolverForProject, + languageSettingsProvider: LanguageSettingsProvider, + packagePartProvider: PackagePartProvider ): ResolverForModule { val (syntheticFiles, moduleContentScope) = moduleContent val project = moduleContext.project val declarationProviderFactory = DeclarationProviderFactoryService.createDeclarationProviderFactory( - project, moduleContext.storageManager, syntheticFiles, - if (moduleInfo.isLibrary) GlobalSearchScope.EMPTY_SCOPE else moduleContentScope, - moduleInfo + project, moduleContext.storageManager, syntheticFiles, + if (moduleInfo.isLibrary) GlobalSearchScope.EMPTY_SCOPE else moduleContentScope, + moduleInfo ) val trace = CodeAnalyzerInitializer.getInstance(project).createTrace() val container = createContainerToResolveCommonCode( - moduleContext, trace, declarationProviderFactory, moduleContentScope, targetEnvironment, packagePartProvider, - languageSettingsProvider.getLanguageVersionSettings(moduleInfo, project) + moduleContext, trace, declarationProviderFactory, moduleContentScope, targetEnvironment, packagePartProvider, + languageSettingsProvider.getLanguageVersionSettings(moduleInfo, project) ) val packageFragmentProviders = listOf( - container.get().packageFragmentProvider, - container.get() + container.get().packageFragmentProvider, + container.get() ) return ResolverForModule(CompositePackageFragmentProvider(packageFragmentProviders), container) } private fun createContainerToResolveCommonCode( - moduleContext: ModuleContext, - bindingTrace: BindingTrace, - declarationProviderFactory: DeclarationProviderFactory, - moduleContentScope: GlobalSearchScope, - targetEnvironment: TargetEnvironment, - packagePartProvider: PackagePartProvider, - languageVersionSettings: LanguageVersionSettings + moduleContext: ModuleContext, + bindingTrace: BindingTrace, + declarationProviderFactory: DeclarationProviderFactory, + moduleContentScope: GlobalSearchScope, + targetEnvironment: TargetEnvironment, + packagePartProvider: PackagePartProvider, + languageVersionSettings: LanguageVersionSettings ): StorageComponentContainer = createContainer("ResolveCommonCode", targetPlatform) { configureModule(moduleContext, targetPlatform, TargetPlatformVersion.NoVersion, bindingTrace) @@ -154,7 +154,7 @@ object CommonAnalyzerFacade : AnalyzerFacade() { useImpl() val metadataFinderFactory = ServiceManager.getService(moduleContext.project, MetadataFinderFactory::class.java) - ?: error("No MetadataFinderFactory in project") + ?: error("No MetadataFinderFactory in project") useInstance(metadataFinderFactory.create(moduleContentScope)) targetEnvironment.configure(this) diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt index f7670ac94f2..6192b8b2570 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowBuilder.kt @@ -29,6 +29,7 @@ import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue interface ControlFlowBuilder { // Subroutines fun enterSubroutine(subroutine: KtElement, invocationKind: InvocationKind? = null) + fun exitSubroutine(subroutine: KtElement, invocationKind: InvocationKind? = null): Pseudocode val currentSubroutine: KtElement diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt index 4ba4f721aee..2b4f0a5e6ac 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowInformationProvider.kt @@ -624,7 +624,7 @@ class ControlFlowInformationProvider private constructor( if (!VariableUseState.isUsed(variableUseState)) { if (element.isSingleUnderscore) return when { - // KtDestructuringDeclarationEntry -> KtDestructuringDeclaration -> KtParameter -> KtParameterList + // KtDestructuringDeclarationEntry -> KtDestructuringDeclaration -> KtParameter -> KtParameterList element is KtDestructuringDeclarationEntry && element.parent.parent?.parent is KtParameterList -> report(Errors.UNUSED_DESTRUCTURED_PARAMETER_ENTRY.on(element, variableDescriptor), ctxt) @@ -866,7 +866,7 @@ class ControlFlowInformationProvider private constructor( class KindAndCall(var kind: TailRecursionKind, internal val call: ResolvedCall<*>) val calls = HashMap() - traverseCalls traverse@{ instruction, resolvedCall -> + traverseCalls traverse@ { instruction, resolvedCall -> // is this a recursive call? val functionDescriptor = resolvedCall.resultingDescriptor if (functionDescriptor.original != subroutineDescriptor) return@traverse diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt index 783384069c0..36f59816bd3 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/ControlFlowProcessor.kt @@ -1021,23 +1021,23 @@ class ControlFlowProcessor(private val trace: BindingTrace) { private fun visitInlinedFunction(lambdaFunctionLiteral: KtFunction, invocationKind: InvocationKind) { // Defer emitting of inlined declaration deferredGeneratorsStack.peek().add({ builder -> - val beforeDeclaration = builder.createUnboundLabel("before inlined declaration") - val afterDeclaration = builder.createUnboundLabel("after inlined declaration") + val beforeDeclaration = builder.createUnboundLabel("before inlined declaration") + val afterDeclaration = builder.createUnboundLabel("after inlined declaration") - builder.bindLabel(beforeDeclaration) + builder.bindLabel(beforeDeclaration) - if (!invocationKind.isDefinitelyVisited()) { - builder.nondeterministicJump(afterDeclaration, lambdaFunctionLiteral, null) - } + if (!invocationKind.isDefinitelyVisited()) { + builder.nondeterministicJump(afterDeclaration, lambdaFunctionLiteral, null) + } - generate(lambdaFunctionLiteral, invocationKind) + generate(lambdaFunctionLiteral, invocationKind) - if (invocationKind.canBeRevisited()) { - builder.nondeterministicJump(beforeDeclaration, lambdaFunctionLiteral, null) - } + if (invocationKind.canBeRevisited()) { + builder.nondeterministicJump(beforeDeclaration, lambdaFunctionLiteral, null) + } - builder.bindLabel(afterDeclaration) - }) + builder.bindLabel(afterDeclaration) + }) } override fun visitNamedFunction(function: KtNamedFunction) { @@ -1544,8 +1544,10 @@ class ControlFlowProcessor(private val trace: BindingTrace) { //noinspection EnumSwitchStatementWhichMissesCases when (kind) { ExplicitReceiverKind.DISPATCH_RECEIVER -> explicitReceiver = resolvedCall.dispatchReceiver - ExplicitReceiverKind.EXTENSION_RECEIVER, ExplicitReceiverKind.BOTH_RECEIVERS -> explicitReceiver = resolvedCall.extensionReceiver - ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> {} + ExplicitReceiverKind.EXTENSION_RECEIVER, ExplicitReceiverKind.BOTH_RECEIVERS -> explicitReceiver = + resolvedCall.extensionReceiver + ExplicitReceiverKind.NO_EXPLICIT_RECEIVER -> { + } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariableDataCollector.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariableDataCollector.kt index 14a566440da..0294fd79cd4 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariableDataCollector.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariableDataCollector.kt @@ -29,28 +29,28 @@ import org.jetbrains.kotlin.resolve.BindingContext import org.jetbrains.kotlin.resolve.BindingContextUtils class PseudocodeVariableDataCollector( - private val bindingContext: BindingContext, - private val pseudocode: Pseudocode + private val bindingContext: BindingContext, + private val pseudocode: Pseudocode ) { val blockScopeVariableInfo = computeBlockScopeVariableInfo(pseudocode) fun > collectData( - traversalOrder: TraversalOrder, - initialInfo: I, - instructionDataMergeStrategy: (Instruction, Collection) -> Edges + traversalOrder: TraversalOrder, + initialInfo: I, + instructionDataMergeStrategy: (Instruction, Collection) -> Edges ): Map> { return pseudocode.collectData( - traversalOrder, - instructionDataMergeStrategy, - { from, to, info -> filterOutVariablesOutOfScope(from, to, info) }, - initialInfo + traversalOrder, + instructionDataMergeStrategy, + { from, to, info -> filterOutVariablesOutOfScope(from, to, info) }, + initialInfo ) } private fun > filterOutVariablesOutOfScope( - from: Instruction, - to: Instruction, - info: I + from: Instruction, + to: Instruction, + info: I ): I { // If an edge goes from deeper scope to a less deep one, this means that it points outside of the deeper scope. val toDepth = to.blockScope.depth @@ -74,9 +74,11 @@ class PseudocodeVariableDataCollector( val variableDeclarationElement = instruction.variableDeclarationElement val descriptor = bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, variableDeclarationElement) ?: return@traverse val variableDescriptor = BindingContextUtils.variableDescriptorForDeclaration(descriptor) - ?: throw AssertionError("Variable or class descriptor should correspond to " + - "the instruction for ${instruction.element.text}.\n" + - "Descriptor: $descriptor") + ?: throw AssertionError( + "Variable or class descriptor should correspond to " + + "the instruction for ${instruction.element.text}.\n" + + "Descriptor: $descriptor" + ) blockScopeVariableInfo.registerVariableDeclaredInScope(variableDescriptor, instruction.blockScope) } }) @@ -85,8 +87,8 @@ class PseudocodeVariableDataCollector( } interface BlockScopeVariableInfo { - val declaredIn : Map - val scopeVariables : Map> + val declaredIn: Map + val scopeVariables: Map> } class BlockScopeVariableInfoImpl : BlockScopeVariableInfo { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariablesData.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariablesData.kt index 10d86a9a7d9..f8e19329bd0 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariablesData.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/PseudocodeVariablesData.kt @@ -42,14 +42,14 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon private val pseudocodeVariableDataCollector = PseudocodeVariableDataCollector(bindingContext, pseudocode) private class VariablesForDeclaration( - val valsWithTrivialInitializer: Set, - val nonTrivialVariables: Set + val valsWithTrivialInitializer: Set, + val nonTrivialVariables: Set ) { val allVars = - if (nonTrivialVariables.isEmpty()) - valsWithTrivialInitializer - else - LinkedHashSet(valsWithTrivialInitializer).also { it.addAll(nonTrivialVariables) } + if (nonTrivialVariables.isEmpty()) + valsWithTrivialInitializer + else + LinkedHashSet(valsWithTrivialInitializer).also { it.addAll(nonTrivialVariables) } } private val declaredVariablesForDeclaration = hashMapOf() @@ -65,10 +65,10 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon get() = pseudocodeVariableDataCollector.blockScopeVariableInfo fun getDeclaredVariables(pseudocode: Pseudocode, includeInsideLocalDeclarations: Boolean): Set = - getAllDeclaredVariables(pseudocode, includeInsideLocalDeclarations).allVars + getAllDeclaredVariables(pseudocode, includeInsideLocalDeclarations).allVars fun isVariableWithTrivialInitializer(variableDescriptor: VariableDescriptor) = - variableDescriptor in rootVariables.valsWithTrivialInitializer + variableDescriptor in rootVariables.valsWithTrivialInitializer private fun getAllDeclaredVariables(pseudocode: Pseudocode, includeInsideLocalDeclarations: Boolean): VariablesForDeclaration { if (!includeInsideLocalDeclarations) { @@ -86,9 +86,9 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } private fun addVariablesFromPseudocode( - pseudocode: Pseudocode, - nonTrivialVariables: MutableSet, - valsWithTrivialInitializer: MutableSet + pseudocode: Pseudocode, + nonTrivialVariables: MutableSet, + valsWithTrivialInitializer: MutableSet ) { getUpperLevelDeclaredVariables(pseudocode).let { nonTrivialVariables.addAll(it.nonTrivialVariables) @@ -107,14 +107,13 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon if (instruction is VariableDeclarationInstruction) { val variableDeclarationElement = instruction.variableDeclarationElement val descriptor = - variableDescriptorForDeclaration( - bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, variableDeclarationElement) - ) ?: continue + variableDescriptorForDeclaration( + bindingContext.get(BindingContext.DECLARATION_TO_DESCRIPTOR, variableDeclarationElement) + ) ?: continue if (!containsDoWhile && isValWithTrivialInitializer(variableDeclarationElement, descriptor)) { valsWithTrivialInitializer.add(descriptor) - } - else { + } else { nonTrivialVariables.add(descriptor) } } @@ -124,8 +123,8 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } private fun isValWithTrivialInitializer(variableDeclarationElement: KtDeclaration, descriptor: VariableDescriptor) = - variableDeclarationElement is KtParameter || variableDeclarationElement is KtObjectDeclaration || - variableDeclarationElement.safeAs()?.isVariableWithTrivialInitializer(descriptor) == true + variableDeclarationElement is KtParameter || variableDeclarationElement is KtObjectDeclaration || + variableDeclarationElement.safeAs()?.isVariableWithTrivialInitializer(descriptor) == true private fun KtVariableDeclaration.isVariableWithTrivialInitializer(descriptor: VariableDescriptor): Boolean { if (descriptor.isPropertyWithoutBackingField()) return true @@ -148,18 +147,20 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon if (rootVariables.nonTrivialVariables.isEmpty()) return resultForValsWithTrivialInitializer - return pseudocodeVariableDataCollector.collectData(TraversalOrder.FORWARD, InitControlFlowInfo()) { - instruction: Instruction, incomingEdgesData: Collection -> + return pseudocodeVariableDataCollector.collectData( + TraversalOrder.FORWARD, + InitControlFlowInfo() + ) { instruction: Instruction, incomingEdgesData: Collection -> val enterInstructionData = mergeIncomingEdgesDataForInitializers(instruction, incomingEdgesData, blockScopeVariableInfo) val exitInstructionData = addVariableInitStateFromCurrentInstructionIfAny( - instruction, enterInstructionData, blockScopeVariableInfo) + instruction, enterInstructionData, blockScopeVariableInfo + ) Edges(enterInstructionData, exitInstructionData) - }.mapValues { - (instruction, edges) -> - val trivialEdges = resultForValsWithTrivialInitializer[instruction]!! - Edges(trivialEdges.incoming.replaceDelegate(edges.incoming), trivialEdges.outgoing.replaceDelegate(edges.outgoing)) - } + }.mapValues { (instruction, edges) -> + val trivialEdges = resultForValsWithTrivialInitializer[instruction]!! + Edges(trivialEdges.incoming.replaceDelegate(edges.incoming), trivialEdges.outgoing.replaceDelegate(edges.outgoing)) + } } private fun computeInitInfoForTrivialVals(): Map> { @@ -170,8 +171,7 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon val enterState = ReadOnlyInitControlFlowInfoImpl(declaredSet, initSet, null) when (instruction) { is VariableDeclarationInstruction -> - extractValWithTrivialInitializer(instruction)?.let { - variableDescriptor -> + extractValWithTrivialInitializer(instruction)?.let { variableDescriptor -> declaredSet = declaredSet.add(variableDescriptor) } is WriteValueInstruction -> { @@ -193,12 +193,12 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon // WriteValueInstruction having KtDeclaration as an element means // it must be a write happened at the same time when // the variable (common variable/parameter/object) has been declared - element is KtDeclaration + element is KtDeclaration private inner class ReadOnlyInitControlFlowInfoImpl( - val declaredSet: ImmutableSet, - val initSet: ImmutableSet, - private val delegate: ReadOnlyInitControlFlowInfo? + val declaredSet: ImmutableSet, + val initSet: ImmutableSet, + private val delegate: ReadOnlyInitControlFlowInfo? ) : ReadOnlyInitControlFlowInfo { override fun getOrNull(variableDescriptor: VariableDescriptor): VariableControlFlowState? { if (variableDescriptor in declaredSet) { @@ -208,16 +208,15 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } override fun checkDefiniteInitializationInWhen(merge: ReadOnlyInitControlFlowInfo): Boolean = - delegate?.checkDefiniteInitializationInWhen(merge) ?: false + delegate?.checkDefiniteInitializationInWhen(merge) ?: false fun replaceDelegate(newDelegate: ReadOnlyInitControlFlowInfo): ReadOnlyInitControlFlowInfo = - ReadOnlyInitControlFlowInfoImpl(declaredSet, initSet, newDelegate) + ReadOnlyInitControlFlowInfoImpl(declaredSet, initSet, newDelegate) override fun asMap(): ImmutableMap { val initial = delegate?.asMap() ?: ImmutableHashMap.empty() - return declaredSet.fold(initial) { - acc, variableDescriptor -> + return declaredSet.fold(initial) { acc, variableDescriptor -> acc.put(variableDescriptor, getOrNull(variableDescriptor)!!) } } @@ -244,17 +243,16 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } private fun addVariableInitStateFromCurrentInstructionIfAny( - instruction: Instruction, - enterInstructionData: InitControlFlowInfo, - blockScopeVariableInfo: BlockScopeVariableInfo): InitControlFlowInfo { + instruction: Instruction, + enterInstructionData: InitControlFlowInfo, + blockScopeVariableInfo: BlockScopeVariableInfo + ): InitControlFlowInfo { if (instruction is MagicInstruction) { if (instruction.kind === MagicKind.EXHAUSTIVE_WHEN_ELSE) { - return enterInstructionData.iterator().fold(enterInstructionData) { - result, (key, value) -> + return enterInstructionData.iterator().fold(enterInstructionData) { result, (key, value) -> if (!value.definitelyInitialized()) { result.put(key, VariableControlFlowState.createInitializedExhaustively(value.isDeclared)) - } - else result + } else result } } } @@ -262,9 +260,9 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon return enterInstructionData } val variable = - PseudocodeUtil.extractVariableDescriptorIfAny(instruction, bindingContext) - ?.takeIf { it in rootVariables.nonTrivialVariables } - ?: return enterInstructionData + PseudocodeUtil.extractVariableDescriptorIfAny(instruction, bindingContext) + ?.takeIf { it in rootVariables.nonTrivialVariables } + ?: return enterInstructionData var exitInstructionData = enterInstructionData if (instruction is WriteValueInstruction) { // if writing to already initialized object @@ -275,12 +273,11 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon val enterInitState = enterInstructionData.getOrNull(variable) val initializationAtThisElement = VariableControlFlowState.create(instruction.element is KtProperty, enterInitState) exitInstructionData = exitInstructionData.put(variable, initializationAtThisElement, enterInitState) - } - else { + } else { // instruction instanceof VariableDeclarationInstruction val enterInitState = - enterInstructionData.getOrNull(variable) - ?: getDefaultValueForInitializers(variable, instruction, blockScopeVariableInfo) + enterInstructionData.getOrNull(variable) + ?: getDefaultValueForInitializers(variable, instruction, blockScopeVariableInfo) if (!enterInitState.mayBeInitialized() || !enterInitState.isDeclared) { val variableDeclarationInfo = VariableControlFlowState.create(enterInitState.initState, isDeclared = true) @@ -303,12 +300,14 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } } - return pseudocodeVariableDataCollector.collectData(TraversalOrder.BACKWARD, UseControlFlowInfo()) { instruction: Instruction, incomingEdgesData: Collection -> + return pseudocodeVariableDataCollector.collectData( + TraversalOrder.BACKWARD, + UseControlFlowInfo() + ) { instruction: Instruction, incomingEdgesData: Collection -> val enterResult: UseControlFlowInfo = if (incomingEdgesData.size == 1) { incomingEdgesData.single() - } - else { + } else { incomingEdgesData.fold(UseControlFlowInfo()) { result, edgeData -> edgeData.iterator().fold(result) { subResult, (variableDescriptor, variableUseState) -> subResult.put(variableDescriptor, variableUseState.merge(subResult.getOrNull(variableDescriptor))) @@ -317,38 +316,35 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } val variableDescriptor = - PseudocodeUtil.extractVariableDescriptorFromReference(instruction, bindingContext) - ?.takeIf { it in rootVariables.nonTrivialVariables } + PseudocodeUtil.extractVariableDescriptorFromReference(instruction, bindingContext) + ?.takeIf { it in rootVariables.nonTrivialVariables } if (variableDescriptor == null || instruction !is ReadValueInstruction && instruction !is WriteValueInstruction) { Edges(enterResult, enterResult) - } - else { + } else { val exitResult = - if (instruction is ReadValueInstruction) { - enterResult.put(variableDescriptor, VariableUseState.READ) + if (instruction is ReadValueInstruction) { + enterResult.put(variableDescriptor, VariableUseState.READ) + } else { + var variableUseState: VariableUseState? = enterResult.getOrNull(variableDescriptor) + if (variableUseState == null) { + variableUseState = VariableUseState.UNUSED } - else { - var variableUseState: VariableUseState? = enterResult.getOrNull(variableDescriptor) - if (variableUseState == null) { - variableUseState = VariableUseState.UNUSED - } - when (variableUseState) { - VariableUseState.UNUSED, VariableUseState.ONLY_WRITTEN_NEVER_READ -> - enterResult.put(variableDescriptor, VariableUseState.ONLY_WRITTEN_NEVER_READ) - VariableUseState.WRITTEN_AFTER_READ, VariableUseState.READ -> - enterResult.put(variableDescriptor, VariableUseState.WRITTEN_AFTER_READ) - } + when (variableUseState) { + VariableUseState.UNUSED, VariableUseState.ONLY_WRITTEN_NEVER_READ -> + enterResult.put(variableDescriptor, VariableUseState.ONLY_WRITTEN_NEVER_READ) + VariableUseState.WRITTEN_AFTER_READ, VariableUseState.READ -> + enterResult.put(variableDescriptor, VariableUseState.WRITTEN_AFTER_READ) } + } Edges(enterResult, exitResult) } - }.mapValues { - (_, edges) -> + }.mapValues { (_, edges) -> - Edges( + Edges( edgesForTrivialVals.incoming.replaceDelegate(edges.incoming), edgesForTrivialVals.outgoing.replaceDelegate(edges.outgoing) - ) - } + ) + } } private fun computeUseInfoForTrivialVals(): Edges { @@ -373,8 +369,8 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } private inner class ReadOnlyUseControlFlowInfoImpl( - val used: Set, - val delegate: ReadOnlyUseControlFlowInfo? + val used: Set, + val delegate: ReadOnlyUseControlFlowInfo? ) : ReadOnlyUseControlFlowInfo { override fun getOrNull(variableDescriptor: VariableDescriptor): VariableUseState? { if (variableDescriptor in used) return VariableUseState.READ @@ -382,13 +378,12 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon } fun replaceDelegate(newDelegate: ReadOnlyUseControlFlowInfo): ReadOnlyUseControlFlowInfo = - ReadOnlyUseControlFlowInfoImpl(used, newDelegate) + ReadOnlyUseControlFlowInfoImpl(used, newDelegate) override fun asMap(): ImmutableMap { val initial = delegate?.asMap() ?: ImmutableHashMap.empty() - return used.fold(initial) { - acc, variableDescriptor -> + return used.fold(initial) { acc, variableDescriptor -> acc.put(variableDescriptor, getOrNull(variableDescriptor)!!) } } @@ -417,24 +412,24 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon @JvmStatic fun getDefaultValueForInitializers( - variable: VariableDescriptor, - instruction: Instruction, - blockScopeVariableInfo: BlockScopeVariableInfo + variable: VariableDescriptor, + instruction: Instruction, + blockScopeVariableInfo: BlockScopeVariableInfo ): VariableControlFlowState { //todo: think of replacing it with "MapWithDefaultValue" val declaredIn = blockScopeVariableInfo.declaredIn[variable] val declaredOutsideThisDeclaration = - declaredIn == null //declared outside this pseudocode - || declaredIn.blockScopeForContainingDeclaration != instruction.blockScope.blockScopeForContainingDeclaration + declaredIn == null //declared outside this pseudocode + || declaredIn.blockScopeForContainingDeclaration != instruction.blockScope.blockScopeForContainingDeclaration return VariableControlFlowState.create(isInitialized = declaredOutsideThisDeclaration) } private val EMPTY_INIT_CONTROL_FLOW_INFO = InitControlFlowInfo() private fun mergeIncomingEdgesDataForInitializers( - instruction: Instruction, - incomingEdgesData: Collection, - blockScopeVariableInfo: BlockScopeVariableInfo + instruction: Instruction, + incomingEdgesData: Collection, + blockScopeVariableInfo: BlockScopeVariableInfo ): InitControlFlowInfo { if (incomingEdgesData.size == 1) return incomingEdgesData.single() if (incomingEdgesData.isEmpty()) return EMPTY_INIT_CONTROL_FLOW_INFO @@ -448,7 +443,7 @@ class PseudocodeVariablesData(val pseudocode: Pseudocode, private val bindingCon var isDeclared = true for (edgeData in incomingEdgesData) { val varControlFlowState = edgeData.getOrNull(variable) - ?: getDefaultValueForInitializers(variable, instruction, blockScopeVariableInfo) + ?: getDefaultValueForInitializers(variable, instruction, blockScopeVariableInfo) initState = initState?.merge(varControlFlowState.initState) ?: varControlFlowState.initState if (!varControlFlowState.isDeclared) { isDeclared = false diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt index f904097fb74..6818f88eee9 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/UnreachableCode.kt @@ -33,8 +33,8 @@ interface UnreachableCode { } class UnreachableCodeImpl( - private val reachableElements: Set, - private val unreachableElements: Set + private val reachableElements: Set, + private val unreachableElements: Set ) : UnreachableCode { // This is needed in order to highlight only '1 < 2' and not '1', '<' and '2' as well @@ -42,30 +42,29 @@ class UnreachableCodeImpl( override fun getUnreachableTextRanges(element: KtElement): List { return if (element.hasChildrenInSet(reachableElements)) { - with (element.getLeavesOrReachableChildren().removeReachableElementsWithMeaninglessSiblings().mergeAdjacentTextRanges()) { + with(element.getLeavesOrReachableChildren().removeReachableElementsWithMeaninglessSiblings().mergeAdjacentTextRanges()) { if (isNotEmpty()) this // Specific case like condition in when: // element is dead but its only child is alive and has the same text range else listOf(element.textRange.endOffset.let { TextRange(it, it) }) } - } - else { + } else { listOf(element.textRange!!) } } private fun KtElement.hasChildrenInSet(set: Set): Boolean = - PsiTreeUtil.collectElements(this) { it != this }.any { it in set } + PsiTreeUtil.collectElements(this) { it != this }.any { it in set } private fun KtElement.getLeavesOrReachableChildren(): List { val children = ArrayList() acceptChildren(object : PsiElementVisitor() { override fun visitElement(element: PsiElement) { - val isReachable = element is KtElement && reachableElements.contains(element) && !element.hasChildrenInSet(unreachableElements) + val isReachable = + element is KtElement && reachableElements.contains(element) && !element.hasChildrenInSet(unreachableElements) if (isReachable || element.children.isEmpty()) { children.add(element) - } - else { + } else { element.acceptChildren(this) } } @@ -102,8 +101,7 @@ class UnreachableCodeImpl( private fun List.mergeAdjacentTextRanges(): List { val result = ArrayList() - val lastRange = fold(null as TextRange?) { - currentTextRange, element -> + val lastRange = fold(null as TextRange?) { currentTextRange, element -> val elementRange = element.textRange!! when { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.kt index 685a7fafd23..f1119319e4f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/WhenChecker.kt @@ -54,10 +54,10 @@ val List.hasUnknown: Boolean private interface WhenExhaustivenessChecker { fun getMissingCases( - expression: KtWhenExpression, - context: BindingContext, - subjectDescriptor: ClassDescriptor?, - nullable: Boolean + expression: KtWhenExpression, + context: BindingContext, + subjectDescriptor: ClassDescriptor?, + nullable: Boolean ): List fun isApplicable(subjectType: KotlinType): Boolean = false @@ -72,7 +72,7 @@ object NullMissingCase : WhenMissingCase() { // It's not a regular exhaustiveness checker, invoke it only inside other checkers private object WhenOnNullableExhaustivenessChecker /* : WhenExhaustivenessChecker*/ { fun getMissingCases(expression: KtWhenExpression, context: BindingContext, nullable: Boolean) = - if (nullable) getNullCaseIfMissing(expression, context) else listOf() + if (nullable) getNullCaseIfMissing(expression, context) else listOf() private fun getNullCaseIfMissing(expression: KtWhenExpression, context: BindingContext): List { for (entry in expression.entries) { @@ -99,10 +99,10 @@ class BooleanMissingCase(val b: Boolean) : WhenMissingCase() { private object WhenOnBooleanExhaustivenessChecker : WhenExhaustivenessChecker { override fun getMissingCases( - expression: KtWhenExpression, - context: BindingContext, - subjectDescriptor: ClassDescriptor?, - nullable: Boolean + expression: KtWhenExpression, + context: BindingContext, + subjectDescriptor: ClassDescriptor?, + nullable: Boolean ): List { // It's assumed (and not checked) that expression is of the boolean type var containsFalse = false @@ -117,8 +117,8 @@ private object WhenOnBooleanExhaustivenessChecker : WhenExhaustivenessChecker { } } return (if (!containsTrue) listOf(BooleanMissingCase(true)) else listOf()) + - (if (!containsFalse) listOf(BooleanMissingCase(false)) else listOf()) + - WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) + (if (!containsFalse) listOf(BooleanMissingCase(false)) else listOf()) + + WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) } override fun isApplicable(subjectType: KotlinType): Boolean { @@ -126,7 +126,7 @@ private object WhenOnBooleanExhaustivenessChecker : WhenExhaustivenessChecker { } } -class ClassMissingCase(val descriptor: ClassDescriptor): WhenMissingCase() { +class ClassMissingCase(val descriptor: ClassDescriptor) : WhenMissingCase() { val classIsSingleton get() = descriptor.kind.isSingleton val classFqName get() = DescriptorUtils.getFqNameFromTopLevelClass(descriptor) @@ -138,11 +138,11 @@ class ClassMissingCase(val descriptor: ClassDescriptor): WhenMissingCase() { internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChecker { private fun getReference(expression: KtExpression?): KtSimpleNameExpression? = - when (expression) { - is KtSimpleNameExpression -> expression - is KtQualifiedExpression -> getReference(expression.selectorExpression) - else -> null - } + when (expression) { + is KtSimpleNameExpression -> expression + is KtQualifiedExpression -> getReference(expression.selectorExpression) + else -> null + } protected val ClassDescriptor.deepSealedSubclasses: List get() = this.sealedSubclasses.flatMap { @@ -154,9 +154,9 @@ internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChe get() = (this as? KtWhenConditionIsPattern)?.isNegated ?: false private fun KtWhenCondition.isRelevant(checkedDescriptor: ClassDescriptor) = - this !is KtWhenConditionWithExpression || - DescriptorUtils.isObject(checkedDescriptor) || - DescriptorUtils.isEnumEntry(checkedDescriptor) + this !is KtWhenConditionWithExpression || + DescriptorUtils.isObject(checkedDescriptor) || + DescriptorUtils.isEnumEntry(checkedDescriptor) private fun KtWhenCondition.getCheckedDescriptor(context: BindingContext): ClassDescriptor? { return when (this) { @@ -175,9 +175,9 @@ internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChe } protected fun getMissingClassCases( - whenExpression: KtWhenExpression, - subclasses: Set, - context: BindingContext + whenExpression: KtWhenExpression, + subclasses: Set, + context: BindingContext ): List { // when on empty enum / sealed is considered non-exhaustive, see test whenOnEmptySealed if (subclasses.isEmpty()) return listOf(UnknownMissingCase) @@ -188,8 +188,8 @@ internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChe val negated = condition.negated val checkedDescriptor = condition.getCheckedDescriptor(context) ?: continue val checkedDescriptorSubclasses = - if (checkedDescriptor.modality == Modality.SEALED) checkedDescriptor.deepSealedSubclasses - else listOf(checkedDescriptor) + if (checkedDescriptor.modality == Modality.SEALED) checkedDescriptor.deepSealedSubclasses + else listOf(checkedDescriptor) // Checks are important only for nested subclasses of the sealed class // In additional, check without "is" is important only for objects @@ -201,8 +201,7 @@ internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChe if (checkedDescriptors.containsAll(checkedDescriptorSubclasses)) return listOf() checkedDescriptors.addAll(subclasses) checkedDescriptors.removeAll(checkedDescriptorSubclasses) - } - else { + } else { checkedDescriptors.addAll(checkedDescriptorSubclasses) } } @@ -213,19 +212,19 @@ internal abstract class WhenOnClassExhaustivenessChecker : WhenExhaustivenessChe private object WhenOnEnumExhaustivenessChecker : WhenOnClassExhaustivenessChecker() { override fun getMissingCases( - expression: KtWhenExpression, - context: BindingContext, - subjectDescriptor: ClassDescriptor?, - nullable: Boolean + expression: KtWhenExpression, + context: BindingContext, + subjectDescriptor: ClassDescriptor?, + nullable: Boolean ): List { assert(isEnumClass(subjectDescriptor)) { "isWhenOnEnumExhaustive should be called with an enum class descriptor" } val entryDescriptors = - DescriptorUtils.getAllDescriptors(subjectDescriptor!!.unsubstitutedInnerClassesScope) - .filter(::isEnumEntry) - .filterIsInstance() - .toSet() + DescriptorUtils.getAllDescriptors(subjectDescriptor!!.unsubstitutedInnerClassesScope) + .filter(::isEnumEntry) + .filterIsInstance() + .toSet() return getMissingClassCases(expression, entryDescriptors, context) + - WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) + WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) } override fun isApplicable(subjectType: KotlinType): Boolean { @@ -236,10 +235,10 @@ private object WhenOnEnumExhaustivenessChecker : WhenOnClassExhaustivenessChecke internal object WhenOnSealedExhaustivenessChecker : WhenOnClassExhaustivenessChecker() { override fun getMissingCases( - expression: KtWhenExpression, - context: BindingContext, - subjectDescriptor: ClassDescriptor?, - nullable: Boolean + expression: KtWhenExpression, + context: BindingContext, + subjectDescriptor: ClassDescriptor?, + nullable: Boolean ): List { assert(DescriptorUtils.isSealedClass(subjectDescriptor)) { "isWhenOnSealedClassExhaustive should be called with a sealed class descriptor: $subjectDescriptor" @@ -247,7 +246,7 @@ internal object WhenOnSealedExhaustivenessChecker : WhenOnClassExhaustivenessChe val allSubclasses = subjectDescriptor!!.deepSealedSubclasses return getMissingClassCases(expression, allSubclasses.toSet(), context) + - WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) + WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, nullable) } override fun isApplicable(subjectType: KotlinType): Boolean { @@ -258,13 +257,15 @@ internal object WhenOnSealedExhaustivenessChecker : WhenOnClassExhaustivenessChe object WhenChecker { - private val exhaustivenessCheckers = listOf(WhenOnBooleanExhaustivenessChecker, - WhenOnEnumExhaustivenessChecker, - WhenOnSealedExhaustivenessChecker) + private val exhaustivenessCheckers = listOf( + WhenOnBooleanExhaustivenessChecker, + WhenOnEnumExhaustivenessChecker, + WhenOnSealedExhaustivenessChecker + ) @JvmStatic fun isWhenByEnum(expression: KtWhenExpression, context: BindingContext) = - getClassDescriptorOfTypeIfEnum(whenSubjectType(expression, context)) != null + getClassDescriptorOfTypeIfEnum(whenSubjectType(expression, context)) != null @JvmStatic fun getClassDescriptorOfTypeIfEnum(type: KotlinType?): ClassDescriptor? { @@ -276,26 +277,26 @@ object WhenChecker { } @JvmStatic - fun getClassDescriptorOfTypeIfSealed(type: KotlinType?): ClassDescriptor? - = type?.let { TypeUtils.getClassDescriptor(it) }?.takeIf { DescriptorUtils.isSealedClass(it) } + fun getClassDescriptorOfTypeIfSealed(type: KotlinType?): ClassDescriptor? = + type?.let { TypeUtils.getClassDescriptor(it) }?.takeIf { DescriptorUtils.isSealedClass(it) } @JvmStatic fun whenSubjectType(expression: KtWhenExpression, context: BindingContext) = - expression.subjectExpression?.let { context.get(SMARTCAST, it)?.defaultType ?: context.getType(it) } + expression.subjectExpression?.let { context.get(SMARTCAST, it)?.defaultType ?: context.getType(it) } @JvmStatic fun getEnumMissingCases( - expression: KtWhenExpression, - context: BindingContext, - enumClassDescriptor: ClassDescriptor + expression: KtWhenExpression, + context: BindingContext, + enumClassDescriptor: ClassDescriptor ) = WhenOnEnumExhaustivenessChecker.getMissingCases(expression, context, enumClassDescriptor, false) @JvmStatic fun getSealedMissingCases( - expression: KtWhenExpression, - context: BindingContext, - sealedClassDescriptor: ClassDescriptor + expression: KtWhenExpression, + context: BindingContext, + sealedClassDescriptor: ClassDescriptor ) = WhenOnSealedExhaustivenessChecker.getMissingCases(expression, context, sealedClassDescriptor, false) fun getMissingCases(expression: KtWhenExpression, context: BindingContext): List { @@ -308,15 +309,15 @@ object WhenChecker { @JvmStatic fun isWhenExhaustive(expression: KtWhenExpression, trace: BindingTrace) = - if (getMissingCases(expression, trace.bindingContext).isEmpty()) { - trace.record(BindingContext.EXHAUSTIVE_WHEN, expression) - true - } else { - false - } + if (getMissingCases(expression, trace.bindingContext).isEmpty()) { + trace.record(BindingContext.EXHAUSTIVE_WHEN, expression) + true + } else { + false + } fun containsNullCase(expression: KtWhenExpression, context: BindingContext) = - WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, true).isEmpty() + WhenOnNullableExhaustivenessChecker.getMissingCases(expression, context, true).isEmpty() fun checkDuplicatedLabels(expression: KtWhenExpression, trace: BindingTrace) { if (expression.subjectExpression == null) return @@ -331,11 +332,11 @@ object WhenChecker { is KtWhenConditionWithExpression -> { val constantExpression = condition.expression ?: continue@conditions val constant = ConstantExpressionEvaluator.getConstant( - constantExpression, trace.bindingContext) ?: continue@conditions + constantExpression, trace.bindingContext + ) ?: continue@conditions if (checkedConstants.contains(constant)) { trace.report(Errors.DUPLICATE_LABEL_IN_WHEN.on(constantExpression)) - } - else { + } else { checkedConstants.add(constant) } @@ -346,12 +347,12 @@ object WhenChecker { val typeWithIsNegation = type to condition.isNegated if (checkedTypes.contains(typeWithIsNegation)) { trace.report(Errors.DUPLICATE_LABEL_IN_WHEN.on(typeReference)) - } - else { + } else { checkedTypes.add(typeWithIsNegation) } } - else -> {} + else -> { + } } } } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/ControlFlowInstructionsGenerator.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/ControlFlowInstructionsGenerator.kt index fba85f518ed..19dbbfdf51f 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/ControlFlowInstructionsGenerator.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/ControlFlowInstructionsGenerator.kt @@ -58,8 +58,7 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { val worker = builders.pop() builder = if (!builders.isEmpty()) { builders.peek() - } - else { + } else { null } return worker @@ -70,8 +69,7 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { val shouldInlnie = invocationKind != null if (builder != null && subroutine is KtFunctionLiteral) { pushBuilder(subroutine, builder.returnSubroutine, shouldInlnie) - } - else { + } else { pushBuilder(subroutine, subroutine, shouldInlnie) } delegateBuilder.enterBlockScope(subroutine) @@ -86,8 +84,7 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { val builder = builders.peek() if (invocationKind == null) { builder.declareFunction(subroutine, worker.pseudocode) - } - else { + } else { builder.declareInlinedFunction(subroutine, worker.pseudocode, invocationKind) } } @@ -95,9 +92,9 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { } private inner class ControlFlowInstructionsGeneratorWorker( - scopingElement: KtElement, - override val returnSubroutine: KtElement, - shouldInline: Boolean + scopingElement: KtElement, + override val returnSubroutine: KtElement, + shouldInline: Boolean ) : ControlFlowBuilder { val pseudocode: PseudocodeImpl = PseudocodeImpl(scopingElement, shouldInline) @@ -128,12 +125,13 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { } val info = LoopInfo( - expression, - createUnboundLabel("loop entry point"), - createUnboundLabel("loop exit point"), - createUnboundLabel("body entry point"), - createUnboundLabel("body exit point"), - createUnboundLabel("condition entry point")) + expression, + createUnboundLabel("loop entry point"), + createUnboundLabel("loop exit point"), + createUnboundLabel("body entry point"), + createUnboundLabel("body exit point"), + createUnboundLabel("condition entry point") + ) bindLabel(info.entryPoint) elementToLoopInfo.put(expression, info) return info @@ -158,9 +156,10 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { override fun enterSubroutine(subroutine: KtElement, invocationKind: InvocationKind?) { val blockInfo = SubroutineInfo( - subroutine, - /* entry point */ createUnboundLabel(), - /* exit point */ createUnboundLabel()) + subroutine, + /* entry point */ createUnboundLabel(), + /* exit point */ createUnboundLabel() + ) elementToSubroutineInfo.put(subroutine, blockInfo) allBlocks.push(blockInfo) bindLabel(blockInfo.entryPoint) @@ -173,10 +172,11 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { override fun getLoopConditionEntryPoint(loop: KtLoopExpression): Label? = elementToLoopInfo[loop]?.conditionEntryPoint override fun getLoopExitPoint(loop: KtLoopExpression): Label? =// It's quite possible to have null here, see testBreakInsideLocal - elementToLoopInfo[loop]?.exitPoint + elementToLoopInfo[loop]?.exitPoint - override fun getSubroutineExitPoint(labelElement: KtElement): Label? =// It's quite possible to have null here, e.g. for non-local returns (see KT-10823) - elementToSubroutineInfo[labelElement]?.exitPoint + override fun getSubroutineExitPoint(labelElement: KtElement): Label? = +// It's quite possible to have null here, e.g. for non-local returns (see KT-10823) + elementToSubroutineInfo[labelElement]?.exitPoint private val currentScope: BlockScope get() = blockScopes.peek() @@ -191,8 +191,8 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { val currentScope = currentScope assert(currentScope.block === block) { "Exit from not the current block scope.\n" + - "Current scope is for a block: " + currentScope.block.text + ".\n" + - "Exit from the scope for: " + block.text + "Current scope is for a block: " + currentScope.block.text + ".\n" + + "Exit from the scope for: " + block.text } blockScopes.pop() } @@ -252,11 +252,12 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { } override fun write( - assignment: KtElement, - lValue: KtElement, - rValue: PseudoValue, - target: AccessTarget, - receiverValues: Map) { + assignment: KtElement, + lValue: KtElement, + rValue: PseudoValue, + target: AccessTarget, + receiverValues: Map + ) { add(WriteValueInstruction(assignment, currentScope, target, receiverValues, lValue, rValue)) } @@ -342,22 +343,24 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { override fun createAnonymousObject(expression: KtObjectLiteralExpression) = read(expression) override fun createLambda(expression: KtFunction) = - read(if (expression is KtFunctionLiteral) expression.getParent() as KtLambdaExpression else expression) + read(if (expression is KtFunctionLiteral) expression.getParent() as KtLambdaExpression else expression) override fun loadStringTemplate( - expression: KtStringTemplateExpression, - inputValues: List + expression: KtStringTemplateExpression, + inputValues: List ): InstructionWithValue = - if (inputValues.isEmpty()) read(expression) - else magic(expression, expression, inputValues, MagicKind.STRING_TEMPLATE) + if (inputValues.isEmpty()) read(expression) + else magic(expression, expression, inputValues, MagicKind.STRING_TEMPLATE) override fun magic( - instructionElement: KtElement, - valueElement: KtElement?, - inputValues: List, - kind: MagicKind): MagicInstruction { + instructionElement: KtElement, + valueElement: KtElement?, + inputValues: List, + kind: MagicKind + ): MagicInstruction { val instruction = MagicInstruction( - instructionElement, valueElement, currentScope, inputValues, kind, valueFactory) + instructionElement, valueElement, currentScope, inputValues, kind, valueFactory + ) add(instruction) return instruction } @@ -369,32 +372,35 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { } override fun readVariable( - expression: KtExpression, - resolvedCall: ResolvedCall<*>, - receiverValues: Map + expression: KtExpression, + resolvedCall: ResolvedCall<*>, + receiverValues: Map ) = read(expression, resolvedCall, receiverValues) override fun call( - valueElement: KtElement, - resolvedCall: ResolvedCall<*>, - receiverValues: Map, - arguments: Map): CallInstruction { + valueElement: KtElement, + resolvedCall: ResolvedCall<*>, + receiverValues: Map, + arguments: Map + ): CallInstruction { val returnType = resolvedCall.resultingDescriptor.returnType val instruction = CallInstruction( - valueElement, - currentScope, - resolvedCall, - receiverValues, - arguments, - if (returnType != null && KotlinBuiltIns.isNothing(returnType)) null else valueFactory) + valueElement, + currentScope, + resolvedCall, + receiverValues, + arguments, + if (returnType != null && KotlinBuiltIns.isNothing(returnType)) null else valueFactory + ) add(instruction) return instruction } override fun predefinedOperation( - expression: KtExpression, - operation: ControlFlowBuilder.PredefinedOperation, - inputValues: List): OperationInstruction = magic(expression, expression, inputValues, getMagicKind(operation)) + expression: KtExpression, + operation: ControlFlowBuilder.PredefinedOperation, + inputValues: List + ): OperationInstruction = magic(expression, expression, inputValues, getMagicKind(operation)) private fun getMagicKind(operation: ControlFlowBuilder.PredefinedOperation) = when (operation) { ControlFlowBuilder.PredefinedOperation.AND -> MagicKind.AND @@ -403,17 +409,17 @@ class ControlFlowInstructionsGenerator : ControlFlowBuilderAdapter() { } override fun read( - element: KtElement, - target: AccessTarget, - receiverValues: Map + element: KtElement, + target: AccessTarget, + receiverValues: Map ) = ReadValueInstruction(element, currentScope, target, receiverValues, valueFactory).apply { add(this) } private fun read( - expression: KtExpression, - resolvedCall: ResolvedCall<*>? = null, - receiverValues: Map = emptyMap() + expression: KtExpression, + resolvedCall: ResolvedCall<*>? = null, + receiverValues: Map = emptyMap() ) = read(expression, if (resolvedCall != null) AccessTarget.Call(resolvedCall) else AccessTarget.BlackBox, receiverValues) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/TypePredicate.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/TypePredicate.kt index 0c6e66d100b..50e4bfc6336 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/TypePredicate.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/TypePredicate.kt @@ -23,28 +23,28 @@ import org.jetbrains.kotlin.types.KotlinType import org.jetbrains.kotlin.types.TypeUtils import org.jetbrains.kotlin.types.checker.KotlinTypeChecker -interface TypePredicate: (KotlinType) -> Boolean { +interface TypePredicate : (KotlinType) -> Boolean { override fun invoke(typeToCheck: KotlinType): Boolean } -data class SingleType(val targetType: KotlinType): TypePredicate { +data class SingleType(val targetType: KotlinType) : TypePredicate { override fun invoke(typeToCheck: KotlinType): Boolean = KotlinTypeChecker.DEFAULT.equalTypes(typeToCheck, targetType) override fun toString(): String = targetType.render() } -data class AllSubtypes(val upperBound: KotlinType): TypePredicate { +data class AllSubtypes(val upperBound: KotlinType) : TypePredicate { override fun invoke(typeToCheck: KotlinType): Boolean = KotlinTypeChecker.DEFAULT.isSubtypeOf(typeToCheck, upperBound) override fun toString(): String = "{<: ${upperBound.render()}}" } -data class ForAllTypes(val typeSets: List): TypePredicate { +data class ForAllTypes(val typeSets: List) : TypePredicate { override fun invoke(typeToCheck: KotlinType): Boolean = typeSets.all { it(typeToCheck) } override fun toString(): String = "AND{${typeSets.joinToString(", ")}}" } -data class ForSomeType(val typeSets: List): TypePredicate { +data class ForSomeType(val typeSets: List) : TypePredicate { override fun invoke(typeToCheck: KotlinType): Boolean = typeSets.any { it(typeToCheck) } override fun toString(): String = "OR{${typeSets.joinToString(", ")}}" @@ -58,18 +58,18 @@ object AllTypes : TypePredicate { // todo: simplify computed type predicate when possible fun and(predicates: Collection): TypePredicate = - when (predicates.size) { - 0 -> AllTypes - 1 -> predicates.first() - else -> ForAllTypes(predicates.toList()) - } + when (predicates.size) { + 0 -> AllTypes + 1 -> predicates.first() + else -> ForAllTypes(predicates.toList()) + } fun or(predicates: Collection): TypePredicate? = - when (predicates.size) { - 0 -> null - 1 -> predicates.first() - else -> ForSomeType(predicates.toList()) - } + when (predicates.size) { + 0 -> null + 1 -> predicates.first() + else -> ForSomeType(predicates.toList()) + } fun KotlinType.getSubtypesPredicate(): TypePredicate = when { KotlinBuiltIns.isAnyOrNullableAny(this) && isMarkedNullable -> AllTypes @@ -81,4 +81,4 @@ fun KotlinType.getSubtypesPredicate(): TypePredicate = when { private fun KotlinType.render(): String = DescriptorRenderer.SHORT_NAMES_IN_TYPES.renderType(this) fun TypePredicate.expectedTypeFor(keys: Iterable): Map = - keys.fold(SmartFMap.emptyMap()) { map, key -> map.plus(key, this) } + keys.fold(SmartFMap.emptyMap()) { map, key -> map.plus(key, this) } diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt index 916fdd0f69e..830d9192af2 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/AbstractJumpInstruction.kt @@ -24,9 +24,9 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl import org.jetbrains.kotlin.cfg.pseudocode.instructions.Instruction abstract class AbstractJumpInstruction( - element: KtElement, - val targetLabel: Label, - blockScope: BlockScope + element: KtElement, + val targetLabel: Label, + blockScope: BlockScope ) : KtElementInstructionImpl(element, blockScope), JumpInstruction { var resolvedTarget: Instruction? = null set(value) { diff --git a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt index b464761ba90..0cee61c9216 100644 --- a/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt +++ b/compiler/frontend/src/org/jetbrains/kotlin/cfg/pseudocode/instructions/jumps/NondeterministicJumpInstruction.kt @@ -27,17 +27,17 @@ import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionVisitorWithRe import org.jetbrains.kotlin.cfg.pseudocode.instructions.InstructionImpl class NondeterministicJumpInstruction( - element: KtElement, - targetLabels: List