Compare commits

...

20 Commits

Author SHA1 Message Date
Dmitry Savvinov
f8d8f198d0 tmp 2019-02-27 11:17:26 +03:00
Dmitry Savvinov
6b28469b35 Introduce fundamental abstraction of Platform
- Re-use MultiTargetPlatform: rename it to just Platform to prevent
confusion, move to 'core'-module
- Add Platform to ModuleDescriptor, remove corresponding capability,
providing a more straightforward way to get platform of a module
2019-02-26 12:00:52 +03:00
Dmitry Savvinov
154b34a06d Mute some tests failing because of incorrect type refiniment 2019-02-15 15:59:10 +03:00
Dmitry Savvinov
296a294399 Add test on subtyping across platform-common modules 2019-02-15 15:48:38 +03:00
Dmitry Savvinov
81ced4fd6e Wire ModuleDescriptor into various contexts and components 2019-02-15 15:48:15 +03:00
Dmitry Savvinov
79ac480095 Collect all moduleInfos from IDEA model (instead of per-platform)
Then, use all modules in resolvers, rather than only specific for some
platform.

Along with removal of per-platform GlobalFacade, this allows analyzing
sources in MPP platform together.

Note that it brings issues with scopes back.
2019-02-14 17:42:07 +03:00
Dmitry Savvinov
8bf6a36f85 Include this-module along with its parents in expect-actual matching 2019-02-14 17:42:07 +03:00
Dmitry Savvinov
f195a04ab4 Remove unwrapModuleInfo, replace usages with 'as? ModuleSourceInfo' 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
3710219388 Remove PlatformModuleInfo from IDELanguageSettingsProvider 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
6c79c3d7b7 Remove PlatformModuleInfo from multiplatformUtil.kt 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
009b931821 Minor: add comment to ModuleInfo.expectedBy 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
c74d6352e3 Remove getPlatformModuleInfo. Usages are pretty obscure and need further investigation 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
cdeb4a94db Remove CombinedModuleInfo-related hacks from moduleInfosFromIdeaModel. Note that this is a point where we need some new infrastructure 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
8415f9415c Remove IdeaModuleInfo.projectSourcesInfo, because it's an identity without PlatformModuleInfo. Fix usages in oracles, declaration provider factory 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
0b50c92ac8 Remove PlatformModuleInfo, because CombinedModuleInfo was removed 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
69f59011c6 Remove CombinedModuleInfo, fix usages in ProjectResolutionFacadeImpl 2019-02-14 17:42:06 +03:00
Dmitry Savvinov
76564e42c0 Rename *AnalyzerFacade to *ResolverForModuleFactory to prevent confusion with other similar names 2019-02-14 17:42:05 +03:00
Denis Zharkov
d89e23e707 ~ 2019-02-14 17:38:23 +03:00
Denis Zharkov
83149eeee6 ~ 2019-02-14 17:38:23 +03:00
Denis Zharkov
9f2642fa5c ~ KotlinType::refine 2019-02-14 17:38:22 +03:00
129 changed files with 1194 additions and 532 deletions

View File

@@ -16,7 +16,7 @@
package org.jetbrains.kotlin.cli.metadata
import org.jetbrains.kotlin.analyzer.common.CommonAnalyzerFacade
import org.jetbrains.kotlin.analyzer.common.CommonResolverForModuleFactory
import org.jetbrains.kotlin.cli.common.CLIConfigurationKeys
import org.jetbrains.kotlin.cli.common.messages.AnalyzerWithCompilerReport
import org.jetbrains.kotlin.cli.common.messages.CompilerMessageSeverity
@@ -68,7 +68,7 @@ open class MetadataSerializer(
val analyzer = AnalyzerWithCompilerReport(messageCollector, configuration.languageVersionSettings)
analyzer.analyzeAndReport(files) {
CommonAnalyzerFacade.analyzeFiles(files, moduleName, dependOnOldBuiltIns, configuration.languageVersionSettings) { content ->
CommonResolverForModuleFactory.analyzeFiles(files, moduleName, dependOnOldBuiltIns, configuration.languageVersionSettings) { content ->
environment.createPackagePartProvider(content.moduleContentScope)
}
}

View File

@@ -52,7 +52,8 @@ class MethodBinding(val method: Method, private val argumentDescriptors: List<Va
fun computeArguments(argumentDescriptors: List<ValueDescriptor>): List<Any> = argumentDescriptors.map { it.getValue() }
fun Class<*>.bindToConstructor(context: ValueResolveContext): ConstructorBinding {
val constructorInfo = getInfo().constructorInfo ?: error("No constructor for $this: ${getInfo()}")
val constructorInfo = getInfo().constructorInfo
?: error("No constructor for $this: ${getInfo()}")
val candidate = constructorInfo.constructor
return ConstructorBinding(candidate, candidate.bindArguments(constructorInfo.parameters, context))
}

View File

@@ -60,7 +60,7 @@ abstract class TargetPlatform(val platformName: String) {
open val excludedImports: List<FqName> get() = emptyList()
abstract val multiTargetPlatform: MultiTargetPlatform
abstract val platform: Platform
// This function is used in "cat.helm.clean:0.1.1-SNAPSHOT": https://plugins.jetbrains.com/plugin/index?xmlId=cat.helm.clean
@Suppress("DeprecatedCallableAddReplaceWith", "unused")
@@ -80,4 +80,4 @@ interface PlatformConfigurator {
val platformSpecificContainer: StorageComponentContainer
fun configureModuleComponents(container: StorageComponentContainer)
fun configureModuleDependentCheckers(container: StorageComponentContainer)
}
}

View File

@@ -44,7 +44,7 @@ class JvmPlatformParameters(
) : PlatformAnalysisParameters
object JvmAnalyzerFacade : ResolverForModuleFactory() {
object JvmResolverForModuleFactory : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,

View File

@@ -41,5 +41,5 @@ object JvmPlatform : TargetPlatform("JVM") {
override val platformConfigurator: PlatformConfigurator = JvmPlatformConfigurator
override val multiTargetPlatform = MultiTargetPlatform.Specific(platformName)
override val platform = Platform.Specific(platformName)
}

View File

@@ -39,7 +39,7 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.CompilerEnvironment
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.resolve.TargetEnvironment
import org.jetbrains.kotlin.resolve.TargetPlatform
import org.jetbrains.kotlin.storage.StorageManager
@@ -91,9 +91,9 @@ class EmptyResolverForProject<M : ModuleInfo> : ResolverForProject<M>() {
class ResolverForProjectImpl<M : ModuleInfo>(
private val debugName: String,
private val projectContext: ProjectContext,
modules: Collection<M>,
private val modulesFromThisResolver: Collection<M>,
private val modulesContent: (M) -> ModuleContent<M>,
private val modulePlatforms: (M) -> MultiTargetPlatform?,
private val modulePlatforms: (M) -> Platform?,
private val moduleLanguageSettingsProvider: LanguageSettingsProvider,
private val resolverForModuleFactoryByPlatform: (TargetPlatform?) -> ResolverForModuleFactory,
private val platformParameters: (TargetPlatform) -> PlatformAnalysisParameters,
@@ -123,12 +123,13 @@ class ResolverForProjectImpl<M : ModuleInfo>(
// Protected by ("projectContext.storageManager.lock")
private val moduleInfoByDescriptor = mutableMapOf<ModuleDescriptorImpl, M>()
private val moduleInfoToResolvableInfo: Map<M, M> =
modules.flatMap { module -> module.flatten().map { modulePart -> modulePart to module } }.toMap() as Map<M, M>
/** Replace with identity (any module info is resolvable moduleInfo without CombinedModuleInfo) */
// private val moduleInfoToResolvableInfo: Map<M, M> =
// modules.flatMap { module -> listOf(module to module) }.toMap() as Map<M, M>
init {
assert(moduleInfoToResolvableInfo.values.toSet() == modules.toSet())
}
// init {
// assert(moduleInfoToResolvableInfo.values.toSet() == modules.toSet())
// }
override fun tryGetResolverForModule(moduleInfo: M): ResolverForModule? {
if (!isCorrectModuleInfo(moduleInfo)) {
@@ -160,7 +161,9 @@ class ResolverForProjectImpl<M : ModuleInfo>(
private val resolverByModuleDescriptor = mutableMapOf<ModuleDescriptor, ResolverForModule>()
override val allModules: Collection<M> by lazy {
this.moduleInfoToResolvableInfo.keys + delegateResolver.allModules
/** moduleInfoToResolvableInfo.keys were exactly 'modules' anyway */
// this.moduleInfoToResolvableInfo.keys + delegateResolver.allModules
modulesFromThisResolver + delegateResolver.allModules
}
override val name: String
@@ -224,9 +227,8 @@ class ResolverForProjectImpl<M : ModuleInfo>(
}
private fun doGetDescriptorForModule(module: M): ModuleDescriptorImpl {
val moduleFromThisResolver = moduleInfoToResolvableInfo[module]
val moduleFromThisResolver = module.takeIf { it in allModules }
?: return delegateResolver.descriptorForModule(module) as ModuleDescriptorImpl
return projectContext.storageManager.compute {
var moduleData = descriptorByModule.getOrPut(moduleFromThisResolver) {
createModuleDescriptor(moduleFromThisResolver)
@@ -278,14 +280,16 @@ interface PlatformAnalysisParameters {
object Empty : PlatformAnalysisParameters
}
interface CombinedModuleInfo : ModuleInfo {
val containedModules: List<ModuleInfo>
}
/** Just delete it! */
//interface CombinedModuleInfo : ModuleInfo {
// val containedModules: List<ModuleInfo>
//}
fun ModuleInfo.flatten(): List<ModuleInfo> = when (this) {
is CombinedModuleInfo -> listOf(this) + containedModules
else -> listOf(this)
}
/** Replace with identity (no need to flatten anything when combined module info doesn't exist*/
//fun ModuleInfo.flatten(): List<ModuleInfo> = when (this) {
// is CombinedModuleInfo -> listOf(this) + containedModules
// else -> listOf(this)
//}
interface TrackableModuleInfo : ModuleInfo {
fun createModificationTracker(): ModificationTracker

View File

@@ -15,13 +15,14 @@ import org.jetbrains.kotlin.resolve.calls.results.TypeSpecificityComparator
import org.jetbrains.kotlin.resolve.lazy.DelegationFilter
import org.jetbrains.kotlin.resolve.scopes.SyntheticScopes
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.DynamicTypesAllowed
import org.jetbrains.kotlin.types.DynamicTypesSettings
object CommonPlatform : TargetPlatform("Default") {
override fun computePlatformSpecificDefaultImports(storageManager: StorageManager, result: MutableList<ImportPath>) {}
override val multiTargetPlatform: MultiTargetPlatform
get() = MultiTargetPlatform.Common
override val platform: Platform
get() = Platform.Common
override val platformConfigurator: PlatformConfigurator = CommonPlatformConfigurator
@@ -41,3 +42,56 @@ private object CommonPlatformConfigurator : PlatformConfiguratorBase(
}
}
open class CompositeTargetPlatform(val platforms: List<TargetPlatform>) : TargetPlatform("Default") {
override val platformConfigurator: PlatformConfigurator =
CompositePlatformConigurator(platforms.map { it.platformConfigurator as PlatformConfiguratorBase })
override fun computePlatformSpecificDefaultImports(storageManager: StorageManager, result: MutableList<ImportPath>) {
// TODO
return
}
override val platform: Platform
// TODO
get() = Platform.Common
override fun equals(other: Any?): Boolean = this.javaClass == other?.javaClass
override fun hashCode(): Int = this.javaClass.hashCode()
}
class CompositePlatformConigurator(private val configurators: List<PlatformConfiguratorBase>) : PlatformConfiguratorBase(
dynamicTypesSettings = configurators.map { it.dynamicTypesSettings }.merge(),
additionalDeclarationCheckers = configurators.flatMap { it.additionalDeclarationCheckers },
additionalCallCheckers = configurators.flatMap { it.additionalCallCheckers },
additionalTypeCheckers = configurators.flatMap { it.additionalTypeCheckers },
additionalClassifierUsageCheckers = configurators.flatMap { it.additionalClassifierUsageCheckers },
additionalAnnotationCheckers = configurators.flatMap { it.additionalAnnotationCheckers },
identifierChecker = configurators.map { it.identifierChecker }.merge(),
overloadFilter = configurators.map { it.overloadFilter }.merge(),
platformToKotlinClassMap = configurators.map { it.platformToKotlinClassMap }.merge(),
delegationFilter = configurators.map { it.delegationFilter }.merge(),
overridesBackwardCompatibilityHelper = configurators.map { it.overridesBackwardCompatibilityHelper }.merge(),
declarationReturnTypeSanitizer = configurators.map { it.declarationReturnTypeSanitizer }.merge()
) {
override fun configureModuleComponents(container: StorageComponentContainer) {
configurators.forEach { it.configureModuleComponents(container) }
}
override fun configureModuleDependentCheckers(container: StorageComponentContainer) {
configurators.forEach { it.configureModuleDependentCheckers(container) }
}
}
// TODO: hacks below
private fun List<DynamicTypesSettings>.merge(): DynamicTypesSettings =
if (any { it.dynamicTypesAllowed }) DynamicTypesAllowed() else DynamicTypesSettings()
private fun List<OverloadFilter>.merge(): OverloadFilter = first()
private fun List<IdentifierChecker>.merge(): IdentifierChecker = first()
private fun List<PlatformToKotlinClassMap>.merge(): PlatformToKotlinClassMap = first()
private fun List<DelegationFilter>.merge(): DelegationFilter = first()
private fun List<OverridesBackwardCompatibilityHelper>.merge(): OverridesBackwardCompatibilityHelper = first()
private fun List<DeclarationReturnTypeSanitizer>.merge(): DeclarationReturnTypeSanitizer = first()

View File

@@ -54,7 +54,7 @@ class CommonAnalysisParameters(
* A facade that is used to analyze common (platform-independent) modules in multi-platform projects.
* See [CommonPlatform]
*/
object CommonAnalyzerFacade : ResolverForModuleFactory() {
object CommonResolverForModuleFactory : ResolverForModuleFactory() {
private class SourceModuleInfo(
override val name: Name,
override val capabilities: Map<ModuleDescriptor.Capability<*>, Any?>,
@@ -68,7 +68,7 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
fun analyzeFiles(
files: Collection<KtFile>, moduleName: Name, dependOnBuiltIns: Boolean, languageVersionSettings: LanguageVersionSettings,
capabilities: Map<ModuleDescriptor.Capability<*>, Any?> = mapOf(MultiTargetPlatform.CAPABILITY to MultiTargetPlatform.Common),
capabilities: Map<ModuleDescriptor.Capability<*>, Any?> = emptyMap(),
metadataPartProviderFactory: (ModuleContent<ModuleInfo>) -> MetadataPartProvider
): AnalysisResult {
val moduleInfo = SourceModuleInfo(moduleName, capabilities, dependOnBuiltIns)
@@ -86,7 +86,7 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
ProjectContext(project),
listOf(moduleInfo),
modulesContent = { ModuleContent(it, files, GlobalSearchScope.allScope(project)) },
modulePlatforms = { MultiTargetPlatform.Common },
modulePlatforms = { Platform.Common },
moduleLanguageSettingsProvider = object : LanguageSettingsProvider {
override fun getLanguageVersionSettings(
moduleInfo: ModuleInfo,
@@ -99,7 +99,7 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
project: Project
) = TargetPlatformVersion.NoVersion
},
resolverForModuleFactoryByPlatform = { CommonAnalyzerFacade },
resolverForModuleFactoryByPlatform = { CommonResolverForModuleFactory },
platformParameters = { _ -> CommonAnalysisParameters(metadataPartProviderFactory) }
)
@@ -133,7 +133,7 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
val trace = CodeAnalyzerInitializer.getInstance(project).createTrace()
val container = createContainerToResolveCommonCode(
moduleContext, trace, declarationProviderFactory, moduleContentScope, targetEnvironment, metadataPartProvider,
languageVersionSettings
languageVersionSettings, moduleInfo.platform!!, targetPlatformVersion
)
val packageFragmentProviders = listOf(
@@ -151,9 +151,11 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
moduleContentScope: GlobalSearchScope,
targetEnvironment: TargetEnvironment,
metadataPartProvider: MetadataPartProvider,
languageVersionSettings: LanguageVersionSettings
): StorageComponentContainer = createContainer("ResolveCommonCode", targetPlatform) {
configureModule(moduleContext, targetPlatform, TargetPlatformVersion.NoVersion, bindingTrace)
languageVersionSettings: LanguageVersionSettings,
platform: TargetPlatform,
targetPlatformVersion: TargetPlatformVersion
): StorageComponentContainer = createContainer("ResolveCommonCode", platform) {
configureModule(moduleContext, platform, targetPlatformVersion, bindingTrace)
useInstance(moduleContentScope)
useInstance(LookupTracker.DO_NOTHING)
@@ -172,9 +174,11 @@ object CommonAnalyzerFacade : ResolverForModuleFactory() {
?: error("No MetadataFinderFactory in project")
useInstance(metadataFinderFactory.create(moduleContentScope))
targetEnvironment.configure(this)
}
override val targetPlatform: TargetPlatform
get() = CommonPlatform
}
}

View File

@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.psi.psiUtil.endOffset
import org.jetbrains.kotlin.psi.psiUtil.startOffset
import org.jetbrains.kotlin.resolve.AnalyzingUtils
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
@@ -48,7 +48,7 @@ object CheckerTestUtil {
fun getDiagnosticsIncludingSyntaxErrors(
bindingContext: BindingContext,
implementingModulesBindings: List<Pair<MultiTargetPlatform, BindingContext>>,
implementingModulesBindings: List<Pair<Platform, BindingContext>>,
root: PsiElement,
markDynamicCalls: Boolean,
dynamicCallDescriptors: MutableList<DeclarationDescriptor>,
@@ -73,7 +73,7 @@ object CheckerTestUtil {
val sortedBindings = implementingModulesBindings.sortedBy { it.first }
for ((platform, second) in sortedBindings) {
assert(platform is MultiTargetPlatform.Specific) { "Implementing module must have a specific platform: $platform" }
assert(platform is Platform.Specific) { "Implementing module must have a specific platform: $platform" }
result.addAll(
getDiagnosticsIncludingSyntaxErrors(
@@ -81,7 +81,7 @@ object CheckerTestUtil {
root,
markDynamicCalls,
dynamicCallDescriptors,
(platform as MultiTargetPlatform.Specific).platform,
(platform as Platform.Specific).platform,
withNewInference,
languageVersionSettings,
dataFlowValueFactory,

View File

@@ -22,7 +22,7 @@ import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.PackageFragmentProvider
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.storage.ExceptionTracker
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.storage.StorageManager
@@ -99,8 +99,8 @@ fun ContextForNewModule(
projectContext: ProjectContext,
moduleName: Name,
builtIns: KotlinBuiltIns,
multiTargetPlatform: MultiTargetPlatform?
platform: Platform?
): MutableModuleContext {
val module = ModuleDescriptorImpl(moduleName, projectContext.storageManager, builtIns, multiTargetPlatform)
val module = ModuleDescriptorImpl(moduleName, projectContext.storageManager, builtIns, platform)
return MutableModuleContextImpl(module, projectContext)
}

View File

@@ -24,9 +24,7 @@ import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.cfg.WhenMissingCase
import org.jetbrains.kotlin.cfg.hasUnknown
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.impl.ModuleDescriptorImpl
import org.jetbrains.kotlin.descriptors.impl.TypeAliasConstructorDescriptor
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.newTable
import org.jetbrains.kotlin.diagnostics.rendering.TabledDescriptorRenderer.newText
@@ -36,7 +34,6 @@ import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRenderer.Companion.DEBUG_TEXT
import org.jetbrains.kotlin.renderer.PropertyAccessorRenderingPolicy
import org.jetbrains.kotlin.resolve.*
import org.jetbrains.kotlin.resolve.calls.callUtil.getType
import org.jetbrains.kotlin.resolve.calls.inference.*
import org.jetbrains.kotlin.resolve.calls.inference.TypeBounds.Bound
import org.jetbrains.kotlin.resolve.calls.inference.TypeBounds.BoundKind.LOWER_BOUND
@@ -45,11 +42,8 @@ import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.Constrain
import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.ConstraintPositionKind.*
import org.jetbrains.kotlin.resolve.calls.inference.constraintPosition.getValidityConstraintForConstituentType
import org.jetbrains.kotlin.resolve.calls.model.ResolvedCall
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowInfo
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactory
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
import org.jetbrains.kotlin.types.expressions.typeInfoFactory.noTypeInfo
import org.jetbrains.kotlin.utils.addToStdlib.firstIsInstanceOrNull
import java.io.PrintWriter
import java.io.StringWriter
@@ -85,10 +79,10 @@ object Renderers {
@JvmField
val PLATFORM = Renderer<ModuleDescriptor> {
val platform = it.getMultiTargetPlatform()
val platform = it.platform
" ${it.getCapability(ModuleInfo.Capability)?.displayedName ?: ""}" + when (platform) {
MultiTargetPlatform.Common -> ""
is MultiTargetPlatform.Specific -> " for " + platform.platform
Platform.Common -> ""
is Platform.Specific -> " for " + platform.platform
null -> ""
}
}

View File

@@ -87,7 +87,7 @@ class SyntheticClassOrObjectDescriptor(
override fun getConstructors() = listOf(_unsubstitutedPrimaryConstructor()) + secondaryConstructors
override fun getDeclaredTypeParameters() = typeParameters
override fun getStaticScope() = MemberScope.Empty
override fun getUnsubstitutedMemberScope() = unsubstitutedMemberScope
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor) = unsubstitutedMemberScope
override fun getSealedSubclasses() = emptyList<ClassDescriptor>()
init {

View File

@@ -62,7 +62,8 @@ class DelegatedPropertyResolver(
private val psiCallResolver: PSICallResolver,
private val postponedArgumentsAnalyzer: PostponedArgumentsAnalyzer,
private val kotlinConstraintSystemCompleter: KotlinConstraintSystemCompleter,
private val callComponents: KotlinCallComponents
private val callComponents: KotlinCallComponents,
private val moduleDescriptor: ModuleDescriptor
) {
fun resolvePropertyDelegate(
@@ -327,7 +328,7 @@ class DelegatedPropertyResolver(
val context =
knownContext ?: ExpressionTypingContext.newContext(
trace, delegateFunctionsScope, dataFlowInfo, expectedType, languageVersionSettings, dataFlowValueFactory
trace, delegateFunctionsScope, dataFlowInfo, expectedType, languageVersionSettings, dataFlowValueFactory, moduleDescriptor
)
val hasThis = propertyDescriptor.extensionReceiverParameter != null || propertyDescriptor.dispatchReceiverParameter != null
@@ -376,7 +377,7 @@ class DelegatedPropertyResolver(
val delegateFunctionsScope = ScopeUtils.makeScopeForDelegateConventionFunctions(scopeForDelegate, propertyDescriptor)
return ExpressionTypingContext.newContext(
trace, delegateFunctionsScope, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE,
languageVersionSettings, dataFlowValueFactory, inferenceExtension
languageVersionSettings, dataFlowValueFactory, inferenceExtension, moduleDescriptor
)
}
@@ -389,7 +390,7 @@ class DelegatedPropertyResolver(
return ExpressionTypingContext.newContext(
trace, scopeForDelegate, dataFlowInfo,
NO_EXPECTED_TYPE, ContextDependency.DEPENDENT, StatementFilter.NONE,
languageVersionSettings, dataFlowValueFactory, inferenceExtension
languageVersionSettings, dataFlowValueFactory, inferenceExtension, moduleDescriptor
)
}
@@ -401,7 +402,15 @@ class DelegatedPropertyResolver(
initializerScope: LexicalScope,
dataFlowInfo: DataFlowInfo
): OverloadResolutionResults<FunctionDescriptor> {
val context = ExpressionTypingContext.newContext(trace, initializerScope, dataFlowInfo, NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory)
val context = ExpressionTypingContext.newContext(
trace,
initializerScope,
dataFlowInfo,
NO_EXPECTED_TYPE,
languageVersionSettings,
dataFlowValueFactory,
moduleDescriptor
)
return getProvideDelegateMethod(propertyDescriptor, delegateExpression, delegateExpressionType, context)
}

View File

@@ -89,6 +89,7 @@ public class DescriptorResolver {
private final DeclarationReturnTypeSanitizer declarationReturnTypeSanitizer;
private final DataFlowValueFactory dataFlowValueFactory;
private final Iterable<DeclarationSignatureAnonymousTypeTransformer> anonymousTypeTransformers;
private final ModuleDescriptor moduleDescriptor;
public DescriptorResolver(
@NotNull AnnotationResolver annotationResolver,
@@ -108,7 +109,8 @@ public class DescriptorResolver {
@NotNull TypeApproximator approximator,
@NotNull DeclarationReturnTypeSanitizer declarationReturnTypeSanitizer,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull Iterable<DeclarationSignatureAnonymousTypeTransformer> anonymousTypeTransformers
@NotNull Iterable<DeclarationSignatureAnonymousTypeTransformer> anonymousTypeTransformers,
@NotNull ModuleDescriptor moduleDescriptor
) {
this.annotationResolver = annotationResolver;
this.builtIns = builtIns;
@@ -128,6 +130,7 @@ public class DescriptorResolver {
this.declarationReturnTypeSanitizer = declarationReturnTypeSanitizer;
this.dataFlowValueFactory = dataFlowValueFactory;
this.anonymousTypeTransformers = anonymousTypeTransformers;
this.moduleDescriptor = moduleDescriptor;
}
public List<KotlinType> resolveSupertypes(
@@ -332,7 +335,7 @@ public class DescriptorResolver {
destructuringDeclaration, new TransientReceiver(type), /* initializer = */ null,
ExpressionTypingContext.newContext(
trace, scopeForDestructuring, DataFlowInfoFactory.EMPTY, TypeUtils.NO_EXPECTED_TYPE,
languageVersionSettings, dataFlowValueFactory
languageVersionSettings, dataFlowValueFactory, moduleDescriptor
)
);
@@ -798,7 +801,7 @@ public class DescriptorResolver {
KtExpression initializer = destructuringDeclaration.getInitializer();
ExpressionTypingContext context = ExpressionTypingContext.newContext(
trace, scopeForDeclarationResolution, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory
trace, scopeForDeclarationResolution, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, dataFlowValueFactory, moduleDescriptor
);
ExpressionReceiver receiver = createReceiverForDestructuringDeclaration(destructuringDeclaration, context);

View File

@@ -290,7 +290,7 @@ class OverloadResolver(
if (member1 !is MemberDescriptor || member2 !is MemberDescriptor) return false
return member1.isActual && member2.isActual &&
member1.getMultiTargetPlatform() != member2.getMultiTargetPlatform()
member1.platform != member2.platform
}
private fun reportRedeclarations(redeclarations: Collection<DeclarationDescriptorNonRoot>) {

View File

@@ -56,18 +56,18 @@ private val DEFAULT_ANNOTATION_CHECKERS = listOf<AdditionalAnnotationChecker>()
abstract class PlatformConfiguratorBase(
private val dynamicTypesSettings: DynamicTypesSettings,
additionalDeclarationCheckers: List<DeclarationChecker>,
additionalCallCheckers: List<CallChecker>,
additionalTypeCheckers: List<AdditionalTypeChecker>,
additionalClassifierUsageCheckers: List<ClassifierUsageChecker>,
additionalAnnotationCheckers: List<AdditionalAnnotationChecker>,
private val identifierChecker: IdentifierChecker,
private val overloadFilter: OverloadFilter,
private val platformToKotlinClassMap: PlatformToKotlinClassMap,
private val delegationFilter: DelegationFilter,
private val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper,
private val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer
val dynamicTypesSettings: DynamicTypesSettings,
val additionalDeclarationCheckers: List<DeclarationChecker>,
val additionalCallCheckers: List<CallChecker>,
val additionalTypeCheckers: List<AdditionalTypeChecker>,
val additionalClassifierUsageCheckers: List<ClassifierUsageChecker>,
val additionalAnnotationCheckers: List<AdditionalAnnotationChecker>,
val identifierChecker: IdentifierChecker,
val overloadFilter: OverloadFilter,
val platformToKotlinClassMap: PlatformToKotlinClassMap,
val delegationFilter: DelegationFilter,
val overridesBackwardCompatibilityHelper: OverridesBackwardCompatibilityHelper,
val declarationReturnTypeSanitizer: DeclarationReturnTypeSanitizer
) : PlatformConfigurator {
private val declarationCheckers: List<DeclarationChecker> = DEFAULT_DECLARATION_CHECKERS + additionalDeclarationCheckers
private val callCheckers: List<CallChecker> = DEFAULT_CALL_CHECKERS + additionalCallCheckers

View File

@@ -70,6 +70,7 @@ public class CallResolver {
private final DataFlowValueFactory dataFlowValueFactory;
private final KotlinBuiltIns builtIns;
private final LanguageVersionSettings languageVersionSettings;
private ModuleDescriptor moduleDescriptor;
private static final PerformanceCounter callResolvePerfCounter = PerformanceCounter.Companion.create("Call resolve", ExpressionTypingVisitorDispatcher.typeInfoPerfCounter);
@@ -130,6 +131,11 @@ public class CallResolver {
this.syntheticScopes = syntheticScopes;
}
@Inject
public void setModuleDescriptor(@NotNull ModuleDescriptor moduleDescriptor) {
this.moduleDescriptor = moduleDescriptor;
}
@NotNull
public OverloadResolutionResults<VariableDescriptor> resolveSimpleProperty(@NotNull BasicCallResolutionContext context) {
KtExpression calleeExpression = context.call.getCalleeExpression();
@@ -297,7 +303,7 @@ public class CallResolver {
return resolveFunctionCall(
BasicCallResolutionContext.create(
trace, scope, call, expectedType, dataFlowInfo, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS,
isAnnotationContext, languageVersionSettings, dataFlowValueFactory, InferenceSession.Companion.getDefault()
isAnnotationContext, languageVersionSettings, dataFlowValueFactory, InferenceSession.Companion.getDefault(), moduleDescriptor
)
);
}
@@ -427,7 +433,8 @@ public class CallResolver {
false,
languageVersionSettings,
dataFlowValueFactory,
InferenceSession.Companion.getDefault());
InferenceSession.Companion.getDefault(),
moduleDescriptor);
if (call.getCalleeExpression() == null) return checkArgumentTypesAndFail(context);

View File

@@ -52,7 +52,8 @@ class CandidateResolver(
private val reflectionTypes: ReflectionTypes,
private val additionalTypeCheckers: Iterable<AdditionalTypeChecker>,
private val smartCastManager: SmartCastManager,
private val dataFlowValueFactory: DataFlowValueFactory
private val dataFlowValueFactory: DataFlowValueFactory,
private val moduleDescriptor: ModuleDescriptor
) {
fun <D : CallableDescriptor> performResolutionForCandidateCall(
context: CallCandidateResolutionContext<D>,

View File

@@ -9,6 +9,7 @@ import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.psi.Call;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingTrace;
@@ -39,11 +40,12 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
super(trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments, resolutionResultsCache,
dataFlowInfoForArguments, statementFilter, isAnnotationContext, isDebuggerContext, collectAllCandidates,
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession);
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
@NotNull
@@ -58,13 +60,14 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
boolean isAnnotationContext,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new BasicCallResolutionContext(trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments,
new ResolutionResultsCacheImpl(), null,
StatementFilter.NONE, isAnnotationContext, false, false,
CallPosition.Unknown.INSTANCE, DEFAULT_EXPRESSION_CONTEXT_PROVIDER, languageVersionSettings,
dataFlowValueFactory, inferenceSession);
dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
@NotNull
@@ -78,13 +81,14 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
@NotNull CheckArgumentTypesMode checkArguments,
boolean isAnnotationContext,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new BasicCallResolutionContext(trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments,
new ResolutionResultsCacheImpl(), null,
StatementFilter.NONE, isAnnotationContext, false, false,
CallPosition.Unknown.INSTANCE, DEFAULT_EXPRESSION_CONTEXT_PROVIDER, languageVersionSettings,
dataFlowValueFactory, InferenceSession.Companion.getDefault());
dataFlowValueFactory, InferenceSession.Companion.getDefault(), moduleDescriptor);
}
@NotNull
@@ -97,7 +101,7 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
context.resolutionResultsCache, dataFlowInfoForArguments,
context.statementFilter, context.isAnnotationContext, context.isDebuggerContext, context.collectAllCandidates,
context.callPosition, context.expressionContextProvider, context.languageVersionSettings, context.dataFlowValueFactory,
context.inferenceSession);
context.inferenceSession, context.moduleDescriptor);
}
@NotNull
@@ -121,12 +125,14 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new BasicCallResolutionContext(
trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments, resolutionResultsCache,
dataFlowInfoForArguments, statementFilter, isAnnotationContext, isDebuggerContext, collectAllCandidates,
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession);
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession,
moduleDescriptor);
}
@NotNull
@@ -134,6 +140,7 @@ public class BasicCallResolutionContext extends CallResolutionContext<BasicCallR
return new BasicCallResolutionContext(
trace, scope, newCall, expectedType, dataFlowInfo, contextDependency, checkArguments, resolutionResultsCache,
dataFlowInfoForArguments, statementFilter, isAnnotationContext, isDebuggerContext, collectAllCandidates,
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession);
callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory, inferenceSession,
moduleDescriptor);
}
}

View File

@@ -10,6 +10,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.CallableDescriptor;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.psi.Call;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingTrace;
@@ -52,12 +53,13 @@ public final class CallCandidateResolutionContext<D extends CallableDescriptor>
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
super(trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments, resolutionResultsCache,
dataFlowInfoForArguments, statementFilter, isAnnotationContext, isDebuggerContext,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
this.candidateCall = candidateCall;
this.tracing = tracing;
this.candidateResolveMode = candidateResolveMode;
@@ -75,7 +77,7 @@ public final class CallCandidateResolutionContext<D extends CallableDescriptor>
context.statementFilter,
candidateResolveMode, context.isAnnotationContext, context.isDebuggerContext, context.collectAllCandidates,
context.callPosition, context.expressionContextProvider, context.languageVersionSettings, context.dataFlowValueFactory,
context.inferenceSession);
context.inferenceSession, context.moduleDescriptor);
}
@NotNull
@@ -88,7 +90,7 @@ public final class CallCandidateResolutionContext<D extends CallableDescriptor>
context.dataFlowInfoForArguments, context.statementFilter,
CandidateResolveMode.FULLY, context.isAnnotationContext, context.isDebuggerContext, context.collectAllCandidates,
context.callPosition, context.expressionContextProvider, context.languageVersionSettings, context.dataFlowValueFactory,
context.inferenceSession);
context.inferenceSession, context.moduleDescriptor);
}
@Override
@@ -105,12 +107,13 @@ public final class CallCandidateResolutionContext<D extends CallableDescriptor>
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new CallCandidateResolutionContext<>(
candidateCall, tracing, trace, scope, call, expectedType, dataFlowInfo, contextDependency, checkArguments,
resolutionResultsCache, dataFlowInfoForArguments, statementFilter,
candidateResolveMode, isAnnotationContext, isDebuggerContext, collectAllCandidates, callPosition, expressionContextProvider,
languageVersionSettings, dataFlowValueFactory, inferenceSession);
languageVersionSettings, dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
}

View File

@@ -9,6 +9,7 @@ import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.psi.Call;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingTrace;
@@ -48,11 +49,12 @@ public abstract class CallResolutionContext<Context extends CallResolutionContex
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
super(trace, scope, expectedType, dataFlowInfo, contextDependency, resolutionResultsCache,
statementFilter, isAnnotationContext, isDebuggerContext, collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings,
dataFlowValueFactory, inferenceSession);
dataFlowValueFactory, inferenceSession, moduleDescriptor);
this.call = call;
this.checkArguments = checkArguments;
if (dataFlowInfoForArguments != null) {

View File

@@ -11,6 +11,7 @@ import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.resolve.StatementFilter;
@@ -61,6 +62,9 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
@NotNull
public final InferenceSession inferenceSession;
@NotNull
public final ModuleDescriptor moduleDescriptor;
/**
* Used for analyzing expression in the given context.
* Should be used for going through parents to find containing function, loop etc.
@@ -88,7 +92,8 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory factory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
this.trace = trace;
this.scope = scope;
@@ -105,6 +110,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
this.languageVersionSettings = languageVersionSettings;
this.dataFlowValueFactory = factory;
this.inferenceSession = inferenceSession;
this.moduleDescriptor = moduleDescriptor;
}
protected abstract Context create(
@@ -120,7 +126,8 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
);
@NotNull
@@ -134,7 +141,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (this.trace == trace) return self();
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -142,7 +149,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (newDataFlowInfo == dataFlowInfo) return self();
return create(trace, scope, newDataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -150,7 +157,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (newInferenceSession == inferenceSession) return self();
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
newInferenceSession);
newInferenceSession, moduleDescriptor);
}
@NotNull
@@ -159,7 +166,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (expectedType == newExpectedType) return self();
return create(trace, scope, dataFlowInfo, newExpectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -167,7 +174,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (newScope == scope) return self();
return create(trace, newScope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -175,7 +182,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (newContextDependency == contextDependency) return self();
return create(trace, scope, dataFlowInfo, expectedType, newContextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -183,7 +190,7 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
if (newResolutionResultsCache == resolutionResultsCache) return self();
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, newResolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -195,28 +202,28 @@ public abstract class ResolutionContext<Context extends ResolutionContext<Contex
public Context replaceCollectAllCandidates(boolean newCollectAllCandidates) {
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
newCollectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
public Context replaceStatementFilter(@NotNull StatementFilter statementFilter) {
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
public Context replaceCallPosition(@NotNull CallPosition callPosition) {
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
public Context replaceExpressionContextProvider(@NotNull Function1<KtExpression, KtExpression> expressionContextProvider) {
return create(trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache, statementFilter,
collectAllCandidates, callPosition, expressionContextProvider, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@Nullable

View File

@@ -12,6 +12,7 @@ import org.jetbrains.kotlin.coroutines.hasFunctionOrSuspendFunctionType
import org.jetbrains.kotlin.coroutines.hasSuspendFunctionType
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.psi.KtExpression
@@ -63,6 +64,8 @@ class TypeTemplate(
override fun render(renderer: DescriptorRenderer, options: DescriptorRendererOptions) =
"~${renderer.renderType(typeVariable.type)}"
override fun refine(moduleDescriptor: ModuleDescriptor) = this
}
class CoroutineInferenceData {

View File

@@ -122,7 +122,10 @@ class ExpectedActualDeclarationChecker(val argumentExtractors: List<ActualAnnota
// However, in compiler context platform & common modules are joined into one module,
// so there is yet no "common module" in this situation.
// So yet we are using own module in compiler context and common module in IDE context.
val commonOrOwnModules = descriptor.module.expectedByModules.ifEmpty { listOf(descriptor.module) }
//
// Also note that we have to include container-module (not only it's parents), because it is possible to declare
// 'expect' in platform module and actualize it right here.
val commonOrOwnModules = (descriptor.module.expectedByModules + listOf(descriptor.module)).ifEmpty { listOf(descriptor.module) }
val compatibility = commonOrOwnModules
.mapNotNull { ExpectedActualResolver.findExpectedForActual(descriptor, it) }
.ifEmpty { return }

View File

@@ -9,9 +9,8 @@ import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.getMultiTargetPlatform
import org.jetbrains.kotlin.resolve.multiplatform.isCommonSource
class OptionalExpectationUsageChecker : ClassifierUsageChecker {
@@ -23,8 +22,9 @@ class OptionalExpectationUsageChecker : ClassifierUsageChecker {
}
val ktFile = element.containingFile as KtFile
// TODO: platforms-api-unification
// The first part is for the compiler, and the second one is for IDE
if (ktFile.isCommonSource != true && targetDescriptor.module.getMultiTargetPlatform() != MultiTargetPlatform.Common) {
if (ktFile.isCommonSource != true && targetDescriptor.module.platform != Platform.Common) {
context.trace.report(Errors.OPTIONAL_DECLARATION_USAGE_IN_NON_COMMON_SOURCE.on(element))
}
}

View File

@@ -89,7 +89,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
private final NullableLazyValue<ClassDescriptorWithResolutionScopes> companionObjectDescriptor;
private final MemoizedFunctionToNotNull<KtObjectDeclaration, ClassDescriptor> extraCompanionObjectDescriptors;
private final LazyClassMemberScope unsubstitutedMemberScope;
private final NotNullLazyValue<ScopesHolderForClass<LazyClassMemberScope>> unsubstitutedMemberScope;
private final MemberScope staticScope;
private final NullableLazyValue<Void> forceResolveAllContents;
@@ -295,17 +295,21 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
// NOTE: Called from constructor!
@NotNull
protected LazyClassMemberScope createMemberScope(
protected NotNullLazyValue<ScopesHolderForClass<LazyClassMemberScope>> createMemberScope(
@NotNull LazyClassContext c,
@NotNull ClassMemberDeclarationProvider declarationProvider
) {
return new LazyClassMemberScope(c, declarationProvider, this, c.getTrace());
return ScopesHolderForClass.Companion.create(
this,
c.getStorageManager(),
moduleDescriptor -> new LazyClassMemberScope(c, declarationProvider, this, c.getTrace(), moduleDescriptor)
);
}
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope() {
return unsubstitutedMemberScope;
public MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor) {
return unsubstitutedMemberScope.invoke().getScope(moduleDescriptor);
}
@NotNull
@@ -354,7 +358,7 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
@SuppressWarnings("unchecked")
public Collection<CallableMemberDescriptor> getDeclaredCallableMembers() {
return (Collection) CollectionsKt.filter(
DescriptorUtils.getAllDescriptors(unsubstitutedMemberScope),
DescriptorUtils.getAllDescriptors(getUnsubstitutedMemberScope()),
descriptor -> descriptor instanceof CallableMemberDescriptor
&& ((CallableMemberDescriptor) descriptor).getKind() != CallableMemberDescriptor.Kind.FAKE_OVERRIDE
);
@@ -369,12 +373,12 @@ public class LazyClassDescriptor extends ClassDescriptorBase implements ClassDes
@NotNull
@Override
public Collection<ClassConstructorDescriptor> getConstructors() {
return unsubstitutedMemberScope.getConstructors();
return ((LazyClassMemberScope) getUnsubstitutedMemberScope()).getConstructors();
}
@Override
public ClassConstructorDescriptor getUnsubstitutedPrimaryConstructor() {
return unsubstitutedMemberScope.getPrimaryConstructor();
return ((LazyClassMemberScope) getUnsubstitutedMemberScope()).getPrimaryConstructor();
}
@NotNull

View File

@@ -47,7 +47,8 @@ open class LazyClassMemberScope(
c: LazyClassContext,
declarationProvider: ClassMemberDeclarationProvider,
thisClass: ClassDescriptorWithResolutionScopes,
trace: BindingTrace
trace: BindingTrace,
private val moduleDescriptor: ModuleDescriptor = c.moduleDescriptor
) : AbstractLazyMemberScope<ClassDescriptorWithResolutionScopes, ClassMemberDeclarationProvider>(c, declarationProvider, thisClass, trace) {
private val descriptorsFromDeclaredElements = storageManager.createLazyValue {
@@ -73,7 +74,7 @@ open class LazyClassMemberScope(
protected open fun computeExtraDescriptors(location: LookupLocation): Collection<DeclarationDescriptor> {
val result = ArrayList<DeclarationDescriptor>()
for (supertype in thisDescriptor.typeConstructor.supertypes) {
for (descriptor in supertype.memberScope.getContributedDescriptors()) {
for (descriptor in supertype.refine(moduleDescriptor).memberScope.getContributedDescriptors()) {
if (descriptor is FunctionDescriptor) {
result.addAll(getContributedFunctions(descriptor.name, location))
} else if (descriptor is PropertyDescriptor) {
@@ -96,7 +97,7 @@ open class LazyClassMemberScope(
by lazy(LazyThreadSafetyMode.PUBLICATION) {
mutableSetOf<Name>().apply {
addAll(declarationProvider.getDeclarationNames())
thisDescriptor.typeConstructor.supertypes.flatMapTo(this) {
thisDescriptor.typeConstructor.getSupertypes(moduleDescriptor).flatMapTo(this) {
it.memberScope.getVariableNames()
}
}
@@ -106,7 +107,7 @@ open class LazyClassMemberScope(
by lazy(LazyThreadSafetyMode.PUBLICATION) {
mutableSetOf<Name>().apply {
addAll(declarationProvider.getDeclarationNames())
thisDescriptor.typeConstructor.supertypes.flatMapTo(this) {
thisDescriptor.typeConstructor.getSupertypes(moduleDescriptor).flatMapTo(this) {
it.memberScope.getFunctionNames()
}
@@ -199,7 +200,7 @@ open class LazyClassMemberScope(
val location = NoLookupLocation.FOR_ALREADY_TRACKED
val fromSupertypes = arrayListOf<SimpleFunctionDescriptor>()
for (supertype in thisDescriptor.typeConstructor.supertypes) {
for (supertype in thisDescriptor.typeConstructor.getSupertypes(moduleDescriptor)) {
fromSupertypes.addAll(supertype.memberScope.getContributedFunctions(name, location))
}
result.addAll(generateDelegatingDescriptors(name, EXTRACT_FUNCTIONS, result))
@@ -341,7 +342,7 @@ open class LazyClassMemberScope(
// Members from supertypes
val fromSupertypes = ArrayList<PropertyDescriptor>()
for (supertype in thisDescriptor.typeConstructor.supertypes) {
for (supertype in thisDescriptor.typeConstructor.getSupertypes(moduleDescriptor)) {
fromSupertypes.addAll(supertype.memberScope.getContributedVariables(name, NoLookupLocation.FOR_ALREADY_TRACKED))
}
result.addAll(generateDelegatingDescriptors(name, EXTRACT_PROPERTIES, result))

View File

@@ -18,7 +18,6 @@ package org.jetbrains.kotlin.resolve.lazy.descriptors
import com.intellij.openapi.vfs.StandardFileSystems
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.local.CoreLocalFileSystem
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiManager
import org.jetbrains.kotlin.descriptors.*
@@ -49,6 +48,7 @@ import org.jetbrains.kotlin.resolve.source.toSourceElement
import org.jetbrains.kotlin.script.KotlinScriptDefinition
import org.jetbrains.kotlin.script.ScriptDependenciesProvider
import org.jetbrains.kotlin.script.ScriptPriorities
import org.jetbrains.kotlin.storage.NotNullLazyValue
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.typeUtil.isNothing
import org.jetbrains.kotlin.types.typeUtil.isUnit
@@ -127,14 +127,19 @@ class LazyScriptDescriptor(
override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R =
visitor.visitScriptDescriptor(this, data)
override fun createMemberScope(c: LazyClassContext, declarationProvider: ClassMemberDeclarationProvider): LazyScriptClassMemberScope =
LazyScriptClassMemberScope(
// Must be a ResolveSession for scripts
c as ResolveSession,
declarationProvider,
this,
c.trace
)
override fun createMemberScope(
c: LazyClassContext,
declarationProvider: ClassMemberDeclarationProvider
): NotNullLazyValue<ScopesHolderForClass<LazyClassMemberScope>> =
ScopesHolderForClass.create(this, c.storageManager) {
LazyScriptClassMemberScope(
// Must be a ResolveSession for scripts
c as ResolveSession,
declarationProvider,
this,
c.trace
)
}
override fun getUnsubstitutedPrimaryConstructor() = super.getUnsubstitutedPrimaryConstructor()!!

View File

@@ -40,7 +40,7 @@ class ScriptProvidedPropertiesDescriptor(script: LazyScriptDescriptor) :
)
}
override fun getUnsubstitutedMemberScope(): MemberScope = memberScope()
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor): MemberScope = memberScope()
val properties: () -> List<ScriptProvidedPropertyDescriptor> = script.resolveSession.storageManager.createLazyValue {
script.scriptDefinition().providedProperties.mapNotNull { (name, type) ->
@@ -75,4 +75,4 @@ class ScriptProvidedPropertiesDescriptor(script: LazyScriptDescriptor) :
p.println("Scope of script provided properties: $scriptId")
}
}
}
}

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.types;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.storage.NotNullLazyValue;
import org.jetbrains.kotlin.storage.StorageManager;
@@ -43,7 +44,7 @@ public class DeferredType extends WrappedType {
trace.record(DEFERRED_TYPE, new Box<>(deferredType));
return deferredType;
}
@NotNull
/*package private*/ static DeferredType createRecursionIntolerant(
@NotNull StorageManager storageManager,
@@ -59,10 +60,40 @@ public class DeferredType extends WrappedType {
private final NotNullLazyValue<KotlinType> lazyValue;
private DeferredType(@NotNull NotNullLazyValue<KotlinType> lazyValue) {
private DeferredType(
@NotNull NotNullLazyValue<KotlinType> lazyValue
) {
super();
this.lazyValue = lazyValue;
}
@NotNull
@Override
public KotlinType refine(@NotNull ModuleDescriptor moduleDescriptor) {
return new DeferredType(new NotNullLazyValue<KotlinType>() {
@NotNull
@Override
public String renderDebugInformation() {
return lazyValue.renderDebugInformation();
}
@Override
public boolean isComputed() {
return lazyValue.isComputed();
}
@Override
public boolean isComputing() {
return lazyValue.isComputing();
}
@Override
public KotlinType invoke() {
return lazyValue.invoke().refine(moduleDescriptor);
}
});
}
public boolean isComputing() {
return lazyValue.isComputing();
}

View File

@@ -23,7 +23,6 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.resolve.calls.inference.CallHandle;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystem;
import org.jetbrains.kotlin.resolve.calls.inference.ConstraintSystemBuilderImpl;
@@ -138,15 +137,7 @@ public class TypeIntersector {
return TypeUtils.makeNullableAsSpecified(resultingTypes.get(0), allNullable);
}
IntersectionTypeConstructor constructor = new IntersectionTypeConstructor(resultingTypes);
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
Annotations.Companion.getEMPTY(),
constructor,
Collections.emptyList(),
allNullable,
constructor.createScopeForKotlinType()
);
return new IntersectionTypeConstructor(resultingTypes).createType();
}
/**

View File

@@ -8,6 +8,8 @@ package org.jetbrains.kotlin.types.expressions;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.config.LanguageVersionSettings;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.modules.Module;
import org.jetbrains.kotlin.psi.KtExpression;
import org.jetbrains.kotlin.resolve.BindingTrace;
import org.jetbrains.kotlin.resolve.StatementFilter;
@@ -27,10 +29,11 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
@NotNull DataFlowInfo dataFlowInfo,
@NotNull KotlinType expectedType,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull ModuleDescriptor moduleDescriptor
) {
return newContext(trace, scope, dataFlowInfo, expectedType, ContextDependency.INDEPENDENT, StatementFilter.NONE,
languageVersionSettings, dataFlowValueFactory, InferenceSession.Companion.getDefault());
languageVersionSettings, dataFlowValueFactory, InferenceSession.Companion.getDefault(), moduleDescriptor);
}
@NotNull
@@ -41,25 +44,11 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
@NotNull KotlinType expectedType,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return newContext(trace, scope, dataFlowInfo, expectedType, ContextDependency.INDEPENDENT, StatementFilter.NONE,
languageVersionSettings, dataFlowValueFactory, inferenceSession);
}
@NotNull
public static ExpressionTypingContext newContext(
@NotNull BindingTrace trace,
@NotNull LexicalScope scope,
@NotNull DataFlowInfo dataFlowInfo,
@NotNull KotlinType expectedType,
@NotNull ContextDependency contextDependency,
@NotNull StatementFilter statementFilter,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory) {
return newContext(trace, scope, dataFlowInfo, expectedType, contextDependency,
new ResolutionResultsCacheImpl(), statementFilter, false, languageVersionSettings, dataFlowValueFactory,
InferenceSession.Companion.getDefault());
languageVersionSettings, dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
@NotNull
@@ -72,11 +61,28 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
@NotNull StatementFilter statementFilter,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull ModuleDescriptor moduleDescriptor) {
return newContext(trace, scope, dataFlowInfo, expectedType, contextDependency,
new ResolutionResultsCacheImpl(), statementFilter, false, languageVersionSettings, dataFlowValueFactory,
InferenceSession.Companion.getDefault(), moduleDescriptor);
}
@NotNull
public static ExpressionTypingContext newContext(
@NotNull BindingTrace trace,
@NotNull LexicalScope scope,
@NotNull DataFlowInfo dataFlowInfo,
@NotNull KotlinType expectedType,
@NotNull ContextDependency contextDependency,
@NotNull StatementFilter statementFilter,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return newContext(trace, scope, dataFlowInfo, expectedType, contextDependency,
new ResolutionResultsCacheImpl(), statementFilter, false, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
@NotNull
@@ -87,7 +93,7 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
context.statementFilter,
context.isAnnotationContext, context.isDebuggerContext, context.collectAllCandidates,
context.callPosition, context.expressionContextProvider, context.languageVersionSettings,
context.dataFlowValueFactory, context.inferenceSession);
context.dataFlowValueFactory, context.inferenceSession, context.moduleDescriptor);
}
@NotNull
@@ -99,7 +105,7 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
context.isAnnotationContext, isDebuggerContext, context.collectAllCandidates,
context.callPosition, context.expressionContextProvider,
context.languageVersionSettings,
context.dataFlowValueFactory, context.inferenceSession);
context.dataFlowValueFactory, context.inferenceSession, context.moduleDescriptor);
}
@NotNull
@@ -114,13 +120,14 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
boolean isAnnotationContext,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new ExpressionTypingContext(
trace, scope, dataFlowInfo, expectedType, contextDependency, resolutionResultsCache,
statementFilter, isAnnotationContext, false, false,
CallPosition.Unknown.INSTANCE, DEFAULT_EXPRESSION_CONTEXT_PROVIDER, languageVersionSettings, dataFlowValueFactory,
inferenceSession);
inferenceSession, moduleDescriptor);
}
private ExpressionTypingContext(
@@ -138,11 +145,12 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
super(trace, scope, expectedType, dataFlowInfo, contextDependency, resolutionResultsCache,
statementFilter, isAnnotationContext, isDebuggerContext, collectAllCandidates, callPosition, expressionContextProvider,
languageVersionSettings, dataFlowValueFactory, inferenceSession);
languageVersionSettings, dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
@Override
@@ -159,12 +167,13 @@ public class ExpressionTypingContext extends ResolutionContext<ExpressionTypingC
@NotNull Function1<KtExpression, KtExpression> expressionContextProvider,
@NotNull LanguageVersionSettings languageVersionSettings,
@NotNull DataFlowValueFactory dataFlowValueFactory,
@NotNull InferenceSession inferenceSession
@NotNull InferenceSession inferenceSession,
@NotNull ModuleDescriptor moduleDescriptor
) {
return new ExpressionTypingContext(trace, scope, dataFlowInfo,
expectedType, contextDependency, resolutionResultsCache,
statementFilter, isAnnotationContext, isDebuggerContext,
collectAllCandidates, callPosition, expressionContextProvider,
languageVersionSettings, dataFlowValueFactory, inferenceSession);
languageVersionSettings, dataFlowValueFactory, inferenceSession, moduleDescriptor);
}
}

View File

@@ -104,9 +104,10 @@ public class ExpressionTypingServices {
@NotNull KtExpression contextExpression,
@NotNull ContextDependency contextDependency
) {
ExpressionTypingContext context = ExpressionTypingContext.newContext(
ExpressionTypingContext context = ExpressionTypingContext.
newContext(
trace, scope, dataFlowInfo, expectedType, contextDependency, statementFilter, getLanguageVersionSettings(),
expressionTypingComponents.dataFlowValueFactory
expressionTypingComponents.dataFlowValueFactory, expressionTypingComponents.moduleDescriptor
);
if (contextExpression != expression) {
context = context.replaceExpressionContextProvider(arg -> arg == expression ? contextExpression : null);
@@ -149,7 +150,8 @@ public class ExpressionTypingServices {
checkFunctionReturnType(function, ExpressionTypingContext.newContext(
trace,
functionInnerScope, dataFlowInfo, expectedReturnType != null ? expectedReturnType : NO_EXPECTED_TYPE, getLanguageVersionSettings(),
expressionTypingComponents.dataFlowValueFactory
expressionTypingComponents.dataFlowValueFactory,
expressionTypingComponents.moduleDescriptor
));
}
@@ -218,7 +220,8 @@ public class ExpressionTypingServices {
ExpressionTypingContext context = ExpressionTypingContext.newContext(
trace, functionInnerScope, dataFlowInfo, NO_EXPECTED_TYPE, getLanguageVersionSettings(),
expressionTypingComponents.dataFlowValueFactory
expressionTypingComponents.dataFlowValueFactory,
expressionTypingComponents.moduleDescriptor
);
KotlinTypeInfo typeInfo = expressionTypingFacade.getTypeInfo(bodyExpression, context, function.hasBlockBody());

View File

@@ -181,6 +181,16 @@ public abstract class ExpressionTypingVisitorDispatcher extends KtVisitor<Kotlin
if (result.getType() instanceof DeferredType) {
result = result.replaceType(((DeferredType) result.getType()).getDelegate());
}
KotlinType refinedType =
result.getType() != null
? result.getType().refine(components.moduleDescriptor)
: null;
if (refinedType != result.getType()) {
result = result.replaceType(refinedType);
}
context.trace.record(BindingContext.EXPRESSION_TYPE_INFO, expression, result);
}
catch (ReenteringLazyValueComputationException e) {

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.types.expressions
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.ValueParameterDescriptor
import org.jetbrains.kotlin.diagnostics.Errors
import org.jetbrains.kotlin.psi.KtParameter
@@ -37,7 +38,8 @@ class ValueParameterResolver(
private val expressionTypingServices: ExpressionTypingServices,
private val constantExpressionEvaluator: ConstantExpressionEvaluator,
private val languageVersionSettings: LanguageVersionSettings,
private val dataFlowValueFactory: DataFlowValueFactory
private val dataFlowValueFactory: DataFlowValueFactory,
private val moduleDescriptor: ModuleDescriptor
) {
fun resolveValueParameters(
valueParameters: List<KtParameter>,
@@ -51,7 +53,7 @@ class ValueParameterResolver(
val contextForDefaultValue = ExpressionTypingContext.newContext(
trace, scopeForDefaultValue, dataFlowInfo, TypeUtils.NO_EXPECTED_TYPE,
languageVersionSettings, dataFlowValueFactory
languageVersionSettings, dataFlowValueFactory, moduleDescriptor
)
for ((descriptor, parameter) in valueParameterDescriptors.zip(valueParameters)) {

View File

@@ -46,7 +46,7 @@ open class KnownClassDescriptor(
this.declaredTypeParameters = declaredTypeParameters
this.supertypes = supertypes
this.typeConstructor = ClassTypeConstructorImpl(this, declaredTypeParameters, supertypes, LockBasedStorageManager.NO_LOCKS)
this.defaultType = TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope)
this.defaultType = TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope, { unsubstitutedMemberScope })
}
companion object {
@@ -112,9 +112,18 @@ open class KnownClassDescriptor(
override fun getMemberScope(typeArguments: MutableList<out TypeProjection>): MemberScope = MemberScope.Empty
override fun getMemberScope(typeSubstitution: TypeSubstitution): MemberScope = MemberScope.Empty
override fun getMemberScope(
typeArguments: MutableList<out TypeProjection>,
moduleDescriptor: ModuleDescriptor
): MemberScope = MemberScope.Empty
override fun getMemberScope(typeSubstitution: TypeSubstitution, moduleDescriptor: ModuleDescriptor): MemberScope = MemberScope.Empty
override fun getStaticScope(): MemberScope = MemberScope.Empty
override fun getUnsubstitutedInnerClassesScope(): MemberScope = MemberScope.Empty
override fun getUnsubstitutedMemberScope(): MemberScope = MemberScope.Empty
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor): MemberScope = MemberScope.Empty
override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = null

View File

@@ -20,7 +20,6 @@ import org.jetbrains.kotlin.resolve.scopes.TypeIntersectionScope
import org.jetbrains.kotlin.resolve.scopes.receivers.ExtensionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.storage.LockBasedStorageManager
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.*
@@ -463,7 +462,15 @@ open class WrappedClassDescriptor(
override fun getMemberScope(typeSubstitution: TypeSubstitution) = MemberScope.Empty
override fun getMemberScope(
typeArguments: MutableList<out TypeProjection>,
moduleDescriptor: ModuleDescriptor
): MemberScope = MemberScope.Empty
override fun getMemberScope(typeSubstitution: TypeSubstitution, moduleDescriptor: ModuleDescriptor): MemberScope = MemberScope.Empty
override fun getUnsubstitutedMemberScope() = MemberScope.Empty
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor) = MemberScope.Empty
override fun getUnsubstitutedInnerClassesScope() = MemberScope.Empty
@@ -477,7 +484,7 @@ open class WrappedClassDescriptor(
private val _defaultType: SimpleType by lazy {
TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope)
TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope) { unsubstitutedMemberScope }
}
override fun getDefaultType(): SimpleType = _defaultType
@@ -545,7 +552,15 @@ open class WrappedEnumEntryDescriptor(
override fun getMemberScope(typeSubstitution: TypeSubstitution) = MemberScope.Empty
override fun getMemberScope(
typeArguments: MutableList<out TypeProjection>,
moduleDescriptor: ModuleDescriptor
): MemberScope = MemberScope.Empty
override fun getMemberScope(typeSubstitution: TypeSubstitution, moduleDescriptor: ModuleDescriptor): MemberScope = MemberScope.Empty
override fun getUnsubstitutedMemberScope() = MemberScope.Empty
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor) = MemberScope.Empty
override fun getUnsubstitutedInnerClassesScope() = MemberScope.Empty
@@ -562,7 +577,7 @@ open class WrappedEnumEntryDescriptor(
private val _defaultType: SimpleType by lazy {
TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope)
TypeUtils.makeUnsubstitutedType(this, unsubstitutedMemberScope) { unsubstitutedMemberScope }
}
override fun getDefaultType(): SimpleType = _defaultType

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.resolve.calls.inference.model
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.calls.model.LambdaKotlinCallArgument
@@ -33,6 +34,7 @@ class TypeVariableTypeConstructor(private val builtIns: KotlinBuiltIns, val debu
NewTypeVariableConstructor {
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()
override fun getSupertypes(): Collection<KotlinType> = emptyList()
override fun getSupertypes(module: ModuleDescriptor): Collection<KotlinType> = getSupertypes()
override fun isFinal(): Boolean = false
override fun isDenotable(): Boolean = false
override fun getDeclarationDescriptor(): ClassifierDescriptor? = null

View File

@@ -21,6 +21,7 @@ import org.jetbrains.kotlin.builtins.ReflectionTypes
import org.jetbrains.kotlin.config.LanguageVersionSettings
import org.jetbrains.kotlin.descriptors.CallableDescriptor
import org.jetbrains.kotlin.descriptors.FunctionDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.resolve.calls.components.*
import org.jetbrains.kotlin.resolve.calls.inference.addSubsystemFromArgument
import org.jetbrains.kotlin.resolve.calls.inference.components.ConstraintInjector

View File

@@ -12,7 +12,7 @@ import com.intellij.psi.search.GlobalSearchScope
import junit.framework.TestCase
import org.jetbrains.kotlin.TestsCompilerError
import org.jetbrains.kotlin.analyzer.AnalysisResult
import org.jetbrains.kotlin.analyzer.common.CommonAnalyzerFacade
import org.jetbrains.kotlin.analyzer.common.CommonResolverForModuleFactory
import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns
import org.jetbrains.kotlin.cli.jvm.compiler.NoScopeRecordCliBindingTrace
import org.jetbrains.kotlin.cli.jvm.compiler.TopDownAnalyzerFacadeForJVM
@@ -166,13 +166,13 @@ abstract class AbstractDiagnosticsTest : BaseDiagnosticsTest() {
val actualText = StringBuilder()
for (testFile in files) {
val module = testFile.module
val isCommonModule = modules[module]!!.getMultiTargetPlatform() == MultiTargetPlatform.Common
val isCommonModule = modules[module]!!.platform == Platform.Common
val implementingModules =
if (!isCommonModule) emptyList()
else modules.entries.filter { (testModule) -> module in testModule?.getDependencies().orEmpty() }
val implementingModulesBindings = implementingModules.mapNotNull { (testModule, moduleDescriptor) ->
val platform = moduleDescriptor.getCapability(MultiTargetPlatform.CAPABILITY)
if (platform is MultiTargetPlatform.Specific) platform to moduleBindings[testModule]!!
val platform = moduleDescriptor.platform
if (platform is Platform.Specific) platform to moduleBindings[testModule]!!
else null
}
val moduleDescriptor = modules[module]!!
@@ -354,12 +354,11 @@ abstract class AbstractDiagnosticsTest : BaseDiagnosticsTest() {
val moduleDescriptor = moduleContext.module as ModuleDescriptorImpl
val platform = moduleDescriptor.getMultiTargetPlatform()
if (platform == MultiTargetPlatform.Common) {
return CommonAnalyzerFacade.analyzeFiles(
val platform = moduleDescriptor.platform
if (platform == Platform.Common) {
return CommonResolverForModuleFactory.analyzeFiles(
files, moduleDescriptor.name, true, languageVersionSettings,
mapOf(
MultiTargetPlatform.CAPABILITY to MultiTargetPlatform.Common,
MODULE_FILES to files
)
) { _ ->
@@ -414,7 +413,7 @@ abstract class AbstractDiagnosticsTest : BaseDiagnosticsTest() {
// E.g. "<!JVM:ACTUAL_WITHOUT_EXPECT!>...<!>
val result = ArrayList<KtFile>(0)
for (dependency in dependencies) {
if (dependency.getCapability(MultiTargetPlatform.CAPABILITY) == MultiTargetPlatform.Common) {
if (dependency.platform == Platform.Common) {
val files = dependency.getCapability(MODULE_FILES)
?: error("MODULE_FILES should have been set for the common module: $dependency")
result.addAll(files)
@@ -585,7 +584,7 @@ abstract class AbstractDiagnosticsTest : BaseDiagnosticsTest() {
val nameSuffix = moduleName.substringAfterLast("-", "")
val platform =
if (nameSuffix.isEmpty()) null
else if (nameSuffix == "common") MultiTargetPlatform.Common else MultiTargetPlatform.Specific(nameSuffix.toUpperCase())
else if (nameSuffix == "common") Platform.Common else Platform.Specific(nameSuffix.toUpperCase())
return ModuleDescriptorImpl(Name.special("<$moduleName>"), storageManager, JvmBuiltIns(storageManager), platform)
}

View File

@@ -45,7 +45,7 @@ import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtDeclaration
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.resolve.calls.smartcasts.DataFlowValueFactoryImpl
import org.jetbrains.kotlin.test.KotlinTestUtils
import org.jetbrains.kotlin.utils.addIfNotNull
@@ -223,7 +223,7 @@ abstract class BaseDiagnosticsTest : KotlinMultiFileTestWithJava<TestModule, Tes
fun getActualText(
bindingContext: BindingContext,
implementingModulesBindings: List<Pair<MultiTargetPlatform, BindingContext>>,
implementingModulesBindings: List<Pair<Platform, BindingContext>>,
actualText: StringBuilder,
skipJvmSignatureDiagnostics: Boolean,
languageVersionSettings: LanguageVersionSettings,

View File

@@ -156,7 +156,8 @@ public class ExpectedResolveDataUtil {
LanguageVersionSettings languageVersionSettings = CommonConfigurationKeysKt.getLanguageVersionSettings(environment.getConfiguration());
ExpressionTypingContext context = ExpressionTypingContext.newContext(
new BindingTraceContext(), lexicalScope,
DataFlowInfoFactory.EMPTY, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, container.getDataFlowValueFactory());
DataFlowInfoFactory.EMPTY, TypeUtils.NO_EXPECTED_TYPE, languageVersionSettings, container.getDataFlowValueFactory(),
emptyModule);
KtExpression callElement = KtPsiFactory(project).createExpression(name);

View File

@@ -27,7 +27,7 @@ import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.load.kotlin.PackagePartProvider
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade
import org.jetbrains.kotlin.resolve.jvm.JvmResolverForModuleFactory
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
@@ -42,9 +42,9 @@ fun createResolveSessionForFiles(
"test",
projectContext, listOf(testModule),
{ ModuleContent(it, syntheticFiles, GlobalSearchScope.allScope(project)) },
modulePlatforms = { JvmPlatform.multiTargetPlatform },
modulePlatforms = { JvmPlatform.platform },
moduleLanguageSettingsProvider = LanguageSettingsProvider.Default,
resolverForModuleFactoryByPlatform = { JvmAnalyzerFacade },
resolverForModuleFactoryByPlatform = { JvmResolverForModuleFactory },
platformParameters = { _ ->
JvmPlatformParameters(
packagePartProviderFactory = { PackagePartProvider.Empty },

View File

@@ -31,7 +31,7 @@ import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.renderer.*;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.MemberComparator;
import org.jetbrains.kotlin.resolve.MultiTargetPlatform;
import org.jetbrains.kotlin.resolve.Platform;
import org.jetbrains.kotlin.resolve.scopes.ChainedMemberScope;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
import org.jetbrains.kotlin.test.KotlinTestUtils;
@@ -243,7 +243,7 @@ public class RecursiveDescriptorComparator {
// 'expected' declarations do not belong to the platform-specific module, even though they participate in the analysis
if (descriptor instanceof MemberDescriptor && ((MemberDescriptor) descriptor).isExpect() &&
module.getCapability(MultiTargetPlatform.CAPABILITY) != MultiTargetPlatform.Common.INSTANCE) return false;
module.getPlatform() != Platform.Common.INSTANCE) return false;
return module.equals(DescriptorUtils.getContainingModule(descriptor));
}

View File

@@ -37,7 +37,7 @@ import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.constants.EnumValue
import org.jetbrains.kotlin.resolve.descriptorUtil.annotationClass
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade
import org.jetbrains.kotlin.resolve.jvm.JvmResolverForModuleFactory
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.test.ConfigurationKind
@@ -69,9 +69,9 @@ class MultiModuleJavaAnalysisCustomTest : KtUsefulTestCase() {
"test",
projectContext, modules,
modulesContent = { module -> ModuleContent(module, module.kotlinFiles, module.javaFilesScope) },
modulePlatforms = { JvmPlatform.multiTargetPlatform },
modulePlatforms = { JvmPlatform.platform },
moduleLanguageSettingsProvider = LanguageSettingsProvider.Default,
resolverForModuleFactoryByPlatform = { JvmAnalyzerFacade },
resolverForModuleFactoryByPlatform = { JvmResolverForModuleFactory },
platformParameters = { _ ->
JvmPlatformParameters(
packagePartProviderFactory = { PackagePartProvider.Empty },

View File

@@ -99,6 +99,7 @@ class LazyJavaClassDescriptor(
override fun getTypeConstructor(): TypeConstructor = typeConstructor
private val unsubstitutedMemberScope = LazyJavaClassMemberScope(c, this, jClass)
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor) = unsubstitutedMemberScope
override fun getUnsubstitutedMemberScope() = unsubstitutedMemberScope
private val innerClassesScope = InnerClassesScopeWrapper(getUnsubstitutedMemberScope())

View File

@@ -14,16 +14,22 @@
* limitations under the License.
*/
@file:Suppress("Reformat")
package org.jetbrains.kotlin.load.java.lazy.types
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.descriptors.resolveClassByFqName
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.load.java.components.TypeUsage
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRendererOptions
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.types.checker.KotlinTypeChecker
@@ -80,6 +86,11 @@ class RawTypeImpl(lowerBound: SimpleType, upperBound: SimpleType) : FlexibleType
if (newLower == newUpper) return newLower
return renderer.renderFlexibleType(newLower, newUpper, builtIns)
}
override fun refine(moduleDescriptor: ModuleDescriptor): FlexibleType {
if (moduleDescriptor.builtIns === lowerBound.builtIns) return this
return RawTypeImpl(lowerBound.refine(moduleDescriptor), upperBound.refine(moduleDescriptor))
}
}
internal object RawSubstitution : TypeSubstitution() {
@@ -125,14 +136,21 @@ internal object RawSubstitution : TypeSubstitution() {
if (type.isError) return ErrorUtils.createErrorType("Raw error type: ${type.constructor}") to false
val memberScope = declaration.getMemberScope(RawSubstitution)
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
type.annotations, type.constructor,
type.constructor.parameters.map {
type.annotations, type.constructor,
type.constructor.parameters.map {
parameter ->
computeProjection(parameter, attr)
},
type.isMarkedNullable, declaration.getMemberScope(RawSubstitution)
) to true
type.isMarkedNullable, memberScope
) factory@ { moduleDescriptor ->
val fqName = declaration.fqNameOrNull() ?: return@factory memberScope
moduleDescriptor
.resolveClassByFqName(fqName, NoLookupLocation.FOR_ALREADY_TRACKED)
?.getMemberScope(RawSubstitution, moduleDescriptor) ?: memberScope
} to true
}
fun computeProjection(

View File

@@ -242,4 +242,6 @@ internal class NotNullTypeParameter(override val delegate: SimpleType) : CustomT
override fun replaceAnnotations(newAnnotations: Annotations) = NotNullTypeParameter(delegate.replaceAnnotations(newAnnotations))
override fun makeNullableAsSpecified(newNullability: Boolean) =
if (newNullability) delegate.makeNullableAsSpecified(true) else this
override fun replaceDelegate(delegate: SimpleType) = NotNullTypeParameter(delegate)
}

View File

@@ -82,7 +82,7 @@ class FunctionClassDescriptor(
override fun getTypeConstructor(): TypeConstructor = typeConstructor
override fun getUnsubstitutedMemberScope() = memberScope
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor) = memberScope
override fun getCompanionObjectDescriptor() = null
override fun getConstructors() = emptyList<ClassConstructorDescriptor>()

View File

@@ -19,13 +19,20 @@ import java.util.List;
public interface ClassDescriptor extends ClassifierDescriptorWithTypeParameters, ClassOrPackageFragmentDescriptor {
@NotNull
MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments);
@NotNull
MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments, @NotNull ModuleDescriptor moduleDescriptor);
@NotNull
MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution);
@NotNull
MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution, @NotNull ModuleDescriptor moduleDescriptor);
@NotNull
MemberScope getUnsubstitutedMemberScope();
@NotNull
MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor);
@NotNull
MemberScope getUnsubstitutedInnerClassesScope();

View File

@@ -19,6 +19,7 @@ package org.jetbrains.kotlin.descriptors
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.Platform
interface ModuleDescriptor : DeclarationDescriptor {
override fun getContainingDeclaration(): DeclarationDescriptor? = null
@@ -30,6 +31,10 @@ interface ModuleDescriptor : DeclarationDescriptor {
*/
val stableName: Name?
// NB: this field should actually be non-null, but making it so implies a LOT of work, so we postpone it for a moment
// TODO: make it non-null
val platform: Platform?
fun shouldSeeInternalsOf(targetModule: ModuleDescriptor): Boolean
override fun <R, D> accept(visitor: DeclarationDescriptorVisitor<R, D>, data: D): R {

View File

@@ -73,7 +73,7 @@ class NotFoundClasses(private val storageManager: StorageManager, private val mo
override fun isExternal() = false
override val annotations: Annotations get() = Annotations.EMPTY
override fun getUnsubstitutedMemberScope() = MemberScope.Empty
override fun getUnsubstitutedMemberScope(module: ModuleDescriptor) = MemberScope.Empty
override fun getStaticScope() = MemberScope.Empty
override fun getConstructors(): Collection<ClassConstructorDescriptor> = emptySet()
override fun getUnsubstitutedPrimaryConstructor(): ClassConstructorDescriptor? = null

View File

@@ -0,0 +1,70 @@
/*
* Copyright 2010-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.descriptors
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.storage.MemoizedFunctionToNotNull
import org.jetbrains.kotlin.storage.NotNullLazyValue
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.TypeConstructor
import org.jetbrains.kotlin.types.isExpectClass
import org.jetbrains.kotlin.utils.DFS
class ScopesHolderForClass<T : MemberScope>(private val scopeOrMemoizedFunction: Any) {
fun getScope(moduleDescriptor: ModuleDescriptor): T =
@Suppress("UNCHECKED_CAST")
when (scopeOrMemoizedFunction) {
is MemoizedFunctionToNotNull<*, *> ->
(scopeOrMemoizedFunction as MemoizedFunctionToNotNull<ModuleDescriptor, T>).invoke(moduleDescriptor)
else -> scopeOrMemoizedFunction as T
}
companion object {
fun <T : MemberScope> create(
classDescriptor: ClassDescriptor,
storageManager: StorageManager,
scopeFactory: (ModuleDescriptor) -> T
): NotNullLazyValue<ScopesHolderForClass<T>> {
return storageManager.createLazyValue {
val typeConstructor = classDescriptor.typeConstructor
val value: Any =
if (typeConstructor.areThereExpectSupertypes())
storageManager.createMemoizedFunction(scopeFactory)
else
scopeFactory(classDescriptor.module)
ScopesHolderForClass<T>(value)
}
}
}
}
fun TypeConstructor.areThereExpectSupertypes(): Boolean {
var result = false
DFS.dfs(
listOf(this),
DFS.Neighbors { current ->
current.supertypes.map { it.constructor }
},
DFS.VisitedWithSet(),
object : DFS.AbstractNodeHandler<TypeConstructor, Unit>() {
override fun beforeChildren(current: TypeConstructor): Boolean {
if (current.isExpectClass()) {
result = true
return false
}
return true
}
override fun result() = Unit
}
)
return result
}

View File

@@ -17,11 +17,14 @@
package org.jetbrains.kotlin.descriptors.impl;
import kotlin.jvm.functions.Function0;
import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorVisitor;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.scopes.InnerClassesScopeWrapper;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
import org.jetbrains.kotlin.resolve.scopes.SubstitutingScope;
@@ -42,7 +45,17 @@ public abstract class AbstractClassDescriptor implements ClassDescriptor {
this.defaultType = storageManager.createLazyValue(new Function0<SimpleType>() {
@Override
public SimpleType invoke() {
return TypeUtils.makeUnsubstitutedType(AbstractClassDescriptor.this, getUnsubstitutedMemberScope());
return TypeUtils.makeUnsubstitutedType(
AbstractClassDescriptor.this, getUnsubstitutedMemberScope(),
new Function1<ModuleDescriptor, MemberScope>() {
@Override
public MemberScope invoke(ModuleDescriptor moduleDescriptor) {
ClassDescriptor descriptor = KotlinTypeKt.refineDescriptor(AbstractClassDescriptor.this, moduleDescriptor);
if (descriptor == null) return getUnsubstitutedMemberScope(moduleDescriptor);
return descriptor.getUnsubstitutedMemberScope(moduleDescriptor);
}
}
);
}
});
this.unsubstitutedInnerClassesScope = storageManager.createLazyValue(new Function0<MemberScope>() {
@@ -85,23 +98,41 @@ public abstract class AbstractClassDescriptor implements ClassDescriptor {
@NotNull
@Override
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments, @NotNull ModuleDescriptor moduleDescriptor) {
assert typeArguments.size() == getTypeConstructor().getParameters().size() : "Illegal number of type arguments: expected "
+ getTypeConstructor().getParameters().size() + " but was " + typeArguments.size()
+ " for " + getTypeConstructor() + " " + getTypeConstructor().getParameters();
if (typeArguments.isEmpty()) return getUnsubstitutedMemberScope();
if (typeArguments.isEmpty()) return getUnsubstitutedMemberScope(moduleDescriptor);
TypeSubstitutor substitutor = TypeConstructorSubstitution.create(getTypeConstructor(), typeArguments).buildSubstitutor();
return new SubstitutingScope(getUnsubstitutedMemberScope(), substitutor);
return new SubstitutingScope(getUnsubstitutedMemberScope(moduleDescriptor), substitutor);
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution, @NotNull ModuleDescriptor moduleDescriptor) {
if (typeSubstitution.isEmpty()) return getUnsubstitutedMemberScope(moduleDescriptor);
TypeSubstitutor substitutor = TypeSubstitutor.create(typeSubstitution);
return new SubstitutingScope(getUnsubstitutedMemberScope(moduleDescriptor), substitutor);
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
return getMemberScope(typeArguments, DescriptorUtils.getContainingModule(this));
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution) {
if (typeSubstitution.isEmpty()) return getUnsubstitutedMemberScope();
return getMemberScope(typeSubstitution, DescriptorUtils.getContainingModule(this));
}
TypeSubstitutor substitutor = TypeSubstitutor.create(typeSubstitution);
return new SubstitutingScope(getUnsubstitutedMemberScope(), substitutor);
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope() {
return getUnsubstitutedMemberScope(DescriptorUtils.getContainingModule(this));
}
@NotNull

View File

@@ -24,6 +24,7 @@ import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.types.*
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
abstract class AbstractTypeAliasDescriptor(
containingDeclaration: DeclarationDescriptor,
@@ -90,7 +91,13 @@ abstract class AbstractTypeAliasDescriptor(
protected abstract fun getTypeConstructorTypeParameters(): List<TypeParameterDescriptor>
protected fun computeDefaultType(): SimpleType =
TypeUtils.makeUnsubstitutedType(this, classDescriptor?.unsubstitutedMemberScope ?: MemberScope.Empty)
TypeUtils.makeUnsubstitutedType(this, classDescriptor?.unsubstitutedMemberScope ?: MemberScope.Empty) { moduleDescriptor ->
classDescriptor
?.refineDescriptor(moduleDescriptor)
?.safeAs<ClassDescriptor>()
?.unsubstitutedMemberScope
?: MemberScope.Empty
}
private val typeConstructor = object : TypeConstructor {
override fun getDeclarationDescriptor(): TypeAliasDescriptor =
@@ -102,6 +109,9 @@ abstract class AbstractTypeAliasDescriptor(
override fun getSupertypes(): Collection<KotlinType> =
declarationDescriptor.underlyingType.constructor.supertypes
override fun getSupertypes(moduleDescriptor: ModuleDescriptor) =
declarationDescriptor.underlyingType.constructor.getSupertypes(moduleDescriptor)
override fun isFinal(): Boolean =
declarationDescriptor.underlyingType.constructor.isFinal

View File

@@ -79,7 +79,7 @@ public class ClassDescriptorImpl extends ClassDescriptorBase {
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope() {
public MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor) {
return unsubstitutedMemberScope;
}

View File

@@ -76,7 +76,7 @@ public class EnumEntrySyntheticClassDescriptor extends ClassDescriptorBase {
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope() {
public MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor) {
return scope;
}

View File

@@ -12,6 +12,7 @@ import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.DescriptorUtils;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
import org.jetbrains.kotlin.resolve.scopes.SubstitutingScope;
import org.jetbrains.kotlin.storage.LockBasedStorageManager;
@@ -82,28 +83,46 @@ public class LazySubstitutingClassDescriptor implements ClassDescriptor {
@NotNull
@Override
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
MemberScope memberScope = original.getMemberScope(typeArguments);
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments, @NotNull ModuleDescriptor moduleDescriptor) {
MemberScope memberScope = original.getMemberScope(typeArguments, moduleDescriptor);
if (originalSubstitutor.isEmpty()) {
return memberScope;
}
return new SubstitutingScope(memberScope, getSubstitutor());
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution, @NotNull ModuleDescriptor moduleDescriptor) {
MemberScope memberScope = original.getMemberScope(typeSubstitution, moduleDescriptor);
if (originalSubstitutor.isEmpty()) {
return memberScope;
}
return new SubstitutingScope(memberScope, getSubstitutor());
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
return getMemberScope(typeArguments, DescriptorUtils.getContainingModule(this));
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution) {
MemberScope memberScope = original.getMemberScope(typeSubstitution);
if (originalSubstitutor.isEmpty()) {
return memberScope;
}
return new SubstitutingScope(memberScope, getSubstitutor());
return getMemberScope(typeSubstitution, DescriptorUtils.getContainingModule(this));
}
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope() {
MemberScope memberScope = original.getUnsubstitutedMemberScope();
return getUnsubstitutedMemberScope(DescriptorUtils.getContainingModule(original));
}
@NotNull
@Override
public MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor) {
MemberScope memberScope = original.getUnsubstitutedMemberScope(moduleDescriptor);
if (originalSubstitutor.isEmpty()) {
return memberScope;
}

View File

@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.descriptors.PackageViewDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.resolve.MultiTargetPlatform
import org.jetbrains.kotlin.resolve.Platform
import org.jetbrains.kotlin.storage.StorageManager
import org.jetbrains.kotlin.utils.sure
import java.lang.IllegalArgumentException
@@ -34,8 +34,8 @@ class ModuleDescriptorImpl @JvmOverloads constructor(
private val storageManager: StorageManager,
override val builtIns: KotlinBuiltIns,
// May be null in compiler context, should be not-null in IDE context
multiTargetPlatform: MultiTargetPlatform? = null,
capabilities: Map<ModuleDescriptor.Capability<*>, Any?> = emptyMap(),
override val platform: Platform? = null,
private val capabilities: Map<ModuleDescriptor.Capability<*>, Any?> = emptyMap(),
override val stableName: Name? = null
) : DeclarationDescriptorImpl(Annotations.EMPTY, moduleName), ModuleDescriptor {
init {
@@ -44,8 +44,6 @@ class ModuleDescriptorImpl @JvmOverloads constructor(
}
}
private val capabilities = capabilities + (multiTargetPlatform?.let { mapOf(MultiTargetPlatform.CAPABILITY to it) } ?: emptyMap())
private var dependencies: ModuleDependencies? = null
private var packageFragmentProviderForModuleContent: PackageFragmentProvider? = null

View File

@@ -162,7 +162,7 @@ public class MutableClassDescriptor extends ClassDescriptorBase {
@Override
@NotNull
public MemberScope getUnsubstitutedMemberScope() {
public MemberScope getUnsubstitutedMemberScope(@NotNull ModuleDescriptor moduleDescriptor) {
return MemberScope.Empty.INSTANCE; // used for getDefaultType
}

View File

@@ -17,31 +17,22 @@
package org.jetbrains.kotlin.resolve
import org.jetbrains.kotlin.descriptors.MemberDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.module
sealed class MultiTargetPlatform : Comparable<MultiTargetPlatform> {
object Common : MultiTargetPlatform() {
override fun compareTo(other: MultiTargetPlatform): Int =
sealed class Platform : Comparable<Platform> {
object Common : Platform() {
override fun compareTo(other: Platform): Int =
if (other is Common) 0 else -1
}
data class Specific(val platform: String) : MultiTargetPlatform() {
override fun compareTo(other: MultiTargetPlatform): Int =
data class Specific(val platform: String) : Platform() {
override fun compareTo(other: Platform): Int =
when (other) {
is Common -> 1
is Specific -> platform.compareTo(other.platform)
}
}
companion object {
@JvmField
val CAPABILITY = ModuleDescriptor.Capability<MultiTargetPlatform>("MULTI_TARGET_PLATFORM")
}
}
fun ModuleDescriptor.getMultiTargetPlatform(): MultiTargetPlatform? =
module.getCapability(MultiTargetPlatform.CAPABILITY)
fun MemberDescriptor.getMultiTargetPlatform(): String? =
(module.getMultiTargetPlatform() as? MultiTargetPlatform.Specific)?.platform
val MemberDescriptor.platform
get() = module.platform

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.resolve.calls.inference
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.scopes.MemberScope
@@ -52,6 +53,8 @@ class CapturedTypeConstructorImpl(
return listOf(superType)
}
override fun getSupertypes(moduleDescriptor: ModuleDescriptor) = getSupertypes()
override fun isFinal() = true
override fun isDenotable() = false
@@ -97,6 +100,12 @@ class CapturedType(
override fun replaceAnnotations(newAnnotations: Annotations): CapturedType =
CapturedType(typeProjection, constructor, isMarkedNullable, newAnnotations)
override fun refine(moduleDescriptor: ModuleDescriptor) =
CapturedType(
TypeProjectionImpl(typeProjection.projectionKind, typeProjection.type.refine(moduleDescriptor)),
constructor, isMarkedNullable, annotations
)
}
fun createCapturedType(typeProjection: TypeProjection): KotlinType = CapturedType(typeProjection)

View File

@@ -82,6 +82,7 @@ class IntegerValueTypeConstructor(
private fun unsignedType(classId: ClassId): SimpleType = module.findClassAcrossModuleDependencies(classId)!!.defaultType
override fun getSupertypes(): Collection<KotlinType> = supertypes
override fun getSupertypes(module: ModuleDescriptor): Collection<KotlinType> = supertypes
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()

View File

@@ -16,12 +16,29 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.SupertypeLoopChecker
import org.jetbrains.kotlin.storage.MemoizedFunctionToNotNull
import org.jetbrains.kotlin.storage.NullableLazyValue
import org.jetbrains.kotlin.storage.StorageManager
abstract class AbstractTypeConstructor(storageManager: StorageManager) : TypeConstructor {
abstract class AbstractTypeConstructor(private val storageManager: StorageManager) : TypeConstructor {
override fun getSupertypes() = supertypes().supertypesWithoutCycles
private val supertypesByModule: NullableLazyValue<MemoizedFunctionToNotNull<ModuleDescriptor, Supertypes>> =
storageManager.createNullableLazyValue {
if (supertypes().allSupertypes.any(KotlinType::isExpectClass)) {
storageManager.createMemoizedFunction { moduleDescriptor: ModuleDescriptor ->
computeLazyValue(moduleDescriptor).invoke()
}
} else {
null
}
}
override fun getSupertypes(moduleDescriptor: ModuleDescriptor) =
supertypesByModule()?.invoke(moduleDescriptor)?.supertypesWithoutCycles ?: getSupertypes()
// In current version diagnostic about loops in supertypes is reported on each vertex (supertype reference) that lies on the cycle.
// To achieve that we store both versions of supertypes --- before and after loops disconnection.
// The first one is used for computation of neighbours in supertypes graph (see Companion.computeNeighbours)
@@ -30,35 +47,44 @@ abstract class AbstractTypeConstructor(storageManager: StorageManager) : TypeCon
var supertypesWithoutCycles: List<KotlinType> = listOf(ErrorUtils.ERROR_TYPE_FOR_LOOP_IN_SUPERTYPES)
}
private val supertypes = storageManager.createLazyValueWithPostCompute(
{ Supertypes(computeSupertypes()) },
{ Supertypes(listOf(ErrorUtils.ERROR_TYPE_FOR_LOOP_IN_SUPERTYPES)) },
{ supertypes ->
// It's important that loops disconnection begins in post-compute phase, because it guarantees that
// when we start calculation supertypes of supertypes (for computing neighbours), they start their disconnection loop process
// either, and as we want to report diagnostic about loops on all declarations they should see consistent version of 'allSupertypes'
var resultWithoutCycles =
private val supertypes = computeLazyValue(moduleDescriptor = null)
private fun computeLazyValue(moduleDescriptor: ModuleDescriptor?) =
storageManager.createLazyValueWithPostCompute(
{ Supertypes(computeSupertypes().refineIfNeeded(moduleDescriptor)) },
{ Supertypes(listOf(ErrorUtils.ERROR_TYPE_FOR_LOOP_IN_SUPERTYPES)) },
{ supertypes ->
// It's important that loops disconnection begins in post-compute phase, because it guarantees that
// when we start calculation supertypes of supertypes (for computing neighbours), they start their disconnection loop process
// either, and as we want to report diagnostic about loops on all declarations they should see consistent version of 'allSupertypes'
var resultWithoutCycles =
supertypeLoopChecker.findLoopsInSupertypesAndDisconnect(
this, supertypes.allSupertypes,
{ it.computeNeighbours(useCompanions = false).refineIfNeeded(moduleDescriptor) },
{ reportSupertypeLoopError(it) }
)
if (resultWithoutCycles.isEmpty()) {
resultWithoutCycles = defaultSupertypeIfEmpty()?.let { listOf(it) }.orEmpty()
}
// We also check if there are a loop with additional edges going from owner of companion to
// the companion itself.
// Note that we use already disconnected types to not report two diagnostics on cyclic supertypes
supertypeLoopChecker.findLoopsInSupertypesAndDisconnect(
this, supertypes.allSupertypes,
{ it.computeNeighbours(useCompanions = false) },
{ reportSupertypeLoopError(it) }
this, resultWithoutCycles,
{ it.computeNeighbours(useCompanions = true) },
{ reportScopesLoopError(it) }
)
if (resultWithoutCycles.isEmpty()) {
resultWithoutCycles = defaultSupertypeIfEmpty()?.let { listOf(it) }.orEmpty()
}
supertypes.supertypesWithoutCycles = (resultWithoutCycles as? List<KotlinType>) ?: resultWithoutCycles.toList()
})
// We also check if there are a loop with additional edges going from owner of companion to
// the companion itself.
// Note that we use already disconnected types to not report two diagnostics on cyclic supertypes
supertypeLoopChecker.findLoopsInSupertypesAndDisconnect(
this, resultWithoutCycles,
{ it.computeNeighbours(useCompanions = true) },
{ reportScopesLoopError(it) }
)
supertypes.supertypesWithoutCycles = (resultWithoutCycles as? List<KotlinType>) ?: resultWithoutCycles.toList()
})
private fun Collection<KotlinType>.refineIfNeeded(moduleDescriptor: ModuleDescriptor?) =
if (moduleDescriptor == null)
this
else
map { it.refine(moduleDescriptor) }
private fun TypeConstructor.computeNeighbours(useCompanions: Boolean): Collection<KotlinType> =
(this as? AbstractTypeConstructor)?.let { abstractClassifierDescriptor ->
@@ -79,3 +105,8 @@ abstract class AbstractTypeConstructor(storageManager: StorageManager) : TypeCon
// Only for debugging
fun renderAdditionalDebugInformation(): String = "supertypes=${supertypes.renderDebugInformation()}"
}
private fun KotlinType.isExpectClass() = constructor.isExpectClass()
internal fun TypeConstructor.isExpectClass() = true
//declarationDescriptor?.safeAs<ClassDescriptor>()?.isExpect == true

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.scopes.MemberScope
@@ -35,6 +36,8 @@ open class ErrorType @JvmOverloads internal constructor(
override fun makeNullableAsSpecified(newNullability: Boolean): SimpleType =
ErrorType(constructor, memberScope, arguments, newNullability)
override fun refine(moduleDescriptor: ModuleDescriptor) = this
}
class UnresolvedType(
@@ -46,4 +49,6 @@ class UnresolvedType(
) : ErrorType(constructor, memberScope, arguments, isMarkedNullable) {
override fun makeNullableAsSpecified(newNullability: Boolean): SimpleType =
UnresolvedType(presentableName, constructor, memberScope, arguments, newNullability)
override fun refine(moduleDescriptor: ModuleDescriptor) = this
}

View File

@@ -30,6 +30,7 @@ import org.jetbrains.kotlin.descriptors.impl.TypeParameterDescriptorImpl;
import org.jetbrains.kotlin.incremental.components.LookupLocation;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.Name;
import org.jetbrains.kotlin.resolve.Platform;
import org.jetbrains.kotlin.resolve.descriptorUtil.DescriptorUtilsKt;
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter;
import org.jetbrains.kotlin.resolve.scopes.MemberScope;
@@ -80,6 +81,12 @@ public class ErrorUtils {
return Name.special("<ERROR MODULE>");
}
@Nullable
@Override
public Platform getPlatform() {
return null;
}
@NotNull
@Override
public PackageViewDescriptor getPackage(@NotNull FqName fqName) {
@@ -365,13 +372,13 @@ public class ErrorUtils {
@NotNull
@Override
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments) {
public MemberScope getMemberScope(@NotNull List<? extends TypeProjection> typeArguments, @NotNull ModuleDescriptor moduleDescriptor) {
return createErrorScope("Error scope for class " + getName() + " with arguments: " + typeArguments);
}
@NotNull
@Override
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution) {
public MemberScope getMemberScope(@NotNull TypeSubstitution typeSubstitution, @NotNull ModuleDescriptor moduleDescriptor) {
return createErrorScope("Error scope for class " + getName() + " with arguments: " + typeSubstitution);
}
}
@@ -488,6 +495,12 @@ public class ErrorUtils {
return emptyList();
}
@NotNull
@Override
public Collection<KotlinType> getSupertypes(@NotNull ModuleDescriptor moduleDescriptor) {
return emptyList();
}
@Override
public boolean isFinal() {
return false;
@@ -585,6 +598,12 @@ public class ErrorUtils {
return errorTypeConstructor.getSupertypes();
}
@NotNull
@Override
public Collection<KotlinType> getSupertypes(@NotNull ModuleDescriptor moduleDescriptor) {
return getSupertypes();
}
@Override
public boolean isFinal() {
return errorTypeConstructor.isFinal();

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
class FunctionPlaceholders(private val builtIns: KotlinBuiltIns) {
@@ -52,6 +53,8 @@ class FunctionPlaceholderTypeConstructor(
return errorTypeConstructor.supertypes
}
override fun getSupertypes(moduleDescriptor: ModuleDescriptor) = errorTypeConstructor.supertypes
override fun isFinal(): Boolean {
return errorTypeConstructor.isFinal
}

View File

@@ -18,7 +18,9 @@ package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.TypeIntersectionScope
import java.util.*
@@ -34,6 +36,7 @@ class IntersectionTypeConstructor(typesToIntersect: Collection<KotlinType>) : Ty
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()
override fun getSupertypes(): Collection<KotlinType> = intersectedTypes
override fun getSupertypes(module: ModuleDescriptor): Collection<KotlinType> = supertypes
fun createScopeForKotlinType(): MemberScope =
TypeIntersectionScope.create("member scope for intersection type $this", intersectedTypes)
@@ -60,6 +63,15 @@ class IntersectionTypeConstructor(typesToIntersect: Collection<KotlinType>) : Ty
return intersectedTypes == other.intersectedTypes
}
fun createType() =
KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
Annotations.EMPTY, this, listOf(), false, this.createScopeForKotlinType()
) { moduleDescriptor: ModuleDescriptor ->
IntersectionTypeConstructor(intersectedTypes.map {
it.refine(moduleDescriptor)
}).createScopeForKotlinType()
}
override fun hashCode(): Int = hashCode
}
@@ -80,4 +92,4 @@ inline fun IntersectionTypeConstructor.transformComponents(
if (!changed) return null
return IntersectionTypeConstructor(newSupertypes)
}
}

View File

@@ -16,10 +16,13 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotated
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRendererOptions
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.types.checker.StrictEqualityTypeChecker
@@ -49,6 +52,8 @@ sealed class KotlinType : Annotated {
abstract fun unwrap(): UnwrappedType
abstract fun refine(moduleDescriptor: ModuleDescriptor): KotlinType
final override fun hashCode(): Int {
if (isError) return super.hashCode()
@@ -107,11 +112,13 @@ abstract class WrappedType : KotlinType() {
*
* todo: specify what happens with internal structure when we apply some [TypeSubstitutor]
*/
sealed class UnwrappedType: KotlinType() {
sealed class UnwrappedType : KotlinType() {
abstract fun replaceAnnotations(newAnnotations: Annotations): UnwrappedType
abstract fun makeNullableAsSpecified(newNullability: Boolean): UnwrappedType
override final fun unwrap(): UnwrappedType = this
abstract override fun refine(moduleDescriptor: ModuleDescriptor): UnwrappedType
}
/**
@@ -123,6 +130,8 @@ abstract class SimpleType : UnwrappedType() {
abstract override fun replaceAnnotations(newAnnotations: Annotations): SimpleType
abstract override fun makeNullableAsSpecified(newNullability: Boolean): SimpleType
abstract override fun refine(moduleDescriptor: ModuleDescriptor): SimpleType
override fun toString(): String {
return buildString {
for (annotation in annotations) {
@@ -158,6 +167,8 @@ abstract class FlexibleType(val lowerBound: SimpleType, val upperBound: SimpleTy
override val memberScope: MemberScope get() = delegate.memberScope
override fun toString(): String = DescriptorRenderer.DEBUG_TEXT.renderType(this)
abstract override fun refine(moduleDescriptor: ModuleDescriptor): FlexibleType
}
val KotlinType.isError: Boolean
@@ -165,3 +176,9 @@ val KotlinType.isError: Boolean
unwrapped is ErrorType ||
(unwrapped is FlexibleType && unwrapped.delegate is ErrorType)
}
fun DeclarationDescriptor.refineDescriptor(moduleDescriptor: ModuleDescriptor): ClassDescriptor? {
if (this !is ClassifierDescriptor) return null
val fqName = this.fqNameOrNull() ?: return null
return moduleDescriptor.resolveClassByFqName(fqName, NoLookupLocation.FOR_ALREADY_TRACKED)
}

View File

@@ -16,23 +16,40 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.TypeAliasDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.*
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.incremental.components.NoLookupLocation
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameOrNull
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import java.lang.IllegalStateException
object KotlinTypeFactory {
private fun computeMemberScope(constructor: TypeConstructor, arguments: List<TypeProjection>): MemberScope {
val descriptor = constructor.declarationDescriptor
private fun computeMemberScope(
constructor: TypeConstructor,
arguments: List<TypeProjection>,
moduleDescriptor: ModuleDescriptor? = null
): MemberScope {
val basicDescriptor = constructor.declarationDescriptor
val descriptor =
if (moduleDescriptor != null)
basicDescriptor?.fqNameOrNull()?.let {
moduleDescriptor.resolveClassByFqName(it, NoLookupLocation.FOR_ALREADY_TRACKED)
} ?: basicDescriptor
else
basicDescriptor
return when (descriptor) {
is TypeParameterDescriptor -> descriptor.getDefaultType().memberScope
is ClassDescriptor -> {
if (arguments.isEmpty())
descriptor.defaultType.memberScope
else
descriptor.getMemberScope(TypeConstructorSubstitution.create(constructor, arguments))
descriptor.getMemberScope(
TypeConstructorSubstitution.create(constructor, arguments),
moduleDescriptor ?: descriptor.module
)
}
is TypeAliasDescriptor -> ErrorUtils.createErrorScope("Scope for abbreviation: ${descriptor.name}", true)
else -> throw IllegalStateException("Unsupported classifier: $descriptor for constructor: $constructor")
@@ -50,18 +67,40 @@ object KotlinTypeFactory {
return constructor.declarationDescriptor!!.defaultType
}
return simpleTypeWithNonTrivialMemberScope(annotations, constructor, arguments, nullable, computeMemberScope(constructor, arguments))
return simpleTypeWithNonTrivialMemberScope(
annotations, constructor, arguments, nullable,
computeMemberScope(constructor, arguments)
) { moduleDescriptor ->
computeMemberScope(constructor, arguments, moduleDescriptor)
}
}
@JvmStatic
fun simpleTypeWithNonTrivialMemberScope(
annotations: Annotations,
constructor: TypeConstructor,
arguments: List<TypeProjection>,
nullable: Boolean,
memberScope: MemberScope
): SimpleType =
SimpleTypeImpl(constructor, arguments, nullable, memberScope, { memberScope })
.let {
if (annotations.isEmpty())
it
else
AnnotatedSimpleType(it, annotations)
}
@JvmStatic
fun simpleTypeWithNonTrivialMemberScope(
annotations: Annotations,
constructor: TypeConstructor,
arguments: List<TypeProjection>,
nullable: Boolean,
memberScope: MemberScope
memberScope: MemberScope,
scopeFactory: (ModuleDescriptor) -> MemberScope
): SimpleType =
SimpleTypeImpl(constructor, arguments, nullable, memberScope)
SimpleTypeImpl(constructor, arguments, nullable, memberScope, scopeFactory)
.let {
if (annotations.isEmpty())
it
@@ -96,7 +135,8 @@ private class SimpleTypeImpl(
override val constructor: TypeConstructor,
override val arguments: List<TypeProjection>,
override val isMarkedNullable: Boolean,
override val memberScope: MemberScope
override val memberScope: MemberScope,
private val scopeFactory: (ModuleDescriptor) -> MemberScope
) : SimpleType() {
override val annotations: Annotations get() = Annotations.EMPTY
@@ -119,6 +159,12 @@ private class SimpleTypeImpl(
throw IllegalStateException("SimpleTypeImpl should not be created for error type: $memberScope\n$constructor")
}
}
override fun refine(moduleDescriptor: ModuleDescriptor): SimpleType {
if (constructor.declarationDescriptor?.module === moduleDescriptor) return this
return SimpleTypeImpl(constructor, arguments, isMarkedNullable, scopeFactory(moduleDescriptor), scopeFactory)
}
}
abstract class DelegatingSimpleTypeImpl(override val delegate: SimpleType) : DelegatingSimpleType() {
@@ -137,14 +183,20 @@ abstract class DelegatingSimpleTypeImpl(override val delegate: SimpleType) : Del
private class AnnotatedSimpleType(
delegate: SimpleType,
override val annotations: Annotations
) : DelegatingSimpleTypeImpl(delegate)
) : DelegatingSimpleTypeImpl(delegate) {
override fun replaceDelegate(delegate: SimpleType) = AnnotatedSimpleType(delegate, annotations)
}
private class NullableSimpleType(delegate: SimpleType) : DelegatingSimpleTypeImpl(delegate) {
override val isMarkedNullable: Boolean
get() = true
override fun replaceDelegate(delegate: SimpleType) = NullableSimpleType(delegate)
}
private class NotNullSimpleType(delegate: SimpleType) : DelegatingSimpleTypeImpl(delegate) {
override val isMarkedNullable: Boolean
get() = false
override fun replaceDelegate(delegate: SimpleType) = NotNullSimpleType(delegate)
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.scopes.MemberScope
@@ -32,6 +33,10 @@ abstract class DelegatingSimpleType : SimpleType() {
override val arguments: List<TypeProjection> get() = delegate.arguments
override val isMarkedNullable: Boolean get() = delegate.isMarkedNullable
override val memberScope: MemberScope get() = delegate.memberScope
abstract fun replaceDelegate(delegate: SimpleType): DelegatingSimpleType
override fun refine(moduleDescriptor: ModuleDescriptor) = replaceDelegate(delegate.refine(moduleDescriptor))
}
class AbbreviatedType(override val delegate: SimpleType, val abbreviation: SimpleType) : DelegatingSimpleType() {
@@ -42,6 +47,8 @@ class AbbreviatedType(override val delegate: SimpleType, val abbreviation: Simpl
override fun makeNullableAsSpecified(newNullability: Boolean)
= AbbreviatedType(delegate.makeNullableAsSpecified(newNullability), abbreviation.makeNullableAsSpecified(newNullability))
override fun replaceDelegate(delegate: SimpleType) = AbbreviatedType(delegate, abbreviation)
}
fun KotlinType.getAbbreviatedType(): AbbreviatedType? = unwrap() as? AbbreviatedType
@@ -52,12 +59,19 @@ fun SimpleType.withAbbreviation(abbreviatedType: SimpleType): SimpleType {
return AbbreviatedType(this, abbreviatedType)
}
class LazyWrappedType(storageManager: StorageManager, computation: () -> KotlinType): WrappedType() {
class LazyWrappedType(
private val storageManager: StorageManager,
private val computation: () -> KotlinType
): WrappedType() {
private val lazyValue = storageManager.createLazyValue(computation)
override val delegate: KotlinType get() = lazyValue()
override fun isComputed(): Boolean = lazyValue.isComputed()
override fun refine(moduleDescriptor: ModuleDescriptor) = LazyWrappedType(storageManager) {
computation().refine(moduleDescriptor)
}
}
class DefinitelyNotNullType private constructor(val original: SimpleType) : DelegatingSimpleType(), CustomTypeVariable {
@@ -105,6 +119,8 @@ class DefinitelyNotNullType private constructor(val original: SimpleType) : Dele
if (newNullability) delegate.makeNullableAsSpecified(newNullability) else this
override fun toString(): String = "$delegate!!"
override fun replaceDelegate(delegate: SimpleType) = DefinitelyNotNullType(delegate)
}
val KotlinType.isDefinitelyNotNullType: Boolean
@@ -124,13 +140,7 @@ private fun KotlinType.makeIntersectionTypeDefinitelyNotNullOrNotNull(): SimpleT
val typeConstructor = constructor as? IntersectionTypeConstructor ?: return null
val definitelyNotNullConstructor = typeConstructor.makeDefinitelyNotNullOrNotNull() ?: return null
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(
annotations,
definitelyNotNullConstructor,
listOf(),
false,
definitelyNotNullConstructor.createScopeForKotlinType()
)
return definitelyNotNullConstructor.createType()
}
private fun IntersectionTypeConstructor.makeDefinitelyNotNullOrNotNull(): IntersectionTypeConstructor? {

View File

@@ -16,24 +16,31 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassifierDescriptorWithTypeParameters
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.resolve.descriptorUtil.module
class StarProjectionImpl(
private val typeParameter: TypeParameterDescriptor
private val typeParameter: TypeParameterDescriptor,
private val moduleDescriptor: ModuleDescriptor
) : TypeProjectionBase() {
constructor(typeParameter: TypeParameterDescriptor) : this(typeParameter, typeParameter.module)
override fun isStarProjection() = true
override fun getProjectionKind() = Variance.OUT_VARIANCE
// No synchronization here: there's no problem in accidentally computing this twice
private val _type: KotlinType by lazy(LazyThreadSafetyMode.PUBLICATION) {
typeParameter.starProjectionType()
typeParameter.starProjectionType().refine(moduleDescriptor)
}
override fun getType() = _type
override fun refine(moduleDescriptor: ModuleDescriptor) = StarProjectionImpl(typeParameter, moduleDescriptor)
}
fun TypeParameterDescriptor.starProjectionType(): KotlinType {
@@ -58,4 +65,6 @@ class TypeBasedStarProjectionImpl(
override fun getProjectionKind() = Variance.OUT_VARIANCE
override fun getType() = _type
override fun refine(moduleDescriptor: ModuleDescriptor): TypeProjection = TypeBasedStarProjectionImpl(_type.refine(moduleDescriptor!!))
}

View File

@@ -5,6 +5,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.scopes.MemberScope
@@ -38,4 +39,6 @@ class StubType(
override fun toString(): String {
return "NonFixed: $originalTypeVariable"
}
}
override fun refine(moduleDescriptor: ModuleDescriptor) = this
}

View File

@@ -21,6 +21,7 @@ import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
import java.util.Collection;
@@ -37,6 +38,10 @@ public interface TypeConstructor {
@ReadOnly
List<TypeParameterDescriptor> getParameters();
@NotNull
@ReadOnly
Collection<KotlinType> getSupertypes(@NotNull ModuleDescriptor moduleDescriptor);
@NotNull
@ReadOnly
Collection<KotlinType> getSupertypes();

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.types;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
public interface TypeProjection {
@NotNull
@@ -26,4 +27,7 @@ public interface TypeProjection {
KotlinType getType();
boolean isStarProjection();
@NotNull
TypeProjection refine(@NotNull ModuleDescriptor moduleDescriptor);
}

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.types;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.descriptors.ModuleDescriptor;
public class TypeProjectionImpl extends TypeProjectionBase {
private final Variance projection;
@@ -47,4 +48,10 @@ public class TypeProjectionImpl extends TypeProjectionBase {
public boolean isStarProjection() {
return false;
}
@NotNull
@Override
public TypeProjection refine(ModuleDescriptor moduleDescriptor) {
return new TypeProjectionImpl(projection, type.refine(moduleDescriptor));
}
}

View File

@@ -10,10 +10,7 @@ import kotlin.jvm.functions.Function1;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.kotlin.builtins.KotlinBuiltIns;
import org.jetbrains.kotlin.descriptors.ClassDescriptor;
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor;
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor;
import org.jetbrains.kotlin.descriptors.*;
import org.jetbrains.kotlin.descriptors.annotations.Annotations;
import org.jetbrains.kotlin.name.FqName;
import org.jetbrains.kotlin.name.FqNameUnsafe;
@@ -59,6 +56,12 @@ public class TypeUtils {
public String toString() {
return name;
}
@NotNull
@Override
public DelegatingSimpleType replaceDelegate(@NotNull SimpleType delegate) {
throw new IllegalStateException(name);
}
}
@NotNull
@@ -184,7 +187,10 @@ public class TypeUtils {
}
@NotNull
public static SimpleType makeUnsubstitutedType(ClassifierDescriptor classifierDescriptor, MemberScope unsubstitutedMemberScope) {
public static SimpleType makeUnsubstitutedType(
ClassifierDescriptor classifierDescriptor, MemberScope unsubstitutedMemberScope,
Function1<ModuleDescriptor, MemberScope> scopeFactory
) {
if (ErrorUtils.isError(classifierDescriptor)) {
return ErrorUtils.createErrorType("Unsubstituted type for " + classifierDescriptor);
}
@@ -195,7 +201,7 @@ public class TypeUtils {
typeConstructor,
arguments,
false,
unsubstitutedMemberScope
unsubstitutedMemberScope, scopeFactory
);
}

View File

@@ -176,7 +176,7 @@ fun KotlinType.getImmediateSuperclassNotAny(): KotlinType? {
fun KotlinType.asTypeProjection(): TypeProjection = TypeProjectionImpl(this)
fun KotlinType.contains(predicate: (UnwrappedType) -> Boolean) = TypeUtils.contains(this, predicate)
fun KotlinType.replaceArgumentsWithStarProjections() = replaceArgumentsWith(::StarProjectionImpl)
fun KotlinType.replaceArgumentsWithStarProjections() = replaceArgumentsWith { StarProjectionImpl(it) }
fun KotlinType.replaceArgumentsWithNothing() = replaceArgumentsWith { it.builtIns.nothingType.asTypeProjection() }
private inline fun KotlinType.replaceArgumentsWith(replacement: (TypeParameterDescriptor) -> TypeProjection): KotlinType {

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRendererOptions
@@ -38,6 +39,8 @@ class SimpleTypeWithEnhancement(
override fun makeNullableAsSpecified(newNullability: Boolean): SimpleType
= origin.makeNullableAsSpecified(newNullability).wrapEnhancement(enhancement.unwrap().makeNullableAsSpecified(newNullability)) as SimpleType
override fun replaceDelegate(delegate: SimpleType) = SimpleTypeWithEnhancement(delegate, enhancement)
}
class FlexibleTypeWithEnhancement(
@@ -60,6 +63,9 @@ class FlexibleTypeWithEnhancement(
}
override val delegate: SimpleType get() = origin.delegate
override fun refine(moduleDescriptor: ModuleDescriptor) =
FlexibleTypeWithEnhancement(origin.refine(moduleDescriptor), enhancement.refine(moduleDescriptor))
}
fun KotlinType.getEnhancement(): KotlinType? = when (this) {

View File

@@ -16,7 +16,6 @@
package org.jetbrains.kotlin.types.checker
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.types.*
import java.util.*
import kotlin.collections.LinkedHashSet
@@ -123,8 +122,7 @@ object TypeIntersector {
if (filteredSuperAndEqualTypes.size < 2) return filteredSuperAndEqualTypes.single()
val constructor = IntersectionTypeConstructor(inputTypes)
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(Annotations.EMPTY, constructor, listOf(), false, constructor.createScopeForKotlinType())
return IntersectionTypeConstructor(inputTypes).createType()
}
private fun isStrictSupertype(subtype: KotlinType, supertype: KotlinType): Boolean {

View File

@@ -18,6 +18,7 @@ package org.jetbrains.kotlin.types.checker
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ClassifierDescriptor
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.resolve.calls.inference.CapturedTypeConstructor
@@ -143,6 +144,13 @@ class NewCapturedType(
override fun makeNullableAsSpecified(newNullability: Boolean) =
NewCapturedType(captureStatus, constructor, lowerType, annotations, newNullability)
override fun refine(moduleDescriptor: ModuleDescriptor) =
NewCapturedType(
captureStatus,
constructor.refine(moduleDescriptor),
lowerType?.refine(moduleDescriptor), annotations, isMarkedNullable
)
}
class NewCapturedTypeConstructor(override val projection: TypeProjection, private var supertypes: List<UnwrappedType>? = null) :
@@ -155,6 +163,7 @@ class NewCapturedTypeConstructor(override val projection: TypeProjection, privat
}
override fun getSupertypes() = supertypes ?: emptyList()
override fun getSupertypes(module: ModuleDescriptor): Collection<KotlinType> = getSupertypes()
override fun getParameters(): List<TypeParameterDescriptor> = emptyList()
override fun isFinal() = false
@@ -162,5 +171,8 @@ class NewCapturedTypeConstructor(override val projection: TypeProjection, privat
override fun getDeclarationDescriptor(): ClassifierDescriptor? = null
override fun getBuiltIns(): KotlinBuiltIns = projection.type.builtIns
internal fun refine(moduleDescriptor: ModuleDescriptor) =
NewCapturedTypeConstructor(projection.refine(moduleDescriptor), supertypes?.map { it.refine(moduleDescriptor) })
override fun toString() = "CapturedType($projection)"
}

View File

@@ -154,7 +154,7 @@ object NewKotlinTypeChecker : KotlinTypeChecker {
is IntersectionTypeConstructor -> if (type.isMarkedNullable) {
val newConstructor = constructor.transformComponents(transform = { it.makeNullable() }) ?: constructor
return KotlinTypeFactory.simpleTypeWithNonTrivialMemberScope(type.annotations, newConstructor, listOf(), false, newConstructor.createScopeForKotlinType())
return newConstructor.createType()
}
}

View File

@@ -17,6 +17,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.renderer.DescriptorRenderer
import org.jetbrains.kotlin.renderer.DescriptorRendererOptions
@@ -47,4 +48,6 @@ class DynamicType(builtIns: KotlinBuiltIns, override val annotations: Annotation
override fun replaceAnnotations(newAnnotations: Annotations): DynamicType = DynamicType(delegate.builtIns, newAnnotations)
override fun render(renderer: DescriptorRenderer, options: DescriptorRendererOptions): String = "dynamic"
override fun refine(moduleDescriptor: ModuleDescriptor) = this
}

View File

@@ -16,6 +16,7 @@
package org.jetbrains.kotlin.types
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.descriptors.TypeParameterDescriptor
import org.jetbrains.kotlin.descriptors.annotations.Annotations
import org.jetbrains.kotlin.renderer.DescriptorRenderer
@@ -134,4 +135,7 @@ class FlexibleTypeImpl(lowerBound: SimpleType, upperBound: SimpleType) : Flexibl
override fun makeNullableAsSpecified(newNullability: Boolean): UnwrappedType
= KotlinTypeFactory.flexibleType(lowerBound.makeNullableAsSpecified(newNullability), upperBound.makeNullableAsSpecified(newNullability))
override fun refine(moduleDescriptor: ModuleDescriptor) =
KotlinTypeFactory.flexibleType(lowerBound.refine(moduleDescriptor), upperBound.refine(moduleDescriptor)) as FlexibleType
}

View File

@@ -20,6 +20,7 @@ import org.jetbrains.kotlin.resolve.NonReportingOverrideStrategy
import org.jetbrains.kotlin.resolve.OverridingUtil
import org.jetbrains.kotlin.resolve.descriptorUtil.classId
import org.jetbrains.kotlin.resolve.descriptorUtil.computeSealedSubclasses
import org.jetbrains.kotlin.resolve.descriptorUtil.module
import org.jetbrains.kotlin.resolve.scopes.DescriptorKindFilter
import org.jetbrains.kotlin.resolve.scopes.MemberScope
import org.jetbrains.kotlin.resolve.scopes.StaticScopeForKotlinEnum
@@ -52,7 +53,10 @@ class DeserializedClassDescriptor(
private val staticScope = if (kind == ClassKind.ENUM_CLASS) StaticScopeForKotlinEnum(c.storageManager, this) else MemberScope.Empty
private val typeConstructor = DeserializedClassTypeConstructor()
private val memberScope = DeserializedClassMemberScope()
private val memberScopeHolder = ScopesHolderForClass.create(this, c.storageManager, this::DeserializedClassMemberScope)
private val memberScope get() = memberScopeHolder().getScope(module)
private val enumEntries = if (kind == ClassKind.ENUM_CLASS) EnumEntryClassDescriptors() else null
private val containingDeclaration = outerContext.containingDeclaration
@@ -98,7 +102,8 @@ class DeserializedClassDescriptor(
override fun isExternal() = Flags.IS_EXTERNAL_CLASS.get(classProto.flags)
override fun getUnsubstitutedMemberScope(): MemberScope = memberScope
override fun getUnsubstitutedMemberScope(moduleDescriptor: ModuleDescriptor): MemberScope =
memberScopeHolder().getScope(moduleDescriptor)
override fun getStaticScope() = staticScope
@@ -200,7 +205,7 @@ class DeserializedClassDescriptor(
get() = SupertypeLoopChecker.EMPTY
}
private inner class DeserializedClassMemberScope : DeserializedMemberScope(
private inner class DeserializedClassMemberScope(private val moduleDescriptor: ModuleDescriptor) : DeserializedMemberScope(
c, classProto.functionList, classProto.propertyList, classProto.typeAliasList,
classProto.nestedClassNameList.map(c.nameResolver::getName).let { { it } } // workaround KT-13454
) {
@@ -226,7 +231,7 @@ class DeserializedClassDescriptor(
override fun computeNonDeclaredFunctions(name: Name, functions: MutableCollection<SimpleFunctionDescriptor>) {
val fromSupertypes = ArrayList<SimpleFunctionDescriptor>()
for (supertype in classDescriptor.getTypeConstructor().supertypes) {
for (supertype in classDescriptor.getTypeConstructor().getSupertypes(moduleDescriptor)) {
fromSupertypes.addAll(supertype.memberScope.getContributedFunctions(name, NoLookupLocation.FOR_ALREADY_TRACKED))
}
@@ -240,7 +245,7 @@ class DeserializedClassDescriptor(
override fun computeNonDeclaredProperties(name: Name, descriptors: MutableCollection<PropertyDescriptor>) {
val fromSupertypes = ArrayList<PropertyDescriptor>()
for (supertype in classDescriptor.getTypeConstructor().supertypes) {
for (supertype in classDescriptor.getTypeConstructor().getSupertypes(moduleDescriptor)) {
fromSupertypes.addAll(supertype.memberScope.getContributedVariables(name, NoLookupLocation.FOR_ALREADY_TRACKED))
}
generateFakeOverrides(name, fromSupertypes, descriptors)

View File

@@ -36,7 +36,7 @@ import org.jetbrains.kotlin.serialization.js.KotlinJavascriptSerializationUtil
import org.jetbrains.kotlin.serialization.js.createKotlinJavascriptPackageFragmentProvider
import org.jetbrains.kotlin.utils.KotlinJavascriptMetadataUtils
object JsAnalyzerFacade : ResolverForModuleFactory() {
object JsResolverForModuleFactory : ResolverForModuleFactory() {
override fun <M : ModuleInfo> createResolverForModule(
moduleDescriptor: ModuleDescriptorImpl,
moduleContext: ModuleContext,

View File

@@ -209,7 +209,8 @@ class ShadowedDeclarationsFilter(
val context = BasicCallResolutionContext.create(bindingTrace, scope, newCall, TypeUtils.NO_EXPECTED_TYPE, dataFlowInfo,
ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS,
false, /* languageVersionSettings */ resolutionFacade.frontendService(),
resolutionFacade.frontendService<DataFlowValueFactory>())
resolutionFacade.frontendService<DataFlowValueFactory>(),
resolutionFacade.frontendService<ModuleDescriptor>())
val callResolver = resolutionFacade.frontendService<CallResolver>()
val results = if (isFunction) callResolver.resolveFunctionCall(context) else callResolver.resolveSimpleProperty(context)
val resultingDescriptors = results.resultingCalls.map { it.resultingDescriptor }

View File

@@ -8,7 +8,7 @@ package org.jetbrains.kotlin.caches.resolve
import com.intellij.openapi.roots.libraries.PersistentLibraryKind
import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory
import org.jetbrains.kotlin.analyzer.common.CommonAnalyzerFacade
import org.jetbrains.kotlin.analyzer.common.CommonResolverForModuleFactory
import org.jetbrains.kotlin.builtins.DefaultBuiltIns
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.context.ProjectContext
@@ -28,7 +28,7 @@ class CommonPlatformKindResolution : IdePlatformKindResolution {
override val kind get() = CommonIdePlatformKind
override val resolverForModuleFactory: ResolverForModuleFactory
get() = CommonAnalyzerFacade
get() = CommonResolverForModuleFactory
override fun createBuiltIns(settings: PlatformAnalysisSettings, projectContext: ProjectContext): KotlinBuiltIns {
return DefaultBuiltIns.Instance

View File

@@ -10,7 +10,7 @@ import com.intellij.openapi.vfs.VirtualFile
import org.jetbrains.kotlin.analyzer.ResolverForModuleFactory
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.idea.caches.resolve.JsAnalyzerFacade
import org.jetbrains.kotlin.idea.caches.resolve.JsResolverForModuleFactory
import org.jetbrains.kotlin.idea.caches.resolve.PlatformAnalysisSettings
import org.jetbrains.kotlin.idea.framework.JSLibraryKind
import org.jetbrains.kotlin.js.resolve.JsPlatform
@@ -27,7 +27,7 @@ class JsPlatformKindResolution : IdePlatformKindResolution {
override val kind get() = JsIdePlatformKind
override val resolverForModuleFactory: ResolverForModuleFactory
get() = JsAnalyzerFacade
get() = JsResolverForModuleFactory
override fun createBuiltIns(settings: PlatformAnalysisSettings, projectContext: ProjectContext): KotlinBuiltIns {
return JsPlatform.builtIns

View File

@@ -14,7 +14,7 @@ import org.jetbrains.kotlin.builtins.jvm.JvmBuiltIns
import org.jetbrains.kotlin.context.ProjectContext
import org.jetbrains.kotlin.idea.caches.resolve.PlatformAnalysisSettings
import org.jetbrains.kotlin.platform.impl.JvmIdePlatformKind
import org.jetbrains.kotlin.resolve.jvm.JvmAnalyzerFacade
import org.jetbrains.kotlin.resolve.jvm.JvmResolverForModuleFactory
class JvmPlatformKindResolution : IdePlatformKindResolution {
override fun isLibraryFileForPlatform(virtualFile: VirtualFile): Boolean {
@@ -27,7 +27,7 @@ class JvmPlatformKindResolution : IdePlatformKindResolution {
override val kind get() = JvmIdePlatformKind
override val resolverForModuleFactory: ResolverForModuleFactory
get() = JvmAnalyzerFacade
get() = JvmResolverForModuleFactory
override fun createBuiltIns(settings: PlatformAnalysisSettings, projectContext: ProjectContext): KotlinBuiltIns {
return if (settings.sdk != null) JvmBuiltIns(projectContext.storageManager) else DefaultBuiltIns.Instance

View File

@@ -367,7 +367,9 @@ internal object IDELightClassContexts {
private val codegenAffectingAnnotations: CodegenAffectingAnnotations,
private val callResolver: CallResolver,
private val languageVersionSettings: LanguageVersionSettings,
private val dataFlowValueFactory: DataFlowValueFactory,constantExpressionEvaluator: ConstantExpressionEvaluator,
private val dataFlowValueFactory: DataFlowValueFactory,
private val moduleDescriptor: ModuleDescriptor,
constantExpressionEvaluator: ConstantExpressionEvaluator,
storageManager: StorageManager
) : AnnotationResolverImpl(callResolver, constantExpressionEvaluator, storageManager) {
@@ -395,7 +397,8 @@ internal object IDELightClassContexts {
trace, scope, CallMaker.makeCall(null, null, annotationEntry), TypeUtils.NO_EXPECTED_TYPE,
DataFlowInfoFactory.EMPTY, ContextDependency.INDEPENDENT, CheckArgumentTypesMode.CHECK_VALUE_ARGUMENTS,
true, languageVersionSettings,
dataFlowValueFactory
dataFlowValueFactory,
moduleDescriptor
),
annotationEntry.calleeExpression!!.constructorReferenceExpression!!,
annotationConstructor.returnType

View File

@@ -22,7 +22,6 @@ import com.intellij.util.PathUtil
import com.intellij.util.SmartList
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.kotlin.analyzer.CombinedModuleInfo
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.TrackableModuleInfo
import org.jetbrains.kotlin.caches.project.LibraryModuleInfo
@@ -44,6 +43,7 @@ import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.resolve.TargetPlatform
import org.jetbrains.kotlin.resolve.jvm.GlobalSearchScopeWithModuleSources
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.utils.addIfNotNull
import java.util.*
@@ -128,6 +128,7 @@ private fun ideaModelDependencies(
interface ModuleSourceInfo : IdeaModuleInfo, TrackableModuleInfo {
val module: Module
// Non-transitive!
override val expectedBy: List<ModuleSourceInfo>
override val displayedName get() = module.name
@@ -326,6 +327,9 @@ data class SdkInfo(val project: Project, val sdk: Sdk) : IdeaModuleInfo {
override fun contentScope(): GlobalSearchScope = SdkScope(project, sdk)
override fun dependencies(): List<IdeaModuleInfo> = listOf(this)
override val platform: TargetPlatform
get() = JvmPlatform
}
object NotUnderContentRootModuleInfo : IdeaModuleInfo {
@@ -409,36 +413,33 @@ interface SourceForBinaryModuleInfo : IdeaModuleInfo {
override val moduleOrigin: ModuleOrigin
get() = ModuleOrigin.OTHER
}
data class PlatformModuleInfo(
val platformModule: ModuleSourceInfo,
private val commonModules: List<ModuleSourceInfo> // NOTE: usually contains a single element for current implementation
) : IdeaModuleInfo, CombinedModuleInfo, TrackableModuleInfo {
override val capabilities: Map<ModuleDescriptor.Capability<*>, Any?>
get() = platformModule.capabilities
override fun contentScope() = GlobalSearchScope.union(containedModules.map { it.contentScope() }.toTypedArray())
override val containedModules: List<ModuleSourceInfo> = listOf(platformModule) + commonModules
override val platform: TargetPlatform?
get() = platformModule.platform
override val moduleOrigin: ModuleOrigin
get() = platformModule.moduleOrigin
override fun dependencies() = platformModule.dependencies()
override fun modulesWhoseInternalsAreVisible() = containedModules.flatMap { it.modulesWhoseInternalsAreVisible() }
override val name: Name
get() = Name.special("<Platform module ${platformModule.displayedName} including ${commonModules.map { it.displayedName }}>")
override fun createModificationTracker() = platformModule.createModificationTracker()
}
fun IdeaModuleInfo.projectSourceModules(): List<ModuleSourceInfo>? =
(this as? ModuleSourceInfo)?.let(::listOf) ?: (this as? PlatformModuleInfo)?.containedModules
/** Remove because CombinedModuleInfo is removed */
//data class PlatformModuleInfo(
// val platformModule: ModuleSourceInfo,
// private val commonModules: List<ModuleSourceInfo> // NOTE: usually contains a single element for current implementation
//) : IdeaModuleInfo, CombinedModuleInfo, TrackableModuleInfo {
// override val capabilities: Map<ModuleDescriptor.Capability<*>, Any?>
// get() = platformModule.capabilities
//
// override fun contentScope() = GlobalSearchScope.union(containedModules.map { it.contentScope() }.toTypedArray())
//
// override val containedModules: List<ModuleSourceInfo> = listOf(platformModule) + commonModules
//
// override val platform: TargetPlatform?
// get() = platformModule.platform
//
// override val moduleOrigin: ModuleOrigin
// get() = platformModule.moduleOrigin
//
// override fun dependencies() = platformModule.dependencies()
//
// override fun modulesWhoseInternalsAreVisible() = containedModules.flatMap { it.modulesWhoseInternalsAreVisible() }
//
// override val name: Name
// get() = Name.special("<Platform module ${platformModule.displayedName} including ${commonModules.map { it.displayedName }}>")
//
// override fun createModificationTracker() = platformModule.createModificationTracker()
//}
enum class SourceType {
PRODUCTION,

View File

@@ -15,35 +15,16 @@ import com.intellij.openapi.roots.LibraryOrderEntry
import com.intellij.openapi.roots.ModuleRootManager
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.psi.util.CachedValueProvider
import org.jetbrains.kotlin.analyzer.common.CommonPlatform
import org.jetbrains.kotlin.resolve.TargetPlatform
import java.util.concurrent.ConcurrentHashMap
fun getModuleInfosFromIdeaModel(project: Project, platform: TargetPlatform): List<IdeaModuleInfo> {
val modelInfosCache = project.cached(CachedValueProvider {
fun getModuleInfosFromIdeaModel(project: Project): List<IdeaModuleInfo> {
return project.cached(CachedValueProvider {
CachedValueProvider.Result(collectModuleInfosFromIdeaModel(project), ProjectRootModificationTracker.getInstance(project))
})
return modelInfosCache.forPlatform(platform)
}
private class IdeaModelInfosCache(
val moduleSourceInfos: List<ModuleSourceInfo>,
val libraryInfos: List<LibraryInfo>,
val sdkInfos: List<SdkInfo>
) {
private val resultByPlatform = ConcurrentHashMap<TargetPlatform, List<IdeaModuleInfo>>()
fun forPlatform(platform: TargetPlatform): List<IdeaModuleInfo> {
return resultByPlatform.getOrPut(platform) {
mergePlatformModules(moduleSourceInfos, platform) + libraryInfos + sdkInfos
}
}
}
private fun collectModuleInfosFromIdeaModel(
project: Project
): IdeaModelInfosCache {
): List<IdeaModuleInfo> {
val ideaModules = ModuleManager.getInstance(project).modules.toList()
//TODO: (module refactoring) include libraries that are not among dependencies of any module
@@ -59,31 +40,40 @@ private fun collectModuleInfosFromIdeaModel(
}
}
return IdeaModelInfosCache(
moduleSourceInfos = ideaModules.flatMap(Module::correspondingModuleInfos),
libraryInfos = ideaLibraries.flatMap { createLibraryInfo(project, it) },
sdkInfos = (sdksFromModulesDependencies + getAllProjectSdks()).filterNotNull().toSet().map { SdkInfo(project, it) }
)
return ideaModules.flatMap(Module::correspondingModuleInfos) +
ideaLibraries.flatMap { createLibraryInfo(project, it) } +
(sdksFromModulesDependencies + getAllProjectSdks()).filterNotNull().toSet().map { SdkInfo(project, it) }
}
private fun mergePlatformModules(
allModules: List<ModuleSourceInfo>,
platform: TargetPlatform
): List<IdeaModuleInfo> {
if (platform is CommonPlatform) return allModules
val platformModules =
allModules.flatMap { module ->
if (module.platform == platform && module.expectedBy.isNotEmpty())
listOf(module to module.expectedBy)
else emptyList()
}.map { (module, expectedBys) ->
PlatformModuleInfo(module, expectedBys)
}
val rest = allModules - platformModules.flatMap { it.containedModules }
return rest + platformModules
}
/** This function used to:
* a) Introduce PlatformModuleInfo, on which other hacks heavily rely (see how we essentially re-wrap ModuleInfo + expectedBy-list
* into PlatformModuleInfo)
* b) Remove common modules from platform resolvers (see how we remove from allModules all contained modules (this will include
* expectedBy's)
*
* Now, common modules should be properly resolved by common resolver (remember that "common" resolver now actually is a more complex
* thing, essentially it is a "MixedPlatform", not just "Common")
*
* Visibility of common symbols from platform modules should be also added.
*/
//private fun mergePlatformModules(
// allModules: List<ModuleSourceInfo>,
// platform: TargetPlatform
//): List<IdeaModuleInfo> {
// if (platform is CommonPlatform) return allModules
//
// val platformModules =
// allModules.flatMap { module ->
// if (module.platform == platform && module.expectedBy.isNotEmpty())
// listOf(module to module.expectedBy)
// else emptyList()
// }.map { (module, expectedBys) ->
// PlatformModuleInfo(module, expectedBys)
// }
//
// val rest = allModules - platformModules.flatMap { it.containedModules }
// return rest + platformModules
//}
internal fun getAllProjectSdks(): Collection<Sdk> {
return ProjectJdkTable.getInstance().allJdks.toList()

View File

@@ -11,10 +11,8 @@ import com.intellij.openapi.externalSystem.service.project.IdeModelsProviderImpl
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.roots.ProjectRootModificationTracker
import com.intellij.psi.PsiElement
import com.intellij.psi.util.CachedValueProvider
import org.jetbrains.kotlin.analyzer.ModuleInfo
import org.jetbrains.kotlin.analyzer.common.CommonPlatform
import org.jetbrains.kotlin.caches.resolve.KotlinCacheService
import org.jetbrains.kotlin.descriptors.ModuleDescriptor
import org.jetbrains.kotlin.idea.caches.project.SourceType.PRODUCTION
@@ -26,7 +24,6 @@ import org.jetbrains.kotlin.idea.project.platform
import org.jetbrains.kotlin.idea.util.rootManager
import org.jetbrains.kotlin.platform.impl.CommonIdePlatformKind
import org.jetbrains.kotlin.platform.impl.isCommon
import org.jetbrains.kotlin.resolve.TargetPlatform
val Module.isNewMPPModule: Boolean
get() = facetSettings?.kind?.isNewMPP ?: false
@@ -91,9 +88,10 @@ private fun Module.findOldFashionedImplementedModuleNames(): List<String> {
val ModuleDescriptor.implementingDescriptors: List<ModuleDescriptor>
get() {
val moduleInfo = getCapability(ModuleInfo.Capability)
if (moduleInfo is PlatformModuleInfo) {
return listOf(this)
}
/** Same */
// if (moduleInfo is PlatformModuleInfo) {
// return listOf(this)
// }
val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList()
val implementingModuleInfos = moduleSourceInfo.module.implementingModules.mapNotNull { it.toInfo(moduleSourceInfo.sourceType) }
return implementingModuleInfos.mapNotNull { it.toDescriptor() }
@@ -105,10 +103,14 @@ private fun Module.toInfo(type: SourceType): ModuleSourceInfo? = when (type) {
}
/**
* This function returns immediate parents in dependsOn graph
*/
val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor>
get() {
val moduleInfo = getCapability(ModuleInfo.Capability)
if (moduleInfo is PlatformModuleInfo) return listOf(this)
/** This is weird, but strangely makes sense: combined module implements itself */
// if (moduleInfo is PlatformModuleInfo) return listOf(this)
val moduleSourceInfo = moduleInfo as? ModuleSourceInfo ?: return emptyList()
@@ -118,19 +120,32 @@ val ModuleDescriptor.implementedDescriptors: List<ModuleDescriptor>
private fun ModuleSourceInfo.toDescriptor() = KotlinCacheService.getInstance(module.project)
.getResolutionFacadeByModuleInfo(this, platform)?.moduleDescriptor
fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? {
assert(desiredPlatform !is CommonPlatform) { "Platform module cannot have Common platform" }
val moduleInfo = getNullableModuleInfo() as? ModuleSourceInfo ?: return null
return when (moduleInfo.platform) {
is CommonPlatform -> {
val correspondingImplementingModule = moduleInfo.module.implementingModules.map { it.toInfo(moduleInfo.sourceType) }
.firstOrNull { it?.platform == desiredPlatform } ?: return null
PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy)
}
desiredPlatform -> {
val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null
PlatformModuleInfo(moduleInfo, expectedBy)
}
else -> null
}
}
/** This function used to emulate a behaviour somewhat similar to projection (on module-level):
* Given a module, get a platform-view of that module
*
* This was implemented by following algo:
* - if it is a common-module, they find along its children a module with required platform.
* Then, build a PlatformModuleInfo for that children (it will include a given module, but will provide a semantic
* of platform-view of that given module)
* - otherwise, build a PlatformModuleInfo straightforwardly. This function returns null if requested module hadn't childs,
* seems like it is just for consistency.
*
* In a new world, operation of projection of module shouldn't be really necessary.
* Each client should be dealt with on case-by-case basis
*/
//fun PsiElement.getPlatformModuleInfo(desiredPlatform: TargetPlatform): PlatformModuleInfo? {
// assert(desiredPlatform !is CommonPlatform) { "Platform module cannot have Common platform" }
// val moduleInfo = getNullableModuleInfo() as? ModuleSourceInfo ?: return null
// return when (moduleInfo.platform) {
// is CommonPlatform -> {
// val correspondingImplementingModule = moduleInfo.module.implementingModules.map { it.toInfo(moduleInfo.sourceType) }
// .firstOrNull { it?.platform == desiredPlatform } ?: return null
// PlatformModuleInfo(correspondingImplementingModule, correspondingImplementingModule.expectedBy)
// }
// desiredPlatform -> {
// val expectedBy = moduleInfo.expectedBy.takeIf { it.isNotEmpty() } ?: return null
// PlatformModuleInfo(moduleInfo, expectedBy)
// }
// else -> null
// }
//}

View File

@@ -51,7 +51,7 @@ class IDEKotlinAsJavaSupport(private val project: Project): KotlinAsJavaSupport(
.get(packageFqName.asString(), project, scope).platformSourcesFirst()
}
val groupedByFqNameAndModuleInfo = facadeFilesInPackage.groupBy {
Pair(it.javaFileFacadeFqName, it.getModuleInfoPreferringJvmPlatform())
Pair(it.javaFileFacadeFqName, it.getModuleInfo())
}
return groupedByFqNameAndModuleInfo.flatMap {
@@ -156,7 +156,7 @@ class IDEKotlinAsJavaSupport(private val project: Project): KotlinAsJavaSupport(
}
override fun getFacadeClasses(facadeFqName: FqName, scope: GlobalSearchScope): Collection<PsiClass> {
val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy(PsiElement::getModuleInfoPreferringJvmPlatform)
val filesByModule = findFilesForFacade(facadeFqName, scope).groupBy(PsiElement::getModuleInfo)
return filesByModule.flatMap {
createLightClassForFileFacade(facadeFqName, it.value, it.key)
@@ -219,7 +219,7 @@ class IDEKotlinAsJavaSupport(private val project: Project): KotlinAsJavaSupport(
facadeFqName: FqName
): List<PsiClass> {
if (sourceFiles.isEmpty()) return listOf()
if (moduleInfo !is ModuleSourceInfo && moduleInfo !is PlatformModuleInfo) return listOf()
if (moduleInfo !is ModuleSourceInfo) return listOf()
val lightClassForFacade = KtLightClassForFacade.createForFacade(
psiManager, facadeFqName, moduleInfo.contentScope(), sourceFiles
@@ -325,6 +325,9 @@ class IDEKotlinAsJavaSupport(private val project: Project): KotlinAsJavaSupport(
}
}
internal fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo {
return getPlatformModuleInfo(JvmPlatform) ?: getModuleInfo()
}
/** Some hack to allow light-classes work in MPP, see ced3cf090464c83c2c1579aa2c40c653da8c5356
* New behaviour is unknown, investigation needed
*/
//internal fun PsiElement.getModuleInfoPreferringJvmPlatform(): IdeaModuleInfo {
// return getPlatformModuleInfo(JvmPlatform) ?: getModuleInfo()
//}

View File

@@ -66,7 +66,7 @@ internal val LOG = Logger.getInstance(KotlinCacheService::class.java)
// since in the current implementation types from one module are leaking into other modules' resolution
// meaning that we can't just change those setting on a per module basis
data class PlatformAnalysisSettings(
val platform: TargetPlatform, val sdk: Sdk?,
val sdk: Sdk?,
val isAdditionalBuiltInFeaturesSupported: Boolean,
// Effectively unused as a property. Needed only to distinguish different modes when being put in a map
val isReleaseCoroutines: Boolean
@@ -99,7 +99,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
val sdk = dependenciesModuleInfo.sdk
val platform = JvmPlatform // TODO: Js scripts?
val settings = PlatformAnalysisSettings(
platform, sdk, true,
sdk, true,
LanguageFeature.ReleaseCoroutines.defaultState == LanguageFeature.State.ENABLED
)
@@ -163,7 +163,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
private val modulesContext = librariesContext.contextWithNewLockAndCompositeExceptionTracker()
val facadeForModules = ProjectResolutionFacade(
"facadeForModules", "$resolverForModulesName for platform ${settings.platform}",
"facadeForModules", "$resolverForModulesName",
project, modulesContext, settings,
reuseDataFrom = facadeForLibraries,
moduleFilter = { !it.isLibraryClasses() },
@@ -176,7 +176,7 @@ class KotlinCacheServiceImpl(val project: Project) : KotlinCacheService {
}
private fun IdeaModuleInfo.platformSettings(targetPlatform: TargetPlatform) = PlatformAnalysisSettings(
targetPlatform, sdk,
sdk,
supportsAdditionalBuiltInsMembers(),
isReleaseCoroutines()
)

View File

@@ -44,7 +44,6 @@ import org.jetbrains.kotlin.platform.idePlatformKind
import org.jetbrains.kotlin.psi.KtElement
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.resolve.CompositeBindingContext
import org.jetbrains.kotlin.resolve.TargetPlatform
import org.jetbrains.kotlin.resolve.jvm.JvmPlatformParameters
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform
import org.jetbrains.kotlin.utils.addToStdlib.firstNotNullResult
@@ -110,7 +109,7 @@ internal class ProjectResolutionFacade(
projectContext
)
val allModuleInfos = (allModules ?: getModuleInfosFromIdeaModel(project, settings.platform)).toMutableSet()
val allModuleInfos = (allModules ?: getModuleInfosFromIdeaModel(project)).toMutableSet()
val syntheticFilesByModule = syntheticFiles.groupBy(KtFile::getModuleInfo)
val syntheticFilesModules = syntheticFilesByModule.keys
@@ -124,9 +123,21 @@ internal class ProjectResolutionFacade(
val jvmPlatformParameters = JvmPlatformParameters(
packagePartProviderFactory = { IDEPackagePartProvider(it.moduleContentScope) },
/** This callback in the following chain:
* JavaClass -> ModuleInfo -> ResolverForModule -> Container -> JavaDescriptorResolver
* (in particular, it is used to implement transition "JavaClass -> ModuleInfo")
*
* In CMI world, we'll return platform module for JavaClass from CommonModule (don't even ask me
* where the fuck we've found JavaClass in common module), which emulates compiler' behaviour
*
* I don't know what should we do in new world, because use-case is completely not clear and needs
* investigation (note that it was actually introduced later than CMI, see 3a8499b10e9687d0372c2e6242ed4091576642ae)
*/
moduleByJavaClass = { javaClass: JavaClass ->
val psiClass = (javaClass as JavaClassImpl).psi
psiClass.getPlatformModuleInfo(JvmPlatform)?.platformModule ?: psiClass.getNullableModuleInfo()
// psiClass.getPlatformModuleInfo(JvmPlatform)?.platformModule ?: psiClass.getNullableModuleInfo()
psiClass.getNullableModuleInfo()
}
)
@@ -139,10 +150,10 @@ internal class ProjectResolutionFacade(
projectContext,
modulesToCreateResolversFor,
modulesContentFactory,
modulePlatforms = { module -> module.platform?.multiTargetPlatform },
modulePlatforms = { module -> module.platform?.platform },
moduleLanguageSettingsProvider = IDELanguageSettingsProvider,
resolverForModuleFactoryByPlatform = { modulePlatform ->
val platform = modulePlatform ?: settings.platform
val platform = modulePlatform ?: TODO()
platform.idePlatformKind.resolution.resolverForModuleFactory
},
platformParameters = { platform ->
@@ -216,7 +227,9 @@ internal class ProjectResolutionFacade(
private companion object {
private fun createBuiltIns(settings: PlatformAnalysisSettings, projectContext: ProjectContext): KotlinBuiltIns {
return settings.platform.idePlatformKind.resolution.createBuiltIns(settings, projectContext)
// return settings.platform.idePlatformKind.resolution.createBuiltIns(settings, projectContext)
// TODO: what we do about built-ins?
return JvmPlatform.idePlatformKind.resolution.createBuiltIns(settings, projectContext)
}
}
}

View File

@@ -24,7 +24,7 @@ import org.jetbrains.kotlin.analyzer.PackageOracleFactory
import org.jetbrains.kotlin.idea.caches.PerModulePackageCacheService
import org.jetbrains.kotlin.idea.caches.project.IdeaModuleInfo
import org.jetbrains.kotlin.idea.caches.project.ModuleOrigin
import org.jetbrains.kotlin.idea.caches.project.projectSourceModules
import org.jetbrains.kotlin.idea.caches.project.ModuleSourceInfo
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.name.isSubpackageOf
import org.jetbrains.kotlin.resolve.jvm.KotlinJavaPsiFacade
@@ -37,11 +37,11 @@ class IdePackageOracleFactory(val project: Project) : PackageOracleFactory {
return when (moduleInfo.platform) {
JvmPlatform -> when (moduleInfo.moduleOrigin) {
ModuleOrigin.LIBRARY -> JavaPackagesOracle(moduleInfo, project)
ModuleOrigin.MODULE -> JvmSourceOracle(moduleInfo, project)
ModuleOrigin.MODULE -> JvmSourceOracle(moduleInfo as ModuleSourceInfo, project)
ModuleOrigin.OTHER -> PackageOracle.Optimistic
}
else -> when (moduleInfo.moduleOrigin) {
ModuleOrigin.MODULE -> KotlinSourceFilesOracle(moduleInfo, project)
ModuleOrigin.MODULE -> KotlinSourceFilesOracle(moduleInfo as ModuleSourceInfo, project)
else -> PackageOracle.Optimistic // binaries for non-jvm platform need some oracles based on their structure
}
}
@@ -54,16 +54,17 @@ class IdePackageOracleFactory(val project: Project) : PackageOracleFactory {
override fun packageExists(fqName: FqName) = facade.findPackage(fqName.asString(), scope) != null
}
private class KotlinSourceFilesOracle(moduleInfo: IdeaModuleInfo, private val project: Project) : PackageOracle {
private class KotlinSourceFilesOracle(private val moduleInfo: ModuleSourceInfo, project: Project) : PackageOracle {
private val cacheService = ServiceManager.getService(project, PerModulePackageCacheService::class.java)
private val sourceModules = moduleInfo.projectSourceModules()
/** Without combined moduleInfo, only one source module corresponds to one moduleInfo */
// private val sourceModules = moduleInfo.projectSourceModules()
override fun packageExists(fqName: FqName): Boolean {
return sourceModules?.any { cacheService.packageExists(fqName, it) } ?: false
return cacheService.packageExists(fqName, moduleInfo)
}
}
private class JvmSourceOracle(moduleInfo: IdeaModuleInfo, project: Project) : PackageOracle {
private class JvmSourceOracle(moduleInfo: ModuleSourceInfo, project: Project) : PackageOracle {
private val javaPackagesOracle = JavaPackagesOracle(moduleInfo, project)
private val kotlinSourceOracle = KotlinSourceFilesOracle(moduleInfo, project)

View File

@@ -53,7 +53,6 @@ object IDELanguageSettingsProvider : LanguageSettingsProvider {
)
is ScriptModuleInfo -> getLanguageSettingsForScripts(project, moduleInfo.scriptDefinition).languageVersionSettings
is ScriptDependenciesInfo.ForFile -> getLanguageSettingsForScripts(project, moduleInfo.scriptDefinition).languageVersionSettings
is PlatformModuleInfo -> moduleInfo.platformModule.module.languageVersionSettings
else -> project.getLanguageVersionSettings()
}

View File

@@ -22,13 +22,20 @@ import com.intellij.openapi.roots.ProjectFileIndex;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import kotlin.collections.CollectionsKt;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.kotlin.analyzer.common.CommonPlatform;
import org.jetbrains.kotlin.analyzer.common.CompositeTargetPlatform;
import org.jetbrains.kotlin.js.resolve.JsPlatform;
import org.jetbrains.kotlin.platform.DefaultIdeTargetPlatformKindProvider;
import org.jetbrains.kotlin.psi.KtCodeFragment;
import org.jetbrains.kotlin.psi.KtFile;
import org.jetbrains.kotlin.psi.KtPsiFactoryKt;
import org.jetbrains.kotlin.resolve.TargetPlatform;
import org.jetbrains.kotlin.resolve.jvm.platform.JvmPlatform;
import org.jetbrains.kotlin.resolve.konan.platform.KonanPlatform;
import java.util.ArrayList;
public class TargetPlatformDetector {
public static final TargetPlatformDetector INSTANCE = new TargetPlatformDetector();
@@ -68,7 +75,13 @@ public class TargetPlatformDetector {
@NotNull
public static TargetPlatform getPlatform(@NotNull Module module) {
return ProjectStructureUtil.getCachedPlatformForModule(module);
// TODO: hack
TargetPlatform declaredPlatform = ProjectStructureUtil.getCachedPlatformForModule(module);
if (declaredPlatform instanceof CommonPlatform) {
return new CompositeTargetPlatform(CollectionsKt.listOf(JvmPlatform.INSTANCE, JsPlatform.INSTANCE, KonanPlatform.INSTANCE));
} else {
return declaredPlatform;
}
}
}

Some files were not shown because too many files have changed in this diff Show More